public async Task ProgressiveCallsCallerProgress() { WampPlayground playground = new WampPlayground(); CallerCallee dualChannel = await playground.GetCallerCalleeDualChannel(); IWampChannel calleeChannel = dualChannel.CalleeChannel; IWampChannel callerChannel = dualChannel.CallerChannel; await calleeChannel.RealmProxy.Services.RegisterCallee(new LongOpService()); MyCallback callback = new MyCallback(); callerChannel.RealmProxy.RpcCatalog.Invoke (callback, new CallOptions() { ReceiveProgress = true }, "com.myapp.longop", new object[] { 10 }); callback.Task.Wait(2000); CollectionAssert.AreEquivalent(Enumerable.Range(0, 10), callback.ProgressiveResults); Assert.That(callback.Task.Result, Is.EqualTo(10)); }
public void RequestContextIsSet() { WampPlayground playground = new WampPlayground(); IWampHost host = playground.Host; WampRequestContext context = null; Mock <ICalculator> calculatorMock = new Mock <ICalculator>(); calculatorMock.Setup(x => x.Square(It.IsAny <int>())) .Callback((int x) => context = WampRequestContext.Current) .Returns((int x) => x * x); host.HostService(calculatorMock.Object); host.Open(); IWampChannel <MockRaw> channel = playground.CreateNewChannel(); channel.Open(); ICalculator proxy = channel.GetRpcProxy <ICalculator>(); int sixteen = proxy.Square(4); Assert.That(context.SessionId, Is.EqualTo(channel.GetMonitor().SessionId)); }
public void AsyncAwaitTaskWork() { WampPlayground playground = new WampPlayground(); IWampHost host = playground.Host; Mock <INumberProcessor> mock = new Mock <INumberProcessor>(); mock.Setup(x => x.ProcessNumber(It.IsAny <int>())) .Returns(async(int x) => { await Task.CompletedTask; }); host.HostService(mock.Object); host.Open(); IWampChannel <MockRaw> channel = playground.CreateNewChannel(); channel.Open(); INumberProcessor proxy = channel.GetRpcProxy <INumberProcessor>(); Task task = proxy.ProcessNumber(4); mock.Verify(x => x.ProcessNumber(4)); }
public void NoAuthenticationThrowsException() { JsonFormatter formatter = new JsonFormatter(); WampCraPlayground <JToken> playground = new WampCraPlayground <JToken> (formatter, new MockWampCraAuthenticaticationBuilder <JToken>()); IWampChannelFactory <JToken> channelFactory = playground.ChannelFactory; IWampHost host = playground.Host; host.HostService(new Sample()); host.Open(); IControlledWampConnection <JToken> connection = playground.CreateClientConnection(); IWampChannel <JToken> channel = channelFactory.CreateChannel(connection); channel.Open(); Task <string> result = channel.GetRpcProxy <ISampleAsync>() .Hello("Foobar"); AggregateException aggregateException = result.Exception; Exception exception = aggregateException.InnerException; WampRpcCallException casted = exception as WampRpcCallException; Assert.IsNotNull(casted); }
public void AuthenticationFailure() { JsonFormatter formatter = new JsonFormatter(); WampCraPlayground <JToken> playground = new WampCraPlayground <JToken> (formatter, new MockWampCraAuthenticaticationBuilder <JToken>()); IWampChannelFactory <JToken> channelFactory = playground.ChannelFactory; IWampHost host = playground.Host; host.HostService(new Sample()); host.Open(); IControlledWampConnection <JToken> connection = playground.CreateClientConnection(); IWampChannel <JToken> channel = channelFactory.CreateChannel(connection); channel.Open(); IWampCraProcedures proceduresProxy = channel.GetRpcProxy <IWampCraProcedures>(); WampRpcCallException callException = Assert.Throws <WampRpcCallException> (() => proceduresProxy.Authenticate(formatter, "foobar", null, "secret2")); }
public void AuthenticationSuccess() { JsonFormatter formatter = new JsonFormatter(); WampCraPlayground <JToken> playground = new WampCraPlayground <JToken> (formatter, new MockWampCraAuthenticaticationBuilder <JToken>()); IWampChannelFactory <JToken> channelFactory = playground.ChannelFactory; IWampHost host = playground.Host; host.HostService(new Sample()); host.Open(); IControlledWampConnection <JToken> connection = playground.CreateClientConnection(); IWampChannel <JToken> channel = channelFactory.CreateChannel(connection); channel.Open(); channel.GetRpcProxy <IWampCraProcedures>(). Authenticate(formatter, "foobar", null, "secret"); string result = channel.GetRpcProxy <ISample>() .Hello("Foobar"); Assert.IsNotNullOrEmpty(result); }
public async Task ProgressiveCallsCalleeProxyProgress() { WampPlayground playground = new WampPlayground(); CallerCallee dualChannel = await playground.GetCallerCalleeDualChannel(); IWampChannel calleeChannel = dualChannel.CalleeChannel; IWampChannel callerChannel = dualChannel.CallerChannel; MyOperation myOperation = new MyOperation(); await calleeChannel.RealmProxy.RpcCatalog.Register(myOperation, new RegisterOptions()); ILongOpService proxy = callerChannel.RealmProxy.Services.GetCalleeProxyPortable <ILongOpService>(); List <int> results = new List <int>(); MyProgress <int> progress = new MyProgress <int>(i => results.Add(i)); Task <int> result = proxy.LongOp(10, progress); result.Wait(); CollectionAssert.AreEquivalent(Enumerable.Range(0, 10), results); Assert.That(result.Result, Is.EqualTo(10)); }
private static Task <long?> Publish(IWampChannel publisherChannel, string topicUri, object[] arguments) { IWampTopicProxy topicProxy = publisherChannel.RealmProxy.TopicContainer.GetTopicByUri(topicUri); return(topicProxy.Publish(new PublishOptions(), arguments)); }
public async Task NotAuthenticatedIntegrationTest() { WampAuthenticationPlayground playground = new WampAuthenticationPlayground (new WampCraUserDbAuthenticationFactory (new MyAuthenticationProvider(), new MyUserDb())); SetupHost(playground); IWampClientAuthenticator authenticator = new WampCraClientAuthenticator(authenticationId: "peter", secret: "SECRET"); IWampChannel channel = playground.CreateNewChannel("realm1", authenticator); IWampRealmProxy realmProxy = channel.RealmProxy; WampConnectionBrokenException openException = null; try { await channel.Open().ConfigureAwait(false); } catch (WampConnectionBrokenException ex) { openException = ex; } Assert.That(openException, Is.Not.Null); Assert.That(openException.CloseType, Is.EqualTo(SessionCloseType.Abort)); Assert.That(openException.Reason, Is.EqualTo(WampErrors.NotAuthorized)); }
private static async Task RawTest(bool hasSessionId, RegisterOptions registerOptions, CallOptions callOptions) { WampPlayground playground = new WampPlayground(); CallerCallee dualChannel = await playground.GetCallerCalleeDualChannel(); IWampChannel calleeChannel = dualChannel.CalleeChannel; IWampChannel callerChannel = dualChannel.CallerChannel; MyOperation myOperation = new MyOperation(); await calleeChannel.RealmProxy.RpcCatalog.Register(myOperation, registerOptions); MyCallback myCallback = new MyCallback(); callerChannel.RealmProxy.RpcCatalog.Invoke(myCallback, callOptions, myOperation.Procedure); long?expectedCaller = null; if (hasSessionId) { expectedCaller = dualChannel.CallerSessionId; } if (callOptions.DiscloseMe == false && registerOptions.DiscloseCaller == true) { Assert.That(myCallback.ErrorUri, Is.EqualTo(WampErrors.DiscloseMeNotAllowed)); } else { Assert.That(myOperation.Details.Caller, Is.EqualTo(expectedCaller)); } }
protected override async Task RunAsync(IWampChannel channel) { await channel.Open().ConfigureAwait(false); ICancellableServiceProxy proxy = channel.RealmProxy.Services.GetCalleeProxy <ICancellableServiceProxy>(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); Task <int> invocationTask = proxy.LongCancellableOpAsync(4096, cancellationTokenSource.Token); await Task.Delay(1000).ConfigureAwait(false); // Cancel the operation cancellationTokenSource.Cancel(); try { await invocationTask.ConfigureAwait(false); } catch (WampException ex) { Console.WriteLine($"Call was canceled. Details: Error: {ex.ErrorUri}, [{string.Join(", ", ex.Arguments ?? Enumerable.Empty<object>())}], {{{string.Join(", ", ex.ArgumentsKeywords?.Select(x => $"{x.Key} : {x.Value}") ?? Enumerable.Empty<object>())}}}"); } }
static void Main(string[] args) { DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory(); IWampChannel <JToken> channel = channelFactory.CreateChannel("ws://127.0.0.1:9000/"); channel.Open(); ICalculator proxy = channel.GetRpcProxy <ICalculator>(); int five = proxy.Add(2, 3); Console.WriteLine("2 + 3 = " + five); IAsyncCalculator asyncProxy = channel.GetRpcProxy <IAsyncCalculator>(); Task <int> asyncFive = asyncProxy.Add(2, 3); Console.WriteLine("2 + 3 = " + asyncFive.Result); Console.ReadLine(); }
public async Task KillAllTest(int killer) { WampPlayground playground = SetupHost(); List <IWampChannel> channels = new List <IWampChannel>(); for (int i = 0; i < 30; i++) { IWampChannel channel = playground.CreateNewChannel("realm1"); channels.Add(channel); } Dictionary <int, (string reason, string message)> disconnectionDetails = await OpenChannels(channels).ConfigureAwait(false); Assert.That(disconnectionDetails.Count, Is.EqualTo(0)); IWampSessionManagementServiceProxy proxy = channels[killer].RealmProxy.Services .GetCalleeProxy <IWampSessionManagementServiceProxy>(); const string expectedReason = "wamp.myreason"; const string expectedMessage = "Bye bye bye"; await proxy.KillAllAsync(expectedReason, expectedMessage).ConfigureAwait(false); AssertClosedChannels(Enumerable.Range(0, 30).Except(new[] { killer }), disconnectionDetails, expectedMessage, expectedReason); }
public async Task PatternRpcTest(string procedureToInvoke, string matchedProcedure) { WampPlayground playground = new WampPlayground(); playground.Host.Open(); IWampChannel calleeChannel = playground.CreateNewChannel("realm1"); await calleeChannel.Open(); Action <MyOperation, InvocationDetails> action = (operation, details) => { Assert.That(details.Procedure, Is.EqualTo(procedureToInvoke)); Assert.That(operation.Procedure, Is.EqualTo(matchedProcedure)); }; await Register(calleeChannel, "com.myapp.manage.47837483.create", "exact", action); await Register(calleeChannel, "com.myapp", "prefix", action); await Register(calleeChannel, "com.myapp.manage", "prefix", action); await Register(calleeChannel, "com....", "wildcard", action); await Register(calleeChannel, ".myapp...create", "wildcard", action); IWampChannel callerChannel = playground.CreateNewChannel("realm1"); await callerChannel.Open(); var callback = new MyCallback(); callerChannel.RealmProxy.RpcCatalog.Invoke (callback, new CallOptions(), procedureToInvoke); Assert.That(callback.Called, Is.EqualTo(true)); }
public async Task ProgressiveCancellationTokenCancelCallsInterrupt() { WampPlayground playground = new WampPlayground(); CallerCallee dualChannel = await playground.GetCallerCalleeDualChannel(); IWampChannel calleeChannel = dualChannel.CalleeChannel; IWampChannel callerChannel = dualChannel.CallerChannel; MyCancellableOperation myOperation = new MyCancellableOperation("com.myapp.longop"); await calleeChannel.RealmProxy.RpcCatalog.Register(myOperation, new RegisterOptions()); ICancellableLongOpService proxy = callerChannel.RealmProxy.Services.GetCalleeProxy <ICancellableLongOpService>(); CancellationTokenSource tokenSource = new CancellationTokenSource(); MyProgress <int> progress = new MyProgress <int>(x => { }); Task <int> result = proxy.LongOp(10, progress, tokenSource.Token); Assert.That(myOperation.CancellableInvocation.InterruptCalled, Is.False); tokenSource.Cancel(); Assert.That(myOperation.CancellableInvocation.InterruptCalled, Is.True); }
public async Task PositionalTupleObservableOnNextPublishesEventWithPositionalArguments() { WampPlayground playground = new WampPlayground(); PublisherSubscriber dualChannel = await playground.GetPublisherSubscriberDualChannel(); IWampChannel publisher = dualChannel.Publisher; IWampChannel subscriber = dualChannel.Subscriber; var subject = publisher.RealmProxy.Services.GetSubject ("com.myapp.mytopic2", new MyPositionalTupleEventConverter()); IWampTopicProxy topicProxy = subscriber.RealmProxy.TopicContainer.GetTopicByUri("com.myapp.mytopic2"); MyCustomSubscriber myCustomSubscriber = new MyCustomSubscriber(); IAsyncDisposable subscribe = await topicProxy.Subscribe(myCustomSubscriber, new SubscribeOptions()); // subject.OnNext(("Hello", 37, 23)); subject.OnNext(ValueTuple.Create("Hello", 37, 23)); Assert.That(myCustomSubscriber.ArgumentsKeywords, Is.Null.Or.Empty); ISerializedValue[] arguments = myCustomSubscriber.Arguments; Assert.That(arguments[0].Deserialize <string>(), Is.EqualTo("Hello")); Assert.That(arguments[1].Deserialize <int>(), Is.EqualTo(37)); Assert.That(arguments[2].Deserialize <int>(), Is.EqualTo(23)); }
protected override async Task RunAsync(IWampChannel channel) { await channel.Open().ConfigureAwait(false); await Task.Yield(); IWampSubject topic = channel.RealmProxy.Services.GetSubject("com.myapp.topic1"); IObservable <int> timer = Observable.Timer(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1)).Select((x, i) => i); WampEvent TopicSelector(int value) { return(new WampEvent() { Arguments = new object[] { value }, Options = new PublishOptions() { DiscloseMe = true } }); } using (IDisposable disposable = timer.Select(value => TopicSelector(value)).Subscribe(topic)) { Console.WriteLine("Hit enter to stop publishing"); Console.ReadLine(); } Console.WriteLine("Stopped publishing"); Console.ReadLine(); }
public async Task CancelProgressiveCallsCalleeCancellationToken() { WampPlayground playground = new WampPlayground(); CallerCallee dualChannel = await playground.GetCallerCalleeDualChannel(); IWampChannel calleeChannel = dualChannel.CalleeChannel; IWampChannel callerChannel = dualChannel.CallerChannel; CancellableService service = new CancellableService(); await calleeChannel.RealmProxy.Services.RegisterCallee(service); MyCallback callback = new MyCallback(); IWampCancellableInvocationProxy cancellable = callerChannel.RealmProxy.RpcCatalog.Invoke (callback, new CallOptions() { ReceiveProgress = true }, "com.myapp.longop", new object[] { 100 }); Assert.That(service.CancellationToken, Is.Not.Null); Assert.That(service.CancellationToken.IsCancellationRequested, Is.False); cancellable.Cancel(new CancelOptions()); Assert.That(service.CancellationToken.IsCancellationRequested, Is.True); }
public void Connect(ClientEnv env) { SetEnv(env); var factory = new DefaultWampChannelFactory(); _channel = factory.CreateJsonChannel(_serverAddress, "mtcrossbar"); while (!_channel.RealmProxy.Monitor.IsConnected) { try { Console.WriteLine($"Trying to connect to server {_serverAddress}..."); _channel.Open().Wait(); } catch { Console.WriteLine("Retrying in 5 sec..."); Thread.Sleep(5000); } } Console.WriteLine($"Connected to server {_serverAddress}"); _realmProxy = _channel.RealmProxy; _service = _realmProxy.Services.GetCalleeProxy <IRpcMtFrontend>(); }
private static async Task <Registration> RegisterCallee (WampPlayground playground, Action <Registration> action, string invocationPolicy) { IWampChannel calleeChannel = playground.CreateNewChannel("realm1"); await calleeChannel.Open(); Registration registration = null; MyOperation operation = new MyOperation(() => action(registration)); IAsyncDisposable disposable = await calleeChannel.RealmProxy.RpcCatalog.Register (operation, new RegisterOptions() { Invoke = invocationPolicy }); registration = new Registration(operation, disposable); return(registration); }
public async Task SubscriberGetsArgumentsArrayEventAsPositionalTuple() { WampPlayground playground = new WampPlayground(); PublisherSubscriber dualChannel = await playground.GetPublisherSubscriberDualChannel(); IWampChannel publisher = dualChannel.Publisher; IWampChannel subscriber = dualChannel.Subscriber; var subject = subscriber.RealmProxy.Services.GetSubject ("com.myapp.topic2", new MyPositionalTupleEventConverter()); MyPositionalSubscriber mySubscriber = new MyPositionalSubscriber(); subject.Subscribe(mySubscriber); IWampTopicProxy topicProxy = publisher.RealmProxy.TopicContainer.GetTopicByUri("com.myapp.topic2"); long?publish = await topicProxy.Publish(new PublishOptions(), new object[] { "Hello", 47, 23, }); Assert.That(mySubscriber.Number1, Is.EqualTo(47)); Assert.That(mySubscriber.Number2, Is.EqualTo(23)); Assert.That(mySubscriber.C, Is.EqualTo("Hello")); }
public async Task KillByAuthIdTest(int killingChannel, int killedChannel, IEnumerable <int> expectedDeadChannels) { WampAuthenticationPlayground playground = SetupAuthenticationHost(); List <IWampChannel> channels = new List <IWampChannel>(); for (int i = 0; i < 30; i++) { IWampChannel channel = playground.CreateNewChannel("realm1", new WampCraClientAuthenticator("user" + i % 15, "secret")); channels.Add(channel); } Dictionary <int, (string reason, string message)> disconnectionDetails = await OpenChannels(channels); Assert.That(disconnectionDetails.Count, Is.EqualTo(0)); IWampSessionManagementServiceProxy proxy = channels[killingChannel].RealmProxy.Services.GetCalleeProxy <IWampSessionManagementServiceProxy>(); const string expectedReason = "wamp.myreason"; const string expectedMessage = "Bye bye bye"; await proxy.KillByAuthIdAsync("user" + killedChannel, expectedReason, expectedMessage).ConfigureAwait(false); AssertClosedChannels(expectedDeadChannels, disconnectionDetails, expectedMessage, expectedReason); }
public BrokerConnection(string uri, string realm) { _channel = new WampChannelFactory() .ConnectToRealm(realm) .WebSocketTransport(uri) .JsonSerialization() .Build(); Func <Task> connect = async() => { Log.InfoFormat("Trying to connect to broker {0}", uri); try { await _channel.Open(); Log.Debug("Connection Opened."); _subject.OnNext(Connected.Yes(new Broker(_channel))); } catch (Exception) { Log.Debug("Connection Failed."); _subject.OnNext(Connected.No <IBroker>()); throw; } }; _reconnector = new WampChannelReconnector(_channel, connect); }
static async Task Main(string[] args) { string url = "ws://127.0.0.1:8080/ws/"; string realm = "realm1"; WampChannelFactory channelFactory = new WampChannelFactory(); IWampChannel channel = channelFactory.ConnectToRealm(realm) .WebSocketTransport(new Uri(url)) .JsonSerialization() .Build(); // Fire this code when the connection establishes channel.RealmProxy.Monitor.ConnectionEstablished += (sender, e) => { Console.WriteLine("Session open! :" + e.SessionId); }; // Fire this code when the connection has broken channel.RealmProxy.Monitor.ConnectionBroken += (sender, e) => { Console.WriteLine("Session closed! :" + e.Reason); }; await channel.Open().ConfigureAwait(false); // Your code goes here: use WAMP via the channel variable to // call, register, subscribe and publish .. await Task.Delay(1000); }
static void Main(string[] args) { //Sample modeled and compatible with Autobahn Python https://github.com/tavendo/AutobahnPython [examples/twisted/wamp1/authentication/client.py] JsonSerializer serializer = new JsonSerializer(); JsonFormatter formatter = new JsonFormatter(serializer); DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory(serializer); IWampChannel <JToken> channel = channelFactory.CreateChannel("ws://127.0.0.1:9000/"); channel.Open(); try { IWampCraProcedures proxy = channel.GetRpcProxy <IWampCraProcedures>(); //TODO: This can authenticates as a user, or as anonymous based on conditional. WampCraPermissions permissions; if (true) { permissions = Authenticate(proxy, formatter, "foobar", null, "secret"); } else { permissions = Authenticate(proxy, formatter, null, null, null); } Console.WriteLine("permissions: {0}", formatter.Serialize(permissions)); } catch (WampRpcCallException ex) { Console.Out.WriteLine("Authenticate WampRpcCallException: '{0}' to uri '{1}'", ex.Message, ex.ProcUri); } try { //Expect failure if running against default server sample and anonymous. ISample proxy = channel.GetRpcProxy <ISample>(); string result = proxy.Hello("Foobar"); Console.WriteLine(result); } catch (WampRpcCallException ex) { Console.Out.WriteLine("Hello WampRpcCallException: '{0}' to uri '{1}'", ex.Message, ex.ProcUri); } //server sample allows for subscribe for anon and foobar user. ISubject <string> subject = channel.GetSubject <string>("http://example.com/topics/mytopic1"); IDisposable cancelation = subject.Subscribe(x => Console.WriteLine("mytopic1: " + x)); //server sample does not allow for publish if anon. Therefore, if logged in, expect to see // this in console, otherwise it will silently fail to publish (Wamp1 makes it silent). subject.OnNext("Hello World From Client!"); Console.ReadLine(); channel.Close(); }
public TestBroker() { _channel = new WampChannelFactory() .ConnectToRealm("com.checkout.store") .WebSocketTransport(new Uri(TestAddress.Broker)) .JsonSerialization() .Build(); }
public void Dispose() { this.Disconnect(); this._factory = null; this._channel = null; this._parameters = null; }
public TestBroker() { _channel = new WampChannelFactory() .ConnectToRealm("com.weareadaptive.reactivetrader") .WebSocketTransport(new Uri(TestAddress.Broker)) .JsonSerialization() .Build(); }
public void Start() { _wampChannel = new DefaultWampChannelFactory().CreateJsonChannel(Helper.ApiUrlWssBase, "realm1"); _wampChannel.RealmProxy.Monitor.ConnectionBroken += OnConnectionBroken; _wampChannel.RealmProxy.Monitor.ConnectionError += OnConnectionError; _wampChannel.RealmProxy.Monitor.ConnectionEstablished += OnConnectionEstablished; _wampChannelOpenTask = _wampChannel.Open(); }
public TestBroker() { WebSocketFactory.Init(() => new ClientWebSocketConnection()); _channel = new WampChannelFactory() .ConnectToRealm("com.weareadaptive.reactivetrader") .WebSocketTransport(TestAddress.Broker) .JsonSerialization() .Build(); }
public TestBroker() { WebSocketFactory.Init(() => new ClientWebSocketConnection()); _channel = new WampChannelFactory() .ConnectToRealm("com.weareadaptive.reactivetrader") .WebSocketTransport(TestAddress.Broker) .JsonSerialization() .Build(); }
public void Connect() { DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory(); this.serverws = channelFactory.CreateChannel(Manager.wsUrl); try { serverws.Open(); this.ServeurIsConnected = true; } catch (Exception e) { Console.WriteLine(e.Message); this.ServeurIsConnected = false; } }
public ExecuteTradeIntegrationTests() { var broker = new TestBroker(); _channel = broker.OpenChannel().Result; _heartbeatStream = _channel.RealmProxy.Services.GetSubject<dynamic>("status") .Publish() .RefCount(); _executionServiceInstance = _heartbeatStream .Where(hb => hb.Type == ServiceTypes.Execution) .Select(hb => hb.Instance) .Take(1) .Timeout(ResponseTimeout) .ToTask() .Result; _timeoutCancellationTokenSource = new CancellationTokenSource(); }