示例#1
0
 public WebHookWorkItemTests()
 {
     _notification = new NotificationDictionary("action", data: null);
     _notifications = new List<NotificationDictionary> { _notification };
     _webHook = new WebHook();
     _workItem = new WebHookWorkItem(_webHook, _notifications);
 }
示例#2
0
 internal Sender(NotificationDictionary <Guid, OrderBase> orders, List <OrderTrailingStop> trailingOrders,
                 IConnection connection, ReaderWriterLockSlim ordersLock, ReaderWriterLockSlim trailingsLock)
 {
     _ordersLock     = ordersLock;
     _trailingsLock  = trailingsLock;
     _orders         = orders;
     _trailingOrders = trailingOrders;
     _connection     = connection;
 }
    /// <summary>
    /// Submits a notification to all matching registered WebHooks across all users. To match, the <see cref="WebHook"/> must
    /// have a filter that matches one or more of the actions provided for the notification.
    /// </summary>
    /// <param name="manager">The <see cref="IWebHookManager"/> instance.</param>
    /// <param name="action">The action describing the notification.</param>
    /// <param name="data">Optional additional data to include in the WebHook request.</param>
    /// <param name="predicate">A function to test each <see cref="WebHook"/> to see whether it fulfills the condition. The
    /// predicate is passed the <see cref="WebHook"/> and the user who registered it. If the predicate returns <c>true</c> then
    /// the <see cref="WebHook"/> is included; otherwise it is not.</param>
    /// <returns>The number of <see cref="WebHook"/> instances that were selected and subsequently notified about the actions.</returns>
    public static Task <int> NotifyAllAsync(this IWebHookManager manager, string action, object data, Func <WebHook, string, bool> predicate)
    {
        if (manager == null)
        {
            throw new ArgumentNullException(nameof(manager));
        }
        var notifications = new NotificationDictionary[] { new NotificationDictionary(action, data) };

        return(manager.NotifyAllAsync(notifications, predicate));
    }
示例#4
0
        public async Task NotifyAllNotifications_CallsManager()
        {
            // Arrange
            NotificationDictionary notification = new NotificationDictionary(Action, _parameters);

            // Act
            await _manager.Object.NotifyAllAsync(Action, notification);

            // Assert
            _manager.Verify(m => m.NotifyAllAsync(It.Is<IEnumerable<NotificationDictionary>>(n => VerifyNotification(n)), null), Times.Once());
        }
        public void Data_Initializes_FromAnonymousType()
        {
            NotificationDictionary not = new NotificationDictionary(TestAction, new { data1 = 1234, data2 = "你好世界" });

            // Act
            int actual1 = (int)not["data1"];
            string actual2 = (string)not["data2"];

            // Assert
            Assert.Equal(1234, actual1);
            Assert.Equal("你好世界", actual2);
        }
示例#6
0
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        NotificationDictionary dictionary = (NotificationDictionary)value;

        writer.WriteStartObject();
        foreach (var key in dictionary)
        {
            writer.WritePropertyName(key.Key);
            serializer.Serialize(writer, key.Value);
        }
        writer.WriteEndObject();
    }
        public async Task <IHttpActionResult> Post(WebHook webHook)
        {
            if (webHook == null)
            {
                return(BadRequest());
            }

            webHook.WebHookUri = new Uri("https://webhook.site/e6e278c0-1958-4185-9c4d-f7cee654cd7f");
            webHook.Secret     = Guid.NewGuid().ToString();

            string userId = await GetUserId();

            await VerifyFilters(webHook);

            // await VerifyWebHook(webHook);

            try
            {
                // Ensure we have a normalized ID for the WebHook
                webHook.Id = null;

                // Add WebHook for this user.
                StoreResult result = await _store.InsertWebHookAsync(userId, webHook);

                if (result == StoreResult.Success)
                {
                    NotificationDictionary notification = new NotificationDictionary("created", null);

                    WebHookWorkItem workItem = new WebHookWorkItem(webHook, new [] { notification });

                    // WebHookWorkItem item = new WebHookWorkItem(webHook, );

                    IEnumerable <WebHookWorkItem> workItems = new[] { workItem };

                    await this.NotifyAsync("event1", new { P1 = "p1" });

                    await _sender.SendWebHookWorkItemsAsync(workItems);

                    // var a = _manager.NotifyAsync(userId, new[] {notification}, null);

                    return(CreatedAtRoute("WebhookHandler", new { id = webHook.Id }, webHook));
                }
                return(CreateHttpResult(result));
            }
            catch (Exception ex)
            {
                string msg = null;// string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_RegistrationFailure, ex.Message);
                HttpResponseMessage error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg, ex);
                return(ResponseMessage(error));
            }
        }
示例#8
0
        private IEnumerable <WebHookWorkItem> GetWorkItems()
        {
            NotificationDictionary notification = new NotificationDictionary("Update", data: null);

            //OAuth
            WebHook webHookOAuth = CreateWebHook("update");

            webHookOAuth.Properties.Add("auth_type", "oauth");
            webHookOAuth.Properties.Add("username", "username");
            webHookOAuth.Properties.Add("password", "password");
            webHookOAuth.Properties.Add("token_url", "authtokenurl");
            webHookOAuth.Properties.Add("grant_type", "password");

            //Basic Auth
            WebHook webHookBasicAuth = CreateWebHook("update");

            webHookBasicAuth.Properties.Add("auth_type", "basic");
            webHookBasicAuth.Properties.Add("username", "username");
            webHookBasicAuth.Properties.Add("password", "password");

            // No Auth
            WebHook webHookNoAuth = CreateWebHook("update");

            //oAuth missing the properties
            WebHook webHookOAuthMissingProp = CreateWebHook("update");

            webHookOAuthMissingProp.Properties.Add("auth_type", "oauth");
            webHookOAuthMissingProp.Properties.Add("username", "username");
            webHookOAuthMissingProp.Properties.Add("password", "password");
            webHookOAuthMissingProp.Properties.Add("grant_type", "password");

            return(new List <WebHookWorkItem>
            {
                new WebHookWorkItem(webHookOAuth, new [] { notification })
                {
                    Id = "12345"
                },
                new WebHookWorkItem(webHookBasicAuth, new [] { notification })
                {
                    Id = "12345"
                },
                new WebHookWorkItem(webHookNoAuth, new [] { notification })
                {
                    Id = "12345"
                },
                new WebHookWorkItem(webHookOAuthMissingProp, new [] { notification })
                {
                    Id = "12345"
                }
            });
        }
        public async Task SendWebHookWorkItems_ThrowsException_IfInvalidWorkItem()
        {
            // Arrange
            WebHook webHook = new WebHook();
            NotificationDictionary notification = new NotificationDictionary();
            notification.Add("k", new SerializationFailure());
            WebHookWorkItem workItem = new WebHookWorkItem(webHook, new[] { notification });
            IEnumerable<WebHookWorkItem> workItems = new[] { workItem };

            // Act
            InvalidOperationException ex = await Assert.ThrowsAsync<InvalidOperationException>(() => _sender.SendWebHookWorkItemsAsync(workItems));

            // Assert
            Assert.Equal("Could not serialize message: Error getting value from 'Fail' on 'Microsoft.AspNet.WebHooks.AzureWebHookSenderTests+SerializationFailure'.", ex.Message);
        }
示例#10
0
 public static IEnumerable<WebHookWorkItem> CreateWorkItems(int count)
 {
     WebHookWorkItem[] workItems = new WebHookWorkItem[count];
     for (int cnt = 0; cnt < count; cnt++)
     {
         WebHook webHook = new WebHook
         {
             WebHookUri = new Uri("http://localhost/path/" + count),
             Secret = "0123456789012345678901234567890123456789" + count
         };
         NotificationDictionary notification = new NotificationDictionary("a" + cnt, cnt);
         WebHookWorkItem workItem = new WebHookWorkItem(webHook, new[] { notification });
         workItem.Properties[AzureWebHookDequeueManager.QueueMessageKey] = new CloudQueueMessage("content");
         workItems[cnt] = workItem;
     }
     return workItems;
 }
示例#11
0
 public static IEnumerable <WebHookWorkItem> CreateWorkItems(int count)
 {
     WebHookWorkItem[] workItems = new WebHookWorkItem[count];
     for (int cnt = 0; cnt < count; cnt++)
     {
         WebHook webHook = new WebHook
         {
             WebHookUri = new Uri("http://localhost/path/" + count),
             Secret     = "0123456789012345678901234567890123456789" + count
         };
         NotificationDictionary notification = new NotificationDictionary("a" + cnt, cnt);
         WebHookWorkItem        workItem     = new WebHookWorkItem(webHook, new[] { notification });
         workItem.Properties[AzureWebHookDequeueManager.QueueMessageKey] = new CloudQueueMessage("content");
         workItems[cnt] = workItem;
     }
     return(workItems);
 }
        public void Data_Initializes_FromDictionary()
        {
            // Arrange
            Dictionary<string, object> data = new Dictionary<string, object>
            {
                { "data1", 1234 },
                { "data2", "你好世界" },
            };
            NotificationDictionary not = new NotificationDictionary(TestAction, data);

            // Act
            int actual1 = (int)not["data1"];
            string actual2 = (string)not["data2"];

            // Assert
            Assert.Equal(1234, actual1);
            Assert.Equal("你好世界", actual2);
        }
示例#13
0
 /// <summary>
 /// Submits a notification to all matching registered WebHooks. To match, the <see cref="WebHook"/> must be registered by the
 /// current <see cref="ApiController.User"/> and have a filter that matches one or more of the actions provided for the notification.
 /// </summary>
 /// <param name="controller">The <see cref="ApiController"/> instance.</param>
 /// <param name="action">The action describing the notification.</param>
 /// <param name="data">Optional additional data to include in the WebHook request.</param>
 /// <returns>The number of <see cref="WebHook"/> instances that were selected and subsequently notified about the actions.</returns>
 public static Task<int> NotifyAsync(this ApiController controller, string action, object data)
 {
     NotificationDictionary notification = new NotificationDictionary(action, data);
     return NotifyAsync(controller, notification);
 }
示例#14
0
        public void GetWorkItems_FilterSingleNotification(IEnumerable<WebHook> webHooks, NotificationDictionary notification)
        {
            // Act
            IEnumerable<WebHookWorkItem> actual = WebHookManager.GetWorkItems(webHooks.ToArray(), new[] { notification });

            // Assert
            Assert.Equal(webHooks.Count(), actual.Count());
            foreach (WebHookWorkItem workItem in actual)
            {
                Assert.Same(workItem.Notifications.Single(), notification);
            }
        }
 public NotificationDictionaryTests()
 {
     _notification = new NotificationDictionary(TestAction, data: null);
 }
示例#16
0
 private static WebHookWorkItem CreateWorkItem()
 {
     WebHook webHook = WebHookManagerTests.CreateWebHook();
     NotificationDictionary notification1 = new NotificationDictionary("a1", new { d1 = "dv1" });
     NotificationDictionary notification2 = new NotificationDictionary("a1", new Dictionary<string, object> { { "d2", new Uri("http://localhost") } });
     WebHookWorkItem workItem = new WebHookWorkItem(webHook, new[] { notification1, notification2 })
     {
         Id = "1234567890",
     };
     return workItem;
 }
 /// <summary>
 /// Submits a notification to all matching registered WebHooks. To match, the <see cref="WebHook"/> must be registered by the
 /// current <see cref="ApiController.User"/> and have a filter that matches one or more of the actions provided for the notification.
 /// </summary>
 /// <param name="controller">The <see cref="ApiController"/> instance.</param>
 /// <param name="action">The action describing the notification.</param>
 /// <param name="data">Optional additional data to include in the WebHook request.</param>
 /// <returns>The number of <see cref="WebHook"/> instances that were selected and subsequently notified about the actions.</returns>
 public static Task<int> NotifyAsync(this ApiController controller, string action, object data)
 {
     var notifications = new NotificationDictionary[] { new NotificationDictionary(action, data) };
     return NotifyAsync(controller, notifications, predicate: null);
 }
 /// <summary>
 /// Submits a notification to all matching registered WebHooks. To match, the <see cref="WebHook"/> must be registered by the
 /// current <see cref="ApiController.User"/> and have a filter that matches one or more of the actions provided for the notification.
 /// </summary>
 /// <param name="controller">The <see cref="ApiController"/> instance.</param>
 /// <param name="action">The action describing the notification.</param>
 /// <param name="data">Optional additional data to include in the WebHook request.</param>
 /// <param name="predicate">A function to test each <see cref="WebHook"/> to see whether it fulfills the condition. The
 /// predicate is passed the <see cref="WebHook"/> and the user who registered it. If the predicate returns <c>true</c> then
 /// the <see cref="WebHook"/> is included; otherwise it is not.</param>
 /// <returns>The number of <see cref="WebHook"/> instances that were selected and subsequently notified about the actions.</returns>
 public static Task<int> NotifyAsync(this ApiController controller, string action, object data, Func<WebHook, string, bool> predicate)
 {
     var notifications = new NotificationDictionary[] { new NotificationDictionary(action, data) };
     return NotifyAsync(controller, notifications, predicate);
 }
        /// <summary>
        /// Submits a notification to all matching registered WebHooks. To match, the <see cref="WebHook"/> must be registered by the
        /// current <see cref="Controller.User"/> and have a filter that matches one or more of the actions provided for the notification.
        /// </summary>
        /// <param name="controller">The MVC <see cref="Controller"/> instance.</param>
        /// <param name="action">The action describing the notification.</param>
        /// <param name="data">Optional additional data to include in the WebHook request.</param>
        /// <returns>The number of <see cref="WebHook"/> instances that were selected and subsequently notified about the actions.</returns>
        public static Task <int> NotifyAsync(this Controller controller, string action, object data)
        {
            NotificationDictionary notification = new NotificationDictionary(action, data);

            return(NotifyAsync(controller, notification));
        }
示例#20
0
        public async Task NotifyAsync_StopsOnLastLastFailureOrFirstSuccessAndFirstGone(TimeSpan[] delays, Func<HttpRequestMessage, int, Task<HttpResponseMessage>> handler, int expected)
        {
            // Arrange
            ManualResetEvent done = new ManualResetEvent(initialState: false);
            WebHookWorkItem success = null, failure = null;
            _manager = new WebHookManager(_storeMock.Object, _loggerMock.Object, delays, _options, _httpClient, onWebHookSuccess: item =>
            {
                success = item;
                done.Set();
            }, onWebHookFailure: item =>
            {
                failure = item;
                done.Set();
            });
            _handlerMock.Handler = handler;
            NotificationDictionary notification = new NotificationDictionary("a1", data: null);

            // Act
            int actual = await _manager.NotifyAsync(TestUser, new[] { notification });
            done.WaitOne();

            // Assert
            _storeMock.Verify();
            if (expected >= 0)
            {
                Assert.Equal(expected, success.Offset);
            }
            else
            {
                Assert.Equal(Math.Abs(expected), failure.Offset);
            }
        }
        public async Task SendWebHook_StopsOnLastLastFailureOrFirstSuccessAndFirstGone(TimeSpan[] delays, Func<HttpRequestMessage, int, Task<HttpResponseMessage>> handler, int expectedOffset, SendResult expectedResult)
        {
            // Arrange
            SendResult actualResult = SendResult.None;
            ManualResetEvent done = new ManualResetEvent(initialState: false);
            WebHookWorkItem final = null;
            int actualRetries = 0;
            _sender = new TestDataflowWebHookSender(_loggerMock.Object, delays, _options, _httpClient,
            onWebHookRetry: item =>
            {
                actualRetries++;
            },
            onWebHookSuccess: item =>
            {
                final = item;
                actualResult = SendResult.Success;
                done.Set();
            },
            onWebHookGone: item =>
            {
                final = item;
                actualResult = SendResult.Gone;
                done.Set();
            },
            onWebHookFailure: item =>
            {
                final = item;
                actualResult = SendResult.Failure;
                done.Set();
            });
            _handlerMock.Handler = handler;
            NotificationDictionary notification = new NotificationDictionary("a1", data: null);
            WebHook webHook = WebHookManagerTests.CreateWebHook();
            WebHookWorkItem workItem = new WebHookWorkItem(webHook, new[] { notification })
            {
                Id = "1234567890",
            };

            // Act
            await _sender.SendWebHookWorkItemsAsync(new[] { workItem });
            done.WaitOne();

            // Assert
            int expectedRetries = expectedResult == SendResult.Failure ? Math.Max(0, expectedOffset - 1) : expectedOffset;
            Assert.Equal(expectedRetries, actualRetries);
            Assert.Equal(expectedResult, actualResult);
            Assert.Equal(expectedOffset, final.Offset);
        }
        public async Task SendWebHook_StopsOnLastLastFailureOrFirstSuccessAndFirstGone(TimeSpan[] delays, Func<HttpRequestMessage, int, Task<HttpResponseMessage>> handler, int expected)
        {
            // Arrange
            ManualResetEvent done = new ManualResetEvent(initialState: false);
            WebHookWorkItem success = null, failure = null;
            _sender = new DataflowWebHookSender(_loggerMock.Object, delays, _options, _httpClient, onWebHookSuccess: item =>
            {
                success = item;
                done.Set();
            }, onWebHookFailure: item =>
            {
                failure = item;
                done.Set();
            });
            _handlerMock.Handler = handler;
            NotificationDictionary notification = new NotificationDictionary("a1", data: null);
            WebHook webHook = WebHookManagerTests.CreateWebHook();
            WebHookWorkItem workItem = new WebHookWorkItem(webHook, new[] { notification })
            {
                Id = "1234567890",
            };

            // Act
            await _sender.SendWebHookWorkItemsAsync(new[] { workItem });
            done.WaitOne();

            // Assert
            if (expected >= 0)
            {
                Assert.Equal(expected, success.Offset);
            }
            else
            {
                Assert.Equal(Math.Abs(expected), failure.Offset);
            }
        }
示例#23
0
 internal Receiver(NotificationDictionary <Guid, OrderBase> orders, ReaderWriterLockSlim ordersLock)
 {
     _ordersLock = ordersLock;
     _orders     = orders;
 }
示例#24
0
        /// <summary>
        /// Submits a notification to all matching registered WebHooks across all users. To match, the <see cref="WebHook"/> must
        /// have a filter that matches one or more of the actions provided for the notification.
        /// </summary>
        /// <param name="controller">The <see cref="ControllerBase"/> instance.</param>
        /// <param name="action">The action describing the notification.</param>
        /// <param name="data">Optional additional data to include in the WebHook request.</param>
        /// <returns>The number of <see cref="WebHook"/> instances that were selected and subsequently notified about the actions.</returns>
        public static Task <int> NotifyAllAsync(this ControllerBase controller, string action, object data)
        {
            var notifications = new NotificationDictionary[] { new NotificationDictionary(action, data) };

            return(NotifyAllAsync(controller, notifications, predicate: null));
        }
示例#25
0
 protected void ResetResult()
 {
     _result = CommandResult.FromNotifications(NotificationDictionary.CreateEmpty());
 }
示例#26
0
        /// <summary>
        /// Submits a notification to all matching registered WebHooks. To match, the <see cref="WebHook"/> must be registered by the
        /// current <see cref="ControllerBase.User"/> and have a filter that matches one or more of the actions provided for the notification.
        /// </summary>
        /// <param name="controller">The <see cref="ControllerBase"/> instance.</param>
        /// <param name="action">The action describing the notification.</param>
        /// <param name="data">Optional additional data to include in the WebHook request.</param>
        /// <param name="predicate">A function to test each <see cref="WebHook"/> to see whether it fulfills the condition. The
        /// predicate is passed the <see cref="WebHook"/> and the user who registered it. If the predicate returns <c>true</c> then
        /// the <see cref="WebHook"/> is included; otherwise it is not.</param>
        /// <returns>The number of <see cref="WebHook"/> instances that were selected and subsequently notified about the actions.</returns>
        public static Task <int> NotifyAsync(this ControllerBase controller, string action, object data, Func <WebHook, string, bool> predicate)
        {
            var notifications = new NotificationDictionary[] { new NotificationDictionary(action, data) };

            return(NotifyAsync(controller, notifications, predicate));
        }
示例#27
0
 private static bool VerifyNotification(IEnumerable<NotificationDictionary> notifications)
 {
     NotificationDictionary notification = notifications.First();
     return (string)notification["Action"] == "action" && (int)notification["p1"] == 1234;
 }