/// <summary> /// Creates a PollingFileSystemEventProducer /// </summary> /// <param name="directory">The directory to watch</param> /// <param name="channel">The channel where events should be sent</param> /// <param name="scheduler">Event scheduler</param> /// <param name="fiber">Fiber to schedule on</param> /// <param name="checkInterval">The maximal time between events or polls on a given file</param> /// <param name="checkSubDirectory">Indicates if subdirectorys will be checked or ignored</param> public PollingFileSystemEventProducer(string directory, UntypedChannel channel, [NotNull] Scheduler scheduler, Fiber fiber, TimeSpan checkInterval, bool checkSubDirectory) { if (scheduler == null) { throw new ArgumentNullException("scheduler"); } _directory = directory; _channel = channel; _fiber = fiber; _hashes = new Dictionary <string, Guid>(); _scheduler = scheduler; _checkInterval = checkInterval; _scheduledAction = scheduler.Schedule(3.Seconds(), _fiber, HashFileSystem); var myChannel = new ChannelAdapter(); _connection = myChannel.Connect(connectionConfigurator => { connectionConfigurator.AddConsumerOf <FileSystemChanged>().UsingConsumer(HandleFileSystemChangedAndCreated); connectionConfigurator.AddConsumerOf <FileSystemCreated>().UsingConsumer(HandleFileSystemChangedAndCreated); connectionConfigurator.AddConsumerOf <FileSystemRenamed>().UsingConsumer(HandleFileSystemRenamed); connectionConfigurator.AddConsumerOf <FileSystemDeleted>().UsingConsumer(HandleFileSystemDeleted); }); _fileSystemEventProducer = new FileSystemEventProducer(directory, myChannel, checkSubDirectory); }
public void Should_be_two_consumers_on_the_channel() { SelectiveConsumer <TestMessage> selectiveConsumer = x => y => { }; var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf <TestMessage>() .UsingConsumer(message => { }); x.AddConsumerOf <TestMessage>() .UsingSelectiveConsumer(selectiveConsumer); })) { input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(BroadcastChannel), typeof(TypedChannelAdapter <TestMessage>), typeof(BroadcastChannel <TestMessage>), typeof(ConsumerChannel <TestMessage>), typeof(SelectiveConsumerChannel <TestMessage>), }); } }
public static WcfChannelHost GetCurrentShelfHost(ChannelAdapter myChannel) { var pipeName = GetThisShelfPipeName(); var address = GetBaseAddress(pipeName); return new WcfChannelHost(new ThreadPoolFiber(), myChannel, address, "shelf"); }
public void Sending_a_bid_request_should_get_a_response() { var response = new FutureChannel<Response<Status>>(); UntypedChannel responseChannel = new ChannelAdapter(); responseChannel.Connect(x => x.AddChannel(response)); Auction.Request(new Ask(Id), responseChannel); response.WaitUntilCompleted(2.Seconds()).ShouldBeTrue("Timeout waiting for response"); response.Value.Body.AuctionId.ShouldEqual(Id); // ThreadUtil.Sleep(2.Seconds()); // go ahead and buy something var purchased = new FutureChannel<Response<Purchased>>(); responseChannel.Connect(x => x.AddChannel(purchased)); Auction.Request(new Buy { Quantity = 15, Token = response.Value.Body.Token }, responseChannel); purchased.WaitUntilCompleted(2.Seconds()).ShouldBeTrue("Timeout waiting for purchase"); purchased.Value.Body.Quantity.ShouldEqual(15); purchased.Value.Body.Price.ShouldEqual(response.Value.Body.CurrentBid); }
public void Sending_messages_to_an_instance_stored_using_nhibernate() { var input = new ChannelAdapter(); using (input.Connect(x => { })) ; }
public void A_file_is_created() { _baseDirectory = AppDomain.CurrentDomain.BaseDirectory; _filename = "test2.dat"; _path = Path.Combine(_baseDirectory, _filename); System.IO.File.Delete(_path); _listener = new Future <FileCreated>(); _channel = new ChannelAdapter(); FiberFactory fiberFactory = () => new SynchronousFiber(); _scheduler = new TimerScheduler(fiberFactory()); _producer = new PollingFileSystemEventProducer(_baseDirectory, _channel, _scheduler, fiberFactory(), 20.Seconds()); Thread.Sleep(5.Seconds()); using (_channel.Connect(x => x.AddConsumerOf <FileCreated>().UsingConsumer(m => _listener.Complete(m)))) { System.IO.File.Create(_path); _listener.WaitUntilCompleted(25.Seconds()); } _producer.Dispose(); }
public void Should_property_adapt_itself_to_a_channel_network() { TraceLogger.Configure(LogLevel.Debug); ILogger log = Logger.GetLogger<Sending_a_message_through_a_wcf_channel>(); log.Debug("Starting"); var serviceUri = new Uri("net.pipe://localhost/Pipe"); string pipeName = "Test"; Channel<TestMessage> adapter = new ChannelAdapter<TestMessage>(); using (var host = new WcfChannelHost<TestMessage>(adapter, serviceUri, pipeName)) { log.Debug("Host started"); var future = new Future<TestMessage>(); using (adapter.Connect(x => { x.AddConsumer(m => { log.Debug(l => l.Write("Received: {0}", m.Value)); future.Complete(m); }); })) { var client = new WcfChannelProxy<TestMessage>(new SynchronousFiber(), serviceUri, pipeName); log.Debug("Client started"); client.Send(new TestMessage("Hello!")); future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue(); log.Debug("Complete"); } } }
public void Start() { // file system watcher will fail if directory isn't there, ensure it is if (!System.IO.Directory.Exists(_baseDir)) System.IO.Directory.CreateDirectory(_baseDir); _channel = new ChannelAdapter(); FiberFactory fiberFactory = () => new SynchronousFiber(); _scheduler = new TimerScheduler(fiberFactory()); _producer = new PollingFileSystemEventProducer(_baseDir, _channel, _scheduler, fiberFactory(), 2.Minutes()); _channel.Connect(config => config .AddConsumerOf<FileSystemEvent>() .BufferFor(3.Seconds()) .Distinct(fsEvent => GetChangedDirectory(fsEvent.Path)) .UsingConsumer(fsEvents => fsEvents.Keys.ToList().ForEach(key => { if (key == _baseDir) return; _hostChannel.Send(new FileSystemChange { ShelfName = key }); }))); }
public void EstablishContext() { using (var startEvent = new ManualResetEvent(false)) { _srv = new TestService(); _channelAdaptor = new ChannelAdapter(); _hostChannel = WellknownAddresses.GetServiceCoordinatorHost(_channelAdaptor); using (_channelAdaptor.Connect(config => config.AddConsumerOf<ServiceStarted>().UsingConsumer(msg => startEvent.Set()))) { ServiceConfigurator<TestService> c = new ServiceConfigurator<TestService>(); c.WhenStarted(s => s.Start()); c.WhenStopped(s => s.Stop()); c.WhenPaused(s => { _wasPaused = true; }); c.WhenContinued(s => { _wasContinued = true; }); c.HowToBuildService(name => _srv); _serviceController = c.Create(WellknownAddresses.GetServiceCoordinatorProxy()); _serviceController.Start(); startEvent.WaitOne(5.Seconds()); _serviceController.State.ShouldEqual(ServiceState.Started); } } }
public void Starting_a_socket_server() { TraceLogger.Configure(LogLevel.Debug); _startingEventReceived = new Future <ServerStarting>(); _runningEventReceived = new Future <ServerRunning>(); _input = new ChannelAdapter(); _connection = _input.Connect(x => { x.AddConsumerOf <ServerStarting>() .UsingConsumer(_startingEventReceived.Complete) .HandleOnCallingThread(); x.AddConsumerOf <ServerRunning>() .UsingConsumer(_runningEventReceived.Complete) .HandleOnCallingThread(); }); ServerUri = new Uri("http://localhost:8008/Topshelf"); _server = new HttpServer(ServerUri, new ThreadPoolFiber(), _input, new[] { new VersionConnectionHandler(), }); _server.Start(); }
public void Should_properly_arrive_at_the_destination() { var serviceUri = new Uri("net.pipe://localhost/pipe"); string pipeName = "test"; var future = new Future <TestMessage>(); var message = new TestMessage { Id = Guid.NewGuid(), Name = "Alpha", }; UntypedChannel adapter = new ChannelAdapter(); using (var remote = new WcfChannelHost(new SynchronousFiber(), adapter, serviceUri, pipeName)) { using (adapter.Connect(x => { x.AddConsumerOf <TestMessage>() .UsingConsumer(m => future.Complete(m)); })) { var client = new WcfChannelProxy(new SynchronousFiber(), serviceUri, pipeName); client.Send(message); future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue(); } } future.Value.ShouldNotBeNull(); future.Value.ShouldEqual(message); future.Value.ShouldNotBeTheSameAs(message); }
public void A_file_is_created() { _baseDirectory = AppDomain.CurrentDomain.BaseDirectory; _filename = "test2.dat"; _path = Path.Combine(_baseDirectory, _filename); System.IO.File.Delete(_path); _listener = new Future<FileCreated>(); _channel = new ChannelAdapter(); FiberFactory fiberFactory = () => new SynchronousFiber(); _scheduler = new TimerScheduler(fiberFactory()); _producer = new PollingFileSystemEventProducer(_baseDirectory, _channel, _scheduler, fiberFactory(), 20.Seconds()); Thread.Sleep(5.Seconds()); using (_channel.Connect(x => x.AddConsumerOf<FileCreated>().UsingConsumer(m => _listener.Complete(m)))) { System.IO.File.Create(_path); _listener.WaitUntilCompleted(25.Seconds()); } _producer.Dispose(); }
public void Should_subscribe_the_last_message_consumer() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf <TestMessage>() .BufferFor(2.Seconds()) .HandleOnCallingThread() .Last() .HandleOnCallingThread() .UsingConsumer(message => { }) .HandleOnCallingThread(); })) { input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(BroadcastChannel), typeof(TypedChannelAdapter <TestMessage>), typeof(IntervalChannel <TestMessage>), typeof(LastChannel <TestMessage>), typeof(ConsumerChannel <TestMessage>), }); } }
public void A_request_is_sent_via_wcf() { _pipeUri = new Uri("net.pipe://localhost/pipe"); _response = new Future <Response <TestMessage> >(); _client = new ChannelAdapter(); _clientConnection = _client.Connect(x => { x.SendToWcfChannel(_pipeUri, _pipeName) .HandleOnCallingThread(); x.AddConsumerOf <Response <TestMessage> >() .UsingConsumer(_response.Complete); }); _server = new ChannelAdapter(); _serverConnection = _server.Connect(x => { x.AddConsumerOf <Request <TestMessage> >() .UsingConsumer(request => request.Respond(request.Body)); }); _host = new WcfChannelHost(new PoolFiber(), _server, _pipeUri, _pipeName); }
public void Should_support_single_channels() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf <UpdateValue>() .UsingInstance() .Of <TestInstance>() .DistributedBy(m => m.Id) .PersistUsingNHibernate() .UsingSessionProvider(m => (ISession)null) .OnChannel(m => m.UpdateValueChannel) .CreateNewInstanceBy(m => new TestInstance(m.Id)); })) { input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(BroadcastChannel), typeof(TypedChannelAdapter <UpdateValue>), typeof(InstanceChannel <UpdateValue>), }); } }
protected async Task <T> InvokeChannelApiAsync <T>(ClaimsIdentity claimsIdentity, string method, string conversationId, params object[] args) { var skillConversation = new SkillConversation(conversationId); var channelApiInvokeActivity = Activity.CreateInvokeActivity(); channelApiInvokeActivity.Name = InvokeActivityName; channelApiInvokeActivity.ChannelId = "unknown"; channelApiInvokeActivity.ServiceUrl = skillConversation.ServiceUrl; channelApiInvokeActivity.Conversation = new ConversationAccount(id: skillConversation.ConversationId); channelApiInvokeActivity.From = new ChannelAccount(id: "unknown"); channelApiInvokeActivity.Recipient = new ChannelAccount(id: "unknown", role: RoleTypes.Bot); var activityPayload = args?.Where(arg => arg is Activity).Cast <Activity>().FirstOrDefault(); if (activityPayload != null) { // fix up activityPayload with original conversation.Id and id activityPayload.Conversation.Id = skillConversation.ConversationId; activityPayload.ServiceUrl = skillConversation.ServiceUrl; // use the activityPayload for channel accounts, it will be in From=Bot/Skill Recipient=User, // We want to send it to the bot as From=User, Recipient=Bot so we have correct state context. channelApiInvokeActivity.ChannelId = activityPayload.ChannelId; channelApiInvokeActivity.From = activityPayload.Recipient; channelApiInvokeActivity.Recipient = activityPayload.From; // We want ActivityPayload to also be in User->Bot context, if it is outbound it will go through context.SendActivity which will flip outgoing to Bot->User // regardless this gives us same memory context of User->Bot which is useful for things like EndOfConversation processing being in the correct memory context. activityPayload.From = channelApiInvokeActivity.From; activityPayload.Recipient = channelApiInvokeActivity.Recipient; } var channelApiArgs = new ChannelApiArgs { Method = method, Args = args }; channelApiInvokeActivity.Value = channelApiArgs; // We call our adapter using the BotAppId claim, so turnContext has the bot claims // var claimsIdentity = new ClaimsIdentity(new List<Claim> // { // new Claim(AuthenticationConstants.AudienceClaim, this.BotAppId), // new Claim(AuthenticationConstants.AppIdClaim, this.BotAppId), // new Claim(AuthenticationConstants.ServiceUrlClaim, skillConversation.ServiceUrl), // }); // send up to the bot to process it... await ChannelAdapter.ProcessActivityAsync(claimsIdentity, (Activity)channelApiInvokeActivity, Bot.OnTurnAsync, CancellationToken.None).ConfigureAwait(false); if (channelApiArgs.Exception != null) { throw channelApiArgs.Exception; } // Return the result that was captured in the middleware handler. return((T)channelApiArgs.Result); }
public void Start() { // file system watcher will fail if directory isn't there, ensure it is if (!Directory.Exists(_baseDirectory)) Directory.CreateDirectory(_baseDirectory); _scheduler = new TimerScheduler(new PoolFiber()); _channel = new ChannelAdapter(); _producer = new PollingFileSystemEventProducer(_baseDirectory, _channel, _scheduler, new PoolFiber(), 2.Minutes()); _connection = _channel.Connect(config => { config .AddConsumerOf<FileSystemEvent>() .BufferFor(3.Seconds()) .UseScheduler(_scheduler) .Distinct(fsEvent => GetChangedDirectory(fsEvent.Path)) .UsingConsumer(fsEvents => { fsEvents.Keys.Distinct().Each(key => { if (key == _baseDirectory) return; _serviceChannel.Send(new ServiceFolderChanged(key)); }); }) .HandleOnFiber(_fiber); }); }
public TResponse MakeRequest <TRequest, TResponse>(TRequest message) where TRequest : CashboxMessage { var response = new Magnum.Future <object>(); var channel = new ChannelAdapter(); Exception ex = null; using (channel.Connect(config => { config.AddConsumerOf <ReturnValue>() .UsingConsumer(msg => response.Complete(msg.Value)); config.AddConsumerOf <ReturnException>() .UsingConsumer(msg => ex = msg.Exception); })) { _input.Request(message, channel); if (!response.WaitUntilCompleted(TimeSpan.FromSeconds(180)) && ex != null) { throw ex; } if (response.Value == null) { return(default(TResponse)); } return((TResponse)response.Value); } }
public void Sending_a_bid_request_should_get_a_response() { var response = new FutureChannel <Response <Status> >(); UntypedChannel responseChannel = new ChannelAdapter(); responseChannel.Connect(x => x.AddChannel(response)); Auction.Request(new Ask(Id), responseChannel); response.WaitUntilCompleted(2.Seconds()).ShouldBeTrue("Timeout waiting for response"); response.Value.Body.AuctionId.ShouldEqual(Id); // ThreadUtil.Sleep(2.Seconds()); // go ahead and buy something var purchased = new FutureChannel <Response <Purchased> >(); responseChannel.Connect(x => x.AddChannel(purchased)); Auction.Request(new Buy { Quantity = 15, Token = response.Value.Body.Token }, responseChannel); purchased.WaitUntilCompleted(2.Seconds()).ShouldBeTrue("Timeout waiting for purchase"); purchased.Value.Body.Quantity.ShouldEqual(15); purchased.Value.Body.Price.ShouldEqual(response.Value.Body.CurrentBid); }
public void Sending_a_message_to_an_nhibernate_instance_channel() { _newValue = new Random().Next(1, 500000)/100m; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery("Delete TestInstance").ExecuteUpdate(); session.Save(new TestInstance(27)); transaction.Commit(); } var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf<UpdateValue>() .UsingInstance() .Of<TestInstance>() .HandleOnCallingThread() .DistributedBy(msg => msg.Id) .PersistUsingNHibernate() .UsingSessionProvider(m => SessionFactory.OpenSession()) .OnChannel(m => m.UpdateValueChannel) .CreateNewInstanceBy(m => new TestInstance(m.Id)); })) { // input.Send(new UpdateValue(27, _newValue)); } }
public static HostHost GetCurrentShelfHost(ChannelAdapter myChannel) { var pipeName = GetThisShelfPipeName(); var address = GetBaseAddress(pipeName); return new HostHost(myChannel, address, "shelf"); }
public static HostHost GetCurrentServiceHost(ChannelAdapter myChannel, string serviceName) { var pipeName = GetThisShelfPipeName(); var address = GetBaseAddress(pipeName); return new HostHost(myChannel, address, serviceName); }
public void Should_properly_arrive_at_the_destination() { var serviceUri = new Uri("net.pipe://localhost/pipe"); string pipeName = "test"; var future = new Future<TestMessage>(); var message = new TestMessage { Id = Guid.NewGuid(), Name = "Alpha", }; UntypedChannel adapter = new ChannelAdapter(); using (var remote = new WcfChannelHost(new SynchronousFiber(), adapter, serviceUri, pipeName)) { using (adapter.Connect(x => { x.AddConsumerOf<TestMessage>() .UsingConsumer(m => future.Complete(m)); })) { var client = new WcfChannelProxy(new SynchronousFiber(), serviceUri, pipeName); client.Send(message); future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue(); } } future.Value.ShouldNotBeNull(); future.Value.ShouldEqual(message); future.Value.ShouldNotBeTheSameAs(message); }
public void A_request_is_sent_via_wcf() { _pipeUri = new Uri("net.pipe://localhost/pipe"); _response = new Future<Response<TestMessage>>(); _client = new ChannelAdapter(); _clientConnection = _client.Connect(x => { x.SendToWcfChannel(_pipeUri, _pipeName) .HandleOnCallingThread(); x.AddConsumerOf<Response<TestMessage>>() .UsingConsumer(_response.Complete); }); _server = new ChannelAdapter(); _serverConnection = _server.Connect(x => { x.ReceiveFromWcfChannel(_pipeUri, _pipeName); x.AddConsumerOf<Request<TestMessage>>() .UsingConsumer(request => request.Respond(request.Body)); }); }
public void Sending_a_message_to_an_nhibernate_instance_channel() { _newValue = new Random().Next(1, 500000) / 100m; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery("Delete TestInstance").ExecuteUpdate(); session.Save(new TestInstance(27)); transaction.Commit(); } var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf <UpdateValue>() .UsingInstance() .Of <TestInstance>() .HandleOnCallingThread() .DistributedBy(msg => msg.Id) .PersistUsingNHibernate() .UsingSessionProvider(m => SessionFactory.OpenSession()) .OnChannel(m => m.UpdateValueChannel) .CreateNewInstanceBy(m => new TestInstance(m.Id)); })) { // input.Send(new UpdateValue(27, _newValue)); } }
/// <summary> /// Creates a PollingFileSystemEventProducer /// </summary> /// <param name="directory">The directory to watch</param> /// <param name="channel">The channel where events should be sent</param> /// <param name="scheduler">Event scheduler</param> /// <param name="fiber">Fiber to schedule on</param> /// <param name="checkInterval">The maximal time between events or polls on a given file</param> /// <param name="checkSubDirectory">Indicates if subdirectorys will be checked or ignored</param> public PollingFileSystemEventProducer(string directory, UntypedChannel channel, [NotNull] Scheduler scheduler, Fiber fiber, TimeSpan checkInterval, bool checkSubDirectory) { if (scheduler == null) throw new ArgumentNullException("scheduler"); _directory = directory; _channel = channel; _fiber = fiber; _hashes = new Dictionary<string, Guid>(); _scheduler = scheduler; _checkInterval = checkInterval; _scheduledAction = scheduler.Schedule(3.Seconds(), _fiber, HashFileSystem); var myChannel = new ChannelAdapter(); _connection = myChannel.Connect(connectionConfigurator => { connectionConfigurator.AddConsumerOf<FileSystemChanged>().UsingConsumer(HandleFileSystemChangedAndCreated); connectionConfigurator.AddConsumerOf<FileSystemCreated>().UsingConsumer(HandleFileSystemChangedAndCreated); connectionConfigurator.AddConsumerOf<FileSystemRenamed>().UsingConsumer(HandleFileSystemRenamed); connectionConfigurator.AddConsumerOf<FileSystemDeleted>().UsingConsumer(HandleFileSystemDeleted); }); _fileSystemEventProducer = new FileSystemEventProducer(directory, myChannel, checkSubDirectory); }
public void Run() { Stopwatch timer = Stopwatch.StartNew(); const int channelCount = 10000; const int seedCount = 500; var channels = new UntypedChannel[channelCount]; var connections = new ChannelConnection[channelCount]; var complete = new Future<int>(); var latch = new CountdownLatch(channelCount*seedCount, complete.Complete); for (int i = 0; i < channelCount; i++) { int channelNumber = i; channels[i] = new ChannelAdapter(); connections[i] = channels[i].Connect(x => { x.AddConsumerOf<AMessage>() .UsingConsumer(message => { if (channelNumber < channels.Length - 1) channels[channelNumber + 1].Send(message); latch.CountDown(); }); }); } var body = new AMessage(); for (int i = 0; i < seedCount; i++) { channels[i].Send(body); for (int j = 0; j < i; j++) latch.CountDown(); } bool completed = complete.WaitUntilCompleted(2.Minutes()); timer.Stop(); connections.Each(x => x.Dispose()); if (!completed) { Console.WriteLine("Process did not complete"); return; } Console.WriteLine("Processed {0} messages in with {1} channels in {2}ms", seedCount, channelCount, timer.ElapsedMilliseconds); Console.WriteLine("That's {0} messages per second!", ((long)seedCount*channelCount*1000)/timer.ElapsedMilliseconds); }
public void Sending_a_message_to_an_nhibernate_backed_state_machine() { TraceLogProvider.Configure(LogLevel.Debug); _newValue = new Random().Next(1, 500000)/100m; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery("Delete TestStateMachineInstance").ExecuteUpdate(); transaction.Commit(); } var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumersFor<TestStateMachineInstance>() .BindUsing<TestStateMachineInstanceBinding, int>() .ExecuteOnProducerThread() .CreateNewInstanceUsing(id => new TestStateMachineInstance(id)) .PersistUsingNHibernate() .UseSessionProvider(() => SessionFactory.OpenSession()); })) { input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(BroadcastChannel), typeof(TypedChannelAdapter<CreateOrder>), typeof(InstanceChannel<CreateOrder>), typeof(TypedChannelAdapter<UpdateOrder>), typeof(InstanceChannel<UpdateOrder>), typeof(TypedChannelAdapter<CompleteOrder>), typeof(InstanceChannel<CompleteOrder>), }); var future = new Future<int>(); TestStateMachineInstance.CompletedLatch = new CountdownLatch(1, future.Complete); // input.Send(new CreateOrder { Id = 27 }); input.Send(new UpdateOrder { Id = 27, Value = _newValue, }); input.Send(new CompleteOrder { Id = 27, }); future.WaitUntilCompleted(5.Seconds()).ShouldBeTrue(); } }
public void Should_receive_the_request_message_type() { var responseChannel = new ChannelAdapter(); _channel.Request <Simple>(responseChannel); _received.IsCompleted.ShouldBeTrue("Message was not received"); }
public void Should_receive_the_request_message_type() { var responseChannel = new ChannelAdapter(); _channel.Request<Simple>(responseChannel); _received.IsCompleted.ShouldBeTrue("Message was not received"); }
public void Should_properly_wrap_the_channel_as_synchronized() { Assert.IsNull(SynchronizationContext.Current); var fiber = new PoolFiber(); var input = new ChannelAdapter(); var context = new TestSynchronizationContext(); var future = new Future<TestMessage>(); SynchronizationContext.SetSynchronizationContext(context); Assert.IsNotNull(SynchronizationContext.Current); using (input.Connect(x => { x.AddConsumerOf<TestMessage>() .OnCurrentSynchronizationContext() .UsingConsumer(message => { Trace.WriteLine("Received on Thread: " + Thread.CurrentThread.ManagedThreadId); Assert.IsNotNull(SynchronizationContext.Current); Assert.AreEqual(context, SynchronizationContext.Current); future.Complete(message); }); })) { Trace.WriteLine("Subscribed on Thread: " + Thread.CurrentThread.ManagedThreadId); SynchronizationContext.SetSynchronizationContext(null); input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(BroadcastChannel), typeof(TypedChannelAdapter<TestMessage>), typeof(SynchronizedChannel<TestMessage>), typeof(ConsumerChannel<TestMessage>), }); fiber.Add(() => { Trace.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId); Assert.IsNull(SynchronizationContext.Current); input.Send(new TestMessage()); }); Assert.IsNull(SynchronizationContext.Current); future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue(); } }
public void Should_properly_wrap_the_channel_as_synchronized() { Assert.IsNull(SynchronizationContext.Current); var fiber = new ThreadPoolFiber(); var input = new ChannelAdapter(); var context = new TestSynchronizationContext(); var future = new Future <TestMessage>(); SynchronizationContext.SetSynchronizationContext(context); Assert.IsNotNull(SynchronizationContext.Current); using (input.Connect(x => { x.AddConsumerOf <TestMessage>() .OnCurrentSynchronizationContext() .UsingConsumer(message => { Trace.WriteLine("Received on Thread: " + Thread.CurrentThread.ManagedThreadId); Assert.IsNotNull(SynchronizationContext.Current); Assert.AreEqual(context, SynchronizationContext.Current); future.Complete(message); }); })) { Trace.WriteLine("Subscribed on Thread: " + Thread.CurrentThread.ManagedThreadId); SynchronizationContext.SetSynchronizationContext(null); input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(BroadcastChannel), typeof(TypedChannelAdapter <TestMessage>), typeof(SynchronizedChannel <TestMessage>), typeof(ConsumerChannel <TestMessage>), }); fiber.Add(() => { Trace.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId); Assert.IsNull(SynchronizationContext.Current); input.Send(new TestMessage()); }); Assert.IsNull(SynchronizationContext.Current); future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue(); } }
public void Should_properly_setup_the_message_body() { ChannelAdapter channel = new ChannelAdapter(); channel.Send <Message <MyBody> >(msg => { }); }
/// <summary> /// Generates the PC speaker waveform. /// </summary> private async Task GenerateWaveformAsync() { using var player = Audio.CreatePlayer(); FillWithSilence(player); var buffer = new byte[4096]; var writeBuffer = buffer; bool expandToStereo = false; if (player.Format.Channels == 2) { writeBuffer = new byte[buffer.Length * 2]; expandToStereo = true; } player.BeginPlayback(); int idleCount = 0; while (idleCount < 10000) { if (this.queuedNotes.TryDequeue(out var note)) { int samples = GenerateSquareWave(buffer, note.Period); int periods = note.PeriodCount; if (expandToStereo) { ChannelAdapter.MonoToStereo(buffer.AsSpan(0, samples), writeBuffer.AsSpan(0, samples * 2)); samples *= 2; } while (periods > 0) { Audio.WriteFullBuffer(player, writeBuffer.AsSpan(0, samples)); periods--; } GenerateSilence(buffer); idleCount = 0; } else { while (player.WriteData(buffer) > 0) { } await Task.Delay(5, this.cancelGenerateWaveform.Token); idleCount++; } this.cancelGenerateWaveform.Token.ThrowIfCancellationRequested(); } }
public void After() { _inputConnection.Dispose(); _inputConnection = null; _input = null; _outputConnection.Dispose(); _outputConnection = null; _output = null; }
public void After() { _clientConnection.Dispose(); _clientConnection = null; _client = null; _serverConnection.Dispose(); _serverConnection = null; _server = null; }
public void Sending_a_message_to_an_nhibernate_backed_state_machine() { TraceLogger.Configure(LogLevel.Debug); _newValue = new Random().Next(1, 500000) / 100m; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery("Delete TestStateMachineInstance").ExecuteUpdate(); transaction.Commit(); } var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumersFor <TestStateMachineInstance>() .BindUsing <TestStateMachineInstanceBinding, int>() .HandleOnCallingThread() .CreateNewInstanceBy(id => new TestStateMachineInstance(id)) .PersistUsingNHibernate() .UseSessionProvider(() => SessionFactory.OpenSession()); })) { _networkTypes = input.Flatten().Select(c => c.GetType()); var future = new Future <int>(); TestStateMachineInstance.CompletedLatch = new CountdownLatch(1, future.Complete); // input.Send(new UpdateOrder { Id = 47 }); input.Send(new CreateOrder { Id = 27 }); input.Send(new UpdateOrder { Id = 27, Value = _newValue, }); input.Send(new CompleteOrder { Id = 27, }); future.WaitUntilCompleted(5.Seconds()).ShouldBeTrue(); } }
/// <summary> /// Adds new channels to the context /// </summary> /// <param name="context">The database context</param> private static void RegisterNewChannels(DatabaseContext context) { while (_queueAddedChannels.TryDequeue(out SocketTextChannel? c)) { if (c != null) { Logger.Info($"Registering channel '{c.Guild.Name}/{c.Name}'"); ChannelAdapter.EnableChannel(context, c); } } }
void CreateChannelNetwork() { _connectionChannel = new ChannelAdapter<ConnectionContext>(); _connectionChannelConnection = _connectionChannel.Connect(x => { var channelProvider = new HttpConnectionChannelProvider(_connectionHandlers); var threadPoolChannel = new ThreadPoolChannel<ConnectionContext>(channelProvider, _concurrentConnectionLimit); x.AddChannel(threadPoolChannel); }); }
void CreateChannelNetwork() { _connectionChannel = new ChannelAdapter <ConnectionContext>(); _connectionChannelConnection = _connectionChannel.Connect(x => { var channelProvider = new HttpConnectionChannelProvider(_connectionHandlers); var threadPoolChannel = new ThreadPoolChannel <ConnectionContext>(channelProvider, _concurrentConnectionLimit); x.AddChannel(threadPoolChannel); }); }
public void Should_send_to_a_adapter_consumer_chain() { Future <TestMessage> future = new Future <TestMessage>(); var consumer = new ConsumerChannel <TestMessage>(_fiber, future.Complete); var adapter = new ChannelAdapter <TestMessage>(consumer); adapter.Send(new TestMessage()); future.IsCompleted.ShouldBeTrue(); }
protected override UntypedChannel Visitor(ChannelAdapter channel) { _current = GetVertex(channel.GetHashCode(), () => "Adapter", typeof(ChannelAdapter), typeof(object)); if (_stack.Count > 0) { _edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name)); } return(WithVertex(() => base.Visitor(channel))); }
public void Should_allow_the_selective_consumer_channel_type() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf<TestMessage>() .UsingSelectiveConsumer(message => m => { }); })) { } }
public void Should_allow_the_selective_consumer_channel_type() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf <TestMessage>() .UsingSelectiveConsumer(message => m => { }); })) { } }
public void Sending_a_message_to_an_nhibernate_backed_state_machine() { _newValue = new Random().Next(1, 500000)/100m; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery("Delete TestStateMachineInstance").ExecuteUpdate(); transaction.Commit(); } var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumersFor<TestStateMachineInstance>() .BindUsing<TestStateMachineInstanceBinding, int>() .HandleOnCallingThread() .CreateNewInstanceBy(id => new TestStateMachineInstance(id)) .PersistUsingNHibernate() .UseSessionProvider(() => SessionFactory.OpenSession()); })) { _networkTypes = input.Flatten().Select(c => c.GetType()); var future = new Future<int>(); TestStateMachineInstance.CompletedLatch = new CountdownLatch(1, future.Complete); // input.Send(new UpdateOrder { Id = 47 }); input.Send(new CreateOrder { Id = 27 }); input.Send(new UpdateOrder { Id = 27, Value = _newValue, }); input.Send(new CompleteOrder { Id = 27, }); future.WaitUntilCompleted(5.Seconds()).ShouldBeTrue(); } }
public void A_message_is_sent_to_an_instance() { _auctionId = CombGuid.Generate(); _input = new ChannelAdapter(); _connection = _input.Connect(x => { x.AddConsumerOf <Bid>() .UsingInstance().Of <Auction>() .ObtainedBy(m => new Auction(m.AuctionId)) .OnChannel(auction => auction.BidChannel); }); }
public void Should_be_an_empty_channel_adapter_with_no_consumers() { var input = new ChannelAdapter(); using (input.Connect(x => { })) { input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(ShuntChannel) }); } }
public void Should_allow_an_interval_channel_to_be_created() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf <TestMessage>() .BufferFor(15.Seconds()) .UsingConsumer(messages => { }); })) { } }
public void A_message_is_sent_to_an_instance() { _auctionId = CombGuid.Generate(); _input = new ChannelAdapter(); _connection = _input.Connect(x => { x.AddConsumerOf<Bid>() .UsingInstance().Of<Auction>() .ObtainedBy(m => new Auction(m.AuctionId)) .OnChannel(auction => auction.BidChannel); }); }
public void Should_allow_an_interval_channel_to_be_created() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf<TestMessage>() .BufferFor(15.Seconds()) .UsingConsumer(messages => { }); })) { } }
public void After() { _host.Dispose(); _host = null; _clientConnection.Dispose(); _clientConnection = null; _client = null; _serverConnection.Dispose(); _serverConnection = null; _server = null; }
public void ChangeChannel(string channelId) { if (activeChat != null) { if (activeChat.Id.Equals(channelId)) { return; } activeChat.Hide(); } if (chats.ContainsKey(channelId)) { chats[channelId].Show(); activeChat = chats[channelId]; } else { MessagesAdapter adapter = null; switch (channelId[0]) { case 'D': adapter = new DirectMessageAdapter(Client.DirectMessages.Find((c) => c.id == channelId), this, Client); break; case 'C': adapter = new ChannelAdapter(Client.ChannelLookup[channelId], this, Client); break; case 'G': adapter = new GroupAdapter(Client.GroupLookup[channelId], this, Client); break; } if (adapter != null) { activeChat = new ChatInterface(adapter, this); activeChat.Location = new Point(220, 0); activeChat.Width = Width - 220; activeChat.Height = Height; activeChat.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top; chats.Add(channelId, activeChat); Controls.Add(activeChat); } else if (activeChat != null) { activeChat.Show(); } } }
public void Start() { _input = new ChannelAdapter(); ServerUri = new UriBuilder("http","localhost",_port, "klinger").Uri; _server = new HttpServer(ServerUri, new PoolFiber(), _input, new PatternMatchConnectionHandler[] { new VersionConnectionHandler(), new StatusConnectionHandler(_repo), new ImageConnectionHandler(), new CssConnectionHandler() }); _server.Start(); }
public IDisposable Watch(string directoryToWatch, Action<Directory> actionToTake) { if (!System.IO.Directory.Exists(directoryToWatch)) System.IO.Directory.CreateDirectory(directoryToWatch); _actionToTake = actionToTake; _eventChannel = new ChannelAdapter(); _eventChannel.Connect(x => x.AddConsumerOf<FileCreated>().UsingConsumer(ProcessNewFile)); _scheduler = new TimerScheduler(_fiberFactory()); _watcher = new PollingFileSystemEventProducer(directoryToWatch, _eventChannel, _scheduler, _fiberFactory(), 1.Seconds()); return _watcher; }
public void Should_allow_the_consumer_channel_type() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf <TestMessage>() .OnCurrentSynchronizationContext() .UsingConsumer(message => { }) .HandleOnPoolFiber(); })) { } }
public void Should_allow_the_consumer_channel_type() { var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumerOf<TestMessage>() .OnCurrentSynchronizationContext() .UsingConsumer(message => { }) .HandleOnPoolFiber(); })) { } }
public void Should_receive_the_response_message_type() { var requestChannel = new ChannelAdapter(); requestChannel.Connect(x => { x.AddConsumerOf<Request<Simple>>() .UsingConsumer(request => request.Respond(new SimpleImpl())) .HandleOnCallingThread(); }); requestChannel.Request<Simple>(_channel); _received.IsCompleted.ShouldBeTrue("Message was not received"); }
public void Start() { _input = new ChannelAdapter(); ServerUri = new UriBuilder("http", "localhost", _port, "Topshelf/" + _description.GetServiceName()).Uri; _log.InfoFormat("Loading dashboard at Uri: {0}", ServerUri); _server = new HttpServer(ServerUri, new PoolFiber(), _input, new PatternMatchConnectionHandler[] { new VersionConnectionHandler(), new StaticResourceHandler(@"\.png$", "Topshelf.Dashboard.images.", "image/png", "GET"), new StaticResourceHandler(@"\.css$", "Topshelf.Dashboard.styles.", "text/css", "GET"), new DashboardConnectionHandler(_serviceCoordinator) }); _server.Start(); }
public void Should_add_a_consumer_to_an_empty_adapter_chain() { var adapter = new ChannelAdapter<TestMessage>(new ShuntChannel<TestMessage>()); var future = new Future<TestMessage>(); var consumer = new ConsumerChannel<TestMessage>(_fiber, future.Complete); using (ChannelConnection scope = adapter.Connect(x => { x.AddChannel(consumer); })) { new TraceChannelVisitor().Visit(adapter); adapter.Send(new TestMessage()); } future.IsCompleted.ShouldBeTrue(); }