public MailBeeEmailClient(ConnectionSettings settings)
		{
			_settings = settings;
			_client = settings.GetEmailProtocol() == EmailProtocol.Imap
				? (IMailBeeClient) new ImapMailBeeClient()
				: new Pop3MailBeeClient();
		}
		public void WhenPostExceedsHttpLimit_DoNotRetry_UsingConnectionPooling()
		{
			var pool = new StaticConnectionPool(new []
			{
				new Uri("http://localhost:9200"),
				new Uri("http://127.0.0.1:9200"),
			});
			var settings = new ConnectionSettings(pool);
			var client = new ElasticClient(settings);


			var index = ElasticsearchConfiguration.NewUniqueIndexName();
			var projects = NestTestData.Data;
			var people = NestTestData.People;
			var boolTerms = NestTestData.BoolTerms;
			var bulk = client.Bulk(b => b
				.FixedPath(index)
				.IndexMany(projects)
				.IndexMany(people)
				.IndexMany(boolTerms)
			);

			bulk.IsValid.Should().BeFalse();
			bulk.ConnectionStatus.NumberOfRetries.Should().Be(0);
		}
		public void ShouldFailoverOnThriftConnectionsUsingSniff()
		{
			var uris = new []
			{
				new Uri("http://INVALID_HOST"),
				new Uri("http://INVALID_HOST2"),
				new Uri("http://localhost:9500"),
			};
			var connectionPool = new SniffingConnectionPool(uris, randomizeOnStartup: false);
			var settings = new ConnectionSettings(connectionPool, ElasticsearchConfiguration.DefaultIndex)
				.SniffOnStartup()
				.ExposeRawResponse()
				.SetTimeout(2000);
			var client = new ElasticClient(settings, new ThriftConnection(settings));

			var results = client.Search<dynamic>(s => s.MatchAll());
			results.IsValid.Should().BeTrue("{0}", results.ConnectionStatus.ToString());
			results.ConnectionStatus.NumberOfRetries.Should().Be(0);
			var u = new Uri(results.ConnectionStatus.RequestUrl);
			u.Port.Should().Be(9500);

			results = client.Search<dynamic>(s => s.MatchAll());
			results.IsValid.Should().BeTrue("{0}", results.ConnectionStatus.ToString());
			results.ConnectionStatus.NumberOfRetries.Should().Be(0);
			u = new Uri(results.ConnectionStatus.RequestUrl);
			u.Port.Should().Be(9501);
		}
        public EventStoreEmbeddedNodeConnection(ConnectionSettings settings, string connectionName, IPublisher publisher, ISubscriber bus, IAuthenticationProvider authenticationProvider)
        {
            Ensure.NotNull(publisher, "publisher");
            Ensure.NotNull(settings, "settings");

            Guid connectionId = Guid.NewGuid();

            _settings = settings;
            _connectionName = connectionName;
            _publisher = publisher;
            _authenticationProvider = authenticationProvider;
            _subscriptionBus = new InMemoryBus("Embedded Client Subscriptions");
            _subscriptions = new EmbeddedSubscriber(_subscriptionBus, _authenticationProvider, _settings.Log, connectionId);
            
            _subscriptionBus.Subscribe<ClientMessage.SubscriptionConfirmation>(_subscriptions);
            _subscriptionBus.Subscribe<ClientMessage.SubscriptionDropped>(_subscriptions);
            _subscriptionBus.Subscribe<ClientMessage.StreamEventAppeared>(_subscriptions);
            _subscriptionBus.Subscribe<ClientMessage.PersistentSubscriptionConfirmation>(_subscriptions);
            _subscriptionBus.Subscribe<ClientMessage.PersistentSubscriptionStreamEventAppeared>(_subscriptions);
            _subscriptionBus.Subscribe(new AdHocHandler<ClientMessage.SubscribeToStream>(_publisher.Publish));
            _subscriptionBus.Subscribe(new AdHocHandler<ClientMessage.UnsubscribeFromStream>(_publisher.Publish));
            _subscriptionBus.Subscribe(new AdHocHandler<ClientMessage.ConnectToPersistentSubscription>(_publisher.Publish));

            bus.Subscribe(new AdHocHandler<SystemMessage.BecomeShutdown>(_ => Disconnected(this, new ClientConnectionEventArgs(this, new IPEndPoint(IPAddress.None, 0)))));
        }
Ejemplo n.º 5
0
 public SubscriptionsManager(string connectionName, ConnectionSettings settings)
 {
     Ensure.NotNull(connectionName, "connectionName");
     Ensure.NotNull(settings, "settings");
     _connectionName = connectionName;
     _settings = settings;
 }
        public ElasticsearchRepositoryDocumentNotExistsSpecs()
        {
            var settings = new ConnectionSettings();

            _client = new ElasticClient(settings, new InMemoryConnection(settings, string.Empty, 404));
            _repository = new ElasticsearchRepository(_client);
        }
Ejemplo n.º 7
0
        public void TestIndexTimeout()
        {
            var timeout = 1;
            var s = new ConnectionSettings(Test.Default.Host, Test.Default.Port, timeout)
                        .SetDefaultIndex(Test.Default.DefaultIndex)
                        .SetMaximumAsyncConnections(Test.Default.MaximumAsyncConnections)
                        .UsePrettyResponses();

            var client = new ElasticClient(s);

            var newProject = new ElasticSearchProject
            {
                Name = "COBOLES", //COBOL ES client ?
            };
            var t = client.IndexAsync<ElasticSearchProject>(newProject);
            t.Wait(1000);
              var r = t.Result;
              Assert.True(r.IsValid);
              Assert.IsNotNullOrEmpty(r.Id);

            var cs = r.ConnectionStatus;
            Assert.False(cs.Success);
            Assert.NotNull(cs.Error);
            Assert.NotNull(cs.Error.OriginalException);
            Trace.WriteLine(cs.Error.OriginalException);
            Assert.IsNotNullOrEmpty(cs.Error.ExceptionMessage);
            Assert.IsTrue(cs.Error.OriginalException is WebException);
            var we = cs.Error.OriginalException as WebException;
            Assert.IsTrue(cs.Error.ExceptionMessage.Contains("The request was canceled"));
            Assert.IsTrue(we.Status == WebExceptionStatus.RequestCanceled);
            Assert.True(t.IsCompleted, "task did not complete");
            Assert.False(t.IsFaulted, "task was faulted, wich means the exception did not cleanly pass to ConnectionStatus");
        }
		public async void SniffOnStartShouldOnlyHit9200_WithoutPing_Async()
		{
			var seeds = new[]
			{
				ElasticsearchConfiguration.CreateBaseUri(9202),
				ElasticsearchConfiguration.CreateBaseUri(9201),
				ElasticsearchConfiguration.CreateBaseUri(9200)
			};
			var sniffingConnectionPool = new SniffingConnectionPool(seeds, randomizeOnStartup: false);
			var connectionSettings = new ConnectionSettings(sniffingConnectionPool)
				.SniffOnStartup();
			var client = new ElasticClient(connectionSettings);
			var rootNode = await client.RootNodeInfoAsync();
			var metrics = rootNode.ConnectionStatus.Metrics;
			
			//When the connectionpool is used for the first time the sniff call should already
			//know only 9200 is on and live, no need to ping
			metrics.Requests.Count.Should().Be(1);
			metrics.Requests[0].Node.Port.Should().Be(9200);
			metrics.Requests[0].RequestType.Should().Be(RequestType.ElasticsearchCall);

			for (var i = 0; i < 3; i++)
			{
				rootNode = await client.RootNodeInfoAsync();
				metrics = rootNode.ConnectionStatus.Metrics;
				metrics.Requests.Count.Should().Be(1);
				metrics.Requests[0].Node.Port.Should().Be(9200);
				metrics.Requests[0].RequestType.Should().Be(RequestType.ElasticsearchCall);
			}

		}
        public EventStoreConnectionLogicHandler(IEventStoreConnection esConnection, ConnectionSettings settings)
        {
            Ensure.NotNull(esConnection, "esConnection");
            Ensure.NotNull(settings, "settings");

            _esConnection = esConnection;
            _settings = settings;

            _operations = new OperationsManager(_esConnection.ConnectionName, settings);
            _subscriptions = new SubscriptionsManager(_esConnection.ConnectionName, settings);

            _queue.RegisterHandler<StartConnectionMessage>(msg => StartConnection(msg.Task, msg.EndPointDiscoverer));
            _queue.RegisterHandler<CloseConnectionMessage>(msg => CloseConnection(msg.Reason, msg.Exception));

            _queue.RegisterHandler<StartOperationMessage>(msg => StartOperation(msg.Operation, msg.MaxRetries, msg.Timeout));
            _queue.RegisterHandler<StartSubscriptionMessage>(StartSubscription);

            _queue.RegisterHandler<EstablishTcpConnectionMessage>(msg => EstablishTcpConnection(msg.EndPoints));
            _queue.RegisterHandler<TcpConnectionEstablishedMessage>(msg => TcpConnectionEstablished(msg.Connection));
            _queue.RegisterHandler<TcpConnectionErrorMessage>(msg => TcpConnectionError(msg.Connection, msg.Exception));
            _queue.RegisterHandler<TcpConnectionClosedMessage>(msg => TcpConnectionClosed(msg.Connection));
            _queue.RegisterHandler<HandleTcpPackageMessage>(msg => HandleTcpPackage(msg.Connection, msg.Package));

            _queue.RegisterHandler<TimerTickMessage>(msg => TimerTick());

            _timer = new Timer(_ => EnqueueMessage(TimerTickMessage), null, Consts.TimerPeriod, Consts.TimerPeriod);
        }
		public void FailoverShouldOnlyPingDeadNodes()
		{
			var seeds = new[]
			{
				ElasticsearchConfiguration.CreateBaseUri(9202),
				ElasticsearchConfiguration.CreateBaseUri(9201),
				ElasticsearchConfiguration.CreateBaseUri(9200)
			};
			var sniffingConnectionPool = new SniffingConnectionPool(seeds, randomizeOnStartup: false);
			var connectionSettings = new ConnectionSettings(sniffingConnectionPool);
			var client = new ElasticClient(connectionSettings);
			var rootNode = client.RootNodeInfo();
			var metrics = rootNode.ConnectionStatus.Metrics;
			
			//ping 9202 + 9201 + 9200 and call 9200
			metrics.Requests.Count.Should().Be(4);
			metrics.Requests[0].Node.Port.Should().Be(9202);
			metrics.Requests[0].RequestType.Should().Be(RequestType.Ping);
			metrics.Requests[0].EllapsedMilliseconds.Should().BeLessOrEqualTo(1100);
			metrics.Requests[1].Node.Port.Should().Be(9201);
			metrics.Requests[1].RequestType.Should().Be(RequestType.Ping);
			metrics.Requests[1].EllapsedMilliseconds.Should().BeLessOrEqualTo(1100);
			metrics.Requests[2].Node.Port.Should().Be(9200);
			metrics.Requests[2].RequestType.Should().Be(RequestType.Ping);
			metrics.Requests[2].EllapsedMilliseconds.Should().BeLessOrEqualTo(1100);
			metrics.Requests[3].Node.Port.Should().Be(9200);
			metrics.Requests[3].RequestType.Should().Be(RequestType.ElasticsearchCall);
			metrics.Requests[3].EllapsedMilliseconds.Should().BeLessOrEqualTo(1100);



			rootNode = client.RootNodeInfo();
			metrics = rootNode.ConnectionStatus.Metrics;
			metrics.Requests.Count.Should().Be(1);
			metrics.Requests[0].Node.Port.Should().Be(9200);
			metrics.Requests[0].RequestType.Should().Be(RequestType.ElasticsearchCall);

			rootNode = client.RootNodeInfo();
			metrics = rootNode.ConnectionStatus.Metrics;
			metrics.Requests.Count.Should().Be(1);
			metrics.Requests[0].Node.Port.Should().Be(9200);
			metrics.Requests[0].RequestType.Should().Be(RequestType.ElasticsearchCall);


			rootNode = client.RootNodeInfo();
			metrics = rootNode.ConnectionStatus.Metrics;
			metrics.Requests.Count.Should().Be(1);
			metrics.Requests[0].Node.Port.Should().Be(9200);
			metrics.Requests[0].RequestType.Should().Be(RequestType.ElasticsearchCall);


			rootNode = client.RootNodeInfo();	
			metrics = rootNode.ConnectionStatus.Metrics;
			metrics.Requests.Count.Should().Be(1);
			metrics.Requests[0].Node.Port.Should().Be(9200);
			metrics.Requests[0].RequestType.Should().Be(RequestType.ElasticsearchCall);


		}
 public OrganizationRequestBuilderVisitor(ICrmMetaDataProvider crmMetadataProvider, DbParameterCollection parameters, IDynamicsAttributeTypeProvider typeProvider, ConnectionSettings settings = null)
 {
     CrmMetadataProvider = crmMetadataProvider;
     Parameters = parameters;
     TypeProvider = typeProvider;
     Settings = settings ?? ConnectionSettings.Default();
     // OrgCommand = new OrganisationRequestCommand();
 }
		private static void CheckConnection(ConnectionSettings settings, PluginProfileErrorCollection errors)
		{
			using (IEmailClient client = new MailBeePop3EmailClient(settings))
			{
				client.CheckConnection(errors);
				client.Disconnect();
			}
		}
Ejemplo n.º 13
0
        private Exchange(ConnectionSettings connectionSettings, string name, string type, bool durable)
            : base(connectionSettings, name)
        {
            this.Type = type;
            this.Durable = durable;

            this.Channel.ExchangeDeclare(this.Name, this.Type, durable);
        }
Ejemplo n.º 14
0
		public void Construct_Client_With_Invalid_Hostname()
		{
			Assert.Throws<UriFormatException>(() =>
			{
				var settings = new ConnectionSettings(new Uri("some mangled hostname:80"), "index");
			});

		}
		public void IdPropertyNotMapped_IdIsInferred()
		{
			var settings = new ConnectionSettings();
			var client = new ElasticClient(settings, connection: new InMemoryConnection());
			var project = new ElasticsearchProject { Id = 123 };

			Assert.AreEqual(project.Id.ToString(), client.Infer.Id<ElasticsearchProject>(project));
		}
Ejemplo n.º 16
0
        public void DeserializeOfStreamDoesNotHoldACopyOfTheResponse()
        {
            var uri = ElasticsearchConfiguration.CreateBaseUri();
            var settings = new ConnectionSettings(uri, ElasticsearchConfiguration.DefaultIndex);
            IElasticClient client = new ElasticClient(settings);

            var results = client.Search<ElasticsearchProject>(s => s.MatchAll());
        }
Ejemplo n.º 17
0
		public void TestConnectSuccessWithUri()
		{
			var settings = new ConnectionSettings(ElasticsearchConfiguration.CreateBaseUri(), "index");
			var client = new ElasticClient(settings);
			var result = client.RootNodeInfo();

			Assert.True(result.IsValid);
			Assert.NotNull(result.ConnectionStatus.HttpStatusCode);
		}
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            ConnectionSettings mailBoxSettings = new ConnectionSettings("imap.yandex.ru", 993, true, "*****@*****.**", "Olya04072010");
            //ConnectionSettings mailBoxSettings = new ConnectionSettings("imap.yandex.ru", 993, true, "*****@*****.**", "17991837!");
            //ConnectionSettings mailBoxSettings = new ConnectionSettings("imap.gmail.com", 993, true, "*****@*****.**", "tmg04092014!");

            ICommand command = new CreateRequestReportCommand(mailBoxSettings);
            command.Execute(null);
        }
        /// <summary>
        /// Sets the application network credentials.
        /// </summary>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        public void SetConnectionSettings(ConnectionSettings credentials)
        {
            ServiceSettings.AuthenticationRequired = credentials.AuthenticationRequired;
            ServiceSettings.Login = credentials.Login;
            ServiceSettings.Password = credentials.Password;
            ServiceSettings.Url = credentials.Url;

            IsolatedStorageSettings.ApplicationSettings["ConnectionSettings"] = credentials;
        }
        public ElasticsearchRepositoryGetByIdSpecs()
        {
            var settings = new ConnectionSettings();

            var output =
                "Nest.Queryify.Tests.TestData.ValidGetResponse.json".ReadAsStringFromEmbeddedResource<ElasticClientQueryObjectTestFixture>();
            _client = new ElasticClient(settings, new InMemoryConnection(settings, output));
            _repository = new ElasticsearchRepository(_client);
        }
		public MailBeePop3EmailClient(ConnectionSettings settings)
		{
			_settings = settings;

			Pop3.LicenseKey = MAILBEE_LICENSE_KEY;

			// Make sure to disable throwing exception explicitly. Otherwise strange things might happen. See bug #5748 for details.
			// So please don't change this option unless you know what you are doing!!!
			_client = new Pop3 {ThrowExceptions = false};
		}
		public void TestUsesDefaultPropertyNameResolver()
		{
			var settings = new ConnectionSettings(UnitTestDefaults.Uri, UnitTestDefaults.DefaultIndex)
				.SetDefaultPropertyNameInferrer(p => p);
			var client = new ElasticClient(settings);
			Expression<Func<UserItemData, object>> exp = (m) => m.UserLabels;
			var propertyName = client.Infer.PropertyPath(exp);
			Assert.AreEqual("UserLabels", propertyName);

		}
Ejemplo n.º 23
0
 public void IndexExistShouldNotThrowOn404()
 {
     var host = Test.Default.Host;
     if (Process.GetProcessesByName("fiddler").Any())
         host = "ipv4.fiddler";
     var connectionPool = new SniffingConnectionPool(new[] { new Uri("http://{0}:9200".F(host)) });
     var settings = new ConnectionSettings(connectionPool, ElasticsearchConfiguration.DefaultIndex)
         .SniffOnStartup();
     var client = new ElasticClient(settings);
 }
        protected override ConnectionSettings GetConnectionSettings()
        {
            if (string.IsNullOrEmpty(AppId))
            {
                PulsusDebugger.Error("The provided AppId is not valid. Please check configuration");
                return null;
            }

            ConnectionSettings connectionSettings = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                var provider = SecureStoreProviderFactory.Create();
                ((ISecureStoreServiceContext)provider).Context = Context;

                using (var credentials = provider.GetCredentials(AppId))
                {
                    if (credentials == null)
                        throw new Exception(string.Format("Unable to retrive the credentials for AppId '{0}'", AppId));

                    // used to validate connection string
                    var connectionStringBuilder = new DbConnectionStringBuilder();

                    foreach (SecureStoreCredential credential in credentials)
                    {
                        // as we don't have access to the credential name we can only evaluate the value
                        // to find a connection string

                        if (credential.CredentialType == SecureStoreCredentialType.Generic)
                        {
                            var connectionString = ReadSecureString(credential.Credential);

                            if (string.IsNullOrEmpty(connectionString))
                                continue;

                            try
                            {
                                connectionStringBuilder.ConnectionString = connectionString;
                            }
                            catch (ArgumentException)
                            {
                                // this is not a connection string so move on
                                continue;
                            }

                            connectionSettings = new ConnectionSettings(connectionString);
                        }
                    }
                }
            });

            if (connectionSettings == null)
                PulsusDebugger.Error("Unable to find a connection string in AppId '{0}' credentials. Please check the secure store", AppId);

            return connectionSettings;
        }
Ejemplo n.º 25
0
		
		public ConnectionSettings GetDefaultConnectionSettings ()
		{
			ConnectionSettings settings = new ConnectionSettings ();
			settings.ProviderIdentifier = Identifier;
			settings.Server = "localhost";
			settings.Port = 4100;
			settings.Username = "******";
			settings.Password = String.Empty;
			settings.Database = String.Empty;
			return settings;
		public CustomConvertersTests()
		{
			var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
				.SetDefaultIndex("nest_test_data")
				.AddContractJsonConverters(
					t => typeof(Enum).IsAssignableFrom(t) ? new Newtonsoft.Json.Converters.StringEnumConverter() : null,
					t => typeof(NestedObject).IsAssignableFrom(t) ? new CustomConverter() : null
				);

			 _serializationClient = new ElasticClient(settings);
		}
		public void MapNumericIdProperty()
		{
			var settings = new ConnectionSettings()
				.MapIdPropertyFor<ElasticsearchProject>(p => p.LongValue);

			var client = new ElasticClient(settings, connection: new InMemoryConnection());

			var project = new ElasticsearchProject { LongValue = 123 };

			Assert.AreEqual(project.LongValue.ToString(), client.Infer.Id<ElasticsearchProject>(project));
		}
        /// <summary>
        /// Constructs a new instance of a <see cref="EventStoreConnection"/>
        /// </summary>
        /// <param name="settings">The <see cref="ConnectionSettings"/> containing the settings for this connection.</param>
        /// <param name="clusterSettings">The <see cref="ClusterSettings" /> containing the settings for this connection.</param>
        /// <param name="endPointDiscoverer">Discoverer of destination node end point.</param>
        /// <param name="connectionName">Optional name of connection (will be generated automatically, if not provided)</param>
        internal EventStoreNodeConnection(ConnectionSettings settings, ClusterSettings clusterSettings, IEndPointDiscoverer endPointDiscoverer, string connectionName)
        {
            Ensure.NotNull(settings, "settings");
            Ensure.NotNull(endPointDiscoverer, "endPointDiscoverer");

            _connectionName = connectionName ?? string.Format("ES-{0}", Guid.NewGuid());
            _settings = settings;
            _clusterSettings = clusterSettings;
            _endPointDiscoverer = endPointDiscoverer;
            _handler = new EventStoreConnectionLogicHandler(this, settings);
        }
Ejemplo n.º 29
0
		
		public ConnectionSettings GetDefaultConnectionSettings ()
		{
			ConnectionSettings settings = new ConnectionSettings ();
			settings.ProviderIdentifier = Identifier;
			settings.Server = "localhost";
			settings.Username = "******";
			settings.Password = String.Empty;
			settings.Database = String.Empty;
			settings.Port = 0; //FIXME: what is the default firebird port?
			return settings;
		public void MapStringIdProperty()
		{
			var settings = new ConnectionSettings()
				.MapIdPropertyFor<ElasticsearchProject>(p => p.Name);

			var client = new ElasticClient(settings, connection: new InMemoryConnection());

			var project = new ElasticsearchProject { Name = "foo" };

			Assert.AreEqual(project.Name, client.Infer.Id<ElasticsearchProject>(project));
		}
 private ConnectionSettings AddBasicAuthentication(ConnectionSettings settings) =>
 !this._config.ShieldEnabled ? settings : settings.BasicAuthentication("es_admin", "es_admin");
Ejemplo n.º 32
0
        /// <summary>
        /// Список ВСЕХ компонентов (ТЭЦ, ГТП, ЩУ, ТГ)
        /// </summary>
        /// <param name="connSett">Параметры соединения с БД концигурации</param>
        /// <param name="bIgnoreTECInUse">Признак использования поля [TEC_LIST].[InUse]</param>
        /// <param name="arTECLimit">Массив-диапазон допустимых идентификаторов ТЭЦ</param>
        /// <param name="bUseData">Признак возможности обращения к данным компонентов собираемого списка</param>
        public List <TEC> InitTEC(ConnectionSettings connSett, bool bIgnoreTECInUse, int [] arTECLimit, bool bUseData)
        {
            SetConnectionSettings(connSett);

            return(InitTEC(bIgnoreTECInUse, arTECLimit, bUseData));
        }
Ejemplo n.º 33
0
 public void DeleteDisk(ConnectionSettings connectionSettings, DiskImageSpecification diskImageToDelete)
 {
     throw new NotImplementedException();
 }
 protected override ConnectionSettings Authenticate(ConnectionSettings s) => s             // <1> Set the client certificate on `ConnectionSettings`
 .ClientCertificate(new X509Certificate2(this.ClusterConfiguration.FileSystem.ClientCertificate));
Ejemplo n.º 35
0
        private void Initialize(ElasticSearchOutputConfiguration esOutputConfiguration)
        {
            Debug.Assert(esOutputConfiguration != null);
            Debug.Assert(this.healthReporter != null);

            this.connectionData = new ElasticSearchConnectionData();
            this.connectionData.Configuration = esOutputConfiguration;

            Uri    esServiceUri;
            string errorMessage;

            bool serviceUriIsValid = Uri.TryCreate(esOutputConfiguration.ServiceUri, UriKind.Absolute, out esServiceUri);

            if (!serviceUriIsValid)
            {
                errorMessage = $"{nameof(ElasticSearchOutput)}:  required 'serviceUri' configuration parameter is invalid";
                this.healthReporter.ReportProblem(errorMessage, EventFlowContextIdentifiers.Configuration);
                throw new Exception(errorMessage);
            }

            string userName = esOutputConfiguration.BasicAuthenticationUserName;
            string password = esOutputConfiguration.BasicAuthenticationUserPassword;
            bool   credentialsIncomplete = string.IsNullOrWhiteSpace(userName) ^ string.IsNullOrWhiteSpace(password);

            if (credentialsIncomplete)
            {
                errorMessage = $"{nameof(ElasticSearchOutput)}: for basic authentication to work both user name and password must be specified";
                healthReporter.ReportWarning(errorMessage, EventFlowContextIdentifiers.Configuration);
                userName = password = null;
            }

            ConnectionSettings connectionSettings = new ConnectionSettings(esServiceUri);

            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
            {
                connectionSettings = connectionSettings.BasicAuthentication(userName, password);
            }

            this.connectionData.Client        = new ElasticClient(connectionSettings);
            this.connectionData.LastIndexName = null;

            if (string.IsNullOrWhiteSpace(esOutputConfiguration.IndexNamePrefix))
            {
                esOutputConfiguration.IndexNamePrefix = string.Empty;
            }
            else
            {
                string lowerCaseIndexNamePrefix = esOutputConfiguration.IndexNamePrefix.ToLowerInvariant();
                if (lowerCaseIndexNamePrefix != esOutputConfiguration.IndexNamePrefix)
                {
                    healthReporter.ReportWarning($"{nameof(ElasticSearchOutput)}: The chosen index name prefix '{esOutputConfiguration.IndexNamePrefix}' "
                                                 + "contains uppercase characters, which are not allowed by Elasticsearch. The prefix will be converted to lowercase.",
                                                 EventFlowContextIdentifiers.Configuration);
                }
                esOutputConfiguration.IndexNamePrefix = lowerCaseIndexNamePrefix + Dash;
            }

            if (string.IsNullOrWhiteSpace(esOutputConfiguration.EventDocumentTypeName))
            {
                string warning = $"{nameof(ElasticSearchOutput)}: '{nameof(ElasticSearchOutputConfiguration.EventDocumentTypeName)}' configuration parameter "
                                 + "should not be empty";
                healthReporter.ReportWarning(warning, EventFlowContextIdentifiers.Configuration);
                esOutputConfiguration.EventDocumentTypeName = ElasticSearchOutputConfiguration.DefaultEventDocumentTypeName;
            }
        }
Ejemplo n.º 36
0
 public void WriteDisk(ConnectionSettings connectionSettings, DiskAccessRequest diskAccessRequest, Stream contents)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 37
0
 private void FrmInstanceProfile_FormClosed(object sender, FormClosedEventArgs e)
 {
     ConnSettingsModified = !ProfileChanged &&
                            !ConnectionSettings.Equals(initialConnSettings, initialProfile?.ConnectionSettings);
 }
 protected virtual ConnectionSettings ConnectionSettings(ConnectionSettings s) => s;
Ejemplo n.º 39
0
        //SortedList<DateTime, OneField> HourlyFieldValues;

        /// <summary>
        /// Конструктор открывает коннект к базе. Закрывает деструктор.
        /// </summary>
        public MySQLtechsite(bool bCalculatedHalfHourValues)
        {
            int iRes = -1;

            m_bCalculatedHalfHourValues = bCalculatedHalfHourValues;

            int iConfigDB = -1;
            ConnectionSettings connSett = Program.ReadConnSettFromFileINI(out iConfigDB);

            connSett.id = ConnectionSettings.UN_ENUMERABLE_ID;

            Console.WriteLine("DB parametrs: IP=" + connSett.server + ", port=" + connSett.port + ", DBName=" + connSett.dbName + ", UID=" + connSett.userName + Environment.NewLine);

            //Соединение дл я БД конфигурации
            m_idListener = DbSources.Sources().Register(connSett, false, @"CONFIG_DB");
            m_connection = DbSources.Sources().GetConnection(m_idListener, out iRes);

            //TYPE_DATABASE_CFG typeConfigDB = TYPE_DATABASE_CFG.UNKNOWN;
            //for (TYPE_DATABASE_CFG t = TYPE_DATABASE_CFG.CFG_190; t < TYPE_DATABASE_CFG.UNKNOWN; t ++) {
            //    if (t.ToString().Contains(iConfigDB.ToString()) == true)
            //    {
            //        typeConfigDB = t;
            //        break;
            //    }
            //    else
            //        ;
            //}

            if (iRes == 0)
            {
                m_admin = new AdminTS(new bool [] { false, true }, TECComponentBase.TYPE.ELECTRO);

                ASUTP.Core.HMark markQueries = new ASUTP.Core.HMark(new int[] { (int)StatisticCommon.CONN_SETT_TYPE.ADMIN, (int)StatisticCommon.CONN_SETT_TYPE.PBR });
                //markQueries.Marked ((int)StatisticCommon.CONN_SETT_TYPE.ADMIN);
                //markQueries.Marked((int)StatisticCommon.CONN_SETT_TYPE.PBR);

                m_admin.InitTEC(m_idListener, FormChangeMode.MODE_TECCOMPONENT.GTP, /*typeConfigDB, */ markQueries, true, new int [] { 0, (int)TECComponent.ID.LK });
                m_listIndexTECComponent = m_admin.GetListIndexTECComponent(FormChangeMode.MODE_TECCOMPONENT.GTP, true);

                m_listIdMCTECComponent = new List <int>();

                int i = -1, j = -1;
                for (i = 0; i < m_listIndexTECComponent.Count; i++)
                {
                    for (j = 0; j < m_admin.allTECComponents[m_listIndexTECComponent[i]].m_listMCentreId.Count; j++)
                    {
                        m_listIdMCTECComponent.Add(m_admin.allTECComponents[m_listIndexTECComponent[i]].m_listMCentreId[j]);
                    }
                }

                //Пересоединение для таблиц ПБР
                if ((DbTSQLInterface.IsConnected(ref m_connection) == true) && (m_listIdMCTECComponent.Count > 0))
                {
                    DbSources.Sources().UnRegister(m_idListener);

                    m_idListener       = DbSources.Sources().Register(m_admin.allTECComponents[m_listIndexTECComponent[0]].tec.connSetts[(int)StatisticCommon.CONN_SETT_TYPE.PBR], false, @"PBR");
                    m_connection       = DbSources.Sources().GetConnection(m_idListener, out iRes);
                    m_strTableNamePPBR = m_admin.allTECComponents[m_listIndexTECComponent[0]].tec.m_strNameTableUsedPPBRvsPBR /*[(int)AdminTS.TYPE_FIELDS.STATIC]*/;
                }
                else
                {
                }
            }
            else
            {
                ;
            }

            {
                //itssAUX.PrintErrorMessage("Ошибка! MySQLtechsite::MySQLtechsite () - чтение файла с шифрованными параметрами соединения (" + m_strFileNameConnSett + ")...");
                itssAUX.PrintErrorMessage("Проверте параметры соединения (" + Program.m_fileINI.m_NameFileINI + "). Затем запустите программу с аргументом /setmysqlpassword..." + Environment.NewLine);
            }
        }
Ejemplo n.º 40
0
 public BaseTests()
 {
     ConnectionSettings.ChangeDatabaseName("RaceStatisticsTest");
 }
Ejemplo n.º 41
0
 public static PayloadData CreateWithSsl(ProtocolCapabilities serverCapabilities, ConnectionSettings cs, bool useCompression, CharacterSet characterSet) =>
 CreateCapabilitiesPayload(serverCapabilities, cs, useCompression, characterSet, ProtocolCapabilities.Ssl).ToPayloadData();
        public void should_de_serialise_date_entry_histogram()
        {
            var widget1Histogram = new[]
            {
                new DateEntry
                {
                    Count      = 5181,
                    Max        = 7.9899997711181641,
                    Mean       = 7.9899997711181641,
                    Min        = 7.9899997711181641,
                    Time       = new DateTime(2012, 11, 1, 0, 0, 0, 0, DateTimeKind.Utc),
                    Total      = 41396.18881416321,
                    TotalCount = 5181
                },
                new DateEntry
                {
                    Count      = 5509,
                    Max        = 7.9899997711181641,
                    Mean       = 7.9899997711181641,
                    Min        = 7.9899997711181641,
                    Time       = new DateTime(2012, 12, 1, 0, 0, 0, 0, DateTimeKind.Utc),
                    Total      = 44016.908739089966,
                    TotalCount = 5509
                }
            };

            var widget2Histogram = new[]
            {
                new DateEntry
                {
                    Count      = 173,
                    Max        = 7.989999771118164,
                    Mean       = 7.9899997711181641,
                    Min        = 7.9899997711181641,
                    Time       = new DateTime(2012, 3, 1, 0, 0, 0, 0, DateTimeKind.Utc),
                    Total      = 1382.2699604034424,
                    TotalCount = 173
                },
                new DateEntry
                {
                    Count      = 162,
                    Max        = 7.989999771118164,
                    Mean       = 7.989999771118164,
                    Min        = 7.989999771118164,
                    Time       = new DateTime(2012, 4, 1, 0, 0, 0, 0, DateTimeKind.Utc),
                    Total      = 1294.3799629211426,
                    TotalCount = 162
                }
            };

            const string mockJsonResponse =
                @"{""took"":378,""timed_out"":false,""_shards"":{""total"":4,""successful"":4,""failed"":0},""hits"":{""total"":3700979,""max_score"":1,""hits"":[]},""facets"":{""widget_1:histogram"":{""_type"":""date_histogram"",""entries"":[{""time"":1351728000000,""count"":5181,""min"":7.989999771118164,""max"":7.989999771118164,""total"":41396.18881416321,""total_count"":5181,""mean"":7.989999771118164},{""time"":1354320000000,""count"":5509,""min"":7.989999771118164,""max"":7.989999771118164,""total"":44016.908739089966,""total_count"":5509,""mean"":7.989999771118164}]},""widget_2:histogram"":{""_type"":""date_histogram"",""entries"":[{""time"":1330560000000,""count"":173,""min"":7.989999771118164,""max"":7.989999771118164,""total"":1382.2699604034424,""total_count"":173,""mean"":7.989999771118164},{""time"":1333238400000,""count"":162,""min"":7.989999771118164,""max"":7.989999771118164,""total"":1294.3799629211426,""total_count"":162,""mean"":7.989999771118164}]},""widget_1:terms"":{""_type"":""terms"",""missing"":0,""total"":14797,""other"":0,""terms"":[{""term"":""widget 1"",""count"":14797}]},""widget_2:terms"":{""_type"":""terms"",""missing"":0,""total"":2002,""other"":0,""terms"":[{""term"":""widget 2"",""count"":2002}]}}}";

            var connectionMockery = new Mock <IConnection>();

            connectionMockery
            .Setup(status => status.PostSync("index/_search", "{}"))
            .Returns(new ConnectionStatus(mockJsonResponse));

            var connectionSettings = new ConnectionSettings(Test.Default.Uri).SetDefaultIndex("index");
            var client             = new ElasticClient(connectionSettings, connectionMockery.Object);

            var response = client.Search(descriptor => descriptor);

            Assert.That(response.FacetItems <DateEntry>("widget_1:histogram"), DateEntriesConstraint.Sequence(widget1Histogram));
            Assert.That(response.FacetItems <DateEntry>("widget_2:histogram"), DateEntriesConstraint.Sequence(widget2Histogram));
        }
        public void SetConnectionSettings(ConnectionSettings connSett)
        {
            pushConnectionsettings(connSett);

            setConnectionSettings(connSett);
        }
 private ConnectionSettings ClusterSettings(ConnectionSettings s, Func <ConnectionSettings, ConnectionSettings> settings) =>
 AddBasicAuthentication(AppendClusterNameToHttpHeaders(settings(s)));
Ejemplo n.º 45
0
        public IElasticClient CreateElasticClient(List <Uri> nodes)
        {
            var pool = CraeteConnectionPool(nodes);

            var settings = new ConnectionSettings(pool);

            //验证 未开启
            //settings.BasicAuthentication("username", "password");
            //验证证书
            //settings.ClientCertificate("");
            //settings.ClientCertificates(new X509CertificateCollection());
            //settings.ServerCertificateValidationCallback();

            //开启 第一次使用时进行嗅探,需链接池支持
            //settings.SniffOnStartup(false);

            //链接最大并发数
            //settings.ConnectionLimit(80);
            //标记为死亡节点的超时时间
            //settings.DeadTimeout(new TimeSpan(10000));
            //settings.MaxDeadTimeout(new TimeSpan(10000));
            //最大重试次数
            //settings.MaximumRetries(5);
            //重试超时时间 默认是RequestTimeout
            //settings.MaxRetryTimeout(new TimeSpan(50000));
            //禁用代理自动检测
            //settings.DisableAutomaticProxyDetection(true);

            //禁用ping 第一次使用节点或使用被标记死亡的节点进行ping
            settings.DisablePing(false);
            //ping 超时设置
            //settings.PingTimeout(new TimeSpan(10000));
            //选择节点
            //settings.NodePredicate(node =>
            //{
            //
            //        return true;
            //
            //});
            //默认操作索引
            //settings.DefaultIndex("");
            //字段名规则 与model字段同名
            //settings.DefaultFieldNameInferrer(name => name);
            //根据Type 获取类型名
            //settings.DefaultTypeNameInferrer(name => name.Name);
            //请求超时设置
            //settings.RequestTimeout(new TimeSpan(10000));
            //调试信息
            //settings.DisableDirectStreaming(true);
            //调试信息
            //settings.EnableDebugMode((apiCallDetails) =>
            //{
            //    //请求完成 返回 apiCallDetails

            //});
            //抛出异常
            settings.ThrowExceptions(true);
            //settings.OnRequestCompleted(apiCallDetails =>
            //{
            //    //请求完成 返回 apiCallDetails
            //});
            //settings.OnRequestDataCreated(requestData =>
            //{
            //    //请求的数据创建完成 返回请求的数据

            //});
            return(new ElasticClient(settings));
        }
Ejemplo n.º 46
0
 public ConnectionSettings Authenticate(ConnectionSettings connectionSettings)
 {
     AuthenticationAction?.Invoke(connectionSettings);
     return(connectionSettings);
 }
Ejemplo n.º 47
0
        private static ByteBufferWriter CreateCapabilitiesPayload(ProtocolCapabilities serverCapabilities, ConnectionSettings cs, bool useCompression, CharacterSet characterSet, ProtocolCapabilities additionalCapabilities = 0)
        {
            var writer = new ByteBufferWriter();

            writer.Write((int)(
                             ProtocolCapabilities.Protocol41 |
                             (cs.InteractiveSession ? (serverCapabilities & ProtocolCapabilities.Interactive) : 0) |
                             ProtocolCapabilities.LongPassword |
                             (serverCapabilities & ProtocolCapabilities.Transactions) |
                             ProtocolCapabilities.SecureConnection |
                             (serverCapabilities & ProtocolCapabilities.PluginAuth) |
                             (serverCapabilities & ProtocolCapabilities.PluginAuthLengthEncodedClientData) |
                             ProtocolCapabilities.MultiStatements |
                             ProtocolCapabilities.MultiResults |
                             ProtocolCapabilities.LocalFiles |
                             (string.IsNullOrWhiteSpace(cs.Database) ? 0 : ProtocolCapabilities.ConnectWithDatabase) |
                             (cs.UseAffectedRows ? 0 : ProtocolCapabilities.FoundRows) |
                             (useCompression ? ProtocolCapabilities.Compress : ProtocolCapabilities.None) |
                             (serverCapabilities & ProtocolCapabilities.ConnectionAttributes) |
                             ProtocolCapabilities.SessionTrack |
                             (serverCapabilities & ProtocolCapabilities.DeprecateEof) |
                             additionalCapabilities));
            writer.Write(0x4000_0000);
            writer.Write((byte)characterSet);
            writer.Write(s_padding);

            return(writer);
        }
Ejemplo n.º 48
0
        //private const string EventStoreLiveUri = "tcp://*****:*****@eventstore-api.arnoldclark.com:1115";

        //static List<Model> _models = new List<Model>(TOTAL_STREAMS);


        public static void Main(string[] args)
        {
            Console.Title = "Event Store Load Test: Producer";
            var settings = ConnectionSettings.Create();

            //settings.UseConsoleLogger();
            //settings.EnableVerboseLogging();

            //settings.KeepReconnecting();
            ////settings.KeepRetrying();
            //settings.LimitReconnectionsTo(1);
            //settings.LimitAttemptsForOperationTo(1);
            //settings.LimitRetriesForOperationTo(1);
            //settings.SetOperationTimeoutTo(new TimeSpan(0, 0, 0, 2));

            //settings.LimitReconnectionsTo(0); ;
            //settings.LimitAttemptsForOperationTo(1);
            //settings.LimitRetriesForOperationTo(1);
            //settings.SetOperationTimeoutTo(TimeSpan.FromSeconds(1));
            //settings.WithConnectionTimeoutOf(TimeSpan.FromSeconds(1));
            //settings.SetReconnectionDelayTo(TimeSpan.FromSeconds(1));
            //settings.LimitOperationsQueueTo(1);


            try
            {
                CreateConnection(settings);
                for (int i = 0; i < 5; i++)
                {
                    RaiseEventFor(i);
                }

                //Console.WriteLine($"Producer: Begin Ganerating {TotalStreams} Streams with {EventsPerStream + 1} events in each, totaling {TotalStreams * (EventsPerStream + 1)} events, at {DateTime.Now}");
                //for (int i = 1; i <= TotalStreams; i++)
                ////Parallel.For(0, TOTAL_STREAMS, i =>
                //{
                //    RaiseEventFor(i);


                //    //for (int j = 0; j < EventsPerStream; j++)
                //    //{
                //    //    //int randomStream = rnd.Next(Math.Max(streamNumber - 10, 1), streamNumber);
                //    //    //int actual = (int)Math.Ceiling((1.0 / ((double)streamNumber)+1) * (double)randomStream);
                //    //    int randomStream = i;
                //    //    string thisStreamName = StreamName + randomStream;
                //    //    connection.AppendToStreamAsync(thisStreamName,
                //    //        ExpectedVersion.Any,
                //    //        RaiseEventFor(i)).Wait();
                //    //}
                //    //Thread.Sleep(20);

                //    if (i % 10000 == 0)
                //        Console.WriteLine($"Events For Stream: {i} at {DateTime.Now}");
                //}//);
                //Console.WriteLine($"{TotalStreams} Streams with {EventsPerStream + 1} events in each, totaling {TotalStreams*(EventsPerStream + 1)} events. Made at {DateTime.Now}");
                //RaiseEventFor(1);
                Console.WriteLine("Press 'x' to quit or 'e' to create an event");

                //while (true)
                //{
                //    RaiseEventFor(1);
                //    Thread.Sleep(5000);
                //}
                string input;
                do
                {
                    input = Console.ReadLine();
                    switch (input)
                    {
                    case "e":
                        RaiseEventFor(1);
                        break;
                    }
                } while (input != "x");
            }
            finally
            {
                Connection?.Close();
            }
        }
Ejemplo n.º 49
0
        static void Main(string[] args)
        {
            elasticSettings = new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
                              .SetDefaultIndex("people");

            client = new ElasticClient(elasticSettings);

            client.DeleteIndex("people");

            // Create an index
            client.CreateIndex("people", c => c
                               .NumberOfReplicas(0)
                               .NumberOfShards(1));

            client.MapFluent <Person>(m => m.IndexAnalyzer("standard")
                                      .Properties(props => props
                                                  .String(s => s
                                                          .Name(p => p.Message)
                                                          .Index(FieldIndexOption.analyzed))
                                                  .Number(n => n
                                                          .Name(p => p.Age))
                                                  .String(s => s
                                                          .Name(p => p.FirstName))
                                                  .String(s => s
                                                          .Name(p => p.Sex))
                                                  .String(s => s
                                                          .Name(p => p.LastName))));

            //Add some people
            var jp = new Person {
                FirstName = "JP", LastName = "Smith", Age = 37, Message = "OMG yay ES!", Sex = "Male"
            };
            var matt = new Person {
                FirstName = "Matt", LastName = "Toto", Age = 32, Message = "I'm JPs brother", Sex = "Male"
            };
            var christine = new Person {
                FirstName = "Christine", LastName = "Toto", Age = 0, Message = "I'm JPs wife", Sex = "Female"
            };
            var kevin = new Person {
                FirstName = "Kevin", LastName = "Toto", Age = 26, Message = "I'm JPs other brother", Sex = "Male"
            };

            client.Index(jp);
            client.Index(matt);
            client.Index(christine);
            client.Index(kevin);

            client.Refresh();


            ///// ** Wildcard search
            var searchResults = client.Search <Person>(s => s
                                                       .From(0)
                                                       .Size(10)
                                                       .Query(q => q
                                                              .Wildcard(f => f.LastName, "to*", Boost: 1.0)
                                                              )
                                                       );

            foreach (var result in searchResults.Documents)
            {
                Console.WriteLine("Found: {0}", result.FirstName + " " + result.LastName);
            }

            Console.ReadKey();
        }
Ejemplo n.º 50
0
        public frmList()
        {
            InitializeComponent();

            if (Config.hCntMain == null)
            {
                Config.hCntMain = new Procedures(ConnectionSettings.GetServer(), ConnectionSettings.GetDatabase(), ConnectionSettings.GetUsername(), ConnectionSettings.GetPassword(), ConnectionSettings.ProgramName);
            }

            dgvData.AutoGenerateColumns = false;

            ToolTip tp = new ToolTip();

            tp.SetToolTip(btAdd, "Добавить");
            tp.SetToolTip(btEdit, "Редактировать");
            tp.SetToolTip(btDelete, "Удалить");
            tp.SetToolTip(btClose, "Выход");
            btAdd.Visible = btEdit.Visible = btDelete.Visible = new List <string> {
                "РКВ"
            }.Contains(UserSettings.User.StatusCode);
        }
Ejemplo n.º 51
0
 public Stream ReadDisk(ConnectionSettings connectionSettings, DiskAccessRequest diskAccessRequest)
 {
     throw new NotImplementedException();
 }
 protected override ConnectionSettings ConnectionSettings(ConnectionSettings s) => s
 .ServerCertificateValidationCallback(
     CertificateValidations.AuthorityPartOfChain(new X509Certificate(this.ClusterConfiguration.FileSystem.UnusedCaCertificate))
     );
Ejemplo n.º 53
0
 public DiskImageSpecification DetachDisk(ConnectionSettings connectionSettings, DiskAccessRequest diskToDetach,
                                          bool deletingMachine)
 {
     throw new NotImplementedException();
 }
 public DbTSQLConfigDatabase(ConnectionSettings connSett)
     : base(connSett, $"{CONN_SETT_TYPE.CONFIG_DB.ToString ()}")
 {
 }
Ejemplo n.º 55
0
 public BaseDA()
 {
     this.connection = new ConnectionSettings();
 }
Ejemplo n.º 56
0
 private void SetConnectionSettingOnLoad()
 {
     // Has Connection
     // - Use Connection's Setting, or default
     ConnectionSettings   = ConnectionSettings.GetForConnection(ConnectionDetail) ?? ConnectionSettings.GetDefault();
     TxtSettingsPath.Text = ConnectionSettings.SettingsPath;
 }
        private static ByteBufferWriter CreateCapabilitiesPayload(ProtocolCapabilities serverCapabilities, ConnectionSettings cs, bool useCompression, CharacterSet characterSet, ProtocolCapabilities additionalCapabilities = 0)
        {
            var writer = new ByteBufferWriter();

            writer.Write((int)(
                             ProtocolCapabilities.Protocol41 |
                             (cs.InteractiveSession ? (serverCapabilities & ProtocolCapabilities.Interactive) : 0) |
                             (serverCapabilities & ProtocolCapabilities.LongPassword) |
                             (serverCapabilities & ProtocolCapabilities.Transactions) |
                             ProtocolCapabilities.SecureConnection |
                             (serverCapabilities & ProtocolCapabilities.PluginAuth) |
                             (serverCapabilities & ProtocolCapabilities.PluginAuthLengthEncodedClientData) |
                             ProtocolCapabilities.MultiStatements |
                             ProtocolCapabilities.MultiResults |
                             (cs.AllowLoadLocalInfile ? (serverCapabilities & ProtocolCapabilities.LocalFiles) : 0) |
                             (string.IsNullOrWhiteSpace(cs.Database) ? 0 : ProtocolCapabilities.ConnectWithDatabase) |
                             (cs.UseAffectedRows ? 0 : ProtocolCapabilities.FoundRows) |
                             (useCompression ? ProtocolCapabilities.Compress : ProtocolCapabilities.None) |
                             (serverCapabilities & ProtocolCapabilities.ConnectionAttributes) |
                             (serverCapabilities & ProtocolCapabilities.SessionTrack) |
                             (serverCapabilities & ProtocolCapabilities.DeprecateEof) |
                             additionalCapabilities));
            writer.Write(0x4000_0000);
            writer.Write((byte)characterSet);
            writer.Write(Padding);
            if ((serverCapabilities & ProtocolCapabilities.LongPassword) == 0)
            {
                // MariaDB writes extended capabilities at the end of the padding
                writer.Write((int)(((long)(serverCapabilities & ProtocolCapabilities.MariaDbComMulti)) >> 32));
            }
            else
            {
                writer.Write(0u);
            }

            return(writer);
        }
        /**
         * Now, hooking up this serializer
         */
        [U] public void MySecondJsonNetSerializer()
        {
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
            var connectionSettings = new ConnectionSettings(
                pool,
                connection: new InMemoryConnection(),
                sourceSerializer: (builtin, settings) => new MySecondCustomJsonNetSerializer(builtin, settings))
                                     .DefaultIndex("my-index");

            //hide
            connectionSettings.DisableDirectStreaming();

            var client = new ElasticClient(connectionSettings);

            /** and indexing an instance of our document type */
            var document = new MyDocument
            {
                Id           = 1,
                Name         = "My first document",
                OwnerId      = 2,
                SubDocuments = new []
                {
                    new MySubDocument {
                        Name = "my first sub document"
                    },
                    new MySubDocument {
                        Name = "my second sub document"
                    },
                }
            };

            var ndexResponse = client.IndexDocument(document);

            /** serializes to */
            //json
            var expected = new JObject
            {
                { "$type", "Tests.ClientConcepts.HighLevel.Serialization.GettingStarted+MyDocument, Tests" },
                { "id", 1 },
                { "name", "My first document" },
                { "ownerId", 2 },
                { "subDocuments", new JArray
                  {
                      new JObject {
                          { "name", "my first sub document" }
                      },
                      new JObject {
                          { "name", "my second sub document" }
                      },
                  } }
            };

            /**
             * the type information is serialized for the outer `MyDocument` instance, but not for each
             * `MySubDocument` instance in the `SubDocuments` collection.
             *
             * When implementing a custom contract resolver derived from `ConnectionSettingsAwareContractResolver`,
             * be careful not to change the behaviour of the resolver for NEST types; doing so will result in
             * unexpected behaviour.
             *
             * [WARNING]
             * --
             * Per the https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm[Json.NET documentation on TypeNameHandling],
             * it should be used with caution when your application deserializes JSON from an external source.
             * --
             */

            // hide
            Expect(expected).FromRequest(ndexResponse);
        }