Exemple #1
0
        public SqlServerConnectionFactory(string server, string database, string username = null, string password = null)
        {
            var connectionPropeties = new SqlServerConnectionProperties(server, database, username, password);

            ConnectionProperties = connectionPropeties;
            _connectionString    = ConnectionProperties.ConnectionString;
        }
Exemple #2
0
        public SqlServerConnectionFactory(string connectionString)
        {
            var connectionStringBuilder = new SqlConnectionStringBuilder(connectionString);

            ConnectionProperties = new SqlServerConnectionProperties(connectionStringBuilder.DataSource, connectionStringBuilder.InitialCatalog, connectionStringBuilder.UserID, connectionStringBuilder.Password);
            _connectionString    = ConnectionProperties.ConnectionString;
        }
 internal WsQueueManager(MQQueueManager ibmQm, WsConnectionProperties properties)
 {
     Debug.Assert(ibmQm != null);
     IbmQueueManager      = ibmQm;
     ConnectionProperties = properties;
     _messageAgent        = new WsMessageAgent(ibmQm);
     GC.SuppressFinalize(this);
 }
 public override ValueTask <ConnectionListener> BindAsync(EndPoint endPoint, IConnectionProperties options = null, CancellationToken cancellationToken = default)
 {
     if (cancellationToken.IsCancellationRequested)
     {
         return(ValueTask.FromCanceled <ConnectionListener>(cancellationToken));
     }
     return(new ValueTask <ConnectionListener>(new VirtualConnectionListener(endPoint)));
 }
    internal Data()
    {
        var connection = new ConnectionProperties();

        // Business logic to configure connection
        connection.Name    = "My Connection";
        connection.Enabled = true;
        Connection         = connection;
    }
            internal async ValueTask <Connection> ConnectAsync(EndPoint endPoint, IConnectionProperties options = null, CancellationToken cancellationToken = default)
            {
                var tcs = new TaskCompletionSource <Connection>();
                await _pendingConnects.Writer.WriteAsync(tcs, cancellationToken).ConfigureAwait(false);

                using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, cancellationToken))
                    using (cts.Token.UnsafeRegister(o => ((TaskCompletionSource <Connection>)o).TrySetCanceled(), tcs))
                    {
                        return(await tcs.Task.ConfigureAwait(false));
                    }
            }
    public override async ValueTask <Connection> AcceptAsync(IConnectionProperties options = null, CancellationToken cancellationToken = default)
    {
        if (await AcceptQueue.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
        {
            while (AcceptQueue.Reader.TryRead(out var item))
            {
                return(item);
            }
        }

        return(null);
    }
    internal ValueTask <ConnectionListener> ListenAsync(EndPoint endPoint, IConnectionProperties options = null, CancellationToken cancellationToken = default)
    {
        MemoryConnectionListener listener;

        if (_listeners.TryGetValue(endPoint, out _) ||
            !_listeners.TryAdd(endPoint, listener = new MemoryConnectionListener(endPoint)))
        {
            throw new IOException($"{endPoint} listener already bound");
        }

        return(new ValueTask <ConnectionListener>(listener));
    }
Exemple #9
0
        public async override ValueTask <Connection> ConnectAsync(EndPoint endPoint, IConnectionProperties options = null, CancellationToken cancellationToken = default)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            };

            await socket.ConnectAsync(endPoint).ConfigureAwait(false);

            await socket.SendAsync(this.getRequest, SocketFlags.None);

            byte[] memory    = null;
            var    arrayPool = ArrayPool <byte> .Shared;

            try
            {
                memory = arrayPool.Rent(MaxImdsResponseSize);

                int totalBytesReceived = 0;
                do
                {
                    int bytesReceived = await socket.ReceiveAsync(new ArraySegment <byte>(memory, totalBytesReceived, MaxImdsResponseSize - totalBytesReceived), SocketFlags.None);

                    if (bytesReceived <= 0)
                    {
                        break;
                    }

                    totalBytesReceived += bytesReceived;

                    if (memory[totalBytesReceived - 1] == '\n' && memory[totalBytesReceived - 2] == '\r' && memory[totalBytesReceived - 3] == '\n' && memory[totalBytesReceived - 4] == '\r')
                    {
                        break;
                    }
                } while (totalBytesReceived < MaxImdsResponseSize);

                if (totalBytesReceived == MaxImdsResponseSize)
                {
                    throw new Exception($"Imds Endpoint is invalid, size must be < {MaxImdsResponseSize}");
                }

                return(new SocketConnection(socket, Encoding.ASCII.GetString(memory, 0, totalBytesReceived)));
            }
            finally
            {
                if (memory != null)
                {
                    arrayPool.Return(memory);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Gets a property, throwing an exception if none found.
        /// </summary>
        /// <typeparam name="T">The type of the property to retrieve.</typeparam>
        /// <param name="properties">The <see cref="IConnectionProperties"/> to retrieve the property from.</param>
        /// <param name="propertyKey">The key of the property.</param>
        /// <returns>The value of the retrieved property.</returns>
        public static T GetProperty <T>(this IConnectionProperties properties, ConnectionPropertyKey <T> propertyKey)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            if (properties.TryGetProperty(typeof(T), out object?objectValue) && objectValue is T typedValue)
            {
                return(typedValue);
            }

            throw new Exception($"Property of type '{nameof(T)}' does not exist in this {nameof(IConnectionProperties)}, but is required.");
        }
    internal ValueTask <Connection> ConnectAsync(EndPoint endPoint, IConnectionProperties options, CancellationToken cancellationToken)
    {
        if (!_listeners.TryGetValue(endPoint, out var listener) && !(endPoint is DnsEndPoint dns && _listeners.TryGetValue(new MemoryEndPoint(dns.Host), out listener)))
        {
            throw new InvalidOperationException($"{endPoint} not bound!");
        }

        var(transport, application) = DuplexPipe.CreatePair(new PipeOptions(), new PipeOptions());

        var serverConnection = Connection.FromPipe(transport, localEndPoint: endPoint, remoteEndPoint: endPoint);
        var clientConnection = Connection.FromPipe(application, localEndPoint: endPoint, remoteEndPoint: endPoint);

        listener.AcceptQueue.Writer.TryWrite(serverConnection);
        return(new ValueTask <Connection>(clientConnection));
    }
Exemple #12
0
        public ConnectionDriversConfig LinkConnection2Drivers(IConnectionProperties cn)
        {
            string vr = cn.DriverVersion;
            string pk = cn.DriverName;
            ConnectionDriversConfig retval = DME.ConfigEditor.DataDriversClasses.Where(c => c.PackageName == pk && c.version == vr).FirstOrDefault();

            if (retval == null)
            {
                if (cn.Category == DatasourceCategory.FILE)
                {
                    List <ConnectionDriversConfig> clss = DME.ConfigEditor.DataDriversClasses.Where(p => p.extensionstoHandle != null).ToList();
                    string ext = Path.GetExtension(cn.FileName).Replace(".", "");
                    retval = clss.Where(c => c.extensionstoHandle.Contains(ext)).FirstOrDefault();
                }
            }
            return(retval);
        }
            public override async ValueTask <Connection> AcceptAsync(IConnectionProperties options = null, CancellationToken cancellationToken = default)
            {
                using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, cancellationToken);

                var network          = new VirtualNetwork();
                var serverConnection = new VirtualConnection(network, isServer: true);
                var clientConnection = new VirtualConnection(network, isServer: false);

                while (true)
                {
                    TaskCompletionSource <Connection> tcs = await _pendingConnects.Reader.ReadAsync(cancellationToken);

                    if (tcs.TrySetResult(clientConnection))
                    {
                        return(serverConnection);
                    }
                }
            }
Exemple #14
0
        /// <summary>
        /// Gets a property.
        /// </summary>
        /// <typeparam name="T">The type of the property to retrieve.</typeparam>
        /// <param name="properties">The <see cref="IConnectionProperties"/> to retrieve the property from.</param>
        /// <param name="propertyKey">The key of the property.</param>
        /// <param name="value">The value of the property retrieved.</param>
        /// <returns>
        /// If a property for the given <paramref name="propertyKey"/> was found, true.
        /// Otherwise, false.
        /// </returns>
        public static bool TryGetProperty <T>(this IConnectionProperties properties, ConnectionPropertyKey <T> propertyKey, [MaybeNullWhen(false)] out T value)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            if (properties.TryGetProperty(typeof(T), out object?objectValue) && objectValue is T typedValue)
            {
                value = typedValue;
                return(true);
            }
            else
            {
                value = default;
                return(false);
            }
        }
        /// <summary>
        /// Retrieves a Type-based property from an <see cref="IConnectionProperties"/>, if it exists.
        /// </summary>
        /// <typeparam name="T">The type of the property to retrieve.</typeparam>
        /// <param name="properties">The connection properties to retrieve a property from.</param>
        /// <param name="property">If <paramref name="properties"/> contains a property of type <typeparamref name="T"/>, receives the property. Otherwise, default.</param>
        /// <returns>If <paramref name="properties"/> contains a property of type <typeparamref name="T"/>, true. Otherwise, false.</returns>
        public static bool TryGet <T>(this IConnectionProperties properties, [MaybeNullWhen(false)] out T property)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            if (properties.TryGet(typeof(T), out object?obj) && obj is T propertyValue)
            {
                property = propertyValue;
                return(true);
            }
            else
            {
                property = default;
                return(false);
            }
        }
        public IQueueManager Connect(string name, IConnectionProperties properties)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                {
                    throw new ArgumentNullException(nameof(name));
                }
                if (properties == null)
                {
                    throw new ArgumentNullException(nameof(properties));
                }

                return(ConnectCore(name, (WsConnectionProperties)properties));
            }
            catch (MQException ibmEx)
            {
                throw ibmEx.ToMqException((data) => data.AddOrReplace("Name", name));
            }
        }
 public override ValueTask <ConnectionListener> ListenAsync(EndPoint endPoint, IConnectionProperties options = null, CancellationToken cancellationToken = default)
 {
     return(_memoryTransport.ListenAsync(endPoint, options, cancellationToken));
 }
        /// <summary>
        /// Establishes a new connection for a request.
        /// </summary>
        /// <param name="message">The request causing this connection to be established. Once connected, it may be reused for many subsequent requests.</param>
        /// <param name="endPoint">The EndPoint to connect to.</param>
        /// <param name="options">Properties, if any, that might change how the connection is made.</param>
        /// <param name="cancellationToken">A cancellation token for the asynchronous operation.</param>
        /// <returns>A new open connection.</returns>
        public virtual async ValueTask <Connection> EstablishConnectionAsync(HttpRequestMessage message, EndPoint?endPoint, IConnectionProperties options, CancellationToken cancellationToken)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (endPoint == null)
            {
                throw new ArgumentNullException(nameof(endPoint));
            }

            Socket socket = CreateSocket(message, endPoint, options);

            try
            {
                using var args      = new TaskSocketAsyncEventArgs();
                args.RemoteEndPoint = endPoint;

                if (socket.ConnectAsync(args))
                {
                    using (cancellationToken.UnsafeRegister(o => Socket.CancelConnectAsync((SocketAsyncEventArgs)o !), args))
                    {
                        await args.Task.ConfigureAwait(false);
                    }
                }

                if (args.SocketError != SocketError.Success)
                {
                    Exception ex = args.SocketError == SocketError.OperationAborted && cancellationToken.IsCancellationRequested
                        ? (Exception) new OperationCanceledException(cancellationToken)
                        : new SocketException((int)args.SocketError);

                    throw ex;
                }

                socket.NoDelay = true;
                return(new SocketConnection(socket));
            }
            catch
            {
                socket.Dispose();
                throw;
            }
        }
 /// <summary>
 /// Creates the socket to be used for a request.
 /// </summary>
 /// <param name="message">The request causing this socket to be opened. Once opened, it may be reused for many subsequent requests.</param>
 /// <param name="endPoint">The EndPoint this socket will be connected to.</param>
 /// <param name="options">Properties, if any, that might change how the socket is initialized.</param>
 /// <returns>A new unconnected socket.</returns>
 public virtual Socket CreateSocket(HttpRequestMessage message, EndPoint?endPoint, IConnectionProperties options)
 {
     return(new Socket(SocketType.Stream, ProtocolType.Tcp));
 }
Exemple #20
0
            protected override Socket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, EndPoint endPoint, IConnectionProperties options)
            {
                Socket socket = new Socket(addressFamily, socketType, protocolType);

                if (options.TryGet(out CustomConnectionOptionsValues vals))
                {
                    socket.NoDelay  = vals.NoDelay;
                    socket.DualMode = vals.DualMode;
                }

                return(socket);
            }
Exemple #21
0
 public IQueueManager ConnectQueueManager(string qmName, IConnectionProperties cp = null)
 {
     return(cp == null?_mqFactory.Connect(qmName) : _mqFactory.Connect(qmName, cp));
 }
 public virtual Socket CreateSocket(HttpRequestMessage message, EndPoint?endPoint, IConnectionProperties options)
 => throw new NotImplementedException();
 public virtual ValueTask <Connection> EstablishConnectionAsync(HttpRequestMessage message, EndPoint?endPoint, IConnectionProperties options, CancellationToken cancellationToken)
 => throw new NotImplementedException();
Exemple #24
0
 public SqlServerConnectionFactory(IConnectionProperties connectionPropeties)
 {
     ConnectionProperties = connectionPropeties;
     _connectionString    = ConnectionProperties.ConnectionString;
 }
Exemple #25
0
        public static DbDelegator Create(IConnectionProperties connectionProperties, IDelegatorBus dataBus = null)
        {
            var f = new SqlServerConnectionFactory(connectionProperties);

            return(new DbDelegator(f, dataBus));
        }