public void CancelledStartShouldBeDisconnected() { var connection = new Client.Connection("http://test"); var transport = new Mock <IClientTransport>(); transport.Setup(m => m.Negotiate(connection)) .Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = "1.2", ConnectionId = "Something" })); transport.Setup(m => m.Start(connection, null, It.IsAny <CancellationToken>())) .Returns(() => { var tcs = new TaskCompletionSource <object>(); tcs.SetCanceled(); return(tcs.Task); }); var aggEx = Assert.Throws <AggregateException>(() => connection.Start(transport.Object).Wait()); var ex = aggEx.Unwrap(); Assert.IsType(typeof(TaskCanceledException), ex); Assert.Equal(ConnectionState.Disconnected, connection.State); }
private Task <ContentProviderResult> ExtractContent(ContentProviderHttpRequest request) { var validProviders = _contentProviders.Where(c => c.IsValidContent(request.RequestUri)) .ToList(); if (validProviders.Count == 0) { return(TaskAsyncHelper.FromResult <ContentProviderResult>(null)); } var tasks = validProviders.Select(c => c.GetContent(request)).ToArray(); var tcs = new TaskCompletionSource <ContentProviderResult>(); Task.Factory.ContinueWhenAll(tasks, completedTasks => { var faulted = completedTasks.FirstOrDefault(t => t.IsFaulted); if (faulted != null) { tcs.SetException(faulted.Exception); } else if (completedTasks.Any(t => t.IsCanceled)) { tcs.SetCanceled(); } else { ContentProviderResult result = completedTasks.Select(t => t.Result) .FirstOrDefault(content => content != null); tcs.SetResult(result); } }); return(tcs.Task); }
public async Task WebSocketHandlerClosesIfWebSocketStateIsCloseSentAfterClosing() { var messageIndex = 0; var webSocketMessages = new[] { new WebSocketReceiveResult(0, WebSocketMessageType.Text, endOfMessage: false), new WebSocketReceiveResult(0, WebSocketMessageType.Text, endOfMessage: false), new WebSocketReceiveResult(0, WebSocketMessageType.Close, endOfMessage: true) }; var webSocket = new Mock <WebSocket>(MockBehavior.Strict); webSocket.Setup(w => w.ReceiveAsync(It.IsAny <ArraySegment <byte> >(), CancellationToken.None)) .Returns(() => TaskAsyncHelper.FromResult(webSocketMessages[messageIndex++])); WebSocketState state = WebSocketState.Open; webSocket.Setup(w => w.State).Returns(() => state); webSocket.Setup(w => w.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None)) .Returns(() => { state = WebSocketState.CloseSent; return(TaskAsyncHelper.Empty); }); webSocket.Setup(w => w.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None)) .Returns(() => { state = WebSocketState.Closed; return(TaskAsyncHelper.Empty); }); var webSocketHandler = new WebSocketHandler(64 * 1024); await webSocketHandler.ProcessWebSocketRequestAsync(webSocket.Object, CancellationToken.None); webSocket.VerifyAll(); }
public void AsyncStartShouldFailIfTransportStartFails() { var connection = new Client.Connection("http://test"); var transport = new Mock <IClientTransport>(); var ex = new Exception(); transport.Setup(m => m.Negotiate(connection, It.IsAny <string>())) .Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = connection.Protocol.ToString(), ConnectionId = "Something", DisconnectTimeout = 120 })); transport.Setup(m => m.Start(connection, null, It.IsAny <CancellationToken>())) .Returns(TaskAsyncHelper.Delay(TimeSpan.FromMilliseconds(100)).Then(() => { throw ex; })); var aggEx = Assert.Throws <AggregateException>(() => connection.Start(transport.Object).Wait()); Assert.Equal(aggEx.Unwrap(), ex); Assert.Equal(ConnectionState.Disconnected, connection.State); }
public void RequestWithMessageIdCallsReceiveOnConnectionThenSend() { var context = new Mock <HttpContextBase>(); var request = new Mock <HttpRequestBase>(); var response = new Mock <HttpResponseBase>(); request.Setup(m => m.Path).Returns("/foo"); var qs = new NameValueCollection(); qs["connectionId"] = "1"; qs["messageId"] = "20"; request.Setup(m => m.QueryString).Returns(qs); context.Setup(m => m.Response).Returns(response.Object); context.Setup(m => m.Request).Returns(request.Object); var json = new Mock <IJsonSerializer>(); var heartBeat = new Mock <ITransportHeartBeat>(); var transport = new Mock <LongPollingTransport>(context.Object, json.Object, heartBeat.Object) { CallBase = true }; var connection = new Mock <IConnection>(); PersistentResponse persistentResponse = null; connection.Setup(m => m.ReceiveAsync(20)).Returns(TaskAsyncHelper.FromResult <PersistentResponse>(persistentResponse)); transport.Object.ProcessRequest(connection.Object)().Wait(); heartBeat.Verify(m => m.AddConnection(transport.Object), Times.Once()); connection.Verify(m => m.ReceiveAsync(20), Times.Once()); transport.Verify(m => m.Send(persistentResponse), Times.Once()); response.VerifySet(m => m.ContentType = "application/json"); response.Verify(m => m.Write(It.IsAny <string>()), Times.Once()); json.Verify(m => m.Stringify(persistentResponse), Times.Once()); }
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); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(_iframedMeetingFormat, request.RequestUri.AbsoluteUri), Title = String.Format(LanguageResources.JoinMeContent_DefaultTitle, request.RequestUri.AbsoluteUri) })); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(@"<img src=""{0}"" />", request.RequestUri), Title = request.RequestUri.AbsoluteUri.ToString() })); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(_iframedMeetingFormat, request.RequestUri.AbsoluteUri), Title = "Join Me Meeting: " + request.RequestUri.AbsoluteUri.ToString() })); }
public Task <ContentProviderResult> GetContent(ContentProviderHttpRequest request) { return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(@"<audio controls=""controls"" src=""{0}"">Your browser does not support the audio tag.</audio>", request.RequestUri), Title = request.RequestUri.AbsoluteUri.ToString() })); }
public void SendCatchesOnReceivedExceptions() { var ex = new Exception(); var wh = new ManualResetEventSlim(); var response = new Mock <IResponse>(MockBehavior.Strict); var httpClient = new Mock <IHttpClient>(MockBehavior.Strict); var connection = new Mock <Client.IConnection>(MockBehavior.Strict); using (var mockStream = new MemoryStream()) { using (var sw = new StreamWriter(mockStream)) { sw.Write("{}"); sw.Flush(); mockStream.Position = 0; response.Setup(r => r.GetStream()).Returns(mockStream); response.Setup(r => r.Dispose()); httpClient.Setup(h => h.Post(It.IsAny <string>(), It.IsAny <Action <Client.Http.IRequest> >(), It.IsAny <IDictionary <string, string> >(), false)) .Returns(TaskAsyncHelper.FromResult(response.Object)); connection.Setup(c => c.Trace(TraceLevels.Messages, It.IsAny <string>(), It.IsAny <object[]>())); connection.SetupGet(c => c.Url).Returns(""); connection.SetupGet(c => c.Protocol).Returns(new Version()); connection.SetupGet(c => c.QueryString).Returns(""); connection.SetupGet(c => c.ConnectionToken).Returns(""); connection.SetupGet(c => c.JsonSerializer).Returns(JsonSerializer.CreateDefault()); connection.Setup(c => c.OnReceived(It.IsAny <JToken>())).Throws(ex); connection.Setup(c => c.OnError(It.IsAny <AggregateException>())).Callback <Exception>(e => { Assert.Equal(ex, e.InnerException); wh.Set(); }); var httpBasedTransport = new Mock <HttpBasedTransport>(httpClient.Object, "") { CallBase = true }; httpBasedTransport.Object.Send(connection.Object, "", null).ContinueWith(sendTask => { Assert.True(sendTask.IsFaulted); Assert.IsType(typeof(AggregateException), sendTask.Exception); Assert.Equal(ex, sendTask.Exception.InnerException); Assert.True(wh.Wait(TimeSpan.FromSeconds(1))); }).Wait(); response.VerifyAll(); httpClient.VerifyAll(); connection.VerifyAll(); } } }
public Task <ContentProviderResult> GetContent(ContentProviderHttpRequest request) { string url = request.RequestUri.ToString(); return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(@"<audio controls=""controls"" src=""{1}"">{0}</audio>", LanguageResources.AudioTagSupportRequired, Encoder.HtmlAttributeEncode(url)), Title = request.RequestUri.AbsoluteUri })); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { string url = request.RequestUri.ToString(); return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(@"<img src=""proxy?url={0}"" />", Encoder.HtmlAttributeEncode(url)), Title = url })); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { string id = request.RequestUri.AbsoluteUri.Split('/').Last(); return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(@"<img src=""https://i.imgur.com/{0}.png"" />", id), Title = request.RequestUri.AbsoluteUri })); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { var spotifyUri = ExtractSpotifyUri(request.RequestUri.AbsolutePath); return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format("<iframe src=\"https://embed.spotify.com/?uri=spotify:{0}\" width=\"300\" height=\"380\" frameborder=\"0\" allowtransparency=\"true\"></iframe>", spotifyUri), Title = String.Format("spotify:track:{0}", spotifyUri) })); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { string format = "<video width=\"640\" height=\"360\" preload=\"none\" controls=\"\" style=\"display: block;\"><source src=\"{0}\" type=\"{1}\">Sorry, you don't have HTML5 video, but you can try to view it directly: <a href=\"{0}\">{0}</a></video>"; string href = request.RequestUri.ToString(); return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(format, Encoder.HtmlAttributeEncode(href), Encoder.HtmlAttributeEncode(GetContentType(request.RequestUri))), Title = href })); }
public static Task <List <T> > ToListAsync <T>(this IQueryable <T> source) { try { // HACK: ZOMG we should make this more efficient return(System.Data.Entity.QueryableExtensions.ToListAsync(source)); } catch { return(TaskAsyncHelper.FromResult(source.ToList())); } }
public override async System.Threading.Tasks.Task <object> ExecuteInsertAsync <T>(Database db, DbCommand cmd, string primaryKeyName, bool useOutputClause, T poco, object[] args) { if (primaryKeyName != null) { AdjustSqlInsertCommandText(cmd, primaryKeyName); return(await db.ExecuteScalarHelperAsync(cmd)); } await db.ExecuteNonQueryHelperAsync(cmd); return(TaskAsyncHelper.FromResult <object>(-1)); }
public Task <ContentProviderResult> ExtractResource(string url) { Uri resultUrl; if (Uri.TryCreate(url, UriKind.Absolute, out resultUrl)) { var request = new ContentProviderHttpRequest(resultUrl); return(ExtractContent(request)); } return(TaskAsyncHelper.FromResult <ContentProviderResult>(null)); }
public async Task FailedHubCallbackDueToReconnectFollowedByInvoke() { // Arrange var testTcs = new TaskCompletionSource <object>(); var crashTcs = new TaskCompletionSource <object>(); var connection = new HubConnection("http://test"); var transport = new Mock <IClientTransport>(); transport.Setup(t => t.Negotiate(connection, /* connectionData: */ It.IsAny <string>())) .Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = connection.Protocol.ToString(), ConnectionId = "Something", DisconnectTimeout = 120 })); transport.Setup(t => t.Start(connection, /* connectionData: */ It.IsAny <string>(), /* disconnectToken: */ It.IsAny <CancellationToken>())) .Returns(TaskAsyncHelper.Empty); transport.Setup(t => t.Send(connection, /* data: */ It.Is <string>(s => s.IndexOf("crash") >= 0), /* connectionData: */ It.IsAny <string>())) .Returns(crashTcs.Task) // We want this task to never complete as the call to EnsureReconnecting will do it for us .Callback(() => { Task.Run(() => { try { // EnsureReconnecting will change the state and ultimately clear the pending invocation callbacks connection.EnsureReconnecting(); testTcs.TrySetResult(null); } catch (Exception ex) { testTcs.SetException(ex); } }); }); var proxy = new HubProxy(connection, "test"); // Act await connection.Start(transport.Object); var crashTask = proxy.Invoke("crash"); var ignore = crashTask.ContinueWith(t => proxy.Invoke("test"), TaskContinuationOptions.ExecuteSynchronously); // We need to ensure this executes sync so we're on the same stack // Assert await Assert.ThrowsAnyAsync <InvalidOperationException>(async() => await crashTask.OrTimeout()); await testTcs.Task.OrTimeout(); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { var parameters = ExtractParameters(request.RequestUri); return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(_gitHubIssuesContentFormat, parameters[1], String.Format(_gitHubIssuesApiFormat, parameters[0], parameters[1]) ), Title = request.RequestUri.AbsoluteUri })); }
public void TestCallWithResultAsync() { Guid inParam1 = Guid.NewGuid(); bool invoked = false; _fixture.HubProxyMock.SetupCallback <Guid>(args => invoked = true) .Returns <string, object[]>((methodName, args) => TaskAsyncHelper.FromResult((Guid)args[0])); Guid outParam1 = _fixture.Proxy.CallAsync(hub => hub.ReturnGuid(inParam1)).Result; invoked.Should().BeTrue(TestConsts.ERR_PROXY_INVOKED_CORRECTLY); outParam1.Should().Be(inParam1, TestConsts.ERR_PROXY_ROUTE_CORRECTLY); }
public virtual Func <IHubIncomingInvokerContext, Task <object> > BuildIncoming(Func <IHubIncomingInvokerContext, Task <object> > invoke) { return(context => { if (OnBeforeIncoming(context)) { return invoke(context).OrEmpty() .Then(result => OnAfterIncoming(result, context)) .Catch(ex => OnIncomingError(ex, context)); } return TaskAsyncHelper.FromResult <object>(null); }); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { string packageName = ExtractPackageName(request.RequestUri); if (!String.IsNullOrEmpty(packageName)) { return(FetchPackage(packageName).Then(package => { if (package != null && package.d.results.Count > 0) { var packageInfo = package.d.results[0]; var projectIcon = String.Empty; if (packageInfo.IconUrl != null) { projectIcon = String.Format("<img class=\"nuget-projecticon\" src=\"{0}\" />", packageInfo.IconUrl); } var projectInfo = new StringBuilder(); projectInfo.AppendFormat("<div class=\"nuget-authors\" ><span>Authors: </span><div class=\"nuget-authors-entry\">{0}</div></div>", packageInfo.Authors); projectInfo.AppendFormat("<div class=\"nuget-downloads\" ><span># Downloads:</span> {0}</div>", packageInfo.DownloadCount); if (packageInfo.ProjectUrl != null) { projectInfo.AppendFormat( "<div class=\"nuget-ProjectUrl\" ><a target=\"_blank\" href=\"{0}\">{0}</a></div>", packageInfo.ProjectUrl); } return new ContentProviderResult() { Content = String.Format(_nugetBadgeFormat, packageInfo.Id, packageInfo.Title, packageInfo.Summary, projectIcon, packageInfo.Description, projectInfo), Title = packageInfo.Title + " NuGet package" }; } return null; })); } return(TaskAsyncHelper.FromResult <ContentProviderResult>(null)); }
public void UncleanDisconnectFiresOnDisconnected() { // Arrange var context = new TestContext("/", new Dictionary <string, string> { { "connectionToken", "1" } }); 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.MockHttpContext.Object)).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); var connection = new Mock <PersistentConnection>() { CallBase = true }; var onDisconnectedCalled = false; connection.Protected().Setup("OnDisconnected", context.MockRequest.Object, "1", false).Callback(() => { onDisconnectedCalled = true; }); var sp = ServiceProviderHelper.CreateServiceProvider(services => { services.AddInstance <ITransportManager>(transportManager.Object); services.AddInstance <IProtectedData>(protectedData.Object); }); connection.Object.Initialize(sp); // Act connection.Object.ProcessRequest(context.MockHttpContext.Object).Wait(); transport.Object.Disconnected(/* clean: */ false); // Assert Assert.True(onDisconnectedCalled); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { var args = ExtractParameters(request.RequestUri); if (args == null || !args.Any()) { return(TaskAsyncHelper.FromResult <ContentProviderResult>(null)); } return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(MediaFormatString, args.ToArray()), Title = request.RequestUri.AbsoluteUri.ToString() })); }
public static Task <int> ExecuteNonQueryAsync(this IDbCommand command) { var sqlCommand = command as SqlCommand; if (sqlCommand != null) { return(Task.Factory.FromAsync( (cb, state) => sqlCommand.BeginExecuteNonQuery(cb, state), iar => sqlCommand.EndExecuteNonQuery(iar), null)); } else { return(TaskAsyncHelper.FromResult(command.ExecuteNonQuery())); } }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { var match = TwitPicUrlRegex.Match(request.RequestUri.AbsoluteUri); if (match.Success) { var id = match.Groups["Id"].Value; return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(_twitPicFormatString, id), Title = request.RequestUri.AbsoluteUri })); } return(TaskAsyncHelper.FromResult <ContentProviderResult>(null)); }
public void FailsIfProtocolVersionIsNull() { var connection = new Connection("http://test"); var transport = new Mock <IClientTransport>(); transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = null })); var aggEx = Assert.Throws <AggregateException>(() => connection.Start(transport.Object).Wait()); var ex = aggEx.Unwrap(); Assert.IsType(typeof(InvalidOperationException), ex); Assert.Equal("Incompatible protocol version.", ex.Message); }
protected override Task <ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { string id = request.RequestUri.AbsoluteUri.Split('/').Last(); string format = @"<img src=""https://i.imgur.com/{0}.jpg"" />"; if (_config.ProxyImages) { format = @"<img src=""proxy?url=http://i.imgur.com/{0}.jpg"" />"; } return(TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(format, id), Title = request.RequestUri.AbsoluteUri })); }