public PendingPublish(ConnectionContext connectionContext, string exchange, ulong publishTag) { _connectionContext = connectionContext; _exchange = exchange; _publishTag = publishTag; _source = new TaskCompletionSource<ulong>(); }
public JsonResult GetRoles(string id) { var usr = Membership.GetUser(id); if (usr == null) return Json(null); using (var db = new ConnectionContext()) { var roles = Roles.GetRolesForUser(usr.UserName); var roleChecks = from x in db.Facults orderby x.FacultId select new RoleCheck { Name = x.Name, RoleCheckId = SqlFunctions.StringConvert((double)x.FacultId).Trim(), IsChecked = roles.Contains(SqlFunctions.StringConvert((double)x.FacultId).Trim()) }; var model = new Member { UserName = usr.UserName, RoleChecks = (roleChecks).ToList() }; model.RoleChecks.Add(new RoleCheck { Name = "Администратор", RoleCheckId = StaticData.AdminRoleName, IsChecked = Roles.IsUserInRole(usr.UserName, StaticData.AdminRoleName), }); return Json(model); } }
public ConnectionContext(ConnectionContext context) : base(context) { SocketInput = context.SocketInput; SocketOutput = context.SocketOutput; ConnectionControl = context.ConnectionControl; }
public MessageSessionAsyncHandler(ConnectionContext context, ITaskSupervisor supervisor, ISessionReceiver receiver, MessageSession session, BrokeredMessage message) { _context = context; _supervisor = supervisor; _receiver = receiver; _session = session; _message = message; }
public Channel<ConnectionContext> GetChannel(ConnectionContext context) { string requestUri = context.GetRequestUri(); Match match = _uriPatternMatcher.Match(requestUri); if (false == match.Success || false == _verbsSupported.Contains(context.Request.HttpMethod)) return null; return CreateChannel(context); }
static IEnumerable<ValueProvider> GetProvidersForConnection(ConnectionContext connectionContext) { if (connectionContext.Request.Cookies.Count > 0) yield return GetCookieCollection(connectionContext.Request); if (connectionContext.Request.ContentType.StartsWith("application/json")) yield return new JsonValueProvider(connectionContext.Request.InputStream); if (connectionContext.Request.QueryString.Count > 0) yield return GetQueryStringCollection(connectionContext.Request); if (connectionContext.Request.Headers.Count > 0) yield return GetHeaderCollection(connectionContext.Request); yield return new RequestContextValueProvider(connectionContext.Request); }
public SessionReceiver(ConnectionContext context, QueueClient queueClient, Uri inputAddress, IPipe<ReceiveContext> receivePipe, ReceiveSettings receiveSettings, IReceiveObserver receiveObserver, ITaskSupervisor supervisor) { _queueClient = queueClient; _inputAddress = inputAddress; _receivePipe = receivePipe; _receiveSettings = receiveSettings; _receiveObserver = receiveObserver; _participant = supervisor.CreateParticipant($"{TypeMetadataCache<Receiver>.ShortName} - {inputAddress}", Stop); var options = new SessionHandlerOptions { AutoComplete = false, AutoRenewTimeout = receiveSettings.AutoRenewTimeout, MaxConcurrentSessions = receiveSettings.MaxConcurrentCalls, MessageWaitTimeout = receiveSettings.MessageWaitTimeout }; options.ExceptionReceived += (sender, x) => { if (!(x.Exception is OperationCanceledException)) { if (_log.IsErrorEnabled) _log.Error($"Exception received on session receiver: {_inputAddress} during {x.Action}", x.Exception); } if (_currentPendingDeliveryCount == 0) { if (_log.IsDebugEnabled) _log.DebugFormat("Session receiver shutdown completed: {0}", _inputAddress); _participant.SetComplete(); } }; IMessageSessionAsyncHandlerFactory handlerFactory = new MessageSessionAsyncHandlerFactory(context, supervisor, this); queueClient.RegisterSessionHandlerFactoryAsync(handlerFactory, options); _participant.SetReady(); }
public Receiver(ConnectionContext context, MessageReceiver messageReceiver, Uri inputAddress, IPipe<ReceiveContext> receivePipe, ReceiveSettings receiveSettings, IReceiveObserver receiveObserver, ITaskSupervisor supervisor) { _context = context; _messageReceiver = messageReceiver; _inputAddress = inputAddress; _receivePipe = receivePipe; _receiveSettings = receiveSettings; _receiveObserver = receiveObserver; _participant = supervisor.CreateParticipant($"{TypeMetadataCache<Receiver>.ShortName} - {inputAddress}", Stop); var options = new OnMessageOptions { AutoComplete = false, AutoRenewTimeout = receiveSettings.AutoRenewTimeout, MaxConcurrentCalls = receiveSettings.MaxConcurrentCalls }; options.ExceptionReceived += (sender, x) => { if (!(x.Exception is OperationCanceledException)) { if (_log.IsErrorEnabled) _log.Error($"Exception received on receiver: {_inputAddress} during {x.Action}", x.Exception); } if (_currentPendingDeliveryCount == 0) { if (_log.IsDebugEnabled) _log.DebugFormat("Receiver shutdown completed: {0}", _inputAddress); _participant.SetComplete(); } }; messageReceiver.OnMessageAsync(OnMessage, options); _participant.SetReady(); }
RabbitMqModelContext(ConnectionContext connectionContext, IModel model, IRabbitMqHost host, ITaskParticipant participant) : base(new PayloadCacheScope(connectionContext)) { _connectionContext = connectionContext; _model = model; _host = host; _participant = participant; _published = new ConcurrentDictionary<ulong, PendingPublish>(); _taskScheduler = new LimitedConcurrencyLevelTaskScheduler(1); _model.ModelShutdown += OnModelShutdown; _model.BasicAcks += OnBasicAcks; _model.BasicNacks += OnBasicNacks; _model.BasicReturn += OnBasicReturn; if (host.Settings.PublisherConfirmation) { _model.ConfirmSelect(); } _participant.SetReady(); }
/// <summary> /// Assigns aSource to this instance of <see cref="UserToken"/>. /// </summary> /// <param name="aSource">A source object.</param> public override void AssignFromSource(object aSource) { if (!(aSource is AdminToken)) { throw new ArgumentException("Invalid Assignment Source for AdminToken"); } _userID = (aSource as AdminToken)._userID; _password = (aSource as AdminToken)._password; _url = (aSource as AdminToken)._url; _method = (aSource as AdminToken)._method; _context = (aSource as AdminToken)._context; _version = (aSource as AdminToken)._version; }
protected abstract Channel<ConnectionContext> CreateChannel(ConnectionContext context);
public Task OnConnectionAsync(ConnectionContext context) { return(Task.Run(() => InnerOnConnectionAsync(context))); }
public override async Task OnConnectedAsync(ConnectionContext connection) { var protocol = new MessageReaderWriter(); var reader = connection.CreateReader(); var writer = connection.CreateWriter(); var connectionTopics = new List <string>(); try { while (true) { var result = await reader.ReadAsync(protocol); var message = result.Message; if (result.IsCompleted) { break; } switch (message.MessageType) { case MessageType.Publish: { if (_topics.TryGetValue(message.Topic, out var topic)) { var data = new Message { MessageType = MessageType.Data, Payload = message.Payload, Topic = message.Topic }; topic.IncrementPublish(); // TODO: Use WhenAll foreach (var pair in topic) { await pair.Value.WriteAsync(protocol, data); } } await writer.WriteAsync(protocol, new Message { Id = message.Id, Topic = message.Topic, MessageType = MessageType.Success }); } break; case MessageType.Subscribe: { var topic = _topics.GetOrAdd(message.Topic); topic.Add(connection.ConnectionId, writer); connectionTopics.Add(message.Topic); await writer.WriteAsync(protocol, new Message { Id = message.Id, Topic = message.Topic, MessageType = MessageType.Success }); } break; case MessageType.Unsubscribe: { RemoveTopic(connection, connectionTopics, message.Topic); await writer.WriteAsync(protocol, new Message { Id = message.Id, Topic = message.Topic, MessageType = MessageType.Success }); } break; default: break; } reader.Advance(); } } finally { for (int i = connectionTopics.Count - 1; i >= 0; i--) { RemoveTopic(connection, connectionTopics, connectionTopics[i]); } } }
public RabbitMqModelContext(ConnectionContext connectionContext, IModel model, ITaskScope taskScope, IRabbitMqHost host) : this(connectionContext, model, host, taskScope.CreateParticipant($"{TypeMetadataCache<RabbitMqModelContext>.ShortName} - {connectionContext.HostSettings.ToDebugString()}")) { }
public WebSocketProtocol(WebSocket websocket, ConnectionContext connection) { WebSocket = websocket; Connection = connection; }
public static MockHubConnectionContext CreateMock(ConnectionContext connection) { return(new MockHubConnectionContext(connection, TimeSpan.FromSeconds(15), NullLoggerFactory.Instance, TimeSpan.FromSeconds(15))); }
static void Main(string[] args) { Console.WriteLine("Main: {0}", Thread.CurrentThread.ManagedThreadId); // Use the factory LibuvTransportContext transport = new LibuvTransportContext { Options = new LibuvTransportOptions(), AppLifetime = new ApplicationLifetime(null), Log = new LibuvTrace(LoggerFactory.Create(builder => { builder.AddConsole(); }).CreateLogger("core")) }; LibuvThread uvThread = new LibuvThread(libUv, transport); uvThread.StartAsync().Wait(); Task.Run(async() => { Console.WriteLine("NIO: {0}", Thread.CurrentThread.ManagedThreadId); LibuvConnectionListener listener = new LibuvConnectionListener(libUv, transport, new IPEndPoint(IPAddress.Parse("0.0.0.0"), 2593)); Console.WriteLine("Binding... ({0})", Thread.CurrentThread.ManagedThreadId); await listener.BindAsync(); Console.WriteLine("Listening... ({0})", Thread.CurrentThread.ManagedThreadId); ConnectionContext connectionContext = await listener.AcceptAsync(); Console.WriteLine("Accepted Connection from {0}", connectionContext.RemoteEndPoint); PipeReader reader = connectionContext.Transport.Input; while (true) { ReadResult readResult = await reader.ReadAsync(); int packetId = readResult.Buffer.FirstSpan[0]; Console.WriteLine($"[0x{packetId:X}] Processing Packet"); int length = PacketLengths[packetId]; int bodyLength = length - 1; int bodyStart = 1; if (length == 0) { length = BinaryPrimitives.ReadUInt16BigEndian(readResult.Buffer.FirstSpan.Slice(1, 2)); bodyLength = length - 3; bodyStart = 3; } else if (length == 0xFFFF) { Console.WriteLine($"[0x{packetId:X}] Unknown Packet"); throw new Exception($"[0x{packetId:X}] Unknown Packet"); } Console.WriteLine($"[0x{packetId:X}] Found length {length}"); Console.WriteLine($"Packet Data: {ByteArrayToString(readResult.Buffer.FirstSpan.ToArray()):X}"); Memory <byte> mem = new Memory <byte>(readResult.Buffer.FirstSpan.Slice(bodyStart, bodyLength).ToArray()); Console.WriteLine($"[0x{packetId:X}] Buffer length {mem.Length}"); _ = uvThread.PostAsync((Tuple <ConnectionContext, Memory <byte> > t) => { // stuff var(conn, mem) = t; // Do stuff wtih memOwner.Memory.Span; Console.WriteLine($"Packet ID: 0x{packetId:X} - Length: {length} - Data: 0x{ByteArrayToString(mem.ToArray())}"); }, Tuple.Create(connectionContext, mem)); reader.AdvanceTo(readResult.Buffer.GetPosition(length)); } }); // Manually putting something on the queue from another thread (or the main thread) uvThread.PostAsync <object>(_ => { Console.WriteLine("Game: {0}", Thread.CurrentThread.ManagedThreadId); }, null); // Send an Initialization Request for Timers /* * uvThread.PostAsync<object>(_ => * { * UvTimerHandle timerHandle = new UvTimerHandle(null); * timerHandle.Init(uvThread.Loop, (callback, handle) => * { * Console.WriteLine("Closed ({0})", Thread.CurrentThread.ManagedThreadId); * }); * Console.WriteLine("Timer Stuff {0}", Thread.CurrentThread.ManagedThreadId); * int count = 10; * void cb2(UvTimerHandle handle) * { * Console.WriteLine("Called!2 {0} ({1})", DateTime.Now, Thread.CurrentThread.ManagedThreadId); * timerHandle.Start(cb2, 2000, 0); * } * void cb1(UvTimerHandle handle) * { * Console.WriteLine("Called!1 {0} ({1})", DateTime.Now, Thread.CurrentThread.ManagedThreadId); * count--; * if (count < 0) * timerHandle.Start(cb2, 2000, 0); * else * timerHandle.Start(cb1, 1000, 0); * } * timerHandle.Start(cb1, 1000, 0); * }, null); */ Console.ReadLine(); }
/// <summary> /// Gets the <see cref="HttpContext"/> associated with the connection, if there is one. /// </summary> /// <param name="connection">The <see cref="ConnectionContext"/> representing the connection.</param> /// <returns>The <see cref="HttpContext"/> associated with the connection, or <see langword="null"/> if the connection is not HTTP-based.</returns> /// <remarks> /// SignalR connections can run on top of HTTP transports like WebSockets or Long Polling, or other non-HTTP transports. As a result, /// this method can sometimes return <see langword="null"/> depending on the configuration of your application. /// </remarks> public static HttpContext?GetHttpContext(this ConnectionContext connection) { return(connection.Features.Get <IHttpContextFeature>()?.HttpContext); }
public override async Task OnConnectedAsync(ConnectionContext connection) { while (await connection.Transport.In.WaitToReadAsync()) { } }
public Channel <ConnectionContext> GetChannel(ConnectionContext message) { return(new BadRequestChannel()); }
public override Task OnConnectedAsync(ConnectionContext connection) { return(Task.CompletedTask); }
public override Task OnConnectedAsync(ConnectionContext connection) { throw new InvalidOperationException(); }
public override Task OnConnectedAsync(ConnectionContext connection) { connection.Transport.In.WaitToReadAsync().Wait(); return(Task.CompletedTask); }
public override Task OnConnectedAsync(ConnectionContext connection) { var tcs = new TaskCompletionSource <object>(); return(tcs.Task); }
/// <summary> /// Returns a number expressing how closely the given shape matches the given context. /// /// Precondition: context is nonempty. /// </summary> /// <param name="shape"></param> /// <param name="context"></param> /// <returns>a double in the range [0, 1], where 1 represents a perfect match</returns> public double PercentMatched(Shape shape, ConnectionContext context) { List <string> neighborClasses = shape.ExternalConnectedShapes.ConvertAll(delegate(Shape s) { return(s.Classification); }); return(PercentMatched(shape, context, neighborClasses)); }
protected override Task DisposeConnection(ConnectionContext connection) { return(Task.CompletedTask); }
public DomainContext() { _ctx = new ConnectionContext(); }
public static WebSocketProtocol CreateFromConnection(ConnectionContext connection, bool isServer, string subProtocol, TimeSpan keepAliveInterval) { var websocket = WebSocket.CreateFromStream(new DuplexPipeStream(connection.Transport.Input, connection.Transport.Output), isServer, subProtocol, keepAliveInterval); return(new WebSocketProtocol(websocket, connection)); }
public byte[] BuildMessage(object obj, ConnectionContext context) { return(Encoding.ASCII.GetBytes(obj as string)); }
void ConnectionComplete(ConnectionContext connectionContext) { connectionContext.End(); int count = Interlocked.Decrement(ref _connectionCount); if (_closing) { if (count == 0) ShutdownListener(); } }
public MessageSessionAsyncHandlerFactory(ConnectionContext context, ITaskSupervisor supervisor, ISessionReceiver receiver) { _context = context; _supervisor = supervisor; _receiver = receiver; }
public SqlExecutionResult[] Run(ConnectionContext scriptExecutionContext, params DbParameter[] sqlParameters) { return SqlDatabaseTestClass.TestService.Execute(scriptExecutionContext, scriptExecutionContext, _action, sqlParameters); }
public (SslServerAuthenticationOptions, ClientCertificateMode) GetOptions(ConnectionContext connection, string serverName) { SniOptions?sniOptions = null; if (!string.IsNullOrEmpty(serverName) && !_exactNameOptions.TryGetValue(serverName, out sniOptions)) { foreach (var(suffix, options) in _wildcardPrefixOptions) { if (serverName.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { sniOptions = options; break; } } } // Fully wildcarded ("*") options can be used even when given an empty server name. sniOptions ??= _wildcardOptions; if (sniOptions is null) { if (serverName is null) { // There was no ALPN throw new AuthenticationException(CoreStrings.FormatSniNotConfiguredToAllowNoServerName(_endpointName)); } else { throw new AuthenticationException(CoreStrings.FormatSniNotConfiguredForServerName(serverName, _endpointName)); } } connection.Features.Set(new HttpProtocolsFeature(sniOptions.HttpProtocols)); var sslOptions = sniOptions.SslOptions; if (sslOptions.ServerCertificate is null) { Debug.Assert(_fallbackServerCertificateSelector != null, "The cached SniOptions ServerCertificate can only be null if there's a fallback certificate selector."); // If a ServerCertificateSelector doesn't return a cert, HttpsConnectionMiddleware doesn't fallback to the ServerCertificate. sslOptions = CloneSslOptions(sslOptions); var fallbackCertificate = _fallbackServerCertificateSelector(connection, serverName); if (fallbackCertificate != null) { HttpsConnectionMiddleware.EnsureCertificateIsAllowedForServerAuth(fallbackCertificate); } sslOptions.ServerCertificate = fallbackCertificate; } if (_onAuthenticateCallback != null) { // From doc comments: "This is called after all of the other settings have already been applied." sslOptions = CloneSslOptions(sslOptions); _onAuthenticateCallback(connection, sslOptions); } return(sslOptions, sniOptions.ClientCertificateMode); }
private async Task InnerOnConnectionAsync(ConnectionContext context) { bool certificateRequired; var feature = new TlsConnectionFeature(); context.Features.Set <ITlsConnectionFeature>(feature); context.Features.Set <ITlsHandshakeFeature>(feature); var memoryPool = context.Features.Get <IMemoryPoolFeature>()?.MemoryPool; var inputPipeOptions = new StreamPipeReaderOptions ( pool: memoryPool, bufferSize: memoryPool.GetMinimumSegmentSize(), minimumReadSize: memoryPool.GetMinimumAllocSize(), leaveOpen: true ); var outputPipeOptions = new StreamPipeWriterOptions ( pool: memoryPool, leaveOpen: true ); SslDuplexPipe sslDuplexPipe = null; if (_options.RemoteCertificateMode == RemoteCertificateMode.NoCertificate) { sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions); certificateRequired = false; } else { sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions, s => new SslStream( s, leaveInnerStreamOpen: false, userCertificateValidationCallback: (sender, certificate, chain, sslPolicyErrors) => { if (certificate == null) { return(_options.RemoteCertificateMode != RemoteCertificateMode.RequireCertificate); } if (_options.RemoteCertificateValidation == null) { if (sslPolicyErrors != SslPolicyErrors.None) { return(false); } } var certificate2 = ConvertToX509Certificate2(certificate); if (certificate2 == null) { return(false); } if (_options.RemoteCertificateValidation != null) { if (!_options.RemoteCertificateValidation(certificate2, chain, sslPolicyErrors)) { return(false); } } return(true); })); certificateRequired = true; } var sslStream = sslDuplexPipe.Stream; using (var cancellationTokeSource = new CancellationTokenSource(Debugger.IsAttached ? Timeout.InfiniteTimeSpan : _options.HandshakeTimeout)) { try { // Adapt to the SslStream signature ServerCertificateSelectionCallback selector = null; if (_certificateSelector != null) { selector = (sender, name) => { context.Features.Set(sslStream); var cert = _certificateSelector(context, name); if (cert != null) { EnsureCertificateIsAllowedForServerAuth(cert); } return(cert); }; } var sslOptions = new SslServerAuthenticationOptions { ServerCertificate = _certificate, ServerCertificateSelectionCallback = selector, ClientCertificateRequired = certificateRequired, EnabledSslProtocols = _options.SslProtocols, CertificateRevocationCheckMode = _options.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, ApplicationProtocols = new List <SslApplicationProtocol>() }; _options.OnAuthenticateAsServer?.Invoke(context, sslOptions); await sslStream.AuthenticateAsServerAsync(sslOptions, cancellationTokeSource.Token).ConfigureAwait(false); } catch (OperationCanceledException) { _logger?.LogDebug(2, "Authentication timed out"); await sslStream.DisposeAsync().ConfigureAwait(false); return; } catch (Exception ex) when(ex is IOException || ex is AuthenticationException) { _logger?.LogDebug(1, ex, "Authentication failed"); await sslStream.DisposeAsync().ConfigureAwait(false); return; } } feature.ApplicationProtocol = sslStream.NegotiatedApplicationProtocol.Protocol; context.Features.Set <ITlsApplicationProtocolFeature>(feature); feature.LocalCertificate = ConvertToX509Certificate2(sslStream.LocalCertificate); feature.RemoteCertificate = ConvertToX509Certificate2(sslStream.RemoteCertificate); feature.CipherAlgorithm = sslStream.CipherAlgorithm; feature.CipherStrength = sslStream.CipherStrength; feature.HashAlgorithm = sslStream.HashAlgorithm; feature.HashStrength = sslStream.HashStrength; feature.KeyExchangeAlgorithm = sslStream.KeyExchangeAlgorithm; feature.KeyExchangeStrength = sslStream.KeyExchangeStrength; feature.Protocol = sslStream.SslProtocol; var originalTransport = context.Transport; try { context.Transport = sslDuplexPipe; // Disposing the stream will dispose the sslDuplexPipe await using (sslStream) await using (sslDuplexPipe) { await _next(context).ConfigureAwait(false); // Dispose the inner stream (SslDuplexPipe) before disposing the SslStream // as the duplex pipe can hit an ODE as it still may be writing. } } finally { // Restore the original so that it gets closed appropriately context.Transport = originalTransport; } }
/// <summary> /// TBD /// </summary> protected override void PreStart() { ConnectionContext.Remember(GetConnectionString()); base.PreStart(); }
public ConnectionContextValueProvider(ConnectionContext connectionContext) { _provider = new MultipleValueProvider(GetProvidersForConnection(connectionContext).ToArray()); }
public async override Task OnConnectedAsync(ConnectionContext connection) { await connection.Transport.Writer.WriteAsync(await connection.Transport.Reader.ReadAsync()); }
public FrameContext(ConnectionContext context) : base(context) { }
private static void Complete(ConnectionContext connection) { connection.Transport.Output.Complete(); connection.Transport.Input.Complete(); }
public DomainContext() { _ctx = new ConnectionContext(); }
public MockHubConnectionContext(ConnectionContext connectionContext, TimeSpan keepAliveInterval, ILoggerFactory loggerFactory, TimeSpan clientTimeoutInterval) : base(connectionContext, keepAliveInterval, loggerFactory, clientTimeoutInterval) { }
protected abstract Connection CreateConnection(ConnectionContext context);
/// <summary> /// TBD /// </summary> protected override void PostStop() { base.PostStop(); ConnectionContext.Forget(GetConnectionString()); }
public RabbitMqModelContext(ConnectionContext connectionContext, IModel model, ITaskScope taskScope, IRabbitMqHost host) : this(connectionContext, model, host, taskScope.CreateParticipant($"{TypeMetadataCache<RabbitMqModelContext>.ShortName} - {connectionContext.HostSettings.ToDebugString()}")) { }
public override async Task OnConnectedAsync(ConnectionContext connection) { await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes(_lastWill)); }
public override async Task OnConnectedAsync(ConnectionContext connection) { var ex = await _throwTcs.Task; throw ex; }
public Task DisposeAsync(ConnectionContext connection) { return(_connectionFactory.DisposeAsync(connection)); }