public void StoreSubscription(SubscriptionModel model)
        {
            if (GetUser(model.PubSubHubUser) == null)
            {
                throw new InvalidOperationException("User does not exist.");
            }

            int maxSubsForUser = GetMaxSubscriptionsForUser(model.PubSubHubUser);
            int userSubCount = GetSubscriptionCountForUser(model.PubSubHubUser);

            if (userSubCount >= maxSubsForUser)
            {
                throw new InvalidOperationException("Storing this subscription would exceed the users subscription limit");
            }

            lock (_dbAccessLock)
            {
                Subscription newSubscription = _entities.CreateObject<Subscription>();
                newSubscription.Callback = model.Callback;
                newSubscription.Digest = model.Digest;
                newSubscription.Mode = model.Mode;
                newSubscription.Verify = model.Verify;
                newSubscription.Topic = model.Topic;
                newSubscription.LastUpdated = DateTime.Now;
                newSubscription.PubSubHubUser = model.PubSubHubUser;

                _loggingService.Info("Saving model to the database " + model);

                _entities.AddToSubscriptionsSet(newSubscription);
                _entities.SaveChanges();

                model.Id = newSubscription.Id;
            }
        }
        private SubscriptionServiceResult CallSubscriber(IHubConfiguration configuration, SubscriptionModel model)
        {
            SubscriptionServiceResult result = new SubscriptionServiceResult()
            {
                Type = SubscriptionResponseResultType.Success
            };

            var request = CreateRequest(configuration, model);

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                _loggingService.Info("Response received: " + response.StatusCode);

                if (response.StatusCode != HttpStatusCode.NoContent)
                {
                    result.Type = SubscriptionResponseResultType.Error;
                    result.ErrorDescription = "The pubsubhub returned " + response.StatusDescription;
                }
                else
                {
                    using (Stream receiveStream = response.GetResponseStream())
                    {
                        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                        {
                            string hubResponse = readStream.ReadToEnd();

                            _loggingService.Info("Response text received: " + hubResponse);
                        }
                    }
                }
            }
            catch (WebException we)
            {
                if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Unauthorized)
                {
                    result.Type = SubscriptionResponseResultType.NotAuthorised;
                    result.ErrorDescription = "The credentials provided were not accepted by the subscription hub";
                }
                else if ((int)((HttpWebResponse)we.Response).StatusCode == 422)
                {
                    result.Type = SubscriptionResponseResultType.NotFound;
                    result.ErrorDescription = model.Mode + " error. The hub did not believe the subscription to exist or the sync callback failed.";
                }
                else
                {
                    string msg = model.Mode + " error. " + we.ToString();
                    _loggingService.Error(msg);
                    result.Type = SubscriptionResponseResultType.Error;
                    result.ErrorDescription = msg;
                }
            }

            return result;
        }        
 public SubscriptionServiceResult UnSubscribe(IHubConfiguration configuration, SubscriptionModel model)
 {
     return CallSubscriber(configuration, model);
 }
        private SubscriptionModel CreateSubscriptionModelFromSubscription(Subscription sub)
        {
            var model = new SubscriptionModel()
            {
                Id = sub.Id,
                Callback = sub.Callback,
                Mode = sub.Mode,
                Digest = sub.Digest,
                Topic = sub.Topic,
                Verify = sub.Verify,
                PendingDeletion = sub.PendingDeletion,
                Verified = sub.Verified,
                LastUpdated = sub.LastUpdated,
                PubSubHubUser = sub.PubSubHubUser
            };

            return model;
        }
        public void SaveChanges(SubscriptionModel model)
        {
            lock (_dbAccessLock)
            {
                Subscription sub = _entities.SubscriptionsSet.First(m => m.Id == model.Id);

                sub.Callback = model.Callback;
                sub.Digest = model.Digest;
                sub.LastUpdated = model.LastUpdated;
                sub.Mode = model.Mode;
                sub.PendingDeletion = model.PendingDeletion;
                sub.Topic = model.Topic;
                sub.Verified = model.Verified;
                sub.Verify = model.Verify;
                sub.PubSubHubUser = model.PubSubHubUser;

                _entities.SaveChanges();
            }
        }
        public void Login_attempts_a_Subscribe_and_NotAuthorisedResponse_leads_to_ErrorDescription_being_set_Test()
        {
            ActionResult actual = null;
            SubscriptionModel model = new SubscriptionModel();
            UserModel userModel = new UserModel()
            {
                Username = "******",
                Password = "******"
            };

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Stub(x => x.GetUser(userModel.Username))
                    .Return(userModel);

                _subscriptionService.Expect(x => x.Subscribe(
                        Arg<IHubConfiguration>.Matches(
                            config => config.HubUsername == userModel.Username &&
                            config.HubPassword == userModel.Password),
                        Arg<SubscriptionModel>.Is.Anything))
                    .Return(new SubscriptionServiceResult() { Type = SubscriptionResponseResultType.NotAuthorised });

            }).Verify(delegate
            {
                actual = _controller.Login(userModel);
            });

            Assert.IsNotNull(actual);
            Assert.IsNull(_controller.ViewData["ErrorDescription"]);
        }
        public void Login_checks_user_has_been_added_to_the_database_and_Error_is_set_when_user_does_not_exist_Test()
        {
            ActionResult actual = null;
            SubscriptionModel model = new SubscriptionModel();
            UserModel userModel = new UserModel()
            {
                Username = "******",
                Password = "******"
            };

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetUser(userModel.Username))
                    .Return(null);

            }).Verify(delegate
            {
                actual = _controller.Login(userModel);
            });

            Assert.IsNotNull(_controller.ViewData.ModelState["_FORM"]);
        }
        public void Create_sets_ViewData_ErrorDescription_when_result_has_Error_type_test()
        {
            SubscriptionModel model = new SubscriptionModel();
            ActionResult actual = null;
            string errorDescription = "an error";

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Stub(x => x.GetMaxSubscriptionsForUser(_controller.HubConfiguration.HubUsername)).Return(10);
                _subscriptionPersistenceService.Stub(x => x.GetSubscriptionCountForUser(_controller.HubConfiguration.HubUsername)).Return(1);

                _subscriptionPersistenceService.Expect(x => x.StoreSubscription(model));

                _subscriptionService.Expect(x => x.Subscribe(_controller.HubConfiguration, model))
                    .Return(new SubscriptionServiceResult()
                    {
                        Type = SubscriptionResponseResultType.Error,
                        ErrorDescription = errorDescription
                    });

            }).Verify(delegate
            {
                actual = _controller.Create(model);
            });
            Assert.IsNotNull(actual);
            Assert.AreEqual(errorDescription, (string)(_controller.ViewData["ErrorDescription"]));
        }
        public void HubUpdate_for_feed_unsubscribe_Test()
        {
            ActionResult actual = null;
            int detailsId = 1;
            string updateContents = "some document contents";
            string hubChallenge = new Guid().ToString();
            SetupResult.For(_request.InputStream).Return(new MemoryStream(new UTF8Encoding().GetBytes(updateContents)));
            SetupResult.For(_request["hub.mode"]).Return("unsubscribe");
            SetupResult.For(_request["hub.challenge"]).Return(hubChallenge);
            SubscriptionModel detailsSub = new SubscriptionModel()
            {
                Verified = true
            };

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionCountById(detailsId)).Return(1);
                _subscriptionPersistenceService.Expect(x => x.DeleteSubscriptionById(detailsId));

            }).Verify(delegate
            {
                actual = _controller.HubUpdate(detailsId);
            });
            Assert.IsNotNull(actual);
            Assert.AreEqual(hubChallenge, _controller.ViewData["hub.challenge"]);
            Assert.AreEqual((int)HttpStatusCode.OK, _response.StatusCode);
        }
        public void HubUpdate_for_feed_update_NotFound_response_Test()
        {
            ActionResult actual = null;
            int detailsId = 1;
            SubscriptionModel detailsSub = new SubscriptionModel()
            {
                Verified = true
            };

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionCountById(detailsId)).Return(0);

            }).Verify(delegate
            {
                actual = _controller.HubUpdate(detailsId);
            });
            Assert.IsNotNull(actual);
            Assert.AreEqual((int)HttpStatusCode.NotFound, _response.StatusCode);
        }
        public void HubUpdate_for_feed_update_Test()
        {
            ActionResult actual = null;
            int detailsId = 1;
            string updateContents = "some document contents";
            SetupResult.For(_request.InputStream).Return(new MemoryStream(new UTF8Encoding().GetBytes(updateContents)));
            SubscriptionModel model = new SubscriptionModel()
            {
                Verified = true,
                PubSubHubUser = "******"
            };
            UserModel userModel = new UserModel();

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionById(detailsId)).Return(model);
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionCountById(detailsId)).Return(1);
                _subscriptionPersistenceService.Expect(x => x.GetUser(model.PubSubHubUser)).Return(userModel);
                _subscriptionListener.Expect(x => x.SubscriptionUpdateReceived(userModel, updateContents));
                _subscriptionPersistenceService.Expect(x => x.SaveChanges(model));

            }).Verify(delegate
            {
                actual = _controller.HubUpdate(detailsId);
            });
            Assert.IsNotNull(actual);
            Assert.AreEqual((int)HttpStatusCode.OK, _response.StatusCode);
        }
        public void HubUpdate_for_unverified_subscription_Test()
        {
            ActionResult actual = null;
            int detailsId = 1;
            SubscriptionModel model = new SubscriptionModel()
            {
                Verified = false
            };

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionById(detailsId)).Return(model);
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionCountById(detailsId)).Return(1);

                _subscriptionPersistenceService.Expect(x => x.SaveChanges(model));

            }).Verify(delegate
            {
                actual = _controller.HubUpdate(detailsId);
            });
            Assert.IsNotNull(actual);
            Assert.IsTrue(model.Verified);
            Assert.AreEqual((int)HttpStatusCode.OK, _response.StatusCode);
        }
        public void Delete_subscription_NotFound_in_subscription_service_sets_ErrorDescription()
        {
            ActionResult actual = null;
            int deleteId = 1;
            SubscriptionModel model = new SubscriptionModel();

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionById(deleteId)).Return(model);

                _subscriptionPersistenceService.Expect(x => x.SaveChanges(model));

                _subscriptionService.Expect(x => x.UnSubscribe(_controller.HubConfiguration, model))
                    .Return(new SubscriptionServiceResult() { Type = SubscriptionResponseResultType.NotFound });

                _subscriptionPersistenceService.Expect(x => x.DeleteSubscriptionById(deleteId));

            }).Verify(delegate
            {
                actual = _controller.Delete(deleteId);
            });
            Assert.IsNotNull(actual);
            Assert.IsNotNull(_controller.ViewData["ErrorDescription"]);
        } 
        public void Delete_stores_subscription_and_makes_subscription_request_to_subscription_service()
        {
            ActionResult actual = null;
            int deleteId = 1;
            SubscriptionModel model = new SubscriptionModel();

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Stub(x => x.GetMaxSubscriptionsForUser(_controller.HubConfiguration.HubUsername)).Return(10);
                _subscriptionPersistenceService.Stub(x => x.GetSubscriptionCountForUser(_controller.HubConfiguration.HubUsername)).Return(1);

                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionById(deleteId)).Return(model);
                
                _subscriptionPersistenceService.Expect(x => x.SaveChanges(model));

                _subscriptionService.Expect(x => x.UnSubscribe(_controller.HubConfiguration, model))
                    .Return(new SubscriptionServiceResult() { Type = SubscriptionResponseResultType.Success });

            }).Verify(delegate
            {
                actual = _controller.Delete(deleteId);
            });
            Assert.IsNotNull(actual);
        }
        public void HubUpdate_for_feed_NotFound_Test()
        {
            SubscriptionModel model = new SubscriptionModel();
            ActionResult actual = null;
            int detailsId = 1;
            string hubChallenge = new Guid().ToString();
            SetupResult.For(_request["hub.mode"]).Return("unsubscribe");
            SetupResult.For(_request["hub.challenge"]).Return(hubChallenge);

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionCountById(detailsId)).Return(0);

            }).Verify(delegate
            {
                actual = _controller.HubUpdate(detailsId);
            });
            Assert.IsNotNull(actual);
            Assert.AreEqual(hubChallenge, _controller.ViewData["hub.challenge"]);
            Assert.AreEqual((int)HttpStatusCode.NotFound, _response.StatusCode);
        }
        private HttpWebRequest CreateRequest(IHubConfiguration configuration, SubscriptionModel model)
        {
            UriBuilder builder = new UriBuilder(configuration.HubRoot);

            string query = "hub.mode=" + model.Mode + "&";
            query += "hub.verify=" + model.Verify + "&";
            query += "hub.callback=" + model.Callback + "/" + model.Id + "&";
            query += "hub.topic=" + model.Topic;
            builder.Query = query;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(builder.Uri);
            byte[] authBytes = Encoding.UTF8.GetBytes((configuration.HubUsername + ":" + configuration.HubPassword).ToCharArray());
            request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);

            request.Method = "POST";
            request.PreAuthenticate = true;

            _loggingService.Info("Making request to hub for subscription: " + request.RequestUri.ToString());

            return request;
        }
        public void Create_sets_error_if_MaxSubscriptions_has_been_reached_test()
        {
            SubscriptionModel model = new SubscriptionModel();
            ActionResult actual = null;

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetMaxSubscriptionsForUser(_controller.HubConfiguration.HubUsername)).Return(10);
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionCountForUser(_controller.HubConfiguration.HubUsername)).Return(10);

            }).Verify(delegate
            {
                actual = _controller.Create(model);
            });
            Assert.IsNotNull(actual);
            Assert.IsNotNull(_controller.ViewData["ErrorDescription"]);
        }