コード例 #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            services.AddDbContext <ProjectDbContext>(x => x.UseMySQL(ConnectionExtensions.GetConnectionString()));
        }
コード例 #2
0
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     if (!optionsBuilder.IsConfigured)
     {
         optionsBuilder.UseMySQL(ConnectionExtensions.GetConnectionString());
     }
 }
コード例 #3
0
        public void SqlJoin_WhenBuilderIsNull_ThrowsException()
        {
            Action action = () => ConnectionExtensions.SqlJoin <ObjectGraphType>(null, null);

            action.Should()
            .Throw <ArgumentNullException>()
            .Which.ParamName.Should()
            .Be("builder");
        }
コード例 #4
0
        protected override void OnBeforeAbort(IConnection connection)
        {
            // Get the reader from the connection and stop it
            AsyncStreamReader _reader = ConnectionExtensions.GetValue <AsyncStreamReader>(connection, m_readerKey);

            if (_reader != null)
            {
                // Stop reading data from the stream
                _reader.StopReading(false);

                // Remove the reader
                connection.Items.Remove(m_readerKey);
            }
        }
コード例 #5
0
        public void Stop(IConnection connection)
        {
            var _httpRequest = ConnectionExtensions.GetValue <IRequest>(connection, c_httpRequestKey);

            if (_httpRequest != null)
            {
                try
                {
                    OnBeforeAbort(connection);
                    _httpRequest.Abort();
                }
                catch (NotImplementedException)
                {
                    // If this isn't implemented then do nothing
                }
            }
        }
コード例 #6
0
        public static void RunHttpsFiddle()
        {
            var fiddleSvr  = new TcpServer(8699);
            var httpClient = HttpClient.Default.UseTimeout();//HttpClient.Create()

            fiddleSvr.UseHttp(
                (options) => {
                options.KeepAliveTimeout = 0;
                options.ReceiveTimeout   = 0;
                options.SendTimeout      = 0;
            },
                (req) => {
                Console.WriteLine($"Fiddle:{req.Url}");
                return(httpClient.SendAsync(req));
            });
            var hosts = new ConcurrentDictionary <int, string>();
            var certs = new ConcurrentDictionary <string, X509Certificate>();

            fiddleSvr.Use(async(conn, handler) => {
                var remotePort = ((System.Net.IPEndPoint)conn.RemoteEndPoint).Port;
                string host;
                var spinWait = new SpinWait();
                do
                {
                    spinWait.SpinOnce();
                } while (!hosts.TryGetValue(remotePort, out host));
                hosts.TryRemove(remotePort, out _);

                if (!certs.TryGetValue(host, out var cert))
                {
                    lock (certs)//OR no lock
                    {
                        if (!certs.TryGetValue(host, out cert))
                        {
                            var rootCert = new X509Certificate2(@"MyCA-Root.pfx", "123456");//install
                            using (var rsa = RSA.Create(2048))
                            {
                                var certReq = new CertificateRequest($"CN={host}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                                certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
                                certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.KeyEncipherment, true));
                                var altName = new SubjectAlternativeNameBuilder();
                                altName.AddDnsName(host);
                                certReq.CertificateExtensions.Add(altName.Build(true));
                                var serialBuf = new byte[16];
                                RandomNumberGenerator.Fill(serialBuf.AsSpan(1));
                                var signCert = certReq.Create(rootCert, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1), serialBuf);//notAfter<rootCert
                                cert         = signCert.CopyWithPrivateKey(rsa);
                                cert         = new X509Certificate2(cert.Export(X509ContentType.Pfx, "123456"), "123456");
                                certs.TryAdd(host, cert);
                            }
                        }
                    }
                }
                var sslOptions = new SslServerAuthenticationOptions()
                {
                    ServerCertificate              = cert,//cert
                    EnabledSslProtocols            = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
                    AllowRenegotiation             = false,
                    CertificateRevocationCheckMode = X509RevocationMode.NoCheck,
                    ClientCertificateRequired      = false
                };
                var ssl = await conn.UseSslAsync(sslOptions);//handShakeTimeout
                await handler.HandleAsync(ssl);
            });
            fiddleSvr.Start();

            var proxySvr = new TcpServer(9699);

            proxySvr.UseHttp(
                (options) => {
                //options.KeepAliveTimeout = 0;
            },
                (req) => {
                return(httpClient.SendAsync(req));
            });
            proxySvr.Use(async(conn, handler) => {
                var req = new HttpRequest();
                await conn.ReceiveAsync(req);
                if (req.Method == HttpMethod.Connect)
                {
                    await req.Content.DrainAsync();
                    var resp = new HttpResponse()
                    {
                        StatusCode   = 200,
                        ReasonPhrase = "Connection Established"
                    };
                    await conn.SendAsync(resp, req);
                    req.Dispose();                                                                         //try finally
                    resp.Dispose();
                    var proxyClient = ClientConnection.Create("localhost", 8699, out var proxyDisposable); //fiddleSvr
                    await proxyClient.OpenAsync();
                    var localPort = ((System.Net.IPEndPoint)proxyClient.LocalEndPoint).Port;
                    hosts.TryAdd(localPort, req.Url.Host);
                    await PipeAsync(proxyClient, conn);
                    proxyDisposable.Dispose(); //try finally
                }
                else
                {
                    var resp = await httpClient.SendAsync(req);
                    await conn.SendAsync(resp, req);
                    req.Dispose();//try finally
                    resp.Dispose();
                    await handler.HandleAsync(conn);
                }
            });
            proxySvr.Start();


            //TEST
            //Browser settings proxy (http https)
            //localhost 9699
            //OR
            //Code
            ConnectionExtensions.UseSsl((conn, options) => {
                options.RemoteCertificateValidationCallback += (a, b, c, d) => true;
            });
            var req1 = new HttpRequest("https://cnblogs.com");

            _Proxy9.SendAsync(req1, (resp) => {
                Console.WriteLine(resp.StatusCode);
                foreach (var item in resp.Headers)
                {
                    Console.WriteLine($"{item.Key}={item.Value}");
                }
            }).Wait();
            var req2 = new HttpRequest("https://cnblogs.com/");

            _Proxy10.SendAsync(req2, (resp) => {
                Console.WriteLine(resp.StatusCode);
                foreach (var item in resp.Headers)
                {
                    Console.WriteLine($"{item.Key}={item.Value}");
                }
            }).Wait();
        }
コード例 #7
0
 internal void SetReadOnly()
 {
     ConnectionExtensions.SetAsReadOnly();
     Standards.SetAsReadOnly();
     MessageExtensions.SetAsReadOnly();
 }
コード例 #8
0
 /// <summary>
 /// If the connection is null or disposed, false;
 /// If the connection is connecting, false;
 /// If the connection is connected, true;
 /// </summary>
 /// <param name="connection"></param>
 /// <returns></returns>
 static bool Refresh(Connection connection)
 {
     return(ConnectionExtensions.IsConnecting(connection) ? false : ConnectionExtensions.IsConnected(connection));
 }
コード例 #9
0
 public static void ExecuteAsync_WithoutParamsGivenNullConnection_ThrowsArgumentNullException()
 {
     Assert.That(() => ConnectionExtensions.ExecuteAsync(null, "test", CancellationToken.None), Throws.ArgumentNullException);
 }
コード例 #10
0
        public static void ExecuteScalarAsync_WithParamsGivenNullConnection_ThrowsArgumentNullException()
        {
            var param = new { Test = "test" };

            Assert.That(() => ConnectionExtensions.ExecuteScalarAsync <string>(null, "test", param, CancellationToken.None), Throws.ArgumentNullException);
        }
コード例 #11
0
        public static void QuerySingleOrNone_WithParamsGivenNullConnection_ThrowsArgumentNullException()
        {
            var param = new { Test = "test" };

            Assert.That(() => ConnectionExtensions.QuerySingleOrNone <string>(null, "test", param, CancellationToken.None), Throws.ArgumentNullException);
        }
コード例 #12
0
 public static void QueryFirstOrNone_WithoutParamsGivenNullConnection_ThrowsArgumentNullException()
 {
     Assert.That(() => ConnectionExtensions.QueryFirstOrNone <string>(null, "test", CancellationToken.None), Throws.ArgumentNullException);
 }