public void TestHandleRegistrationRequestAfterBuildNotification()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                // Setup
                userCache = new UserCache();
                notificationManager = new NotificationManager(0, 0, userCache, false);
                string username = "******";
                string[] recipients = { username };
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding;
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                IBuildServerNotification buildServerNotification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
                string buildKey = Utils.CreateBuildKey(buildServerNotification);

                // Check that the user doesn't exist prior to the notification
                try
                {
                    userCache.GetUser(username);
                    Assert.Fail();
                }
                catch (KeyNotFoundException)
                {
                    // Expected
                }

                // This will create a user in the cache, but without a hostname
                notificationManager.HandleCommand(buildServerNotification, EventArgs.Empty);
                User user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.ActiveBuilds.Contains(buildKey));
                Assert.That(string.IsNullOrEmpty(user.Hostname));

                // Now we create a registration request, which should update the existing user with a hostname
                string hostname = username + "-ws";
                IRequest registrationRequest = new RegistrationRequest(hostname, username);
                notificationManager.HandleCommand(registrationRequest, EventArgs.Empty);
                user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.Hostname, Is.EqualTo(hostname));
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestHandleCommandForPriorityAttentionRequest()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;

            try
            {
                // Setup the notification manager
                object syncRoot = new object();
                int serverPort = 20000;
                int clientPort = 20001;

                // If the timer's expiry (trigger) period is too fast, the test will fail in step 2.
                // We set this (hopefully) sufficiently slow so that we can properly test the
                // sequence of events.
                int priorityTimerPeriod = 10000;

                // Any user's attention required will immediately be set as a priority.
                TimeSpan priorityPeriod = TimeSpan.Zero;

                // Note: The cache's timer starts upon construction
                userCache = new UserCache(priorityTimerPeriod, priorityPeriod);
                notificationManager = new NotificationManager(serverPort, clientPort, userCache, false);

                // A dummy client which the notification manager will notify
                Listener listener = new Listener(IPAddress.Any, clientPort);

                // We only want the attention requests
                AttentionRequest attentionRequest = null;
                listener.OnCommandReceived += (sender, args) =>
                {
                    if (sender.GetType() == typeof(AttentionRequest))
                    {
                        attentionRequest = (AttentionRequest)sender;
                    }

                    lock (syncRoot)
                    {
                        Monitor.Pulse(syncRoot);
                    }
                };

                // Create the requests and notifications
                string username = "******";
                string hostname = "localhost";
                string projectId = "project1";
                string buildConfigId = "buildConfig1";
                string state = BuildServerResponsibilityState.Taken;
                RegistrationRequest registrationRequest = new RegistrationRequest(hostname, username);
                ResponsibilityNotification responsibilityNotification = new ResponsibilityNotification(BuildServerNotificationType.BuildResponsibilityAssigned, projectId, buildConfigId, username, state);

                // Start the server and the client
                notificationManager.Start();
                Assert.That(notificationManager.Running, Is.True);
                listener.Start();
                Assert.That(listener.Running, Is.True);

                // STEP 1
                // Register the dummy client with the server
                lock (syncRoot)
                {
                    // This will cause one attention request and one build active request
                    Utils.SendCommand(hostname, serverPort, Parser.Encode(registrationRequest));
                    Monitor.Wait(syncRoot);
                }

                Assert.That(attentionRequest, Is.Not.Null);
                Assert.That(attentionRequest.IsAttentionRequired, Is.False);
                Assert.That(attentionRequest.IsPriority, Is.False);

                // STEP 2
                attentionRequest = null;
                lock (syncRoot)
                {
                    // This will cause another attention request and another build active request
                    notificationManager.HandleCommand(responsibilityNotification, EventArgs.Empty);
                    Monitor.Wait(syncRoot);
                }

                Assert.That(attentionRequest, Is.Not.Null);
                Assert.That(attentionRequest != null && attentionRequest.IsAttentionRequired, Is.True);
                Assert.That(attentionRequest != null && attentionRequest.IsPriority, Is.False);

                // STEP 3
                // The next two pulses (again for an attention and a build active request) must
                // be because of the timer that expired
                attentionRequest = null;
                lock (syncRoot)
                {
                    Monitor.Wait(syncRoot);
                }

                // Shut down
                notificationManager.Stop();
                Assert.That(notificationManager.Running, Is.False);
                listener.Stop();
                Assert.That(listener.Running, Is.False);

                // Test
                Assert.That(attentionRequest, Is.Not.Null);
                Assert.That(attentionRequest != null && attentionRequest.IsAttentionRequired, Is.True);
                Assert.That(attentionRequest != null && attentionRequest.IsPriority, Is.True);
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestHandleCommandForRegistrationRequestRaisesCommandReceivedEvent()
        {
            // Setup
            Listener listener = new Listener(IPAddress.Any, 0);
            IRequest actualRequest = null;
            listener.OnCommandReceived += delegate(object sender, EventArgs args) { actualRequest = (IRequest)sender; };
            string username = "******";
            string hostname = username + "-ws";
            RegistrationRequest actualRegistrationRequest = new RegistrationRequest(hostname, username);
            string command = Parser.Encode(actualRegistrationRequest);

            // Fire
            listener.HandleCommand(command);

            // Test
            Assert.That(actualRequest, Is.Not.Null);
            Assert.That(actualRequest, Is.InstanceOf(typeof(RegistrationRequest)));
            RegistrationRequest expectedRegistrationRequest = (RegistrationRequest)actualRequest;
            Assert.That(expectedRegistrationRequest.Username, Is.EqualTo(username));
            Assert.That(expectedRegistrationRequest.Hostname, Is.EqualTo(hostname));
        }
        public void TestHandleRegistrationRequest()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                userCache = new UserCache();
                notificationManager = new NotificationManager(0, 0, userCache, false);
                string username = "******";
                string hostname = username + "-ws";
                IRequest registrationRequest = new RegistrationRequest(hostname, username);

                // Check that the user doesn't exist prior to the registration request
                try
                {
                    userCache.GetUser(username);
                    Assert.Fail();
                }
                catch (KeyNotFoundException)
                {
                }

                notificationManager.HandleCommand(registrationRequest, EventArgs.Empty);
                User user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.Hostname, Is.EqualTo(hostname));

                // Registering the same user a second time shouldn't fail
                notificationManager.HandleCommand(registrationRequest, EventArgs.Empty);
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
 public void TestGetRegisteredUsers()
 {
     UserCache userCache = null;
     try
     {
         userCache = new UserCache();
         List<User> userList = new List<User>(userCache.GetRegisteredUsers());
         Assert.That(userList.Count, NUnit.Framework.Is.EqualTo(0));
         string username1 = "user1";
         string hostname1 = username1 + "-ws";
         string username2 = "user2";
         string hostname2 = string.Empty;
         RegistrationRequest request1 = new RegistrationRequest(hostname1, username1);
         RegistrationRequest request2 = new RegistrationRequest(hostname2, username2);
         userCache.Register(request1);
         userCache.Register(request2);
         userList = new List<User>(userCache.GetRegisteredUsers());
         Assert.That(userList.Count, NUnit.Framework.Is.EqualTo(1));
         User user = userList[0];
         Assert.That(user.Hostname, NUnit.Framework.Is.EqualTo(hostname1));
         Assert.That(user.Username, NUnit.Framework.Is.EqualTo(username1));
     }
     finally
     {
         if (userCache != null)
         {
             userCache.Dispose();
         }
     }
 }
 public void TestRegistrationUpdateEvent()
 {
     UserCache userCache = null;
     try
     {
         userCache = new UserCache();
         User user = null;
         userCache.OnUpdate += delegate(object sender, EventArgs args) { user = (User)sender; };
         string username = "******";
         string hostname = username + "-ws";
         RegistrationRequest request = new RegistrationRequest(hostname, username);
         userCache.Register(request);
         Assert.That(user, NUnit.Framework.Is.Not.Null);
         Assert.That(user.Username, NUnit.Framework.Is.EqualTo(username));
         Assert.That(user.Hostname, NUnit.Framework.Is.EqualTo(hostname));
         Assert.That(user.ActiveBuilds.Count, NUnit.Framework.Is.EqualTo(0));
         Assert.That(user.BuildsResponsibleFor.Count, NUnit.Framework.Is.EqualTo(0));
     }
     finally
     {
         if (userCache != null)
         {
             userCache.Dispose();
         }
     }
 }
 public void TestTranslateThrowsExceptionForUnknownRequest()
 {
     IRequest request = new RegistrationRequest(string.Empty, string.Empty);
     Parser.TranslateForDasBlinkenlichten(request);
     Assert.Fail();
 }
        /// <summary>
        /// Registers the device.
        /// </summary>
        private void Register()
        {
            // Ensure the listener is running, otherwise we won't be able to receive requests after registration
            if (!this.Running)
            {
                log.Debug("Server not running - ignoring request to register");
                return;
            }

            try
            {
                string user = Utils.GetUsername();
                if (string.IsNullOrEmpty(user))
                {
                    log.Warn(string.Format("Cannot register: No logged on user - will retry in about {0}s", this.registrationRetryPeriod / 1000));
                    return;
                }

                log.Info(string.Format("Registering device for user {0}", user));
                string host = Utils.GetHostname();
                if (string.IsNullOrEmpty(host))
                {
                    log.Warn(string.Format("Cannot register: Unable to resolve host - will retry in about {0}s", this.registrationRetryPeriod / 1000));
                    return;
                }

                RegistrationRequest request = new RegistrationRequest(host, user);
                string command = Parser.Encode(request);
                log.Info(string.Format("Sending command {0} to host {1}:{2}", command, this.notificationManagerHost, this.notificationManagerPort));
                if (Utils.SendCommand(this.notificationManagerHost, this.notificationManagerPort, command))
                {
                    this.StopRegistrationRetryTimer();
                }
                else
                {
                    log.Warn(string.Format("Could not send command to host - will retry in about {0}s", this.registrationRetryPeriod / 1000));
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
 /// <summary>
 /// Registers the user.
 /// </summary>
 /// <param name="request">The request.</param>
 public void Register(RegistrationRequest request)
 {
     User user = new User(request.Username) {
                                                    Hostname = request.Hostname
                                            };
     this.userCache.AddOrUpdate(user.Username, user, (username, existingUser) =>
     {
         existingUser.Hostname = request.Hostname;
         return existingUser;
     });
     this.userCache.TryGetValue(user.Username, out user);
     this.NotifyUpdate(user);
 }