public async Task A_subscriber_should_received_a_published_event()
        {
            var addSubscriptionRequest = new AddSubscriptionRequest
            {
                Name = "MySub"
            };
            var response = await _subscriberClient.PostAsJson(addSubscriptionRequest, "hooks");

            var addSubscriptionResponse = await response.Content.ReadAs <AddSubscriptionResponse>();

            var addWebHookRequest = new AddWebHookRequest
            {
                Secret           = addSubscriptionResponse.Secret,
                PayloadTargetUri =
                    new Uri($"http://subscriber.example.com/{addSubscriptionResponse.PayloadTargetRelativeUri}"),
                Enabled            = true,
                SubscriptionChoice = SubscriptionChoice.Everything
            };
            await _publisherClient.PostAsJson(addWebHookRequest, "hooks");

            var eventName = "foo";
            var json      = "{ \"id\": 1 }";
            await _webHookPublisher.QueueEvent(eventName, json);

            await _webHookPublisher.DeliverNow();
        }
        public async Task Can_receive_event()
        {
            // Arrange
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };
            var addSubscription = await _client.PostAsJson(request, "hooks");

            var addSubscriptionResponse = await addSubscription.Content.ReadAs <AddSubscriptionResponse>();

            var eventName        = "foo";
            var messageId        = Guid.NewGuid();
            var json             = "{ \"id\": 1 }";
            var signature        = PayloadSignature.CreateSignature(json, addSubscriptionResponse.Secret);
            var content          = new StringContent(json, Encoding.UTF8, "application/json");
            var postEventRequest = new HttpRequestMessage(HttpMethod.Post, addSubscription.Headers.Location)
            {
                Content = content
            };

            SetCustomHeaders(postEventRequest, eventName, messageId, signature);

            // Act
            var response = await _client.SendAsync(postEventRequest);

            var streamMessage = (await _streamStore.ReadAllForwards(Position.Start, 10, true))
                                .Messages.Where(m => m.Type == eventName).SingleOrDefault();

            // Assert
            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            (await streamMessage.GetJsonData()).ShouldBe(json);
            streamMessage.MessageId.ShouldBe(messageId);
        }
Example #3
0
        //Add Subscription
        public async Task <SubscriptionResponse> AddSubscription(AddSubscriptionRequest req)
        {
            string jsonRequest  = CommonService.JsonSerializer <AddSubscriptionRequest>(req);
            string jsonResponse = await PostRequest(jsonRequest, "addsubscription");

            return(CommonService.JsonDeSerializer <SubscriptionResponse>(jsonResponse));
        }
        public async Task When_event_delivered_should_be_in_delivery_stream()
        {
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };
            var addSubscription = await _subscriberClient.PostAsJson(request, "hooks");

            var addSubscriptionResponse = await addSubscription.Content.ReadAs <AddSubscriptionResponse>();

            var hookUri          = new Uri(_subscriberClient.BaseAddress, "hooks");
            var payloadTargetUri = new Uri(hookUri, addSubscription.Headers.Location);

            var addWebHookRequest =
                CreateAddWebHookRequest(payloadTargetUri.ToString(), addSubscriptionResponse.Secret);
            var webhookLocation = await CreateWebHook(addWebHookRequest);

            var eventName = "foo";
            var json      = "bar";
            await _publisher.QueueEvent(eventName, json);

            await _publisher.DeliverNow();

            var response = await _publisherClient.GetAsync($"hooks/{webhookLocation}/deliveries");

            var deliveryEventsPage = await response.Content.ReadAs <DeliveryEventsPage>();

            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            deliveryEventsPage.Items.Length.ShouldBe(1);
            deliveryEventsPage.Items[0].EventName.ShouldBe(eventName);
            deliveryEventsPage.Items[0].EventMessageId.ShouldNotBe(Guid.Empty);
            deliveryEventsPage.Items[0].Success.ShouldBeTrue();
            deliveryEventsPage.Items[0].EventSequence.ShouldBe(0);
        }
        public async Task Can_delete_subscription()
        {
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };
            var response = await _client.PostAsJson(request, "hooks");

            response = await _client.DeleteAsync(response.Headers.Location);

            var getResponse = await _client.GetAsync(response.Headers.Location);

            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            getResponse.StatusCode.ShouldBe(HttpStatusCode.NotFound);
        }
        public async Task Can_get_subscription()
        {
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };
            var response = await _client.PostAsJson(request, "hooks");

            response = await _client.GetAsync(response.Headers.Location);

            var subscription = await response.Content.ReadAs <WebHookSubscription>();

            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            subscription.Name.ShouldBe(request.Name);
            subscription.CreatedUtc.ShouldBeGreaterThan(DateTime.MinValue);
            subscription.PayloadTargetRelativeUri.ShouldNotBeNullOrWhiteSpace();
        }
        public async Task Can_add_subscription()
        {
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };

            var response = await _client.PostAsJson(request, "hooks");

            var subscriptionResponse = await response.Content.ReadAs <AddSubscriptionResponse>();

            response.StatusCode.ShouldBe(HttpStatusCode.Created);
            response.Headers.Location.ShouldNotBeNull();
            subscriptionResponse.Name.ShouldBe(request.Name);
            subscriptionResponse.Secret.ShouldNotBeNullOrWhiteSpace();
            subscriptionResponse.PayloadTargetRelativeUri.ShouldNotBeNullOrWhiteSpace();
        }
        public async Task When_add_subscription_then_should_be_in_collection()
        {
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };
            await _client.PostAsJson(request, "hooks");

            var response = await _client.GetAsync("hooks");

            var subscriptions = await response.Content.ReadAs <WebHookSubscription[]>();

            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            subscriptions.Length.ShouldBe(1);
            subscriptions[0].Name.ShouldBe(request.Name);
            subscriptions[0].PayloadTargetRelativeUri.ShouldNotBeNullOrWhiteSpace();
        }
        public async Task When_subscriber_returns_error_then_should_retry()
        {
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };
            var addSubscription = await _subscriberClient.PostAsJson(request, "hooks");

            var addSubscriptionResponse = await addSubscription.Content.ReadAs <AddSubscriptionResponse>();

            var hookUri           = new Uri(_subscriberClient.BaseAddress, "hooks");
            var payloadTargetUri  = new Uri(hookUri, addSubscription.Headers.Location);
            var addWebHookRequest =
                CreateAddWebHookRequest(payloadTargetUri.ToString(), addSubscriptionResponse.Secret);
            var webhookLocation = await CreateWebHook(addWebHookRequest);

            var eventName = "foo";
            var json      = "bar";
            await _publisher.QueueEvent(eventName, json);


            _subscriberSettings.ReturnErrorOnReceive = true;
            await _publisher.DeliverNow();

            _utcNow = _utcNow.AddSeconds(10);
            _subscriberSettings.ReturnErrorOnReceive = false;
            await _publisher.DeliverNow();

            var response = await _publisherClient.GetAsync($"hooks/{webhookLocation}/deliveries");

            var deliveryEventsPage = await response.Content.ReadAs <DeliveryEventsPage>();

            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            deliveryEventsPage.Items.Length.ShouldBe(2);
            deliveryEventsPage.Items[0].EventName.ShouldBe(eventName);
            deliveryEventsPage.Items[0].EventMessageId.ShouldNotBe(Guid.Empty);
            deliveryEventsPage.Items[0].Success.ShouldBeTrue();
            deliveryEventsPage.Items[0].EventSequence.ShouldBe(0);
            deliveryEventsPage.Items[0].ErrorMessage.ShouldBeNullOrWhiteSpace();

            deliveryEventsPage.Items[1].EventName.ShouldBe(eventName);
            deliveryEventsPage.Items[1].EventMessageId.ShouldNotBe(Guid.Empty);
            deliveryEventsPage.Items[1].Success.ShouldBeFalse();
            deliveryEventsPage.Items[1].EventSequence.ShouldBe(0);
            deliveryEventsPage.Items[1].ErrorMessage.ShouldNotBeNullOrWhiteSpace();
        }
        public async Task When_receive_same_event_twice_then_should_record_it_once()
        {
            // Arrange
            var request = new AddSubscriptionRequest
            {
                Name = "foo"
            };
            var addSubscription = await _client.PostAsJson(request, "hooks");

            var addSubscriptionResponse = await addSubscription.Content.ReadAs <AddSubscriptionResponse>();

            var eventName        = "foo";
            var messageId        = Guid.NewGuid();
            var json             = "{ \"id\": 1 }";
            var signature        = PayloadSignature.CreateSignature(json, addSubscriptionResponse.Secret);
            var postEventRequest = new HttpRequestMessage(HttpMethod.Post, addSubscription.Headers.Location)
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            SetCustomHeaders(postEventRequest, eventName, messageId, signature);
            await _client.SendAsync(postEventRequest);

            // Act
            var secondPostEventRequest = new HttpRequestMessage(HttpMethod.Post, addSubscription.Headers.Location)
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            SetCustomHeaders(postEventRequest, eventName, messageId, signature);
            await _client.SendAsync(secondPostEventRequest);

            (await _streamStore.ReadAllForwards(Position.Start, 10, true))
            .Messages
            .Where(m => m.Type == eventName && m.MessageId == messageId)
            .SingleOrDefault()     // Idempotent!
            .ShouldNotBeNull();
        }
        public IHttpActionResult AddSubscription(AddSubscriptionRequest addSubscriptionRequest)
        {
            var responses = new Responses();

            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var subscription = new Subscription()
                {
                    UserId    = Utility.UserId,
                    PackageId = addSubscriptionRequest.PackageId,
                    CreatedBy = Utility.UserId
                };
                int result = iSubscription.AddSubscription(subscription);

                switch (result)
                {
                case -2:
                    responses.Status      = Utility.ERROR_STATUS_RESPONSE;
                    responses.Description = "Subscription already exists.";
                    break;

                default:
                    if (result > 0)
                    {
                        string userName    = string.Empty;
                        var    userProfile = new UserProfile()
                        {
                            UserId = Utility.UserId
                        };
                        var userProfiles = iUserProfile.GetUserProfile(userProfile);
                        if (userProfiles != null)
                        {
                            userName = userProfiles.First().UserName;

                            var SubscriptionEmailHtmlCode = System.IO.File.ReadAllText(string.Format("{0}", HttpContext.Current.Server.MapPath(string.Format("{0}{1}", ConfigurationManager.AppSettings["EmailTemplatePath"], ConfigurationManager.AppSettings["SubscriptionAddEmailTemplateForUser"]))));

                            var mainTemplateHtmlCode = System.IO.File.ReadAllText(string.Format("{0}", HttpContext.Current.Server.MapPath(string.Format("{0}{1}", ConfigurationManager.AppSettings["EmailTemplatePath"], ConfigurationManager.AppSettings["MainEmailTemplate"]))));
                            mainTemplateHtmlCode = mainTemplateHtmlCode.Replace("[SITEURL]", ConfigurationManager.AppSettings["SiteUrl"]);
                            mainTemplateHtmlCode = mainTemplateHtmlCode.Replace("[SITENAME]", ConfigurationManager.AppSettings["SiteName"]);
                            mainTemplateHtmlCode = mainTemplateHtmlCode.Replace("[PAGECONTENT]", SubscriptionEmailHtmlCode);

                            string subject          = "Subscription | Demystify Fema";
                            string body             = mainTemplateHtmlCode;
                            string displayName      = ConfigurationManager.AppSettings["SiteName"];
                            string emailTo          = userName;
                            bool   isMailSentToUser = Utility.SendMail(emailTo, string.Empty, string.Empty, subject, body, displayName, string.Empty, true);

                            SubscriptionEmailHtmlCode = string.Empty;
                            SubscriptionEmailHtmlCode = System.IO.File.ReadAllText(string.Format("{0}", HttpContext.Current.Server.MapPath(string.Format("{0}{1}", ConfigurationManager.AppSettings["EmailTemplatePath"], ConfigurationManager.AppSettings["SubscriptionAddEmailTemplateForAdmin"]))));
                            SubscriptionEmailHtmlCode = SubscriptionEmailHtmlCode.Replace("[USERNAME]", userName);

                            mainTemplateHtmlCode = string.Empty;
                            mainTemplateHtmlCode = System.IO.File.ReadAllText(string.Format("{0}", HttpContext.Current.Server.MapPath(string.Format("{0}{1}", ConfigurationManager.AppSettings["EmailTemplatePath"], ConfigurationManager.AppSettings["MainEmailTemplate"]))));
                            mainTemplateHtmlCode = mainTemplateHtmlCode.Replace("[SITEURL]", ConfigurationManager.AppSettings["SiteUrl"]);
                            mainTemplateHtmlCode = mainTemplateHtmlCode.Replace("[SITENAME]", ConfigurationManager.AppSettings["SiteName"]);
                            mainTemplateHtmlCode = mainTemplateHtmlCode.Replace("[PAGECONTENT]", SubscriptionEmailHtmlCode);

                            subject     = "Subscription | Demystify Fema";
                            body        = mainTemplateHtmlCode;
                            displayName = ConfigurationManager.AppSettings["SiteName"];
                            bool isMailSentToAdmin = Utility.SendMail(ConfigurationManager.AppSettings["AdminEmailId"], string.Empty, string.Empty, subject, body, displayName, string.Empty, true);
                            try
                            {
                                var objSubscription = new Subscription()
                                {
                                    SubscriptionId    = result,
                                    IsMailSentToUser  = isMailSentToUser,
                                    IsMailSentToAdmin = isMailSentToAdmin,
                                    ModifiedBy        = Utility.UserId
                                };
                                iSubscription.UpdateSubscriptionMailSent(objSubscription);
                            }
                            catch (Exception ex)
                            {
                                Utility.WriteLog("AddSubscription", addSubscriptionRequest, "Error while updating Subscription mail sent. (SubscriptionUserController)", ex.ToString());
                            }
                        }

                        responses.Status      = Utility.SUCCESS_STATUS_RESPONSE;
                        responses.Description = "Subscription added successfully.";
                    }
                    else
                    {
                        responses.Status      = Utility.ERROR_STATUS_RESPONSE;
                        responses.Description = "Error while updating Subscription.";
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                responses.Status      = Utility.ERROR_STATUS_RESPONSE;
                responses.Description = "Error while adding Subscription.";

                Utility.WriteLog("AddSubscription", addSubscriptionRequest, "Error while adding Subscription. (SubscriptionUserController)", ex.ToString());
            }
            return(Ok(responses));
        }
        public async Task <ApiResponse <AddSubscriptionResponse> > AdddSubscriptionAsync(AddSubscriptionRequest request)
        {
            var addResponse = new ApiResponse <AddSubscriptionResponse>(new AddSubscriptionResponse());

            _httpClient.DefaultRequestHeaders.Clear();

            _httpClient.DefaultRequestHeaders.Add(ConstantString.AuthorizationKey, string.Format(ConstantString.AuthorizationValue, request.AccessToken));

            var subsBody          = JsonConvert.SerializeObject(request.AddingSubscription);
            var addingSubsContent = new StringContent(subsBody);

            addingSubsContent.Headers.ContentType = new MediaTypeHeaderValue(ConstantString.JsonContentTypeValue);

            var subsRequest = await _httpClient.PostAsync(ConstantString.SubscriptionSuffix, addingSubsContent).ConfigureAwait(false);

            var content = await subsRequest.Content.ReadAsStringAsync().ConfigureAwait(false);

            addResponse.StatusCode = subsRequest.StatusCode;
            addResponse.Headers    = subsRequest.Headers.ToDictionary(x => x.Key, x => x.Value.ToString());
            addResponse.Body       = JsonConvert.DeserializeObject <AddSubscriptionResponse>(content);

            return(addResponse);
        }