/// <summary>
        /// Returns true if new InternalClient is created. Returns false if InternalClient with ClientID is found
        /// </summary>
        /// <param name="ClientID"></param>
        /// <param name="ClientName"></param>
        /// <returns></returns>
        public static bool CreateInternalClient(string ClientID, string ClientName)
        {
            try
            {
                using (var db = new LiteDatabase(AppKeys.GetDataContextString()))
                {
                    var clients = db.GetCollection <InternalClient>("clients");

                    var newclient = clients.Find(x => x.clientID == ClientID).FirstOrDefault();
                    if (newclient == null)
                    {
                        newclient            = new InternalClient();
                        newclient.clientID   = ClientID;
                        newclient.clientName = ClientName;

                        clients.Insert(newclient);
                        clients.EnsureIndex(x => x.clientID);

                        return(true);
                    }
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An Error has happened in the CreateInternalClient Method : {0}", ex.ToString());
                return(false);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Create a InternalClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param>
        /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <param name="transportType">The transportType used (Http1 or Amqp)</param>
        /// <returns>InternalClient</returns>
        public static InternalClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, TransportType transportType)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, gatewayHostname, authenticationMethod);

#if !NETMF
            if (authenticationMethod is DeviceAuthenticationWithX509Certificate)
            {
                if (connectionStringBuilder.Certificate == null)
                {
                    throw new ArgumentException("certificate must be present in DeviceAuthenticationWithX509Certificate");
                }

                if (!connectionStringBuilder.Certificate.HasPrivateKey)
                {
                    throw new ArgumentException("certificate in DeviceAuthenticationWithX509Certificate must have a private key");
                }

                InternalClient dc = CreateFromConnectionString(connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportType));
                dc.Certificate = connectionStringBuilder.Certificate;
                return(dc);
            }
#endif

            return(CreateFromConnectionString(connectionStringBuilder.ToString(), authenticationMethod, transportType, null));
        }
Exemplo n.º 3
0
        internal void StartLoginServer()
        {
            bool success = false;

            //NOTIFY LOGIN SERVER
            while (success == false)
            {
                try
                {
                    Console.WriteLine("Connect to authentication server: {0}:{1}", _host_2, _port_2);
                    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sock.Connect(_host_2, _port_2);
                    InterNetwork = new InternalClient(sock);
                    InterNetwork.WORLD_NOTIFYCATION();
                    success = true;
                }
                catch (SocketException)
                {
                    Console.WriteLine("Cannot create connection with authentication server");
                    WriteError("NetworkManager", "Cannot create connection with authentication server");
                    Thread.Sleep(60000);
                }
                catch (Exception ex)
                {
                    WriteError("NetworkManager", "A unknown exception occurred: {0} {1}", ex.Source, ex.Message);
                    Thread.Sleep(60000);
                }
            }
        }
Exemplo n.º 4
0
        private static IInternalClient GetApi(CommandLineConfig config)
        {
            if (config.MomentumApiBaseUri == null)
            {
                throw new System.Exception("You must specify a MomentumApiBaseUri");
            }

            var tokenProviderOptions = new LogicTokenProviderOptions
            {
                AuthorizationScope       = config.TokenProvider.AuthorizationScope,
                ClientId                 = config.TokenProvider.ClientId,
                ClientSecret             = config.TokenProvider.ClientSecret,
                AuthorizationTokenIssuer = config.TokenProvider.AuthorizationTokenIssuer,
            };

            if (config.TokenProvider.AuthorizationTokenIssuer != null)
            {
                tokenProviderOptions.AuthorizationTokenIssuer = config.TokenProvider.AuthorizationTokenIssuer;
            }

            var httpClient           = new HttpClient();
            var tokenProviderFactory = new LogicTokenProviderFactory(tokenProviderOptions);
            var tokenProvider        = tokenProviderFactory.GetProvider(httpClient);

            var client = new InternalClient(new TokenCredentials(tokenProvider))
            {
                BaseUri = config.MomentumApiBaseUri,
            };

            Log.Information("Created API with Base URI {BaseUri}", client.BaseUri);
            return(client);
        }
        /// <summary>
        /// Create a InternalClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param>
        /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <param name="transportSettings">Prioritized list of transportTypes and their settings</param>
        /// <param name="options">The options that allow configuration of the device client instance during initialization.</param>
        /// <returns>InternalClient</returns>
        public static InternalClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod,
                                            ITransportSettings[] transportSettings, ClientOptions options = default)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            var connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, gatewayHostname, authenticationMethod);

            // Make sure client options is initialized with the correct transport setting.
            EnsureOptionsIsSetup(connectionStringBuilder.Certificate, ref options);

            if (authenticationMethod is DeviceAuthenticationWithX509Certificate)
            {
                if (connectionStringBuilder.Certificate == null)
                {
                    throw new ArgumentException("No certificate was found. To use certificate authentication certificate must be present.");
                }

                InternalClient dc = CreateFromConnectionString(connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportSettings), options);
                dc.Certificate = connectionStringBuilder.Certificate;
                return(dc);
            }
            return(CreateFromConnectionString(connectionStringBuilder.ToString(), authenticationMethod, transportSettings, null, options));
        }
        public static void UpdatInternalClientByParameter(InternalClientProperties Property, object Value, string ClientID)
        {
            InternalClient client = null;

            using (var db = new LiteDatabase(AppKeys.GetDataContextString()))
            {
                var clients = db.GetCollection <InternalClient>("clients");
                client = clients.Find(x => x.clientID == ClientID).FirstOrDefault();
                if (client != null)
                {
                    var value = new object();
                    if (Property == InternalClientProperties.ClientStyles)
                    {
                        value = (List <InternalClientStyle>)Value;
                    }
                    else
                    {
                        value = Value.ToString();
                    }

                    client.GetType().GetProperty(Property.ToString()).SetValue(client, value);
                    clients.Update(client);
                }
            }
        }
Exemplo n.º 7
0
        private void OnLoggedOn(SteamKit.SteamUser.LoggedOnCallback callback)
        {
            if (callback.Result == EResult.OK)
            {
                SuggestedCellId = callback.CellID;

                _clientReadyEvent.Set();
            }
            else
            {
                if (callback.Result == EResult.AccountLogonDenied || callback.Result == EResult.AccountLoginDeniedNeedTwoFactor)
                {
                    if (callback.Result == EResult.AccountLogonDenied)
                    {
                        EmailAuthCode = _codesProvider.GetEmailAuthenticationCode(Credentials);
                    }
                    else
                    {
                        TwoFactorCode = _codesProvider.GetTwoFactorAuthenticationCode(Credentials);
                    }

                    InternalClient.Connect();
                }
                else
                {
                    FaultException = new SteamLogonException(callback.Result);
                    _clientFaultedEvent.Set();
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Create a InternalClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param>
        /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <param name="transportSettings">Prioritized list of transportTypes and their settings</param>
        /// <param name="options">The options that allow configuration of the device client instance during initialization.</param>
        /// <returns>InternalClient</returns>
        public static InternalClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod,
                                            ITransportSettings[] transportSettings, ClientOptions options = default)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            var connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, gatewayHostname, authenticationMethod);

            if (authenticationMethod is DeviceAuthenticationWithX509Certificate)
            {
                if (connectionStringBuilder.Certificate == null)
                {
                    throw new ArgumentException("certificate must be present in DeviceAuthenticationWithX509Certificate");
                }

                InternalClient dc = CreateFromConnectionString(connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportSettings), options);
                dc.Certificate = connectionStringBuilder.Certificate;
                return(dc);
            }
            return(CreateFromConnectionString(connectionStringBuilder.ToString(), authenticationMethod, transportSettings, null, options));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Create a InternalClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param>
        /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <param name="transportType">The transportType used (Http1, Amqp or Mqtt), <see cref="TransportType"/></param>
        /// <param name="options">The options that allow configuration of the device client instance during initialization.</param>
        /// <returns>InternalClient</returns>
        public static InternalClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, TransportType transportType, ClientOptions options = default)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            if (transportType != TransportType.Amqp_Tcp_Only &&
                transportType != TransportType.Mqtt_Tcp_Only &&
                authenticationMethod is DeviceAuthenticationWithX509Certificate &&
                ((DeviceAuthenticationWithX509Certificate)authenticationMethod).ChainCertificates != null)
            {
                throw new ArgumentException("Certificate chains are only supported on Amqp_Tcp_Only and Mqtt_Tcp_Only");
            }

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, gatewayHostname, authenticationMethod);

            // Make sure client options is initialized with the correct transport setting.
            EnsureOptionsIsSetup(connectionStringBuilder.Certificate, ref options);

            if (authenticationMethod is DeviceAuthenticationWithX509Certificate)
            {
                if (connectionStringBuilder.Certificate == null)
                {
                    throw new ArgumentException("No certificate was found. To use certificate authentication certificate must be present.");
                }

#pragma warning disable CA2000 // This is returned to client so cannot be disposed here.
                InternalClient dc = CreateFromConnectionString(connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportType), options);
#pragma warning restore CA2000
                dc.Certificate = connectionStringBuilder.Certificate;

                // Install all the intermediate certificates in the chain if specified.
                if (connectionStringBuilder.ChainCertificates != null)
                {
                    try
                    {
                        CertificateInstaller.EnsureChainIsInstalled(connectionStringBuilder.ChainCertificates);
                    }
                    catch (Exception ex)
                    {
                        if (Logging.IsEnabled)
                        {
                            Logging.Error(null, $"{nameof(CertificateInstaller)} failed to read or write to cert store due to: {ex}");
                        }
                        throw new UnauthorizedException($"Failed to provide certificates in the chain - {ex.Message}", ex);
                    }
                }

                return(dc);
            }

            return(CreateFromConnectionString(connectionStringBuilder.ToString(), authenticationMethod, transportType, null, options));
        }
Exemplo n.º 10
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException"></exception>
        public Task StartAsync(IManagedMqttClientOptions options)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(InternalClient.StartAsync(options));
        }
Exemplo n.º 11
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException"></exception>
        public Task PublishAsync(ManagedMqttApplicationMessage applicationMessage)
        {
            if (applicationMessage is null)
            {
                throw new ArgumentNullException(nameof(applicationMessage));
            }

            return(InternalClient.PublishAsync(applicationMessage));
        }
Exemplo n.º 12
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException"></exception>
        public Task <MqttClientPublishResult> PublishAsync(MqttApplicationMessage applicationMessage, CancellationToken cancellationToken)
        {
            if (applicationMessage is null)
            {
                throw new ArgumentNullException(nameof(applicationMessage));
            }

            return(InternalClient.PublishAsync(applicationMessage, cancellationToken));
        }
Exemplo n.º 13
0
        private DeviceClient(InternalClient internalClient)
        {
            this.internalClient = internalClient ?? throw new ArgumentNullException(nameof(internalClient));

            if (this.internalClient.IotHubConnectionString?.ModuleId != null)
            {
                throw new ArgumentException("A module ID was specified in the connection string - please use ModuleClient for modules.");
            }
        }
Exemplo n.º 14
0
        public async Task PublishMessage <T>(T messagePayload, string topic) where T : class
        {
            var appMessage = new MqttApplicationMessageBuilder()
                             .WithContentType(typeof(T).Name)
                             .WithPayload(JsonConvert.SerializeObject(messagePayload))
                             .WithTopic(topic)
                             .Build();

            await InternalClient.PublishAsync(appMessage, CancellationToken.None);
        }
Exemplo n.º 15
0
        internal ModuleClient(InternalClient internalClient, ICertificateValidator certValidator)
        {
            this.internalClient = internalClient ?? throw new ArgumentNullException(nameof(internalClient));
            this.certValidator  = certValidator ?? throw new ArgumentNullException(nameof(certValidator));

            if (string.IsNullOrWhiteSpace(this.internalClient.IotHubConnectionString?.ModuleId))
            {
                throw new ArgumentException("A valid module ID should be specified to create a ModuleClient");
            }
        }
Exemplo n.º 16
0
        public override void SetUp()
        {
            base.SetUp();
            client = new InternalClient(endpoint);

            var topology      = new Topology(new int[0]);
            var configuration = new Configuration(topology)
            {
                CurrentNodePort = port, OtherShardsPorts = new int[0]
            };

            container.Configure(c => c.For <IConfiguration>().Use(configuration));
        }
Exemplo n.º 17
0
        private DeviceClient(InternalClient internalClient)
        {
            InternalClient = internalClient ?? throw new ArgumentNullException(nameof(internalClient));

            if (InternalClient.IotHubConnectionString?.ModuleId != null)
            {
                throw new ArgumentException("A module Id was specified in the connection string - please use ModuleClient for modules.");
            }

            if (Logging.IsEnabled)
            {
                Logging.Associate(this, this, internalClient, nameof(DeviceClient));
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Клиент распределенного кеша
        /// </summary>
        /// <param name="options">Настройки работы клиента</param>
        /// <param name="comparer">Функция сравнения ключей</param>
        /// <param name="cache">Внешний кеш. Если не задат то будет использоваться свой внутренний кеш, уникальный на каждый экземпляр этого класса. При заданном значении сторонний код берет на себя переодический вызов ICache.TryFlush</param>
        public DistributedCacheClient(DistributedCacheClientOptions options, IEqualityComparer <Tk> comparer, ICache <Tk, T> cache = null)
        {
            _batchInterval = options.BatchInterval;
            _batchBlock    = new BatchBlock <Tk>(options.BatchSize, new GroupingDataflowBlockOptions()
            {
                BoundedCapacity = options.MaxRequestedMessagesCount
            });

            _cache  = new ClientCache <Tk, T>(_batchBlock, options.RepeatRequestInterval, comparer, cache);
            _client = null;

            _streamFactory = new ChunkedStreamFactory(
                () => new ByteBuffer(System.Buffers.ArrayPool <byte> .Shared.Rent(MESSAGE_BUFFER)),
                chunk => System.Buffers.ArrayPool <byte> .Shared.Return(((ByteBuffer)chunk).SwapBuffer()));
        }
Exemplo n.º 19
0
        internal ModuleClient(InternalClient internalClient, ICertificateValidator certValidator)
        {
            InternalClient = internalClient ?? throw new ArgumentNullException(nameof(internalClient));
            _certValidator = certValidator ?? throw new ArgumentNullException(nameof(certValidator));

            if (string.IsNullOrWhiteSpace(InternalClient.IotHubConnectionString?.ModuleId))
            {
                throw new ArgumentException("A valid module Id should be specified to create a ModuleClient");
            }

            if (Logging.IsEnabled)
            {
                Logging.Associate(this, this, internalClient, nameof(ModuleClient));
            }
        }
Exemplo n.º 20
0
        private void OnDisconnected(SteamKit.SteamClient.DisconnectedCallback callback)
        {
            _clientReadyEvent.Reset();

            if (_cancellationTokenSource.IsCancellationRequested || callback.UserInitiated)
            {
                return;
            }

            Task.Run(async() =>
            {
                await Task.Delay(TimeSpan.FromMilliseconds(100));

                InternalClient.Connect();
            });
        }
Exemplo n.º 21
0
        private InternalClient CreateClient()
        {
            if (this.internalClient != null)
            {
                return(this.internalClient);
            }

            var tokenProvider = this.tokenProviderFactory.GetProvider(this.httpClient);

            this.internalClient = new InternalClient(new TokenCredentials(tokenProvider))
            {
                BaseUri = this.options.CprServiceUri,
            };

            return(this.internalClient);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Create a InternalClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param>
        /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <param name="transportType">The transportType used (Http1, Amqp or Mqtt), <see cref="TransportType"/></param>
        /// <param name="options">The options that allow configuration of the device client instance during initialization.</param>
        /// <returns>InternalClient</returns>
        public static InternalClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, TransportType transportType, ClientOptions options = default)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, gatewayHostname, authenticationMethod);

            if (authenticationMethod is DeviceAuthenticationWithX509Certificate)
            {
                if (connectionStringBuilder.Certificate == null)
                {
                    throw new ArgumentException("certificate must be present in DeviceAuthenticationWithX509Certificate");
                }

                // If the file upload transport settings hasn't been specified, we will create one using the client certificate on the connection string
                if (options?.FileUploadTransportSettings == null)
                {
                    var fileUploadTransportSettings = new Http1TransportSettings {
                        ClientCertificate = connectionStringBuilder.Certificate
                    };
                    if (options == null)
                    {
                        options = new ClientOptions {
                            FileUploadTransportSettings = fileUploadTransportSettings
                        };
                    }
                    else
                    {
                        options.FileUploadTransportSettings = fileUploadTransportSettings;
                    }
                }

                InternalClient dc = CreateFromConnectionString(connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportType), options);
                dc.Certificate = connectionStringBuilder.Certificate;

                return(dc);
            }

            return(CreateFromConnectionString(connectionStringBuilder.ToString(), authenticationMethod, transportType, null, options));
        }
Exemplo n.º 23
0
        private void GetClientUserData()
        {
            if (DataTable.Rows.Count.Equals(0))
            {
                Client = null;
                return;
            }

            var row = DataTable.Rows[0];

            Client.Id                  = row["id_cliente"].ToString();
            Client.FirstName           = row["nombre_cliente"].ToString();
            Client.LastName            = row["apellido_cliente"].ToString();
            Client.Dni                 = row["DNI"].ToString();
            Client.Profile.ProfileId   = 3;
            Client.Profile.ProfileName = row["Rol"].ToString();
        }
Exemplo n.º 24
0
 Task <IIpcResult> IClient.Send(IIpcOperation operation)
 {
     Contract.Requires(operation != null);
     if (InternalClient != null)
     {
         if (global::BuildXL.Ipc.ExternalApi.Commands.Command.Deserialize(operation.Payload) is RegisterFilesForBuildManifestCommand)
         {
             // Override for RegisterFileForBuildManifestCommand (Always true)
             return(Task.FromResult(SendFn(operation)));
         }
         else
         {
             return(InternalClient.Send(operation));
         }
     }
     return(Task.FromResult(SendFn(operation)));
 }
Exemplo n.º 25
0
        /// <summary>
        /// Create a InternalClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT hub</param>
        /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <param name="transportSettings">Prioritized list of transportTypes and their settings</param>
        /// <param name="options">The options that allow configuration of the device client instance during initialization.</param>
        /// <returns>InternalClient</returns>
        internal static InternalClient Create(
            string hostname,
            string gatewayHostname,
            IAuthenticationMethod authenticationMethod,
            ITransportSettings[] transportSettings,
            ClientOptions options = default)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            if (!string.IsNullOrWhiteSpace(options?.ModelId) &&
                transportSettings.Any(x => x.GetTransportType() == TransportType.Http1))
            {
                throw new InvalidOperationException("Plug and Play is not supported over the HTTP transport.");
            }

            var connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, gatewayHostname, authenticationMethod);

            // Make sure client options is initialized with the correct transport setting.
            EnsureOptionsIsSetup(connectionStringBuilder.Certificate, ref options);

            if (authenticationMethod is DeviceAuthenticationWithX509Certificate)
            {
                if (connectionStringBuilder.Certificate == null)
                {
                    throw new ArgumentException("No certificate was found. To use certificate authentication certificate must be present.");
                }

                InternalClient dc = CreateFromConnectionString(
                    connectionStringBuilder.ToString(),
                    PopulateCertificateInTransportSettings(connectionStringBuilder, transportSettings),
                    options);
                dc.Certificate = connectionStringBuilder.Certificate;
                return(dc);
            }

            return(CreateFromConnectionString(connectionStringBuilder.ToString(), authenticationMethod, transportSettings, null, options));
        }
        public static bool UpdateInternalClient(InternalClient Client)
        {
            try
            {
                using (var db = new LiteDatabase(AppKeys.GetDataContextString()))
                {
                    var clients  = db.GetCollection <InternalClient>("clients");
                    var dbclient = clients.Find(x => x.clientID == Client.clientID).FirstOrDefault();

                    //if there is no clientID and no clientName it's not a valid client to update from
                    if (!string.IsNullOrEmpty(Client.clientID) && !string.IsNullOrEmpty(Client.clientName))
                    {
                        //if it is not in the database add it
                        if (dbclient == null)
                        {
                            dbclient            = new InternalClient();
                            dbclient.clientID   = Client.clientID;
                            dbclient.clientName = Client.clientName;

                            clients.Insert(dbclient);
                            clients.EnsureIndex(x => x.clientID);
                        }

                        //never update the client ID or client name after the item has been created.
                        dbclient.EtsyID          = Client.EtsyID;
                        dbclient.EtsyUserName    = Client.EtsyUserName;
                        dbclient.AccessToken     = Client.AccessToken;
                        dbclient.AccessSecretKey = Client.AccessSecretKey;
                        dbclient.ClientStyles    = Client.ClientStyles;
                        dbclient.ClientDesigns   = Client.ClientDesigns;
                        dbclient.EtsyShopIDs     = Client.EtsyShopIDs;
                        clients.Update(dbclient);

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An Error has happened in the GetInternalClientByID Method : {0}", ex.ToString());
                return(false);
            }
            return(false);
        }
Exemplo n.º 27
0
        internal InternalClient CreateClient()
        {
            lock (ClientLocker)
            {
                if (this._internalClient != null)
                {
                    return(this._internalClient);
                }

                var tokenProvider = this._tokenProviderFactory.GetProvider(this.HttpClient);

                this._internalClient = new InternalClient(new TokenCredentials(tokenProvider))
                {
                    BaseUri = this._options.DocumentGenerationServiceUri ?? new Uri("https://gateway.kmdlogic.io/document-generation/v2"),
                };

                return(this._internalClient);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Asks the underlying client to connect to Steam and perform a login with the given <see cref="Credentials"/>.
        /// </summary>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <exception cref="SteamClientFaultedException">Client is faulted.</exception>
        public async Task ConnectAsync(CancellationToken cancellationToken)
        {
            if (_isClientRunning)
            {
                return;
            }

            InternalClient.Connect();

            var readyTask   = _clientReadyEvent.WaitAsync(cancellationToken);
            var faultedTask = _clientFaultedEvent.WaitAsync();

            var task = await Task.WhenAny(readyTask, faultedTask);

            if (task == faultedTask)
            {
                throw new SteamClientFaultedException(FaultException);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Запуск локального кеша. Необходимо выполнить до начала работы с кешем. Завершение операции может быть только при отмене или исключительной ситуации что является завершением работы локального кеша
        /// </summary>
        /// <param name="connection_string">Строка подключения имеет формат "dc://host_or_ip/cache_endpoint"</param>
        /// <param name="keepalive_interval">Интервал времени для проверки подключения с сервером, по умолчанию равен 90 сек</param>
        /// <param name="reconnect_interval">Время ожидания между подключениями в случае потери соединения, по умолчанию равен 3 сек</param>
        /// <param name="reconnect_count">Количество переподключений при разрыве связи. По истечению метод будет завершен с ошибкой, по умолчанию равен 60</param>
        /// <param name="connect_timeout">Время ожидания подключения к серверу</param>
        /// <param name="token">Токен отмены выполнения</param>
        /// <returns></returns>
        public async Task StartAsync(string connection_string, CancellationToken token, TimeSpan?keepalive_interval = null, TimeSpan?reconnect_interval = null, int?reconnect_count = null, TimeSpan?connect_timeout = null)
        {
            if (_client != null)
            {
                throw new InvalidOperationException();
            }

            var conn = DistributedCacheConnectionString.Parse(connection_string.Split(',').First(),
                                                              keepalive_interval ?? TimeSpan.FromSeconds(90), reconnect_interval ?? TimeSpan.FromSeconds(3), reconnect_count ?? 60, connect_timeout ?? TimeSpan.FromSeconds(10));
            var builder = new UriBuilder("ws", conn.Host, conn.Port, conn.Path);

            _client = new InternalClient(builder.Uri, conn.ConnectionOptions.KeepaliveInterval, conn.ConnectionOptions.ReconnectInterval, conn.ConnectionOptions.ConnectTimeout, conn.ConnectionOptions.ReconnectCount);
            await _client.ConnectAsync(token);

            var cache   = _cache.StartAsync(_batchInterval, token);
            var bacth   = StartBatching(token);
            var receive = StartReceive(token);

            await Task.WhenAny(cache, bacth, receive);
        }
Exemplo n.º 30
0
        public DiscordClient()
        {
            m_processID = Process.GetCurrentProcess().Id;

            m_frameQueue   = new Queue <Frame>();
            m_messageQueue = new Queue <IMessage>();
            m_commandQueue = new Queue <ICommand>();

            m_state = e_RPCState.Disconnected;

            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Unix:
            {
                m_internalClient = new UnixClient(this);

                break;
            }

            case PlatformID.Win32NT:
            case PlatformID.Win32S:
            case PlatformID.Win32Windows:
            case PlatformID.WinCE:
            {
                m_internalClient = new WindowsClient(this);

                break;
            }

            default:
            {
                Debug.Assert(false);

                break;
            }
            }

            m_nounce = 0;
        }