public PersistentConnectionHandler(AppFunc next, string path, Type connectionType, ConnectionConfiguration configuration)
 {
     _next = next;
     _path = path;
     _connectionType = connectionType;
     _configuration = configuration;
 }
        /// <summary>
        ///     The test window.
        /// </summary>
        public void TestWindow()
        {
            var mocks = new MockRepository();
            var mockHttpReq = mocks.Stub<IHttpSonarConnector>();
            var mockVsHelpers = mocks.Stub<IVsEnvironmentHelper>();
            var config = new ConnectionConfiguration("serveraddr", "login", "password");

            // set expectations
            using (mocks.Record())
            {
                SetupResult.For(mockHttpReq.HttpSonarGetRequest(config, "/api/issues/search?components=resource"))
                    .Return(File.ReadAllText("TestData/issuessearchbycomponent.txt"));
                SetupResult.For(mockHttpReq.HttpSonarGetRequest(config, "/api/users/search")).Return(File.ReadAllText("TestData/userList.txt"));
            }

            ISonarRestService service = new SonarRestService(mockHttpReq);
            service.GetIssuesInResource(config, "resource");
            var associatedProject = new Resource { Key = "core:Common" };

            this.model = new ExtensionDataModel(service, mockVsHelpers, associatedProject, null);
            var t = new Thread(this.Threadprc);
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
        }
        public void SetUp()
        {
            var configuration = new ConnectionConfiguration
            {
                Hosts = new List<IHostConfiguration>
                {
                    new HostConfiguration { Host = "localhost", Port = 5672 }
                },
                UserName = "******",
                Password = "******"
            };

            configuration.Validate();

            var typeNameSerializer = new TypeNameSerializer();
            connectionFactory = new ConnectionFactoryWrapper(configuration, new DefaultClusterHostSelectionStrategy<ConnectionFactoryInfo>());
            serializer = new JsonSerializer(typeNameSerializer);
            conventions = new Conventions(typeNameSerializer);
            consumerErrorStrategy = new DefaultConsumerErrorStrategy(
                connectionFactory, 
                serializer, 
                new ConsoleLogger(), 
                conventions,
                typeNameSerializer);
         
        }
            public void ConnectionsWithTheSameConnectionIdLongPollingCloseGracefully()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyGroupEchoConnection>("/echo", config);

                        config.Resolver.Register(typeof(IProtectedData), () => new EmptyProtectedData());
                    });

                    string id = Guid.NewGuid().ToString("d");

                    var tasks = new List<Task>();

                    for (int i = 0; i < 1000; i++)
                    {
                        tasks.Add(ProcessRequest(host, "longPolling", id));
                    }

                    ProcessRequest(host, "longPolling", id);

                    Task.WaitAll(tasks.ToArray());

                    Assert.True(tasks.All(t => !t.IsFaulted));
                }
            }
        public void SetUp()
        {
            persistentConnection = MockRepository.GenerateStub<IPersistentConnection>();
            var eventBus = MockRepository.GenerateStub<IEventBus>();

            var configuration = new ConnectionConfiguration
                {
                    Timeout = 1
                };

            var shutdownArgs = new ShutdownEventArgs(
                ShutdownInitiator.Peer,
                AmqpException.ConnectionClosed,
                "connection closed by peer");
            var exception = new OperationInterruptedException(shutdownArgs);

            persistentConnection.Stub(x => x.CreateModel()).WhenCalled(x =>
                {
                    throw exception;
                });

            var logger = MockRepository.GenerateStub<IEasyNetQLogger>();

            persistentChannel = new PersistentChannel(persistentConnection, logger, configuration, eventBus);

        }
		/** 
		 * This however is still a non-failover connection. Meaning if that `node` goes down the operation will not be retried on any other nodes in the cluster.
		 * 
		 * To get a failover connection we have to pass an `IConnectionPool` instance instead of a `Uri`.
		 */

		public void InstantiatingAConnectionPoolClient()
		{
			var node = new Uri("http://mynode.example.com:8082/apiKey");
			var connectionPool = new SniffingConnectionPool(new[] { node });
			var config = new ConnectionConfiguration(connectionPool);
			var client = new ElasticsearchClient(config);
		}
		public void IfResponseIsKnowError_DoNotRetry_ThrowServerException_Async(int status, string exceptionType, string exceptionMessage)
		{
			var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				var connectionPool = new StaticConnectionPool(new[]
				{
					new Uri("http://localhost:9200"),
					new Uri("http://localhost:9201"),
				});
				var connectionConfiguration = new ConnectionConfiguration(connectionPool)
					.ThrowOnElasticsearchServerExceptions()
					.ExposeRawResponse(false);

				fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
				FakeCalls.ProvideDefaultTransport(fake);

				var pingCall = FakeCalls.PingAtConnectionLevelAsync(fake);
				pingCall.Returns(FakeResponse.OkAsync(connectionConfiguration));

				var getCall = FakeCalls.GetCall(fake);
				getCall.Returns(FakeResponse.AnyAsync(connectionConfiguration, status, response: response));

				var client = fake.Resolve<ElasticsearchClient>();

				var e = Assert.Throws<ElasticsearchServerException>(async ()=>await client.InfoAsync());
				AssertServerErrorsOnResponse(e, status, exceptionType, exceptionMessage);

				//make sure a know ElasticsearchServerException does not cause a retry
				//In this case we want to fail early

				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}
 public void Ping_should_work()
 {
     var settings = new ConnectionConfiguration(new Uri(TestConfig.Endpoint));
     var client = new ElasticsearchClient(settings, new AwsHttpConnection(settings, TestConfig.AwsSettings));
     var response = client.Ping();
     Assert.AreEqual(200, response.HttpStatusCode.GetValueOrDefault(-1));
 }
        public void The_AuthMechanisms_property_should_default_to_PlainMechanism()
        {
            ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration();

            connectionConfiguration.AuthMechanisms.Count.ShouldEqual(1);
            connectionConfiguration.AuthMechanisms.Single().ShouldBeOfType<PlainMechanismFactory>();
        }
        /// <summary>
        /// Provides base <see cref="ElasticsearchClient"/> with profiling features to current <see cref="MiniProfiler"/> session.
        /// </summary>
        /// <param name="configuration">Instance of <see cref="ConnectionConfiguration"/>. Its responses will be handled and pushed to <see cref="MiniProfiler"/></param>
		public ProfiledElasticsearchClient(ConnectionConfiguration configuration) 
			: base(configuration)
		{
			ProfilerUtils.ExcludeElasticsearchAssemblies();
			ProfilerUtils.ApplyConfigurationSettings(configuration);
			configuration.SetConnectionStatusHandler(response => MiniProfilerElasticsearch.HandleResponse(response, _profiler));
		}
        public ConsumerDispatcherFactory(ConnectionConfiguration configuration, IEasyNetQLogger logger)
        {
            Preconditions.CheckNotNull(configuration, "configuration");
            Preconditions.CheckNotNull(logger, "logger");

            dispatcher = new Lazy<IConsumerDispatcher>(() => new ConsumerDispatcher(configuration, logger));
        }
        public IConnectionConfiguration Parse(string connectionString)
        {
            ConnectionString = connectionString;

            try
            {
                connectionConfiguration = new ConnectionConfiguration();

                foreach(var pair in
                    (from property in typeof(ConnectionConfiguration).GetProperties()
                     let match = Regex.Match(connectionString, string.Format("[^\\w]*{0}=(?<{0}>[^;]+)", property.Name), RegexOptions.IgnoreCase)
                     where match.Success
                     select new { Property = property, match.Groups[property.Name].Value }))
                    pair.Property.SetValue(connectionConfiguration, TypeDescriptor.GetConverter(pair.Property.PropertyType).ConvertFromString(pair.Value),null);

                if (ContainsKey("host"))
                    connectionConfiguration.ParseHosts(this["host"] as string);

                connectionConfiguration.Validate();
                return connectionConfiguration;
            }
            catch (Exception parseException)
            {
                throw new Exception(string.Format("Connection String parsing exception {0}", parseException.Message));
            }
        }
 public ClientCommandDispatcherFactory(ConnectionConfiguration configuration, IPersistentChannelFactory persistentChannelFactory)
 {
     Preconditions.CheckNotNull(configuration, "configuration");
     Preconditions.CheckNotNull(persistentChannelFactory, "persistentChannelFactory");
     this.configuration = configuration;
     this.persistentChannelFactory = persistentChannelFactory;
 }
        public void SetUp()
        {
            persistentConnection = MockRepository.GenerateStub<IPersistentConnection>();
            channel = MockRepository.GenerateStub<IModel>();
            var eventBus = new EventBus();
            var configuration = new ConnectionConfiguration();

            var shutdownArgs = new ShutdownEventArgs(
                ShutdownInitiator.Peer, 
                AmqpException.ConnectionClosed,
                "connection closed by peer");
            var exception = new OperationInterruptedException(shutdownArgs);
            var first = true;

            persistentConnection.Stub(x => x.CreateModel()).WhenCalled(x =>
                {
                    if (first)
                    {
                        first = false;
                        throw exception;
                    }
                    x.ReturnValue = channel;
                });

            var logger = MockRepository.GenerateStub<IEasyNetQLogger>();

            persistentChannel = new PersistentChannel(persistentConnection, logger, configuration, eventBus);

            new Timer(_ => eventBus.Publish(new ConnectionCreatedEvent())).Change(10, Timeout.Infinite);

            persistentChannel.InvokeChannelAction(x => x.ExchangeDeclare("MyExchange", "direct"));
        }
        public void ServerExceptionIsCaught_KeepResponse(int status, string exceptionType, string exceptionMessage)
        {
            var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                var connectionConfiguration = new ConnectionConfiguration()
                    .ExposeRawResponse(true);

                fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
                FakeCalls.ProvideDefaultTransport(fake);

                var getCall = FakeCalls.GetSyncCall(fake);
                getCall.Returns(FakeResponse.Bad(connectionConfiguration, response: response));

                var client = fake.Resolve<ElasticsearchClient>();

                var result = client.Info();
                result.Success.Should().BeFalse();
                AssertServerErrorsOnResponse(result, status, exceptionType, exceptionMessage);

                result.ResponseRaw.Should().NotBeNull();

                getCall.MustHaveHappened(Repeated.Exactly.Once);

            }
        }
 public ConcurrencyTests()
 {
     _connectionPool = new SniffingConnectionPool(_uris);
     _config = new ConnectionConfiguration(_connectionPool)
         .SniffOnConnectionFault()
         .SniffOnStartup()
         .MaximumRetries(5);
 }
 public PersistentConnectionMiddleware(OwinMiddleware next,
                                       Type connectionType,
                                       ConnectionConfiguration configuration)
     : base(next)
 {
     _connectionType = connectionType;
     _configuration = configuration;
 }
		public StaticConnectionPoolTests()
		{
			_connectionPool = new StaticConnectionPool(_uris);
			_config = new ConnectionConfiguration(_connectionPool);

			_ok = FakeResponse.Ok(_config);
			_bad = FakeResponse.Bad(_config);
		}
Example #19
0
 public void Ping_should_work()
 {
     var httpConnection = new AwsHttpConnection(TestConfig.AwsSettings);
     var pool = new SingleNodeConnectionPool(new Uri(TestConfig.Endpoint));
     var config = new ConnectionConfiguration(pool, httpConnection);
     var client = new ElasticLowLevelClient(config);
     var response = client.Ping<object>();
     Assert.AreEqual(200, response.HttpStatusCode.GetValueOrDefault(-1));
 }
Example #20
0
        private IElasticsearchClient BuildElasticSearchClient(IContext context)
        {
            Configuration.ISettings settings = context.Kernel.Get<Configuration.ISettings>();

            ConnectionConfiguration config = new ConnectionConfiguration(new Uri(settings.ElasticSearch.Host));
            ElasticsearchClient client = new ElasticsearchClient(config);

            return client;
        }
Example #21
0
 public void Asterisk_encoded_url_should_work()
 {
     var httpConnection = new AwsHttpConnection(TestConfig.AwsSettings);
     var pool = new SingleNodeConnectionPool(new Uri(TestConfig.Endpoint));
     var config = new ConnectionConfiguration(pool, httpConnection);
     var client = new ElasticLowLevelClient(config);
     var response = client.Get<Stream>("index*", "type", "id");
     Assert.AreEqual(404, response.HttpStatusCode.GetValueOrDefault(-1));
 }
Example #22
0
 public void Random_encoded_url_should_work()
 {
     var randomString = Guid.NewGuid().ToString("N");
     var httpConnection = new AwsHttpConnection(TestConfig.AwsSettings);
     var pool = new SingleNodeConnectionPool(new Uri(TestConfig.Endpoint));
     var config = new ConnectionConfiguration(pool, httpConnection);
     var client = new ElasticLowLevelClient(config);
     var response = client.Get<Stream>(randomString, string.Join(",", Enumerable.Repeat(randomString, 2)), randomString);
     Assert.AreEqual(404, response.HttpStatusCode.GetValueOrDefault(-1));
 }
Example #23
0
		/**
		 * Here instead of directly passing `node`, we pass a <<sniffing-connection-pool, SniffingConnectionPool>>
		 * which will use our `node` to find out the rest of the available cluster nodes.
		 * Be sure to read more about <<connection-pooling, Connection Pooling and Cluster Failover>>.
		 *
		 * === Configuration Options
		 *
		 *Besides either passing a `Uri` or `IConnectionPool` to `ConnectionConfiguration`, you can also fluently control many more options. For instance:
		 */
		public void SpecifyingClientOptions()
		{
			var node = new Uri("http://mynode.example.com:8082/apiKey");
			var connectionPool = new SniffingConnectionPool(new[] { node });

			var config = new ConnectionConfiguration(connectionPool)
				.DisableDirectStreaming() //<1> Additional options are fluent method calls on `ConnectionConfiguration`
				.BasicAuthentication("user", "pass")
				.RequestTimeout(TimeSpan.FromSeconds(5));
		}
        protected override void InitializeTarget()
        {
            base.InitializeTarget();

            var uri = GetConnectionString(ConnectionStringName) ?? Uri;
            var nodes = uri.Split(',').Select(url => new Uri(url));
            var connectionPool = new StaticConnectionPool(nodes);
            var config = new ConnectionConfiguration(connectionPool);
            _client = new ElasticsearchClient(config, serializer:ElasticsearchSerializer);
        }
        public void SetUp()
        {
            persistentConnection = MockRepository.GenerateStub<IPersistentConnection>();
            persistentConnection.Stub(x => x.CreateModel());
            var configuration = new ConnectionConfiguration();
            eventBus = new EventBus();
            var logger = MockRepository.GenerateStub<IEasyNetQLogger>();

            var persistentChannel = new PersistentChannel(persistentConnection, logger, configuration, eventBus);
        }
        public PersistentChannelFactory(IEasyNetQLogger logger, ConnectionConfiguration configuration, IEventBus eventBus)
        {
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(configuration, "configuration");
            Preconditions.CheckNotNull(eventBus, "eventBus");

            this.logger = logger;
            this.configuration = configuration;
            this.eventBus = eventBus;
        }
        static private ConnectionConfiguration Create(string url)
        {
//            AddDebugListener();
            var settings = new ConnectionConfiguration(new Uri(url))
                .EnableMetrics();
//                .SetConnectTimeout(100)
//                .EnableTrace(true)
//                .SetTimeout(100);
            return settings;
        }
		public SingleNodeConnectionPoolTests()
		{
			_config = new ConnectionConfiguration(new Uri("http://localhost:9200"))
				.MaximumRetries(2);

			_ok = FakeResponse.Ok(_config);
			_bad = FakeResponse.Any(_config, -1);


		}
Example #29
0
        public void NoReconnectsAfterFallback()
        {
            // There was a regression where the SSE transport would try to reconnect after it times out.
            // This test ensures that no longer happens.
            // #2180
            using (var host = new MemoryHost())
            {
                var myReconnect = new MyReconnect();

                host.Configure(app =>
                {
                    Func<AppFunc, AppFunc> middleware = (next) =>
                    {
                        return env =>
                        {
                            var request = new OwinRequest(env);
                            var response = new OwinResponse(env);

                            if (!request.Path.Value.Contains("negotiate") && !request.QueryString.Value.Contains("longPolling"))
                            {
                                response.Body = new MemoryStream();
                            }

                            return next(env);
                        };
                    };

                    app.Use(middleware);

                    var config = new ConnectionConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    config.Resolver.Register(typeof(MyReconnect), () => myReconnect);

                    app.MapSignalR<MyReconnect>("/echo", config);
                });

                var connection = new Connection("http://foo/echo");

                using (connection)
                {
                    connection.Start(host).Wait();

                    // Give SSE an opportunity to reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    Assert.Equal(connection.State, ConnectionState.Connected);
                    Assert.Equal(connection.Transport.Name, "longPolling");
                    Assert.Equal(0, myReconnect.Reconnects);
                }
            }
        }
Example #30
0
        public PublisherConfirms(ConnectionConfiguration configuration, IEasyNetQLogger logger, IEventBus eventBus) : base (eventBus)
        {
            Preconditions.CheckNotNull(configuration, "configuration");
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(eventBus, "eventBus");

            timeoutSeconds = configuration.Timeout;
            this.logger = logger;

            eventBus.Subscribe<PublishChannelCreatedEvent>(OnPublishChannelCreated);
        }
Example #31
0
        public void Should_set_configured_prefetch_count()
        {
            var connectionConfiguration = new ConnectionConfiguration();

            mockBuilder.Channels[1].AssertWasCalled(x => x.BasicQos(0, connectionConfiguration.PrefetchCount, false));
        }
Example #32
0
        public ElasticSearchTextIndex()
        {
            var config = new ConnectionConfiguration(new Uri("http://localhost:9200"));

            client = new ElasticLowLevelClient(config);
        }
 public MongoDbConnection(ConnectionConfiguration connectionConfiguration)
 {
     this.ConnectionConfiguration = connectionConfiguration;
     Setup(this.ConnectionConfiguration);
 }
        static void Main(string[] args)
        {
            IBus myBus = null;

            Console.WriteLine("IoT Device is starting");

            try
            {
                var connection = new ConnectionConfiguration
                {
                    Port     = 5671,
                    UserName = "******",
                    Password = "******",
                    Product  = "IoT Hub"
                };

                var hostConfiguration = new HostConfiguration();
                hostConfiguration.Host           = "10.0.1.50";
                hostConfiguration.Port           = 5671;
                hostConfiguration.Ssl.Enabled    = true;
                hostConfiguration.Ssl.ServerName = "rabbitServer";
                hostConfiguration.Ssl.CertPath   = @"/home/keycert.p12";
                //hostConfiguration.Ssl.CertPath = @"c:\temp\keycert.p12";
                hostConfiguration.Ssl.CertPassphrase         = "strenggeheim";
                hostConfiguration.Ssl.AcceptablePolicyErrors =
                    SslPolicyErrors.RemoteCertificateNameMismatch |
                    SslPolicyErrors.RemoteCertificateChainErrors;
                connection.Hosts = new List <HostConfiguration> {
                    hostConfiguration
                };
                connection.Validate();
                myBus = RabbitHutch.CreateBus(connection, services => { });
                //myBus = RabbitHutch.CreateBus("host=10.0.1.72");

                Console.WriteLine($"Connected with RabbitMQ {myBus.IsConnected}");

                if (myBus.IsConnected)
                {
                    Console.WriteLine("Please enter the count of metering values:");
                    var countAsString = Console.ReadLine();

                    var count  = Convert.ToInt32(countAsString);
                    var random = new Random(DateTime.Now.Second);
                    for (int i = 0; i < count; i++)
                    {
                        var value = random.Next(1, 1800);

                        MeteringValue mv = new MeteringValue
                        {
                            Timestamp = DateTime.UtcNow,
                            ObisCode  = "1-1:1.6.0",
                            Value     = value,
                            Host      = System.Net.Dns.GetHostName()
                        };

                        myBus.Publish(mv);
                        Console.WriteLine($"Send datagram {i}");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                myBus?.Dispose();
            }
            Console.ReadLine();
        }
 /**
  * If your Elasticsearch node does not live at `http://localhost:9200` but instead lives somewhere else, for example, `http://mynode.example.com:8082/apiKey`, then
  * you will need to pass in some instance of `IConnectionConfigurationValues`.
  *
  * The easiest way to do this is:
  */
 public void InstantiatingASingleNodeClient()
 {
     var node   = new Uri("http://mynode.example.com:8082/apiKey");
     var config = new ConnectionConfiguration(node);
     var client = new ElasticLowLevelClient(config);
 }
Example #36
0
        public static void ConfigureRoutes(IAppBuilder app, IDependencyResolver resolver)
        {
            var hubConfig = new HubConfiguration
            {
                Resolver             = resolver,
                EnableDetailedErrors = true
            };

            app.MapSignalR(hubConfig);

            app.MapSignalR("/signalr2/test", new HubConfiguration()
            {
                Resolver = resolver
            });

            var config = new ConnectionConfiguration
            {
                Resolver = resolver
            };

            app.Map("/multisend", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <MySendingConnection>(config);
            });

            app.Map("/echo", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <EchoConnection>(config);
            });

            app.Map("/redirectionConnection", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <RedirectionConnection>(config);
            });

            app.Map("/statusCodeConnection", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <StatusCodeConnection>(config);
            });

            app.Map("/jsonp", map =>
            {
                var jsonpConfig = new ConnectionConfiguration
                {
                    Resolver    = resolver,
                    EnableJSONP = true
                };

                map.MapSignalR <EchoConnection>("/echo", jsonpConfig);

                var jsonpHubsConfig = new HubConfiguration
                {
                    Resolver    = resolver,
                    EnableJSONP = true
                };

                map.MapSignalR(jsonpHubsConfig);
            });

            app.MapSignalR <MyBadConnection>("/ErrorsAreFun", config);
            app.MapSignalR <MyGroupEchoConnection>("/group-echo", config);
            app.MapSignalR <MyReconnect>("/my-reconnect", config);
            app.MapSignalR <ExamineHeadersConnection>("/examine-request", config);
            app.MapSignalR <ExamineReconnectPath>("/examine-reconnect", config);
            app.MapSignalR <MyGroupConnection>("/groups", config);
            app.MapSignalR <MyRejoinGroupsConnection>("/rejoin-groups", config);
            app.MapSignalR <BroadcastConnection>("/filter", config);
            app.MapSignalR <ConnectionThatUsesItems>("/items", config);
            app.MapSignalR <SyncErrorConnection>("/sync-error", config);
            app.MapSignalR <AddGroupOnConnectedConnection>("/add-group", config);
            app.MapSignalR <UnusableProtectedConnection>("/protected", config);
            app.MapSignalR <FallbackToLongPollingConnectionThrows>("/fall-back-throws", config);
            app.MapSignalR <PreserializedJsonConnection>("/preserialize", config);
            app.MapSignalR <AsyncOnConnectedConnection>("/async-on-connected", config);

            // This subpipeline is protected by basic auth
            app.Map("/basicauth", map =>
            {
                map.Use(async(context, next) =>
                {
                    var authorization = context.Request.Headers.Get("Authorization");
                    if (string.IsNullOrEmpty(authorization))
                    {
                        context.Response.StatusCode = 401;
                        context.Response.Headers.Add("WWW-Authenticate", new string[] { "Basic" });
                    }
                    else
                    {
                        var base64Encoded         = authorization.Replace("Basic ", "");
                        byte[] base64EncodedBytes = Convert.FromBase64String(base64Encoded);
                        var base64Decoded         = System.Text.ASCIIEncoding.ASCII.GetString(base64EncodedBytes);
                        var credentials           = base64Decoded.Split(':');
                        var identity = new ClaimsIdentity("Basic");
                        identity.AddClaim(new Claim(ClaimTypes.Name, credentials[0]));
                        context.Request.User = new ClaimsPrincipal(identity);
                        await next();
                    }
                });

                var subConfig = new ConnectionConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR <AuthenticatedEchoConnection>("/echo", subConfig);

                var subHubsConfig = new HubConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR(subHubsConfig);
            });

            // This subpipeline is protected by cookie auth
            app.Map("/cookieauth", map =>
            {
                var options = new CookieAuthenticationOptions()
                {
                    AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                    LoginPath          = CookieAuthenticationDefaults.LoginPath,
                    LogoutPath         = CookieAuthenticationDefaults.LogoutPath,
                };

                map.UseCookieAuthentication(options);

                map.Use(async(context, next) =>
                {
                    if (context.Request.Path.Value.Contains(options.LoginPath.Value))
                    {
                        if (context.Request.Method == "POST")
                        {
                            var form     = await context.Request.ReadFormAsync();
                            var userName = form["UserName"];
                            var password = form["Password"];

                            var identity = new ClaimsIdentity(options.AuthenticationType);
                            identity.AddClaim(new Claim(ClaimTypes.Name, userName));
                            context.Authentication.SignIn(identity);
                        }
                    }
                    else
                    {
                        await next();
                    }
                });

                var subConfig = new ConnectionConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR <AuthenticatedEchoConnection>("/echo", subConfig);

                var subHubsConfig = new HubConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR(subHubsConfig);
            });

            app.Map("/fall-back", map =>
            {
                map.Use((context, next) =>
                {
                    if (!context.Request.Path.Value.Contains("negotiate") &&
                        !context.Request.QueryString.Value.Contains("longPolling"))
                    {
                        context.Response.Body = new MemoryStream();
                    }

                    return(next());
                });

                map.RunSignalR <FallbackToLongPollingConnection>();
            });

            app.Map("/no-init", map =>
            {
                map.Use((context, next) =>
                {
                    if (context.Request.Path.Value.Contains("connect"))
                    {
                        context.Response.Body = new MemoryStream();
                    }

                    return(next());
                });
            });

            app.Map("/force-lp-reconnect", map =>
            {
                var startReceived = new ManualResetEvent(false);

                map.Use((context, next) =>
                {
                    if (context.Request.QueryString.Value.Contains("transport=longPolling"))
                    {
                        // To test reconnect scenarios we need to make sure that the transport is
                        // successfully started before we disconnect the client. For long polling
                        // this means we need to make sure that we don't break the poll request
                        // before we send a response to the start request. Note that the first poll
                        // request is likely to arrive before the start request. The assumption here
                        // is that there is only one active long polling connection at a time.
                        if (context.Request.Path.Value.Contains("/connect"))
                        {
                            // a new connection was started
                            startReceived.Reset();
                        }
                        else if (context.Request.Path.Value.Contains("/start"))
                        {
                            // unblock breaking the poll after start request
                            return(next().ContinueWith(t => startReceived.Set()));
                        }
                        else if (context.Request.Path.Value.Contains("/poll"))
                        {
                            return(Task.Run(async() =>
                            {
                                // don't break the poll until start request is handled or a timeout
                                // if it is a subsequent poll
                                startReceived.WaitOne(3000);
                                // give the start request some additional head start
                                await Task.Delay(100);
                                //subsequent long polling request should not break immediately
                                startReceived.Reset();
                                context.Response.StatusCode = 500;
                                return TaskAsyncHelper.Empty;
                            }));
                        }
                    }

                    return(next());
                });
                map.MapSignalR <ExamineReconnectPath>("/examine-reconnect", config);
                map.MapSignalR(hubConfig);
            });

            // Perf/stress test related
            var performanceConfig = new ConnectionConfiguration
            {
                Resolver = resolver
            };

            app.MapSignalR <StressConnection>("/echo", performanceConfig);

            performanceConfig.Resolver.Register(typeof(IProtectedData), () => new EmptyProtectedData());

            // IMPORTANT: This needs to run last so that it runs in the "default" part of the pipeline

            // Session is enabled for ASP.NET on the session path
            app.Map("/session", map =>
            {
                map.MapSignalR();
            });

            // Redirectors:

            // Valid redirect chain
            // Overload detection doesn't like it when we use this as an extension method
            // We *intentionally* use paths that do NOT end in a trailing '/' in some places as the client needs to support both
            AppBuilderUseExtensions.Use(app, CreateRedirector("/redirect", "/redirect2"));
            AppBuilderUseExtensions.Use(app, CreateRedirector("/redirect2", "/redirect3/"));
            AppBuilderUseExtensions.Use(app, CreateRedirector("/redirect3", "/redirect4"));
            AppBuilderUseExtensions.Use(app, CreateRedirector("/redirect4", "/signalr/"));

            // Looping redirect chain
            AppBuilderUseExtensions.Use(app, CreateRedirector("/redirect-loop", "/redirect-loop2"));
            AppBuilderUseExtensions.Use(app, CreateRedirector("/redirect-loop2", "/redirect-loop"));

            // Wrong protocol version
            AppBuilderUseExtensions.Use(app, CreateRedirector("/redirect-old-proto", "/signalr", protocolVersion: "1.5"));
        }
Example #37
0
        public void AsyncTaskModule_PingServers_AvalilableAfterSomeTime()
        {
            const int storageServer1 = 22131;
            const int storageServer2 = 22132;
            const int distrServer1   = 22134;
            const int distrServer12  = 23134;

            var writer = new HashWriter(new HashMapConfiguration("TestAsyncPing", HashMapCreationMode.CreateNew, 2, 3, HashFileType.Distributor));

            writer.CreateMap();
            writer.SetServer(0, "localhost", storageServer1, 157);
            writer.SetServer(1, "localhost", storageServer2, 157);
            writer.Save();

            #region hell

            var connection = new ConnectionConfiguration("testService", 10);

            var distrconfig = new DistributorHashConfiguration(1);
            var queueconfig = new QueueConfiguration(1, 100);
            var dnet        = new DistributorNetModule(connection,
                                                       new ConnectionTimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout));
            var ddistributor = new DistributorModule(new AsyncTasksConfiguration(TimeSpan.FromMilliseconds(200)),
                                                     new AsyncTasksConfiguration(TimeSpan.FromMilliseconds(200)),
                                                     distrconfig,
                                                     queueconfig, dnet,
                                                     new ServerId("localhost", distrServer1),
                                                     new ServerId("localhost", distrServer12),
                                                     new HashMapConfiguration("TestAsyncPing", HashMapCreationMode.ReadFromFile, 1, 1, HashFileType.Distributor));
            dnet.SetDistributor(ddistributor);

            dnet.Start();
            ddistributor.Start();
            GlobalQueue.Queue.Start();

            #endregion

            var data1 = new InnerData(new Transaction("", ""));
            var data2 = new InnerData(new Transaction("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", ""));

            var dest  = ddistributor.GetDestination(data1, false);
            var dest2 = ddistributor.GetDestination(data2, false);

            dnet.Process(dest.First(), data1);
            dnet.Process(dest2.First(), data1);

            Thread.Sleep(100);

            dest  = ddistributor.GetDestination(data1, false);
            dest2 = ddistributor.GetDestination(data2, false);

            Assert.AreEqual(null, dest);
            Assert.AreEqual(null, dest2);

            TestHelper.OpenWriterHost(new ServerId("localhost", storageServer1),
                                      new ConnectionConfiguration("testService", 10));
            TestHelper.OpenWriterHost(new ServerId("localhost", storageServer2),
                                      new ConnectionConfiguration("testService", 10));

            Thread.Sleep(TimeSpan.FromMilliseconds(800));

            Assert.AreEqual(1, ddistributor.GetDestination(data1, false).Count);
            Assert.AreEqual(1, ddistributor.GetDestination(data2, false).Count);

            ddistributor.Dispose();
        }
Example #38
0
 public static void Main(string[] args)
 {
     var settings       = new ConnectionConfiguration(new Uri("http://127.0.0.1:9200")).RequestTimeout(TimeSpan.FromMinutes(2));
     var lowlevelClient = new ElasticLowLevelClient(settings);
 }
Example #39
0
        private async void searchResult(string srv_url, string index, string type, string srch)
        {
            if (srv_url[srv_url.Length - 1] != '/')
            {
                srv_url += "/";
            }
            if (!srv_url.StartsWith("http"))
            {
                srv_url = "http://" + srv_url;
            }

            int totalCnt = 30;
            int start    = 0;


            try
            {
                var settings = new ConnectionConfiguration(new Uri(srv_url + index + "/" + type + "/"))
                               .RequestTimeout(TimeSpan.FromMinutes(2))
                               .ConnectionLimit(-1);


                var            lowlevelClient = new ElasticLowLevelClient(settings);
                StringResponse searchResponse;
                JObject        details;

                while (start < totalCnt)
                {
                    string requestBody = "{ \"from\":\"" + start.ToString() + "\", \"size\":\"10\", \"query\": { \"match\": { \"PdfText\": \"" + srch + "\"}}}";

                    start += 10;

                    /*var requestBody = PostData.Serializable(
                     *                      new
                     *                      {
                     *                          from = 0,
                     *                          size = 30,
                     *                          query = new
                     *                          {
                     *                              match = new
                     *                              {
                     *                                  PdfText = srch
                     *                              }
                     *                          }
                     *                      }); */

                    searchResponse = lowlevelClient.Search <StringResponse>(requestBody);
                    Console.WriteLine("Search Finished");
                    if (searchResponse.Success)
                    {
                        var reponseJson = searchResponse.Body;

                        Console.Write(reponseJson);

                        details  = JObject.Parse(reponseJson);
                        totalCnt = (int)details["hits"]["total"]["value"];

                        for (int i = 0; i < details["hits"]["hits"].Count(); i++)
                        {
                            Abschluse pdf = new Abschluse();
                            pdf.Id = (int)details["hits"]["hits"][i]["_id"];

                            pdf.PdfLink     = details["hits"]["hits"][i]["_source"]["PdfLink"].ToString();
                            pdf.PdfText     = details["hits"]["hits"][i]["_source"]["PdfText"].ToString();
                            pdf.DocumentUrl = details["hits"]["hits"][i]["_source"]["DocumentUrl"].ToString();

                            m_lstPdfInfos.Add(pdf);
                        }
                    }
                    else
                    {   /*
                         * var dialog = new MessageDialog(searchResponse.DebugInformation);
                         * await dialog.ShowAsync();
                         */
                    }
                }
            }
            catch (Exception e)
            {
                var dialog = new MessageDialog(e.Message + "\n" + m_lstPdfInfos.Count.ToString() + " Rows searched");
                await dialog.ShowAsync();

                Console.WriteLine(e);
                return;
            }
            var dialog1 = new MessageDialog(m_lstPdfInfos.Count.ToString() + " Rows searched");
            await dialog1.ShowAsync();
        }
Example #40
0
 public EFDBContext(ConnectionConfiguration connection) : base(connection.ConnectionString)
 {
 }
Example #41
0
        private static void Main(string[] args)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=192.168.30.128;Initial Catalog=SmartBusExtension;User Id=sa;Password=1qaz2wsx123_@;Connect Timeout=120"))
            {
                SqlCommand cmd = new SqlCommand(@"
                    SELECT * FROM MQUser"
                                                , conn);

                List <SyncArrayConfiguration> arrayConfig = new List <SyncArrayConfiguration>()
                {
                    new SyncArrayConfiguration
                    {
                        SqlCommand = new SqlCommand(@"
                            SELECT id, userid, login,username,avatar
                            FROM MQUser
                            where UserName='******'"
                                                    , conn),
                        AttributeName = "tags"
                    },

                    /**
                     * new SyncArrayConfiguration
                     * {
                     *  SqlCommand = new SqlCommand(@"
                     *      SELECT id_object AS '_id', id, description, xmlData, languageId
                     *      FROM dbo.Categories
                     *      WHERE languageId = 'es'"
                     *      , conn),
                     *  AttributeName = "categories",
                     *  XmlFields = new string[] { "xmlData" }
                     * }
                     **/
                };

                SyncDeleteConfiguration deleteCmd = new SyncDeleteConfiguration
                {
                    SqlCommand = new SqlCommand(@"
                        SELECT id_object AS '_id', createdOn
                        FROM dbo.DeleteLog
                        WHERE id_language = 'es'"
                                                , conn),
                    ColumnsToCompareWithLastSyncDate = new string[] { "[createdOn]" },
                };

                var nodes =
                    new Uri[] {
                    new Uri("http://192.168.30.135:9200"),
                    //new Uri("http://localhost:9201")
                };
                var connectionPool = new SniffingConnectionPool(nodes);
                var esConfig       = new ConnectionConfiguration(connectionPool).UsePrettyResponses();

                var syncConfig = new SyncConfiguration()
                {
                    SqlConnection       = conn,
                    SqlCommand          = cmd,
                    ArraysConfiguration = arrayConfig,
                    ColumnsToCompareWithLastSyncDate = new string[] { "[id]" },
                    //DeleteConfiguration = deleteCmd,
                    ElasticSearchConfiguration = esConfig,
                    BulkSize = 500,
                    _Index   = new Index("mssql_30.128"),
                    _Type    = "notes"
                };

                var sync = new Sync(syncConfig);

                try
                {
                    var response = sync.Exec();
                    if (response.BulkResponses.Any())
                    {
                        foreach (var bulkResponse in response.BulkResponses)
                        {
                            Console.WriteLine("success: " + bulkResponse.Success);
                            Console.WriteLine("http status code: " + bulkResponse.HttpStatusCode);
                            Console.WriteLine("affected documents: " + bulkResponse.AffectedDocuments);
                            Console.WriteLine("started on: " + bulkResponse.StartedOn);
                            Console.WriteLine("bulk duration: " + bulkResponse.Duration + "ms");
                            if (!response.Success)
                            {
                                Console.WriteLine("es original exception: " + bulkResponse.ESexception);
                            }
                            Console.WriteLine("\n");
                        }
                        Console.WriteLine("\nbulk avg duration: " + response.BulkResponses.Average(x => x.Duration) + "ms");
                        Console.WriteLine("\n");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("an error has occurred: " + ex.Message);
                }
                finally
                {
                    Console.WriteLine("Execution has completed. Press any key to continue...");
                    Console.ReadKey();
                }
            }
        }
Example #42
0
 // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
 private static void AssertClientProperty(ConnectionConfiguration busConfig, string propertyName, object expectedValue)
 {
     busConfig.ClientProperties.TryGetValue(propertyName, out object value);
     Assert.Equal(expectedValue, value);
 }
Example #43
0
        public void ConnectionIdsCantBeUsedAsGroups()
        {
            using (var host = new MemoryHost())
            {
                IProtectedData protectedData = null;

                host.Configure(app =>
                {
                    var config = new ConnectionConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    app.MapSignalR <MyConnection>("/echo", config);

                    protectedData = config.Resolver.Resolve <IProtectedData>();
                });

                var connection = new Client.Connection("http://memoryhost/echo");

                using (connection)
                {
                    var connectionTcs = new TaskCompletionSource <string>();
                    var spyTcs        = new TaskCompletionSource <string>();

                    connection.Received += data =>
                    {
                        connectionTcs.SetResult(data.Trim());
                    };

                    connection.Start(host).Wait();

                    var tcs = new TaskCompletionSource <object>();
                    EventSourceStreamReader reader = null;

                    Task.Run(async() =>
                    {
                        try
                        {
                            string url   = GetUrl(protectedData, connection);
                            var response = await host.Get(url, r => { }, isLongRunning: true);
                            reader       = new EventSourceStreamReader(connection, response.GetStream());

                            reader.Message = sseEvent =>
                            {
                                if (sseEvent.EventType == EventType.Data &&
                                    sseEvent.Data != "initialized" &&
                                    sseEvent.Data != "{}")
                                {
                                    spyTcs.TrySetResult(sseEvent.Data);
                                }
                            };

                            reader.Start();
                            tcs.TrySetResult(null);
                        }
                        catch (Exception ex)
                        {
                            tcs.TrySetException(ex);
                        }
                    });

                    tcs.Task.Wait();

                    connection.SendWithTimeout("STUFFF");

                    Assert.True(connectionTcs.Task.Wait(TimeSpan.FromSeconds(5)));
                    Assert.Equal("STUFFF", connectionTcs.Task.Result);
                    Assert.False(spyTcs.Task.Wait(TimeSpan.FromSeconds(5)));
                }
            }
        }
Example #44
0
        public void Should_set_configured_prefetch_count()
        {
            var connectionConfiguration = new ConnectionConfiguration();

            mockBuilder.Channels[1].Received().BasicQos(0, connectionConfiguration.PrefetchCount, false);
        }
Example #45
0
        public static void ConfigureRoutes(IAppBuilder app, IDependencyResolver resolver)
        {
            var hubConfig = new HubConfiguration
            {
                Resolver             = resolver,
                EnableDetailedErrors = true
            };

            app.MapSignalR(hubConfig);

            app.MapSignalR("/signalr2/test", new HubConfiguration()
            {
                Resolver = resolver
            });

            var config = new ConnectionConfiguration
            {
                Resolver = resolver
            };

            app.Map("/multisend", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <MySendingConnection>(config);
            });

            app.Map("/echo", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <EchoConnection>(config);
            });

            app.Map("/redirectionConnection", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <RedirectionConnection>(config);
            });

            app.Map("/statusCodeConnection", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR <StatusCodeConnection>(config);
            });

            app.Map("/jsonp", map =>
            {
                var jsonpConfig = new ConnectionConfiguration
                {
                    Resolver    = resolver,
                    EnableJSONP = true
                };

                map.MapSignalR <EchoConnection>("/echo", jsonpConfig);

                var jsonpHubsConfig = new HubConfiguration
                {
                    Resolver    = resolver,
                    EnableJSONP = true
                };

                map.MapSignalR(jsonpHubsConfig);
            });

            app.MapSignalR <MyBadConnection>("/ErrorsAreFun", config);
            app.MapSignalR <MyGroupEchoConnection>("/group-echo", config);
            app.MapSignalR <MyReconnect>("/my-reconnect", config);
            app.MapSignalR <ExamineHeadersConnection>("/examine-request", config);
            app.MapSignalR <ExamineReconnectPath>("/examine-reconnect", config);
            app.MapSignalR <MyGroupConnection>("/groups", config);
            app.MapSignalR <MyRejoinGroupsConnection>("/rejoin-groups", config);
            app.MapSignalR <BroadcastConnection>("/filter", config);
            app.MapSignalR <ConnectionThatUsesItems>("/items", config);
            app.MapSignalR <SyncErrorConnection>("/sync-error", config);
            app.MapSignalR <AddGroupOnConnectedConnection>("/add-group", config);
            app.MapSignalR <UnusableProtectedConnection>("/protected", config);
            app.MapSignalR <FallbackToLongPollingConnectionThrows>("/fall-back-throws", config);
            app.MapSignalR <PreserializedJsonConnection>("/preserialize", config);
            app.MapSignalR <AsyncOnConnectedConnection>("/async-on-connected", config);

            // This subpipeline is protected by basic auth
            app.Map("/basicauth", map =>
            {
                map.Use(async(context, next) =>
                {
                    var authorization = context.Request.Headers.Get("Authorization");
                    if (string.IsNullOrEmpty(authorization))
                    {
                        context.Response.StatusCode = 401;
                        context.Response.Headers.Add("WWW-Authenticate", new string[] { "Basic" });
                    }
                    else
                    {
                        var base64Encoded         = authorization.Replace("Basic ", "");
                        byte[] base64EncodedBytes = Convert.FromBase64String(base64Encoded);
                        var base64Decoded         = System.Text.ASCIIEncoding.ASCII.GetString(base64EncodedBytes);
                        var credentials           = base64Decoded.Split(':');
                        var identity = new ClaimsIdentity("Basic");
                        identity.AddClaim(new Claim(ClaimTypes.Name, credentials[0]));
                        context.Request.User = new ClaimsPrincipal(identity);
                        await next();
                    }
                });

                var subConfig = new ConnectionConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR <AuthenticatedEchoConnection>("/echo", subConfig);

                var subHubsConfig = new HubConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR(subHubsConfig);
            });

            // This subpipeline is protected by cookie auth
            app.Map("/cookieauth", map =>
            {
                var options = new CookieAuthenticationOptions()
                {
                    AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                    LoginPath          = CookieAuthenticationDefaults.LoginPath,
                    LogoutPath         = CookieAuthenticationDefaults.LogoutPath,
                };

                map.UseCookieAuthentication(options);

                map.Use(async(context, next) =>
                {
                    if (context.Request.Path.Value.Contains(options.LoginPath.Value))
                    {
                        if (context.Request.Method == "POST")
                        {
                            var form     = await context.Request.ReadFormAsync();
                            var userName = form["UserName"];
                            var password = form["Password"];

                            var identity = new ClaimsIdentity(options.AuthenticationType);
                            identity.AddClaim(new Claim(ClaimTypes.Name, userName));
                            context.Authentication.SignIn(identity);
                        }
                    }
                    else
                    {
                        await next();
                    }
                });

                var subConfig = new ConnectionConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR <AuthenticatedEchoConnection>("/echo", subConfig);

                var subHubsConfig = new HubConfiguration
                {
                    Resolver = resolver
                };

                map.MapSignalR(subHubsConfig);
            });

            app.Map("/fall-back", map =>
            {
                map.Use((context, next) =>
                {
                    if (!context.Request.Path.Value.Contains("negotiate") &&
                        !context.Request.QueryString.Value.Contains("longPolling"))
                    {
                        context.Response.Body = new MemoryStream();
                    }

                    return(next());
                });

                map.RunSignalR <FallbackToLongPollingConnection>();
            });

            app.Map("/no-init", map =>
            {
                map.Use((context, next) =>
                {
                    if (context.Request.Path.Value.Contains("connect"))
                    {
                        context.Response.Body = new MemoryStream();
                    }

                    return(next());
                });
            });

            app.Map("/force-lp-reconnect", map =>
            {
                map.Use((context, next) =>
                {
                    if (context.Request.Path.Value.Contains("poll"))
                    {
                        context.Response.StatusCode = 500;
                        return(TaskAsyncHelper.Empty);
                    }

                    return(next());
                });
                map.MapSignalR <ExamineReconnectPath>("/examine-reconnect", config);
                map.MapSignalR(hubConfig);
            });

            // Perf/stress test related
            var performanceConfig = new ConnectionConfiguration
            {
                Resolver = resolver
            };

            app.MapSignalR <StressConnection>("/echo", performanceConfig);

            performanceConfig.Resolver.Register(typeof(IProtectedData), () => new EmptyProtectedData());

            // IMPORTANT: This needs to run last so that it runs in the "default" part of the pipeline

            // Session is enabled for ASP.NET on the session path
            app.Map("/session", map =>
            {
                map.MapSignalR();
            });
        }
        protected override IList <ConnectionData> GetElementSourceCollection()
        {
            var connectionConfig = ConnectionConfiguration.Get();

            return(connectionConfig.GetConnectionsWithoutCurrent());
        }
Example #47
0
        public Notice Search()
        {
            Notice notice = new Notice();

            try
            {
                var settings = new ConnectionConfiguration(new Uri("http://*****:*****@"
                 * {
                 * ""from"": 0,
                 * ""size"": 10,
                 * ""query"": {
                 * ""match"": {
                 * ""firstName"": ""Martijn""
                 * }
                 * }
                 * }");
                 *
                 * var responseBytes = searchResponse.Body;
                 * string s = bytetohex(responseBytes);*/

                //根据字段值匹配

                /*var searchResponse = lowlevelClient.Search<string>("user", "guest", new
                 * {
                 *  from = 0,
                 *  size = 10,
                 *  query = new
                 *  {
                 *      match = new
                 *      {
                 *          FirstName="Martijn"
                 *      }
                 *  }
                 * });*/
                //根据不同的参数 来构建不同的查询条件

                var searchResponse = lowlevelClient.Search <string>("user", "guest", new
                {
                    from  = 0,
                    size  = 10,
                    query = new
                    {
                        match_all = new
                        {
                        }
                    },
                    sort = new
                    {
                        Id = new
                        {
                            order = "desc"
                        }
                    }
                });

                bool successful   = searchResponse.Success;
                var  responseJson = searchResponse.Body;

                //此处模拟在不建实体类的情况下,反转将json返回回dynamic对象
                //var DynamicObject = JsonConvert.DeserializeObject<dynamic>(json);
                //List<ESearchRoot> roots = JsonHelper.JSONStringToList<ESearchRoot>(responseJson);

                /*ESearchRoot root = JsonHelper.JSONStringObject<ESearchRoot>(responseJson);
                 * int _total = 0;
                 * if (root != null)
                 * {
                 *  _total = root.hits.total;
                 *  //foreach(HitsItem item in root.hits.hits)
                 *  //{
                 *  //    item._source.
                 *  //}
                 * }
                 *
                 * if (!successful)
                 * {
                 *  return new Notice
                 *  {
                 *      Result=successful,
                 *      Message=searchResponse.ServerError.Error.Reason
                 *  };
                 * }
                 *
                 * notice = new Notice
                 * {
                 *  Result=true,
                 *  Message=String.Empty
                 * };*/
            }
            catch (ElasticsearchClientException ex)
            {
                notice = new Notice
                {
                    Result  = false,
                    Message = ex.Message
                };
            }
            return(notice);
        }
Example #48
0
        public void ClientProxy_CrudOperations()
        {
            const int distrServer1  = 22206;
            const int distrServer12 = 22207;
            const int storageServer = 22208;

            #region hell

            var writer = new HashWriter(new HashMapConfiguration("TestClientProxy", HashMapCreationMode.CreateNew, 1, 1, HashFileType.Distributor));
            writer.CreateMap();
            writer.SetServer(0, "localhost", storageServer, 157);
            writer.Save();

            var distrHash    = new DistributorHashConfiguration(1);
            var queue        = new QueueConfiguration(1, 100);
            var connection   = new ConnectionConfiguration("testService", 10);
            var distrCache   = new DistributorCacheConfiguration(TimeSpan.FromMilliseconds(10000), TimeSpan.FromMilliseconds(1000000));
            var netReceive1  = new NetReceiverConfiguration(distrServer1, "localhost", "testService");
            var netReceive12 = new NetReceiverConfiguration(distrServer12, "localhost", "testService");
            var trans        = new TransactionConfiguration(1);
            var hashMap      = new HashMapConfiguration("TestClientProxy", HashMapCreationMode.ReadFromFile, 1, 1, HashFileType.Writer);
            var async        = new AsyncTasksConfiguration(TimeSpan.FromSeconds(10));

            var distr = new DistributorSystem(new ServerId("localhost", distrServer1),
                                              new ServerId("localhost", distrServer12),
                                              distrHash, queue, connection, distrCache, netReceive1, netReceive12, trans,
                                              new HashMapConfiguration("TestClientProxy", HashMapCreationMode.ReadFromFile, 1, 1,
                                                                       HashFileType.Distributor), async, async,
                                              new ConnectionTimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout));

            var netReceivedb = new NetReceiverConfiguration(storageServer, "localhost", "testService");
            var restore      = new RestoreModuleConfiguration(4, TimeSpan.FromMinutes(1));

            var storage = new WriterSystem(new ServerId("localhost", storageServer), queue,
                                           netReceivedb, new NetReceiverConfiguration(1, "fake", "fake"), hashMap, connection, restore, restore,
                                           new ConnectionTimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout),
                                           new RestoreModuleConfiguration(-1, TimeSpan.FromHours(1), false, TimeSpan.FromHours(1)));

            #endregion

            distr.Build();
            distr.Start();

            _proxy.Int.SayIAmHere("localhost", distrServer12);

            storage.Build();
            storage.DbModule.AddDbModule(new TestDbInMemory());
            storage.Start();

            const int count = 50;

            for (int i = 0; i < count; i++)
            {
                var state = _proxy.Int.CreateSync(i, i);
                Assert.AreEqual(RequestState.Complete, state.State);
            }

            for (int i = 0; i < count; i++)
            {
                RequestDescription description;
                var read = _proxy.Int.Read(i, out description);

                Assert.AreEqual(i, read);
                Assert.AreEqual(RequestState.Complete, description.State);
            }

            for (int i = 0; i < count; i++)
            {
                var state = _proxy.Int.DeleteSync(i);
                Assert.AreEqual(RequestState.Complete, state.State);
            }

            for (int i = 0; i < count; i++)
            {
                RequestDescription description;
                _proxy.Int.Read(i, out description);

                Assert.AreEqual(RequestState.DataNotFound, description.State);
            }

            distr.Dispose();
            storage.Dispose();
        }
        /**
         * The following is a list of available connection configuration options:
         */
        public void AvailableOptions()
        {
            var config = new ConnectionConfiguration()
                         .DisableAutomaticProxyDetection() // <1> Disable automatic proxy detection. When called, defaults to `true`.
                         .EnableHttpCompression()          // <2> Enable compressed request and responses from Elasticsearch (Note that nodes need to be configured to allow this. See the {ref_current}/modules-http.html[http module settings] for more info).
                         .DisableDirectStreaming();        // <3> By default responses are deserialized directly from the response stream to the object you tell it to. For debugging purposes, it can be very useful to keep a copy of the raw response on the result object, which is what calling this method will do.

            var client = new ElasticLowLevelClient(config);
            var result = client.Search <SearchResponse <object> >(new { size = 12 });

            /** `.ResponseBodyInBytes` will only have a value if the client configuration has `DisableDirectStreaming` set */
            var raw = result.ResponseBodyInBytes;

            /**
             * Please note that using `.DisableDirectStreaming` only makes sense if you need the mapped response **and** the raw response __at the same time__.
             * If you need only a `string` response simply call
             */
            var stringResult = client.Search <string>(new { });

            /**
             * and similarly, if you need only a `byte[]`
             */
            var byteResult = client.Search <byte[]>(new { });

            /** other configuration options */
            config = config
                     .GlobalQueryStringParameters(new NameValueCollection()) // <1> Allows you to set querystring parameters that have to be added to every request. For instance, if you use a hosted elasticserch provider, and you need need to pass an `apiKey` parameter onto every request.
                     .Proxy(new Uri("http://myproxy"), "username", "pass")   // <2> Sets proxy information on the connection.
                     .RequestTimeout(TimeSpan.FromSeconds(4))                // <3> [[request-timeout]] Sets the global maximum time a connection may take. Please note that this is the request timeout, the builtin .NET `WebRequest` has no way to set connection timeouts (see http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout(v=vs.110).aspx[the MSDN documentation on `HttpWebRequest.Timeout` Property]).
                     .ThrowExceptions()                                      // <4> As an alternative to the C/go like error checking on `response.IsValid`, you can instead tell the client to <<thrown-exceptions, throw exceptions>>.
                     .PrettyJson()                                           // <5> forces all serialization to be indented and appends `pretty=true` to all the requests so that the responses are indented as well
                     .BasicAuthentication("username", "password");           // <6> sets the HTTP basic authentication credentials to specify with all requests.

            /**
             * NOTE: Basic authentication credentials can alternatively be specified on the node URI directly:
             */
            var uri      = new Uri("http://*****:*****@localhost:9200");
            var settings = new ConnectionConfiguration(uri);

            /**
             *...but this may become tedious when using connection pooling with multiple nodes.
             *
             * [[thrown-exceptions]]
             * === Exceptions
             * There are three categories of exceptions that may be thrown:
             *
             * `ElasticsearchClientException`:: These are known exceptions, either an exception that occurred in the request pipeline
             * (such as max retries or timeout reached, bad authentication, etc...) or Elasticsearch itself returned an error (could
             * not parse the request, bad query, missing field, etc...). If it is an Elasticsearch error, the `ServerError` property
             * on the response will contain the the actual error that was returned.  The inner exception will always contain the
             * root causing exception.
             *
             * `UnexpectedElasticsearchClientException`:: These are unknown exceptions, for instance a response from Elasticsearch not
             * properly deserialized.  These are usually bugs and {github}/issues[should be reported]. This exception also inherits from `ElasticsearchClientException`
             * so an additional catch block isn't necessary, but can be helpful in distinguishing between the two.
             *
             * Development time exceptions:: These are CLR exceptions like `ArgumentException`, `ArgumentOutOfRangeException`, etc.
             * that are thrown when an API in the client is misused.
             * These should not be handled as you want to know about them during development.
             *
             */
        }
Example #50
0
 public StatusApiController(IOptions <ConnectionConfiguration> apiConfiguration)
 {
     _apiConfiguration = apiConfiguration.Value;
 }
Example #51
0
        /// <summary>
        ///     The get credentials.
        /// </summary>
        private void GetCredentials()
        {
            var cm = new Credential {
                Target = "VSSonarQubeExtension",
            };

            if (!cm.Exists())
            {
                return;
            }

            cm.Load();

            try
            {
                string address     = this.configurationHelper.ReadSetting(Context.GlobalPropsId, OwnersId.ApplicationOwnerId, "ServerAddress").Value;
                string bootatstart = this.configurationHelper.ReadSetting(Context.GlobalPropsId, OwnersId.ApplicationOwnerId, GlobalIds.IsConnectAtStartOn).Value;

                if (address != null && bootatstart.Equals("true"))
                {
                    if (AuthtenticationHelper.EstablishAConnection(this.restService, address, cm.Username, ConnectionConfiguration.ConvertToUnsecureString(cm.SecurePassword)))
                    {
                        this.UserName      = cm.Username;
                        this.ServerAddress = address;
                        this.Password      = ConnectionConfiguration.ConvertToUnsecureString(cm.SecurePassword);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Example #52
0
        public void Should_parse_the_virtual_hostname()
        {
            var connectionConfiguration = ConnectionConfiguration.Create("host=localhost;virtualHost=myVirtualHost");

            Assert.AreEqual("myVirtualHost", connectionConfiguration.VirtualHost);
        }
Example #53
0
 public CallHandler(ConnectionConfiguration configuration, PersistentConnection connection)
 {
     _configuration = configuration;
     _connection    = connection;
 }
        public void IfAllButOneConnectionDiesSubsequentRequestsMustUseTheOneAliveConnection()
        {
            using (var fake = new AutoFake(callsDoNothing: true))
            {
                //Setting up a datetime provider so that we can measure which
                //nodes have been marked alive and dead.
                //we provide a different fake for the method call with the last node
                //as argument.
                var dateTimeProvider = fake.Resolve <IDateTimeProvider>();
                A.CallTo(() => dateTimeProvider.Now()).Returns(DateTime.UtcNow);
                var markOthersDeadCall = A.CallTo(() => dateTimeProvider
                                                  .DeadTime(A <Uri> .That.Not.Matches(u => u.Port == 9203), A <int> ._, A <int?> ._, A <int?> ._));
                var markLastDead = A.CallTo(() => dateTimeProvider
                                            .DeadTime(A <Uri> .That.Matches(u => u.Port == 9203), A <int> ._, A <int?> ._, A <int?> ._));
                var markOthersAliveCall = A.CallTo(() => dateTimeProvider
                                                   .AliveTime(A <Uri> .That.Not.Matches(u => u.Port == 9203), A <int> ._));
                var markLastAlive = A.CallTo(() => dateTimeProvider
                                             .AliveTime(A <Uri> .That.Matches(u => u.Port == 9203), A <int> ._));
                markOthersDeadCall.Returns(DateTime.UtcNow.AddSeconds(60));
                markLastAlive.Returns(new DateTime());
                fake.Provide(dateTimeProvider);

                //Creating the connection pool making sure nodes are not randomized
                //So we are sure 9203 is that last node in the pool
                var connectionPool = new StaticConnectionPool(
                    _uris,
                    randomizeOnStartup: false,
                    dateTimeProvider: dateTimeProvider
                    );
                var config = new ConnectionConfiguration(connectionPool);
                fake.Provide <IConnectionConfigurationValues>(config);

                // provide a simple fake for synchronous get
                var getCall = FakeCalls.GetSyncCall(fake);

                //The first three tries get a 503 causing the first 3 nodes to be marked dead
                //all the subsequent requests should be handled by 9203 which gives a 200 4 times
                getCall.ReturnsNextFromSequence(
                    FakeResponse.Bad(config),
                    FakeResponse.Bad(config),
                    FakeResponse.Bad(config),
                    FakeResponse.Ok(config),
                    FakeResponse.Ok(config),
                    FakeResponse.Ok(config),
                    FakeResponse.Ok(config)
                    );
                //provide a transport with all the dependencies resolved
                var transport = this.ProvideTransport(fake);
                var pingCall  = FakeCalls.PingAtConnectionLevel(fake);
                pingCall.Returns(_ok);

                //instantiate connection with faked dependencies
                var client = fake.Resolve <ElasticsearchClient>();

                //We call the root for each node 4 times, eventhough the first 3 nodes
                //give back a timeout the default ammount of retries is 4 (each provided node)
                //and the last retry will hit our 9203 node.
                Assert.DoesNotThrow(() => client.Info());
                //These calls should not hit the dead nodes and go straight to the active 9203
                Assert.DoesNotThrow(() => client.Info());
                Assert.DoesNotThrow(() => client.Info());
                Assert.DoesNotThrow(() => client.Info());

                //The last node should never be marked dead
                markLastDead.MustNotHaveHappened();
                //the other nodes should never be marked alive
                markOthersAliveCall.MustNotHaveHappened();
                //marking the other 3 nodes dead should only happen once for each
                markOthersDeadCall.MustHaveHappened(Repeated.Exactly.Times(3));
                //every time a connection succeeds on a node it will be marked
                //alive therefor the last node should be marked alive 4 times
                markLastAlive.MustHaveHappened(Repeated.Exactly.Times(4));
            }
        }
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            if (_isDisposed)
            {
                return;
            }

            var connectionConfig = ConnectionConfiguration.Get();

            if (connectionConfig?.CurrentConnectionData == null)
            {
                return;
            }

            ITextSnapshot snapshot     = _buffer.CurrentSnapshot;
            var           triggerPoint = session.GetTriggerPoint(snapshot);

            if (triggerPoint == null)
            {
                return;
            }

            var repository = ConnectionIntellisenseDataRepository.GetRepository(connectionConfig.CurrentConnectionData);

            SnapshotSpan extent = FindTokenSpanAtPosition(session).GetSpan(snapshot);

            ITrackingSpan applicableTo = null;

            if (extent.GetText() == ".")
            {
                extent = new SnapshotSpan(extent.Start + 1, extent.End);
            }

            var line = triggerPoint.Value.GetContainingLine().Extent;

            var relativePath = string.Empty;

            if (line.Start <= extent.Start)
            {
                relativePath = new SnapshotSpan(line.Start, extent.Start).GetText().TrimEnd('.');
            }

            applicableTo = snapshot.CreateTrackingSpan(extent, SpanTrackingMode.EdgeInclusive);

            var intellisenseData = repository.GetEntitiesIntellisenseData();

            if (intellisenseData == null ||
                intellisenseData.Entities == null
                )
            {
                return;
            }

            try
            {
                if (string.IsNullOrEmpty(relativePath))
                {
                    FillEntityNamesInList(completionSets, applicableTo, intellisenseData, false);
                }
                else
                {
                    var usedEntities = GetUsedEntitiesFromPath(relativePath, intellisenseData);

                    if (usedEntities.Any())
                    {
                        repository.GetEntityDataForNamesAsync(usedEntities);
                    }

                    var entityNameHash = GetEntityNameFromPath(relativePath, intellisenseData, out bool isGuid);

                    if (entityNameHash != null)
                    {
                        if (entityNameHash.Count == 1)
                        {
                            var entityName = entityNameHash.First();

                            var entityData = repository.GetEntityAttributeIntellisense(entityName);

                            if (entityData != null)
                            {
                                FillEntityIntellisenseDataAttributes(completionSets, applicableTo, entityData);

                                FillMultiLinkForEntity(completionSets, applicableTo, intellisenseData, entityData);
                            }
                        }
                        else if (entityNameHash.Count > 0)
                        {
                            FillMultiLinkEntityForEntities(completionSets, applicableTo, entityNameHash, intellisenseData);
                        }
                        else if (isGuid)
                        {
                            FillMultiLinkEntityForAll(completionSets, applicableTo, intellisenseData);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(connectionConfig.CurrentConnectionData, ex);
            }
        }
 public void Should_fail_if_host_is_not_present()
 {
     Assert.Throws <UriFormatException>(() => ConnectionConfiguration.Create("amqp://:1234/"));
 }
Example #57
0
        /// <summary>
        /// Returns an EasyNetQ <see cref="IBus"/> connection to a RabbitMQ cluster.
        /// </summary>
        /// <param name="username">Optional username (overrides <see cref="Username"/>).</param>
        /// <param name="password">Optional password (overrides <see cref="Password"/>).</param>
        /// <param name="virtualHost">Optional target virtual host (defaults to <b>"/"</b>).</param>
        /// <param name="busSettings">Optional message bus client settings.</param>
        /// <param name="customServiceAction">
        /// Optionally specifies an action that overrides the default the EasyNetQ
        /// client configuration via dependency injection.
        /// </param>
        /// <returns>The connected <see cref="IBus"/>.</returns>
        public IBus ConnectEasyNetQ(
            string username             = null,
            string password             = null,
            string virtualHost          = "/",
            EasyBusSettings busSettings = null,
            Action <IServiceRegister> customServiceAction = null)
        {
            Covenant.Requires <NotImplementedException>(!TlsEnabled, "$todo(jeff.lill): We don't support RabbitMQ TLS yet.");

            var config = new ConnectionConfiguration()
            {
                Port        = (ushort)AmqpPort,
                UserName    = username ?? Username,
                Password    = password ?? Password,
                VirtualHost = virtualHost
            };

            if (busSettings != null)
            {
                busSettings.ApplyTo(config);
            }

            if (string.IsNullOrEmpty(config.UserName))
            {
                throw new ArgumentNullException($"[{nameof(username)}] is required.");
            }

            if (string.IsNullOrEmpty(config.Password))
            {
                throw new ArgumentNullException($"[{nameof(password)}] is required.");
            }

            var hostConfigs = new List <HostConfiguration>();

            foreach (var host in AmqpHosts)
            {
                hostConfigs.Add(new HostConfiguration()
                {
                    Host = host, Port = (ushort)AmqpPort
                });
            }

            config.Hosts = hostConfigs;

            // Enable Neon based logging if requested (which is the default).

            if (NeonLog)
            {
                // Generate a reasonable [sourceModule] setting.

                var sourceModule = "EasyNetQ";
                var product      = busSettings?.Product ?? string.Empty;
                var appName      = busSettings?.Name ?? string.Empty;

                if (!string.IsNullOrEmpty(product) || !string.IsNullOrEmpty(appName))
                {
                    if (string.IsNullOrEmpty(product))
                    {
                        sourceModule = appName;
                    }
                    else if (string.IsNullOrEmpty(appName))
                    {
                        sourceModule = product;
                    }
                    else if (product != appName)
                    {
                        sourceModule = $"{product}/{appName}";
                    }
                    else
                    {
                        sourceModule = appName;
                    }
                }
                else
                {
                    // We're going to try to default to the current executable name
                    // for the source module.  Note that it's possible that we can't
                    // obtain this name in some situations, e.g. when running
                    // on Integration Services Package (SSIS).  In those cases,
                    // this will default to "EasyNetQ".

                    var appPath = Environment.GetCommandLineArgs()[0];

                    if (!string.IsNullOrWhiteSpace(appPath))
                    {
                        sourceModule = Path.GetFileNameWithoutExtension(appPath);
                    }
                }

                var neonLogger      = LogManager.Default.GetLogger(sourceModule);
                var neonLogProvider = new HiveEasyMQLogProvider(neonLogger);

                LogProvider.SetCurrentLogProvider(neonLogProvider);
            }

            if (customServiceAction == null)
            {
                // Use a NOP service action.

                customServiceAction = r => { };
            }

            var bus = RabbitHutch.CreateBus(config, customServiceAction);

            if (!bus.IsConnected)
            {
                bus.Dispose();

                throw new Exception("Cannot to connect to RabbitMQ.");
            }

            return(bus);
        }
        public void Should_use_explicit_port_setting_over_scheme_default()
        {
            var connectionConfiguration = ConnectionConfiguration.Create("amqp://localhost:1234/");

            Assert.AreEqual(connectionConfiguration.Port, 1234);
        }
Example #59
0
        public void Start()
        {
            try {
                Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Exchange_Svc.MyServiceName));
            } catch (Exception ex) {
                Trace.TraceWarning("{2}\t{0}: не удалось создать папку логов: {1}", _Name, ex.Message, DateTime.Now);
            }

            if (DebugFlag.Enabled)
            {
                try {
                    dbLog = new StreamWriter(Path.Combine(Path.GetTempPath(), Exchange_Svc.MyServiceName, "service.dblog"))
                    {
                        AutoFlush = true
                    };
                } catch (Exception ex) {
                    Trace.TraceWarning("{2}\t{0}: не удалось создать журнал dblog: {1}", _Name, ex.Message, DateTime.Now);
                }
            }

            Trace.TraceInformation("{1}\t{0}: запускается...", _Name, DateTime.Now);

            if (dbConnStr == null || String.IsNullOrWhiteSpace(dbConnStr))
            {
                FailStart("Запуск невозможен: строка подключения к БД не может быть пустой");
            }

            using (var SQLconn = new SqlConnection(dbConnStr)) {
                // Пытаемся подключиться к БД
                int errorCounter = 0;
                while (SQLconn.State == ConnectionState.Closed)
                {
                    try {
                        SQLconn.Open();
                    } catch (Exception ex) {
                        if (ex is InvalidOperationException)
                        {
                            FailStart("Запуск невозможен: ошибка в строке подключения к БД \"{0}\"", dbConnStr);
                        }
                        else if (errorCounter >= 3)
                        {
                            FailStart("Превышено допустимое количество неудачных попыток подключения к БД. Последняя ошибка: {0}", ex.Message);
                        }
                        else
                        {
                            errorCounter++;
                            Trace.TraceWarning("{1}\tНеудачная попытка подключения к БД: {0}", ex.Message, DateTime.Now);
                            Thread.Sleep(1000);
                        }
                    }
                }

                // На этом этапе соединение с БД установлено
                try {
                    new LogRecord()
                    {
                        Source  = _Name,
                        Message = "Успешный запуск, установлено соединение с БД",
                        Details = dbConnStr
                    }
                    .TryWrite(SQLconn, dbLog);
                } catch (Exception ex) {
                    FailStart("Запуск невозможен: ошибка записи в БД, {0}", ex.Message);
                }
                // Получаем список хостов RabbitMQ
                using (var exdb = new exDb(SQLconn)) {
                    exdb.Log     = dbLog;
                    RabbitHosts  = exdb.Hosts.Where(h => exdb.Queues.Any(q => q.Host_Id == h.Host_Id)).ToList();
                    RabbitQueues = exdb.Queues.ToList();
                    if (RabbitHosts.Count == 0)
                    {
                        var msg = "В таблице Hosts нет активных записей. Остановка службы";
                        new LogRecord()
                        {
                            Source  = _Name,
                            IsError = true,
                            Message = msg
                        }
                        .TryWrite(exdb);
                        FailStart(msg);
                    }
                }
                // Подключаемся к хостам RabbitMQ
                foreach (var host in RabbitHosts)
                {
                    var rabbit_conn = new ConnectionConfiguration();
                    rabbit_conn.PrefetchCount     = Convert.ToUInt16((host.PrefetchCount > 0) ? host.PrefetchCount : 1);
                    rabbit_conn.PublisherConfirms = true;
                    //r_conn.Port = Convert.ToUInt16((host.Port > 0) ? host.Port : 5671);
                    if (!String.IsNullOrWhiteSpace(host.VirtualHost))
                    {
                        rabbit_conn.VirtualHost = host.VirtualHost;
                    }
                    if (!String.IsNullOrWhiteSpace(host.Username))
                    {
                        rabbit_conn.UserName = host.Username;
                        if (!String.IsNullOrWhiteSpace(host.Password))
                        {
                            rabbit_conn.Password = host.Password;
                        }
                    }

                    var r_host = new HostConfiguration();
                    r_host.Host = host.Host;
                    r_host.Port = Convert.ToUInt16((host.Port > 0) ? host.Port : host.SslEnabled ? 5671 : 5672);
                    if (host.SslEnabled)
                    {
                        r_host.Ssl.Enabled = true;
                        //r_host.Ssl.ServerName = host.Host;
                        r_host.Ssl.AcceptablePolicyErrors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors | System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable | System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch;
                    }
                    rabbit_conn.Hosts = new[] { r_host };

                    new LogRecord()
                    {
                        Source  = _Name,
                        HostId  = host.Host_Id,
                        Message = String.Format("Подключаемся к {0}серверу RabbitMQ...", host.SslEnabled ? "SSL " : ""),
                        Details = host.ConnectionString
                    }
                    .TryWrite(SQLconn, dbLog);

                    IEasyNetQLogger r_Log = new EasyNetQ.Loggers.NullLogger();
                    if (DebugFlag.Enabled)
                    {
                        try {
                            r_Log = new RabbitTextLogger(new StreamWriter(Path.Combine(Path.GetTempPath(), Exchange_Svc.MyServiceName, String.Format("rabbit_{0}.log", host.Host_Id)))
                            {
                                AutoFlush = true
                            });
                            //r_Log = new EasyNetQ.Loggers.ConsoleLogger();
                        } catch (Exception ex) {
                            Trace.TraceWarning("{4}\t{0}: не удалось создать журнал rabbit_{1} ({2}): {3}", _Name, host.Host_Id, host.ConnectionString, ex.Message, DateTime.Now);
                        }
                    }

                    try {
                        rabbit_conn.Validate();
                        var bus = RabbitHutch.CreateBus(rabbit_conn, services => services.Register <IEasyNetQLogger>(logger => r_Log));
                        Buses.Add(bus);
                        foreach (var q in RabbitQueues.Where(q => q.Host_Id == host.Host_Id))
                        {
                            q.Bus = bus;
                        }

                        for (int i = 0; i < 10; i++)
                        {
                            if (bus.IsConnected)
                            {
                                new LogRecord()
                                {
                                    Source  = _Name,
                                    HostId  = host.Host_Id,
                                    Message = String.Format("Установлено {0}подключение к RabbitMQ", host.SslEnabled ? "SSL " : ""),
                                    Details = host.ConnectionString
                                }
                                .TryWrite(SQLconn, dbLog);

                                break;
                            }
                            Thread.Sleep(10);
                        }
                    } catch (Exception ex) {
                        new LogRecord()
                        {
                            Source  = _Name,
                            IsError = true,
                            Message = String.Format("Ошибка при {0}подключении к серверу RabbitMQ: {1}", host.SslEnabled ? "SSL " : "", ex.Message),
                            Details = rabbit_conn.ToString()
                        }
                        .TryWrite(SQLconn, dbLog);
                    }
//					}
                }

                if (Buses.Count == 0)
                {
                    var msg = "Не удалось подключиться ни к одному из хостов RabbitMQ. Остановка службы";
                    new LogRecord()
                    {
                        Source  = _Name,
                        IsError = true,
                        Message = msg
                    }
                    .TryWrite(SQLconn, dbLog);
                    FailStart(msg);
                }

                // Запускаем обработчики очередей
                workers = new List <Worker>();
                foreach (var queue in RabbitQueues.Where(q => q.Bus != null))
                {
                    Worker w;

                    if (queue.Direction.Trim() == "In")
                    {
                        w = new Receiver(dbConnStr, (IBus)queue.Bus, queue);
                    }
                    else if (queue.Direction.Trim() == "Out")
                    {
                        w = new Sender(dbConnStr, (IBus)queue.Bus, queue);
                    }
                    else
                    {
                        new LogRecord()
                        {
                            Source  = _Name,
                            HostId  = queue.Host.Host_Id,
                            QueueId = queue.Queue_Id,
                            IsError = true,
                            Message = String.Format("Неизвестный тип очереди: '{0}'", queue.Direction),
                            Details = queue.Name
                        }
                        .TryWrite(SQLconn, dbLog);

                        continue;
                    }

                    new LogRecord()
                    {
                        Source  = _Name,
                        HostId  = queue.Host.Host_Id,
                        QueueId = queue.Queue_Id,
                        Message = "Запускаем обработчик очереди сообщений...",
                        Details = w.QueueFullName
                    }
                    .TryWrite(SQLconn, dbLog);

                    w.Run();
                    workers.Add(w);
                }

                timer           = new System.Timers.Timer(30000D);
                timer.AutoReset = true;
                timer.Elapsed  += timer_Elapsed;
                timer.Start();

                                #if DEBUG
                while (!workers.All(w => w.Thread.Join(3000)))
                {
                    continue;
                }
                                #endif
            }
        }
Example #60
0
        protected override ICollection <ConnectionData> GetElementSourceCollection()
        {
            var connectionConfig = ConnectionConfiguration.Get();

            return(connectionConfig.Connections);
        }