public void GroupTokenIsNotNullWhenGroupsChange() { var response = new PersistentResponse(); var groupSet = new DiffSet<string>(new string[] { "a", "b", "c", "d" }); groupSet.GetDiff(); groupSet.Add("g"); var serializer = new Mock<IJsonSerializer>(); HashSet<string> results = null; serializer.Setup(m => m.Serialize(It.IsAny<object>(), It.IsAny<TextWriter>())) .Callback<object, TextWriter>((obj, tw) => { results = new HashSet<string>((IEnumerable<string>)obj); var jsonNet = new JsonNetSerializer(); jsonNet.Serialize(obj, tw); }); var protectedData = new Mock<IProtectedData>(); protectedData.Setup(m => m.Protect(It.IsAny<string>(), It.IsAny<string>())) .Returns<string, string>((value, purpose) => value); protectedData.Setup(m => m.Unprotect(It.IsAny<string>(), It.IsAny<string>())) .Returns<string, string>((value, purpose) => value); Connection.PopulateResponseState(response, groupSet, serializer.Object, protectedData.Object); Assert.NotNull(response.GroupsToken); Assert.True(results.Contains("a")); Assert.True(results.Contains("b")); Assert.True(results.Contains("c")); Assert.True(results.Contains("d")); Assert.True(results.Contains("g")); }
public void GroupTokenIsNotNullWhenGroupsChangeToEmpty() { var response = new PersistentResponse(); var groupSet = new DiffSet<string>(new string[] { "b", "d" }); groupSet.DetectChanges(); groupSet.Remove("b"); groupSet.Remove("d"); var serializer = new Mock<IJsonSerializer>(); HashSet<string> results = null; serializer.Setup(m => m.Serialize(It.IsAny<object>(), It.IsAny<TextWriter>())) .Callback<object, TextWriter>((obj, tw) => { results = new HashSet<string>((IEnumerable<string>)obj); var jsonNet = new JsonNetSerializer(); jsonNet.Serialize(obj, tw); }); var protectedData = new Mock<IProtectedData>(); protectedData.Setup(m => m.Protect(It.IsAny<string>(), It.IsAny<string>())) .Returns<string, string>((value, purpose) => value); protectedData.Setup(m => m.Unprotect(It.IsAny<string>(), It.IsAny<string>())) .Returns<string, string>((value, purpose) => value); Connection.PopulateResponseState(response, groupSet, serializer.Object, protectedData.Object, connectionId: "myconnection"); Assert.NotNull(response.GroupsToken); var parts = response.GroupsToken.Split(new[] { ':' }, 2); Assert.Equal(2, parts.Length); Assert.Equal("myconnection", parts[0]); Assert.Equal(0, results.Count); }
public void AbortUrlTriggersConnectionAbort() { var request = new Mock<IRequest>(); var qs = new NameValueCollection(); request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/abort")); string abortedConnectionId = null; var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, null); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); transportConnection.Setup(m => m.Send(It.IsAny<ConnectionMessage>())) .Callback<ConnectionMessage>(m => { abortedConnectionId = m.Signal; var command = m.Value as Command; Assert.NotNull(command); Assert.Equal(CommandType.Abort, command.CommandType); }) .Returns(TaskAsyncHelper.Empty); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; transport.Object.ConnectionId = "1"; transport.Object.ProcessRequest(transportConnection.Object).Wait(); Assert.Equal("c-1", abortedConnectionId); }
public void AvoidDeadlockIfCancellationTokenTriggeredBeforeSubscribing() { var response = new Mock<IResponse>(); response.Setup(m => m.CancellationToken).Returns(CancellationToken.None); var request = new Mock<IRequest>(); var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect")); var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, response.Object); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); Func<PersistentResponse, object, Task<bool>> callback = null; object state = null; var disposable = new DisposableAction(() => { callback(new PersistentResponse() { Terminal = true }, state); }); transportConnection.Setup(m => m.Receive(It.IsAny<string>(), It.IsAny<Func<PersistentResponse, object, Task<bool>>>(), It.IsAny<int>(), It.IsAny<object>())).Callback<string, Func<PersistentResponse, object, Task<bool>>, int, object>((id, cb, max, st) => { callback = cb; state = st; }) .Returns(disposable); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; var wh = new ManualResetEventSlim(); transport.Object.BeforeCancellationTokenCallbackRegistered = () => { // Trip the cancellation token transport.Object.End(); }; // Act Task.Factory.StartNew(() => { transport.Object.ProcessRequest(transportConnection.Object); wh.Set(); }); Assert.True(wh.Wait(TimeSpan.FromSeconds(2)), "Dead lock!"); }
public void SerializeInterceptsIJsonWritable() { // Arrange var serializer = new JsonNetSerializer(); var sw = new StringWriter(); var value = new Mock<IJsonWritable>(); value.Setup(m => m.WriteJson(It.IsAny<TextWriter>())) .Callback<TextWriter>(tw => tw.Write("Custom")); // Act serializer.Serialize(value.Object, sw); // Assert Assert.Equal("Custom", sw.ToString()); }
public HubRequest Parse(string data) { var serializer = new JsonNetSerializer(); var deserializedData = serializer.Parse<HubInvocation>(data); var request = new HubRequest(); request.Hub = deserializedData.Hub; request.Method = deserializedData.Method; request.Id = deserializedData.Id; request.State = GetState(deserializedData); request.ParameterValues = (deserializedData.Args != null) ? deserializedData.Args.Select(value => new JRawValue(value)).ToArray() : _emptyArgs; return request; }
public void GroupTokenIsNullWhenNoGroups() { var response = new PersistentResponse(); var groupSet = new DiffSet<string>(new string[] { }); var serializer = new JsonNetSerializer(); var protectedData = new Mock<IProtectedData>(); protectedData.Setup(m => m.Protect(It.IsAny<string>(), It.IsAny<string>())) .Returns<string, string>((value, purpose) => value); protectedData.Setup(m => m.Unprotect(It.IsAny<string>(), It.IsAny<string>())) .Returns<string, string>((value, purpose) => value); Connection.PopulateResponseState(response, groupSet, serializer, protectedData.Object); Assert.Null(response.GroupsToken); }
public void SendThrowsNullExceptionWhenConnectionIdIsNull() { var serializer = new JsonNetSerializer(); var counters = new PerformanceCounterManager(); var connection = new Connection(new Mock<IMessageBus>().Object, serializer, "signal", "connectonid", new[] { "test" }, new string[] { }, new Mock<ITraceManager>().Object, new AckHandler(completeAcksOnTimeout: false, ackThreshold: TimeSpan.Zero, ackInterval: TimeSpan.Zero), counters, new Mock<IProtectedData>().Object); Assert.Throws<ArgumentException>(() => connection.Send(null, new object())); }
private static IDictionary<string, object> GetState(HubInvocation deserializedData) { if (deserializedData.State == null) { return new Dictionary<string, object>(); } // Get the raw JSON string and check if it's over 4K string json = deserializedData.State.ToString(); if (json.Length > 4096) { throw new InvalidOperationException(Resources.Error_StateExceededMaximumLength); } var settings = new JsonSerializerSettings(); settings.Converters.Add(new SipHashBasedDictionaryConverter()); var serializer = new JsonNetSerializer(settings); return serializer.Parse<IDictionary<string, object>>(json); }
public void SendingCommandObjectSetsCommandOnBus() { var messageBus = new Mock<IMessageBus>(); var counters = new PerformanceCounterManager(); Message message = null; messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Returns<Message>(m => { message = m; return TaskAsyncHelper.Empty; }); var serializer = new JsonNetSerializer(); var traceManager = new Mock<ITraceManager>(); var connection = new Connection(messageBus.Object, serializer, "signal", "connectonid", new[] { "a", "signal", "connectionid" }, new string[] { }, traceManager.Object, new AckHandler(completeAcksOnTimeout: false, ackThreshold: TimeSpan.Zero, ackInterval: TimeSpan.Zero), counters, new Mock<IProtectedData>().Object); connection.Send("a", new Command { CommandType = CommandType.AddToGroup, Value = "foo" }); Assert.NotNull(message); Assert.True(message.IsCommand); var command = serializer.Parse<Command>(message.Value, message.Encoding); Assert.Equal(CommandType.AddToGroup, command.CommandType); Assert.Equal("foo", command.Value); }
public void GroupThrowsNullExceptionWhenGroupNameIsNull() { Func<string, ClientHubInvocation, IList<string>, Task> send = (signal, value, exclude) => Task.Factory.StartNew(() => { }); var serializer = new JsonNetSerializer(); var counters = new PerformanceCounterManager(); var connection = new Connection(new Mock<IMessageBus>().Object, serializer, "signal", "connectonid", new[] { "test" }, new string[] { }, new Mock<ITraceManager>().Object, new AckHandler(completeAcksOnTimeout: false, ackThreshold: TimeSpan.Zero, ackInterval: TimeSpan.Zero), counters, new Mock<IProtectedData>().Object); var hubContext = new HubContext(send, "test", connection); Assert.Throws<ArgumentException>(() => hubContext.Clients.Group(null)); }
public void RunWithPostReceive(Func<Task> postReceive) { var request = new Mock<IRequest>(); var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect")); var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, null); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); transportConnection.Setup(m => m.Receive(It.IsAny<string>(), It.IsAny<Func<PersistentResponse, Task<bool>>>(), It.IsAny<int>())).Returns(DisposableAction.Empty); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; transport.Object.Connected = postReceive; // Act transport.Object.ProcessRequest(transportConnection.Object); // Assert Assert.True(transport.Object.InitializeTcs.Task.Wait(TimeSpan.FromSeconds(2)), "Initialize task not tripped"); }
public void ReceiveDisconnectBeforeCancellationSetup() { var request = new Mock<IRequest>(); var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect")); var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, null); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); transportConnection.Setup(m => m.Receive(It.IsAny<string>(), It.IsAny<Func<PersistentResponse, Task<bool>>>(), It.IsAny<int>())).Callback<string, Func<PersistentResponse, Task<bool>>, int>((id, cb, max) => { cb(new PersistentResponse() { Disconnect = true }); }) .Returns(DisposableAction.Empty); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; transport.Setup(m => m.Send(It.IsAny<PersistentResponse>())).Returns(TaskAsyncHelper.Empty); bool ended = false; transport.Object.AfterRequestEnd = (ex) => { Assert.Null(ex); ended = true; }; // Act transport.Object.ProcessRequest(transportConnection.Object); // Assert Assert.True(ended); }
public void ReceiveThrowingReturnsFaultedTask() { var request = new Mock<IRequest>(); var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect")); var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, null); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); transportConnection.Setup(m => m.Receive(It.IsAny<string>(), It.IsAny<Func<PersistentResponse, Task<bool>>>(), It.IsAny<int>())).Throws(new InvalidOperationException()); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; // Act var task = transport.Object.ProcessRequest(transportConnection.Object); // Assert Assert.Throws<AggregateException>(() => task.Wait(TimeSpan.FromSeconds(2))); }
public void EnqueAsyncWriteAndEndRequest(Func<Task> writeAsync) { var request = new Mock<IRequest>(); var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect")); var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, null); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); Func<PersistentResponse, Task<bool>> callback = null; transportConnection.Setup(m => m.Receive(It.IsAny<string>(), It.IsAny<Func<PersistentResponse, Task<bool>>>(), It.IsAny<int>())).Callback<string, Func<PersistentResponse, Task<bool>>, int>((id, cb, max) => { callback = cb; }) .Returns(new DisposableAction(() => { callback(new PersistentResponse()); })); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; transport.Setup(m => m.CancellationToken).Returns(CancellationToken.None); var tcs = new TaskCompletionSource<bool>(); transport.Object.EnqueueOperation(writeAsync); transport.Object.AfterRequestEnd = () => { // Trip the cancellation token tcs.TrySetResult(transport.Object.WriteQueue.IsDrained); }; transport.Object.BeforeCancellationTokenCallbackRegistered = () => { transport.Object.End(); }; Assert.True(transport.Object.ProcessRequest(transportConnection.Object).Wait(TimeSpan.FromSeconds(2))); Assert.True(tcs.Task.Result); }
public void SendUrlTriggersReceivedEvent() { var tcs = new TaskCompletionSource<string>(); var request = new Mock<IRequest>(); var form = new NameValueCollection(); form["data"] = "This is my data"; var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Form).Returns(form); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/send")); var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, null); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; transport.Object.Received = data => { tcs.TrySetResult(data); return TaskAsyncHelper.Empty; }; transport.Object.ProcessRequest(transportConnection.Object).Wait(); Assert.Equal("This is my data", tcs.Task.Result); }
public void RequestCompletesAfterFaultedInitializeResponse() { // Arrange var response = new Mock<IResponse>(); response.Setup(m => m.CancellationToken).Returns(CancellationToken.None); var request = new Mock<IRequest>(); var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect")); var counters = new PerformanceCounterManager(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, response.Object); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); transportConnection.Setup(m => m.Receive(It.IsAny<string>(), It.IsAny<Func<PersistentResponse, object, Task<bool>>>(), It.IsAny<int>(), It.IsAny<object>())) .Returns<string, Func<PersistentResponse, object, Task<bool>>, int, object>( (messageId, callback, maxMessages, state) => new DisposableAction(() => callback(new PersistentResponse(), state)) ); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters, traceManager.Object) { CallBase = true }; var queue = new TaskQueue(); transport.Setup(t => t.EnqueueOperation(It.IsAny<Func<object, Task>>(), It.IsAny<object>())) .Returns<Func<object, Task>, object>( (writeAsync, state) => queue.Enqueue(writeAsync, state)); transport.Setup(t => t.InitializeResponse(It.IsAny<ITransportConnection>())) .Returns<ITransportConnection>( pr => TaskAsyncHelper.FromError(new Exception())); transport.Setup(t => t.Send(It.IsAny<PersistentResponse>())) .Returns<PersistentResponse>( pr => transport.Object.EnqueueOperation(() => TaskAsyncHelper.Empty)); var tcs = new TaskCompletionSource<bool>(); transport.Object.AfterRequestEnd = (ex) => { // Trip the cancellation token tcs.TrySetResult(transport.Object.WriteQueue.IsDrained); }; // Act transport.Object.ProcessRequest(transportConnection.Object); // Assert Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(2))); Assert.True(tcs.Task.Result); }
private static KernelBase SetupNinject(ApplicationSettings settings) { var kernel = new StandardKernel(new[] { new FactoryModule() }); kernel.Bind<JabbrContext>() .To<JabbrContext>(); kernel.Bind<IJabbrRepository>() .To<PersistedRepository>(); kernel.Bind<IChatService>() .To<ChatService>(); kernel.Bind<IDataProtection>() .To<JabbRDataProtection>(); kernel.Bind<IFormsAuthenticationProvider>() .To<JabbRFormsAuthenticationProvider>(); kernel.Bind<ILogger>() .To<RealtimeLogger>(); // We're doing this manually since we want the chat repository to be shared // between the chat service and the chat hub itself kernel.Bind<Chat>() .ToMethod(context => { var resourceProcessor = context.Kernel.Get<ContentProviderProcessor>(); var repository = context.Kernel.Get<IJabbrRepository>(); var cache = context.Kernel.Get<ICache>(); var service = new ChatService(cache, repository); return new Chat(resourceProcessor, service, repository, cache); }); kernel.Bind<ICryptoService>() .To<CryptoService>() .InSingletonScope(); kernel.Bind<IResourceProcessor>() .To<ResourceProcessor>() .InSingletonScope(); kernel.Bind<IApplicationSettings>() .ToConstant(settings); kernel.Bind<IJavaScriptMinifier>() .To<AjaxMinMinifier>() .InSingletonScope(); kernel.Bind<IMembershipService>() .To<MembershipService>(); kernel.Bind<IAuthenticationService>() .ToConstant(new AuthenticationService()); kernel.Bind<IAuthenticationCallbackProvider>() .To<JabbRAuthenticationCallbackProvider>(); kernel.Bind<ICache>() .To<DefaultCache>() .InSingletonScope(); kernel.Bind<IChatNotificationService>() .To<ChatNotificationService>(); if (String.IsNullOrEmpty(settings.VerificationKey) || String.IsNullOrEmpty(settings.EncryptionKey)) { kernel.Bind<IKeyProvider>() .ToConstant(new FileBasedKeyProvider()); } else { kernel.Bind<IKeyProvider>() .To<AppSettingKeyProvider>() .InSingletonScope(); } var serializer = new JsonNetSerializer(new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat }); kernel.Bind<IJsonSerializer>() .ToConstant(serializer); kernel.Bind<UploadCallbackHandler>() .ToSelf() .InSingletonScope(); kernel.Bind<UploadProcessor>() .ToSelf() .InSingletonScope(); kernel.Bind<ContentProviderProcessor>() .ToConstant(new ContentProviderProcessor(kernel)); return kernel; }
public void InitializeResponseIsFirstEnqueuedOperation() { // Arrange var response = new Mock<IResponse>(); response.Setup(m => m.CancellationToken).Returns(CancellationToken.None); var request = new Mock<IRequest>(); var qs = new NameValueCollection(); qs["connectionId"] = "1"; request.Setup(m => m.QueryString).Returns(qs); request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect")); var counters = new Mock<IPerformanceCounterManager>(); var heartBeat = new Mock<ITransportHeartbeat>(); var json = new JsonNetSerializer(); var hostContext = new HostContext(request.Object, response.Object); var transportConnection = new Mock<ITransportConnection>(); var traceManager = new Mock<ITraceManager>(); traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo")); transportConnection.Setup(m => m.Receive(It.IsAny<string>(), It.IsAny<Func<PersistentResponse, object, Task<bool>>>(), It.IsAny<int>(), It.IsAny<object>())) .Returns<string, Func<PersistentResponse, object, Task<bool>>, int, object>( (messageId, callback, maxMessages, state) => { callback(new PersistentResponse(), state); return DisposableAction.Empty; }); var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object) { CallBase = true }; var queue = new TaskQueue(); var results = new List<string>(); transport.Setup(t => t.EnqueueOperation(It.IsAny<Func<object, Task>>(), It.IsAny<object>())) .Returns<Func<object, Task>, object>( (writeAsync, state) => { return queue.Enqueue(writeAsync, state); }); transport.Setup(t => t.InitializeResponse(It.IsAny<ITransportConnection>())) .Returns<ITransportConnection>( pr => { results.Add("InitializeResponse"); return TaskAsyncHelper.Empty; }); transport.Setup(t => t.Send(It.IsAny<PersistentResponse>())) .Returns<PersistentResponse>( pr => transport.Object.EnqueueOperation(() => { results.Add("Send"); return TaskAsyncHelper.Empty; })); // Act transport.Object.ProcessRequest(transportConnection.Object); // Assert Assert.Equal("InitializeResponse", results[0]); Assert.Equal("Send", results[1]); }