public void should_not_get_service_if_type_not_exist() { var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); Assert.Null(resolver.GetService(typeof(NotExistedType))); }
public void GarbageCollectingTopicsAfterGettingTopicsNoops() { var dr = new DefaultDependencyResolver(); var configuration = dr.Resolve <IConfigurationManager>(); configuration.KeepAlive = null; using (var bus = new MessageBus(dr)) { var subscriber = new TestSubscriber(new[] { "key" }); IDisposable subscription = null; bus.AfterTopicMarkedSuccessfully = (key, topic) => { bus.GarbageCollectTopics(); }; try { subscription = bus.Subscribe(subscriber, null, (result, state) => TaskAsyncHelper.True, 10, null); Assert.Equal(1, bus.Topics.Count); Topic topic; Assert.True(bus.Topics.TryGetValue("key", out topic)); Assert.Equal(TopicState.HasSubscriptions, topic.State); } finally { if (subscription != null) { subscription.Dispose(); } } } }
public void EnsureHubThrowsWhenCantResolve() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); Assert.Throws<InvalidOperationException>(() => hubManager.EnsureHub("__ELLO__")); }
public void GetTopicDoesNotChangeStateWhenNotDying() { var dr = new DefaultDependencyResolver(); var configuration = dr.Resolve <IConfigurationManager>(); configuration.DisconnectTimeout = TimeSpan.FromSeconds(6); configuration.KeepAlive = null; using (var bus = new MessageBus(dr)) { bus.Subscribe(new TestSubscriber(new[] { "key" }), null, (result, state) => TaskAsyncHelper.True, 10, null); Topic topic; Assert.True(bus.Topics.TryGetValue("key", out topic)); Assert.Equal(TopicState.HasSubscriptions, topic.State); topic = bus.GetTopic("key"); Assert.Equal(TopicState.HasSubscriptions, topic.State); topic.RemoveSubscription(topic.Subscriptions.First()); Assert.Equal(TopicState.NoSubscriptions, topic.State); topic = bus.GetTopic("key"); Assert.Equal(TopicState.NoSubscriptions, topic.State); topic.State = TopicState.Dying; topic = bus.GetTopic("key"); Assert.Equal(TopicState.NoSubscriptions, topic.State); } }
protected override IObjectStorage GetStorage() { var resolver = new DefaultDependencyResolver(); resolver.Register <IJsonSerializer, DefaultJsonSerializer>(); return(new FolderObjectStorage(resolver, "temp")); }
public void SubscriptionWithCancelledTaskCanBeDisposed() { var dr = new DefaultDependencyResolver(); using (var bus = new MessageBus(dr)) { var subscriber = new TestSubscriber(new[] { "key" }); var wh = new ManualResetEventSlim(); IDisposable subscription = bus.Subscribe(subscriber, null, async(result, state) => { if (result.Terminal) { return(false); } await Task.Delay(50); var tcs = new TaskCompletionSource <bool>(); tcs.SetCanceled(); wh.Set(); return(await tcs.Task); }, 10, null); bus.Publish("me", "key", "hello"); wh.Wait(); subscription.Dispose(); } }
public StressRunBase(RunData runData) { RunData = runData; Resolver = new DefaultDependencyResolver(); CancellationTokenSource = new CancellationTokenSource(); _countDown = new CountdownEvent(runData.Senders); }
public void SubscriptionWithCancelledTaskCanBeDisposed() { var dr = new DefaultDependencyResolver(); using (var bus = new MessageBus(dr)) { var subscriber = new TestSubscriber(new[] { "key" }); var wh = new ManualResetEventSlim(); IDisposable subscription = bus.Subscribe(subscriber, null, async (result, state) => { if (result.Terminal) { return false; } await Task.Delay(50); var tcs = new TaskCompletionSource<bool>(); tcs.SetCanceled(); wh.Set(); return await tcs.Task; }, 10, null); bus.Publish("me", "key", "hello"); wh.Wait(); subscription.Dispose(); } }
public void UncleanDisconnectFiresOnDisconnected() { // Arrange var req = new Mock <IRequest>(); req.Setup(m => m.Url).Returns(new Uri("http://foo")); req.Setup(m => m.LocalPath).Returns(""); var qs = new NameValueCollection(); qs["connectionToken"] = "1"; req.Setup(m => m.QueryString).Returns(new NameValueCollectionWrapper(qs)); var res = new Mock <IResponse>(); res.SetupProperty(m => m.StatusCode); var dr = new DefaultDependencyResolver(); var context = new HostContext(req.Object, res.Object); var transport = new Mock <ITransport>(); transport.SetupProperty(m => m.Disconnected); transport.SetupProperty(m => m.ConnectionId); transport.Setup(m => m.GetGroupsToken()).Returns(TaskAsyncHelper.FromResult(string.Empty)); transport.Setup(m => m.ProcessRequest(It.IsAny <Connection>())).Returns(TaskAsyncHelper.Empty); var transportManager = new Mock <ITransportManager>(); transportManager.Setup(m => m.GetTransport(context)).Returns(transport.Object); var protectedData = new Mock <IProtectedData>(); protectedData.Setup(m => m.Unprotect(It.IsAny <string>(), It.IsAny <string>())) .Returns <string, string>((value, purpose) => value); dr.Register(typeof(ITransportManager), () => transportManager.Object); dr.Register(typeof(IProtectedData), () => protectedData.Object); var connection = new Mock <PersistentConnection>() { CallBase = true }; var onDisconnectedCalled = false; connection.Protected().Setup("OnDisconnected", req.Object, "1", false).Callback(() => { onDisconnectedCalled = true; }); connection.Object.Initialize(dr); // Act connection.Object.ProcessRequest(context).Wait(); transport.Object.Disconnected(/* clean: */ false); // Assert Assert.True(onDisconnectedCalled); }
private DefaultDependencyResolver GetDependencyResolver() { var dr = new DefaultDependencyResolver(); var traceManager = new TraceManager(); dr.Register(typeof(ITraceManager), () => traceManager); return(dr); }
protected override IObjectStorage GetStorage() { var resolver = new DefaultDependencyResolver(); resolver.Register <IJsonSerializer, DefaultJsonSerializer>(); resolver.Register <IStorageSerializer, DefaultJsonSerializer>(); return(new IsolatedStorageObjectStorage(resolver)); }
public void GetInValidHub() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var hubDescriptor = hubManager.GetHub("__ELLO__"); Assert.Null(hubDescriptor); }
public void ResolveInvalidHub() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var hubDescriptor = hubManager.ResolveHub("____CoreTestHub____"); Assert.Null(hubDescriptor); }
static SignalRGlobalHost() { Resolver = new DefaultDependencyResolver(); RegisterHub <ClientNotificationServiceHub>(); var hubDescriptorProvider = new SignalRHubDescriptorProvider(Hubs); Resolver.Register(typeof(IHubDescriptorProvider), () => hubDescriptorProvider); }
public IsolatedStorageFileExceptionlessLogTests() { var resolver = new DefaultDependencyResolver(); resolver.Register <IExceptionlessLog, NullExceptionlessLog>(); resolver.Register <IJsonSerializer, DefaultJsonSerializer>(); _storage = new IsolatedStorageObjectStorage(resolver); }
public HubHelper(TypeScriptGeneratorOptions options) { typeHelper = new TypeHelper(options); var defaultDependencyResolver = new DefaultDependencyResolver(); hubmanager = new DefaultHubManager(defaultDependencyResolver); }
public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); // Configure Swagger help page config.EnableSwagger(c => { c.SingleApiVersion("v1", "My API").License(lc => lc.Name("My Company").Url("https://github.com/richardne97/")); c.IncludeXmlComments($"{AppContext.BaseDirectory}{Assembly.GetExecutingAssembly().GetName().Name}.xml"); c.DescribeAllEnumsAsStrings(); c.ApiKey("Authorization").Description("OAuth2 JWT for accessing secure APIs").Name("Authorization").In("header"); }) .EnableSwaggerUi(u => { u.DocumentTitle("My API"); u.EnableApiKeySupport("Authorization", "header"); }); //Enable JWT Authentication config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); //Validating model format while receving request. config.Filters.Add(new Filter.ModelValidatorFilter()); //Enable Attribute Route config.MapHttpAttributeRoutes(); //Injection settings var services = new ServiceCollection(); //Injection setting for controllers. services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes() .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition) .Where(t => typeof(IController).IsAssignableFrom(t) || typeof(IHttpController).IsAssignableFrom(t))); object injectObject = Guid.NewGuid(); services.AddSingleton(typeof(object), injectObject); var resolver = new DefaultDependencyResolver(services.BuildServiceProvider()); //For MVC DependencyResolver.SetResolver(resolver); //For Web API config.DependencyResolver = resolver; //For Web API //Auth Setting app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { AccessTokenFormat = new JwtFormat(JwtTokenParameters.Issuer, JwtTokenParameters.Audience, JwtTokenParameters.SecurityKey) }); //Enable Web Api app.UseWebApi(config); }
public void DisposablesAreTrackedAndDisposed() { var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(MyDisposable), () => new MyDisposable()); var disposable = resolver.Resolve<MyDisposable>(); resolver.Dispose(); Assert.True(disposable.Disposed); }
public void GetHubMethodFromInvalidHub() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); // There is no ________________CoreTestHubWithMethod________________ name var methodDescriptor = hubManager.GetHubMethod("________________CoreTestHubWithMethod________________", "AddNumbers", null, null); Assert.Null(methodDescriptor); }
public void GetInvalidHubMethod() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); // The AddNumbers method has 2 parameters, so should not find the method var methodDescriptor = hubManager.GetHubMethod("CoreTestHubWithMethod", "AddNumbers", null); Assert.Null(methodDescriptor); }
public void GetValidHub() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var hubDescriptor = hubManager.GetHub("CoreTestHub"); Assert.NotNull(hubDescriptor); Assert.False(hubDescriptor.NameSpecified); }
public void ShouldIgnoreCaseWhenDiscoveringHubsUsingManager() { var resolver = new DefaultDependencyResolver(); var manager = new DefaultHubManager(resolver); var hub = manager.GetHub("hubwithoutattribute"); Assert.NotNull(hub); Assert.Equal(hub.Name, "HubWithoutAttribute"); }
public void should_get_service_if_type_exist() { var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); Assert.Equal( typeof(ControllerWithoutAction), resolver.GetService(typeof(ControllerWithoutAction)).GetType()); }
public void ShouldNotResolveHubByFullTypeName() { var resolver = new DefaultDependencyResolver(); var hubResolver = new ReflectedHubDescriptorProvider(resolver); HubDescriptor hub; hubResolver.TryGetHub("SignalR.Tests.HubWithoutAttribute", out hub); Assert.Null(hub); }
public void ShouldNotResolveHubByTypeNameIfAttributeExists() { var resolver = new DefaultDependencyResolver(); var hubResolver = new ReflectedHubDescriptorProvider(resolver); HubDescriptor hub; hubResolver.TryGetHub("HubWithAttribute", out hub); Assert.Null(hub); }
public void ResolveHubsIsNotEmpty() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var hubDescriptor = hubManager.ResolveHubs(); Assert.NotNull(hubDescriptor); Assert.NotEmpty(hubDescriptor); }
public void GetValidHubMethodsWithPredicate() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var methodDescriptors = hubManager.GetHubMethods("CoreTestHubWithMethod", descriptor => descriptor.Name == "AddNumbers"); Assert.NotNull(methodDescriptors); Assert.Equal(methodDescriptors.First().Name, "AddNumbers"); }
public void GetValidHubsWithValidPredicate() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var hubDescriptors = hubManager.GetHubs(descriptor => descriptor.Name == "CoreTestHub"); Assert.NotNull(hubDescriptors); Assert.Equal(hubDescriptors.First().Name, "CoreTestHub"); }
public void SubscriptionWithExistingCursor() { var dr = new DefaultDependencyResolver(); using (var bus = new TestScaleoutBus(dr, topicCount: 2)) { var subscriber = new TestSubscriber(new[] { "key" }); var cd = new CountDownRange <int>(Enumerable.Range(2, 4)); IDisposable subscription = null; // test, test2 = 1 // test1, test3 = 0 // // Cursor 1, 1 bus.SendMany(new[] { new Message("test", "key", "1"), new Message("test", "key", "50") }); // Cursor 0,1|1,1 bus.SendMany(new[] { new Message("test1", "key", "51") }); bus.SendMany(new[] { new Message("test2", "key", "2"), new Message("test3", "key", "3"), new Message("test2", "key", "4"), }); try { subscription = bus.Subscribe(subscriber, "0,00000001|1,00000001", result => { foreach (var m in result.GetMessages()) { int n = Int32.Parse(m.Value); Assert.True(cd.Mark(n)); } return(TaskAsyncHelper.True); }, 10); bus.SendMany(new[] { new Message("test", "key", "5") }); Assert.True(cd.Wait(TimeSpan.FromSeconds(10))); } finally { if (subscription != null) { subscription.Dispose(); } } } }
public void GetHubMethodFromInvalidHub() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); // There is no ________________CoreTestHubWithMethod________________ name var methodDescriptor = hubManager.GetHubMethod("________________CoreTestHubWithMethod________________", "AddNumbers", new IJsonValue[] { null, null }); Assert.Null(methodDescriptor); }
public void SubscriptionDoesNotGetNewMessagesWhenTopicStoreOverrunByOtherStream() { var dr = new DefaultDependencyResolver(); dr.Resolve<IConfigurationManager>().DefaultMessageBufferSize = 10; using (var bus = new TestScaleoutBus(dr, streams: 2)) { var subscriber = new TestSubscriber(new[] { "key" }); IDisposable subscription = null; // The min fragment size is 8 and min fragments is 5 var expectedValues = Enumerable.Range(171, 8); var cd = new OrderedCountDownRange<int>(expectedValues); // This will overwrite the buffer ending up with (40 - 79) for stream 2 for (int i = 0; i < 80; i++) { bus.Publish(0, (ulong)i, new[] { new Message("test", "key", i.ToString()) }); } // This will overwrite the buffer with (140 - 179) for stream 1 for (int i = 100; i < 180; i++) { bus.Publish(1, (ulong)i, new[] { new Message("test", "key", i.ToString()) }); } try { subscription = bus.Subscribe(subscriber, "0,27|1,AA", (result, state) => { foreach (var m in result.GetMessages()) { int n = Int32.Parse(m.GetString()); cd.Expect(n); } return TaskAsyncHelper.True; }, 100, null); Assert.True(cd.Wait(TimeSpan.FromSeconds(10))); } finally { if (subscription != null) { subscription.Dispose(); } } } }
public void SubscriptionDoesNotGetNewMessagesWhenTopicStoreOverrunByOtherStream() { var dr = new DefaultDependencyResolver(); dr.Resolve <IConfigurationManager>().DefaultMessageBufferSize = 10; using (var bus = new TestScaleoutBus(dr, streams: 2)) { var subscriber = new TestSubscriber(new[] { "key" }); IDisposable subscription = null; // The min fragment size is 8 and min fragments is 5 var expectedValues = Enumerable.Range(171, 8); var cd = new OrderedCountDownRange <int>(expectedValues); // This will overwrite the buffer ending up with (40 - 79) for stream 2 for (int i = 0; i < 80; i++) { bus.Publish(0, (ulong)i, new[] { new Message("test", "key", i.ToString()) }); } // This will overwrite the buffer with (140 - 179) for stream 1 for (int i = 100; i < 180; i++) { bus.Publish(1, (ulong)i, new[] { new Message("test", "key", i.ToString()) }); } try { subscription = bus.Subscribe(subscriber, "s-0,27|1,AA", (result, state) => { foreach (var m in result.GetMessages()) { int n = Int32.Parse(m.GetString()); cd.Expect(n); } return(TaskAsyncHelper.True); }, 100, null); Assert.True(cd.Wait(TimeSpan.FromSeconds(10))); } finally { if (subscription != null) { subscription.Dispose(); } } } }
public void ShouldResolveHubByTypeName() { var resolver = new DefaultDependencyResolver(); var hubResolver = new ReflectedHubDescriptorProvider(resolver); HubDescriptor hub; hubResolver.TryGetHub("HubWithoutAttribute", out hub); Assert.NotNull(hub); Assert.Equal(hub.Name, "HubWithoutAttribute"); }
public void ShouldIgnoreCaseWhenDiscoveringHubs() { var resolver = new DefaultDependencyResolver(); var hubResolver = new ReflectedHubDescriptorProvider(resolver); HubDescriptor hub; hubResolver.TryGetHub("hubwithoutattribute", out hub); Assert.NotNull(hub); Assert.Equal(hub.Name, "HubWithoutAttribute"); }
public void Configuration(IServiceCollection services) { Startup.ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(true); DefaultDependencyResolver resolver = new DefaultDependencyResolver(_serviceProvider, _appEvents); DependencyResolver.SetResolver(resolver); }
public void CanRegisterAndResolveTypes() { var resolver = new DefaultDependencyResolver(); resolver.Register <IServiceA, ServiceA>(); var s1 = resolver.Resolve <IServiceA>(); var s2 = resolver.Resolve <IServiceA>(); Assert.Equal(s1, s2); }
public void Configuration(IAppBuilder app) { var services = new ServiceCollection(); ConfigureServices(services); var resolver = new DefaultDependencyResolver(services.BuildServiceProvider()); DependencyResolver.SetResolver(resolver); }
public void SubscriptionWithExistingCursor() { var dr = new DefaultDependencyResolver(); var bus = new TestScaleoutBus(dr, topicCount: 2); var subscriber = new TestSubscriber(new[] { "key" }); var cd = new CountDownRange<int>(Enumerable.Range(2, 4)); IDisposable subscription = null; // test, test2 = 1 // test1, test3 = 0 // // Cursor 1, 1 bus.SendMany(new[] { new Message("test", "key", "1"), new Message("test", "key", "50") }); // Cursor 0,1|1,1 bus.SendMany(new[] { new Message("test1", "key", "51") }); bus.SendMany(new[]{ new Message("test2", "key", "2"), new Message("test3", "key", "3"), new Message("test2", "key", "4"), }); try { subscription = bus.Subscribe(subscriber, "0,00000001|1,00000001", result => { foreach (var m in result.GetMessages()) { int n = Int32.Parse(m.Value); Assert.True(cd.Mark(n)); } return TaskAsyncHelper.True; }, 10); bus.SendMany(new[] { new Message("test", "key", "5") }); Assert.True(cd.Wait(TimeSpan.FromSeconds(10))); } finally { if (subscription != null) { subscription.Dispose(); } } }
public void GetValidHubMethodsWithInvalidPredicate() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var methodDescriptors = hubManager.GetHubMethods("CoreTestHubWithMethod", descriptor => descriptor.Name == "______AddNumbers______"); // Still have an ienumerable sequence Assert.NotNull(methodDescriptors); // But there's nothing in the ienumerable Assert.Empty(methodDescriptors); }
public void start() { var dependencies = new Dictionary<Type, ItemResolver>(); var resolver = new DefaultDependencyResolver(dependencies); DependencyContainer.resolver = () => resolver; typeof (DefaultFrontController).Assembly.GetTypes() .Where(x => x.has_attribute<RegisterAttribute>()) .each(type_to_register => dependencies.Add(type_to_register, new AutoWiringResolver(type_to_register, resolver, new GreediestConstructor()))); }
public void GetValidHubsWithInvalidPredicate() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var hubDescriptors = hubManager.GetHubs(descriptor => descriptor.Name == "CoreTestHub_INVALIDHUB_____"); // Still have an ienumerable sequence Assert.NotNull(hubDescriptors); // But there's nothing in the ienumerable Assert.Empty(hubDescriptors); }
public void ShouldResolveHubByHubNameAttribute() { var resolver = new DefaultDependencyResolver(); var hubResolver = new ReflectedHubDescriptorProvider(resolver); HubDescriptor hub; hubResolver.TryGetHub("NameFromAttribute", out hub); Assert.NotNull(hub); Assert.Equal(hub.Name, "NameFromAttribute"); Assert.Equal(hub.NameSpecified, true); }
public void Initialize(int keepAlive, int? connectionTimeout, int? disconnectTimeout, int? hearbeatInterval, bool enableAutoRejoiningGroups) { var dr = new DefaultDependencyResolver(); _host.Configure(app => { var configuration = dr.Resolve<IConfigurationManager>(); configuration.KeepAlive = keepAlive; if (connectionTimeout != null) { configuration.ConnectionTimeout = TimeSpan.FromSeconds(connectionTimeout.Value); } if (disconnectTimeout != null) { configuration.DisconnectTimeout = TimeSpan.FromSeconds(disconnectTimeout.Value); } if (hearbeatInterval != null) { configuration.HeartbeatInterval = TimeSpan.FromSeconds(hearbeatInterval.Value); } if (enableAutoRejoiningGroups) { dr.Resolve<IHubPipeline>().EnableAutoRejoiningGroups(); } app.MapHubs("/signalr", new HubConfiguration { Resolver = dr }); var config = new ConnectionConfiguration { Resolver = dr }; app.MapConnection<MyBadConnection>("/ErrorsAreFun", config); app.MapConnection<MyGroupEchoConnection>("/group-echo", config); app.MapConnection<MySendingConnection>("/multisend", config); app.MapConnection<MyReconnect>("/my-reconnect", config); app.MapConnection<MyGroupConnection>("/groups", config); app.MapConnection<MyRejoinGroupsConnection>("/rejoin-groups", config); app.MapConnection<FilteredConnection>("/filter", config); app.MapConnection<SyncErrorConnection>("/sync-error", config); app.MapConnection<FallbackToLongPollingConnection>("/fall-back", config); app.MapConnection<AddGroupOnConnectedConnection>("/add-group", config); }); }
public void GetValidHubsWithoutPredicate() { var resolver = new DefaultDependencyResolver(); var hubManager = new DefaultHubManager(resolver); var hubDescriptors = hubManager.GetHubs(predicate: null); Assert.NotNull(hubDescriptors); HubDescriptor coreTestHub = hubDescriptors.First(descriptor => descriptor.Name == "CoreTestHub"); Assert.NotNull(coreTestHub); }
internal static IDisposable ReceiveLoopRun(int connections, int senders, string payload) { var resolver = new DefaultDependencyResolver(); var connectionManager = new ConnectionManager(resolver); var subscriptions = new List<IDisposable>(); var senderCountDown = new CountdownEvent(senders); var connectionCountDown = new CountdownEvent(connections); var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; var context = connectionManager.GetConnectionContext<StressConnection>(); // Initialize performance counters for this run Utility.InitializePerformanceCounters(resolver, cancellationTokenSource.Token); for (int i = 0; i < connections; i++) { var transportConnection = (ITransportConnection)context.Connection; ThreadPool.QueueUserWorkItem(_ => { ReceiveLoop(connectionCountDown, transportConnection, messageId: null, cancellationToken: cancellationToken); }); } for (var i = 1; i <= senders; i++) { ThreadPool.QueueUserWorkItem(_ => { while (!cancellationTokenSource.IsCancellationRequested) { context.Connection.Broadcast(payload); } senderCountDown.Signal(); }); } return new DisposableAction(() => { cancellationTokenSource.Cancel(); // Wait for each loop connectionCountDown.Wait(TimeSpan.FromMilliseconds(500 * connections)); // Wait for all senders to stop senderCountDown.Wait(TimeSpan.FromMilliseconds(1000 * senders)); subscriptions.ForEach(s => s.Dispose()); }); }
public void NewSubscriptionGetsAllMessages() { var dr = new DefaultDependencyResolver(); using (var bus = new TestScaleoutBus(dr)) { var subscriber = new TestSubscriber(new[] { "key" }); var wh = new ManualResetEventSlim(initialState: false); IDisposable subscription = null; try { var firstMessages = new[] { new Message("test1", "key", "1"), new Message("test2", "key", "2") }; bus.Publish(0, 0, firstMessages); subscription = bus.Subscribe(subscriber, null, (result, state) => { if (!result.Terminal) { var ms = result.GetMessages().ToList(); Assert.Equal(2, ms.Count); Assert.Equal("key", ms[0].Key); Assert.Equal("x", ms[0].GetString()); Assert.Equal("key", ms[1].Key); Assert.Equal("y", ms[1].GetString()); wh.Set(); return TaskAsyncHelper.True; } return TaskAsyncHelper.False; }, 10, null); var messages = new[] { new Message("test1", "key", "x"), new Message("test1", "key", "y") }; bus.Publish(0, 1, messages); Assert.True(wh.Wait(TimeSpan.FromSeconds(10))); } finally { if (subscription != null) { subscription.Dispose(); } } } }
public void Initialize(int? keepAlive, int? connectionTimeout, int? disconnectTimeout, bool enableAutoRejoiningGroups) { var dr = new DefaultDependencyResolver(); _host.Configure(app => { var configuration = dr.Resolve<IConfigurationManager>(); if (connectionTimeout != null) { configuration.ConnectionTimeout = TimeSpan.FromSeconds(connectionTimeout.Value); } if (disconnectTimeout != null) { configuration.DisconnectTimeout = TimeSpan.FromSeconds(disconnectTimeout.Value); } if (!keepAlive.HasValue) { configuration.KeepAlive = null; } // Set only if the keep-alive was changed from the default value. else if (keepAlive.Value != -1) { configuration.KeepAlive = TimeSpan.FromSeconds(keepAlive.Value); } app.MapHubs("/signalr2/test", new HubConfiguration()); app.MapHubs("/signalr", new HubConfiguration { EnableDetailedErrors = true, Resolver = dr }); var config = new ConnectionConfiguration { Resolver = dr }; app.MapConnection<MyBadConnection>("/ErrorsAreFun", config); app.MapConnection<MyGroupEchoConnection>("/group-echo", config); app.MapConnection<MySendingConnection>("/multisend", config); app.MapConnection<MyReconnect>("/my-reconnect", config); app.MapConnection<MyGroupConnection>("/groups", config); app.MapConnection<MyRejoinGroupsConnection>("/rejoin-groups", config); app.MapConnection<FilteredConnection>("/filter", config); app.MapConnection<SyncErrorConnection>("/sync-error", config); app.MapConnection<FallbackToLongPollingConnection>("/fall-back", config); app.MapConnection<AddGroupOnConnectedConnection>("/add-group", config); app.MapConnection<UnusableProtectedConnection>("/protected", config); }); }
private SourcererConfigurator() { var assembliesInCallStack = new StackTrace().GetFrames() .Select(f => f.GetMethod()) .Select(m => m.DeclaringType.Assembly) .Distinct() .ToArray(); TypesProvider = new AssemblyScanningTypesProvider(assembliesInCallStack); FactStore = new MemoryFactStore(); Clock = new SystemClock(); DependencyResolver = new DefaultDependencyResolver(assembliesInCallStack); }
public void UntrackedDisposablesAreNotTracked() { var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(MyUntrackedDisposable), () => new MyUntrackedDisposable()); var untrackedDisposable = resolver.Resolve<MyUntrackedDisposable>(); var untrackedDisposableWeakRef = new WeakReference<MyUntrackedDisposable>(untrackedDisposable); untrackedDisposable = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(untrackedDisposableWeakRef.TryGetTarget(out untrackedDisposable)); }
public void SubscriptionWithExistingCursor() { var dr = new DefaultDependencyResolver(); using (var bus = new TestScaleoutBus(dr, streams: 2)) { var subscriber = new TestSubscriber(new[] { "key" }); var cd = new CountDownRange<int>(Enumerable.Range(2, 4)); IDisposable subscription = null; bus.Publish(0, 0, new[] { new Message("test", "key", "1"), new Message("test", "key", "50") }); bus.Publish(1, 0, new[] { new Message("test1", "key", "51") }); bus.Publish(1, 2, new[]{ new Message("test2", "key", "2"), new Message("test3", "key", "3"), new Message("test2", "key", "4"), }); try { subscription = bus.Subscribe(subscriber, "s-0,00000000|1,00000000", (result, state) => { foreach (var m in result.GetMessages()) { int n = Int32.Parse(m.GetString()); Assert.True(cd.Mark(n)); } return TaskAsyncHelper.True; }, 10, null); bus.Publish(0, 2, new[] { new Message("test", "key", "5") }); Assert.True(cd.Wait(TimeSpan.FromSeconds(10))); } finally { if (subscription != null) { subscription.Dispose(); } } } }
public static IDisposable Run(int connections, int senders, string payload, int messageBufferSize = 10) { var resolver = new DefaultDependencyResolver(); var bus = new MessageBus(resolver); var countDown = new CountdownEvent(senders); var subscriptions = new List<IDisposable>(); var cancellationTokenSource = new CancellationTokenSource(); // Initialize performance counters for this run Utility.InitializePerformanceCounters(resolver, cancellationTokenSource.Token); for (int i = 0; i < connections; i++) { string identity = i.ToString(); var subscriber = new Subscriber(identity, new[] { "a", "b", "c" }); IDisposable subscription = bus.Subscribe(subscriber, cursor: null, callback: _ => TaskAsyncHelper.True, maxMessages: messageBufferSize); subscriptions.Add(subscription); } for (var i = 0; i < senders; i++) { ThreadPool.QueueUserWorkItem(_ => { while (!cancellationTokenSource.IsCancellationRequested) { string source = i.ToString(); bus.Publish(source, "a", payload); } countDown.Signal(); }); } return new DisposableAction(() => { cancellationTokenSource.Cancel(); // Wait for all senders to stop countDown.Wait(TimeSpan.FromMilliseconds(1000 * senders)); // Shut the bus down and wait for workers to stop bus.Dispose(); // Dispose of all the subscriptions subscriptions.ForEach(s => s.Dispose()); }); }
public async Task FarmDisconnectRaisesUncleanDisconnects() { // Each node shares the same bus but are independent servers const int nodeCount = 3; var counters = new Infrastructure.PerformanceCounterManager(); var configurationManager = new DefaultConfigurationManager(); configurationManager.DisconnectTimeout = TimeSpan.FromSeconds(6); using (EnableDisposableTracing()) using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000)) using (var loadBalancer = new LoadBalancer(nodeCount)) { var broadcasters = new List<IConnection>(); var disconnectCounter = new DisconnectCounter(); loadBalancer.Configure(app => { var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(IMessageBus), () => bus); resolver.Register(typeof(IConfigurationManager), () => configurationManager); resolver.Register(typeof(FarmConnection), () => new FarmConnection(disconnectCounter)); var connectionManager = resolver.Resolve<IConnectionManager>(); broadcasters.Add(connectionManager.GetConnectionContext<FarmConnection>().Connection); app.MapSignalR<FarmConnection>("/echo", new ConnectionConfiguration { Resolver = resolver }); }); var transport = new Client.Transports.LongPollingTransport(loadBalancer); var connection = new Client.Connection("http://goo/echo"); await connection.Start(transport); for (int i = 0; i < nodeCount; i++) { broadcasters[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)).Wait(); await Task.Delay(TimeSpan.FromSeconds(1)); } ((Client.IConnection)connection).Disconnect(); await Task.Delay(TimeSpan.FromTicks(TimeSpan.FromSeconds(5).Ticks * nodeCount)); Assert.Equal(0, disconnectCounter.CleanDisconnectCount); Assert.Equal(3, disconnectCounter.UncleanDisconnectCount); } }