public void sendMultipleCommandsBeforeClosing() {
			using (ConnectionClient client = new ConnectionClient()) {
				Command command = Command.fromString("PING\r\n");
				Command command2 = Command.fromString("PING\r\n");
				client.connect();
				client.send(command);
				client.send(command2);
			}
		}
        private Connection initConn()
        {
            BoardDelegate bd = new BoardDelegate(board);
            ConnectionClient cc = new ConnectionClient(bd);

            initServerInfo();

            Connection conn = new Connection(addr, port, cc);
            return conn;
        }
Example #3
0
 public ConnectionClient <WorkflowManagerClient, IWorkflowManager> GetWorkflowProxy()
 {
     lock (_locker)
     {
         if (_workflowProxy == null)
         {
             _workflowProxy = new ConnectionClient <WorkflowManagerClient, IWorkflowManager>(GetWorkflowManager());
         }
         return(_workflowProxy);
     }
 }
Example #4
0
 public ConnectionClient <ReportManagerClient, IReportManager> GetReportProxy()
 {
     lock (_locker)
     {
         if (_reportProxy == null)
         {
             _reportProxy = new ConnectionClient <ReportManagerClient, IReportManager>(GetReportManager());
         }
         return(_reportProxy);
     }
 }
Example #5
0
 public ConnectionClient <QueryManagerClient, IQueryManager> GetQueryProxy()
 {
     lock (_locker)
     {
         if (_queryProxy == null)
         {
             _queryProxy = new ConnectionClient <QueryManagerClient, IQueryManager>(GetQueryManager());
         }
         return(_queryProxy);
     }
 }
Example #6
0
 public ConnectionClient <DocManagerClient, IDocManager> GetDocumentProxy()
 {
     lock (_locker)
     {
         if (_documentProxy == null)
         {
             _documentProxy = new ConnectionClient <DocManagerClient, IDocManager>(GetDocumentManager());
         }
         return(_documentProxy);
     }
 }
Example #7
0
 public ConnectionClient <UserManagerClient, IUserManager> GetUserProxy()
 {
     lock (_locker)
     {
         if (_userProxy == null)
         {
             _userProxy = new ConnectionClient <UserManagerClient, IUserManager>(GetUserManager());
         }
         return(_userProxy);
     }
 }
Example #8
0
        public void logout()
        {
            NetworkStream connection = ConnectionClient.getConnectionClient();

            /* LOGOUT ACCOUNT command */
            byte[] bytes;
            bytes = Encoding.ASCII.GetBytes("LOUT");
            connection.Write(bytes, 0, bytes.Length);

            listener.onLogout();
        }
Example #9
0
        public void deleteAccount()
        {
            NetworkStream connection = ConnectionClient.getConnectionClient();

            /* DELETE ACCOUNT command */
            byte[] bytes;
            bytes = Encoding.ASCII.GetBytes("DELA");
            connection.Write(bytes, 0, bytes.Length);

            listener.onLogout();
        }
Example #10
0
 public ConnectionClient <PresentationManagerClient, IPresentationManager> GetPresentationProxy()
 {
     lock (_locker)
     {
         if (_presentationProxy == null)
         {
             _presentationProxy =
                 new ConnectionClient <PresentationManagerClient, IPresentationManager>(GetPresentationManager());
         }
         return(_presentationProxy);
     }
 }
 public Task <int> DeleteAsync(string surveyId, int interviewId)
 {
     CheckSurveyId(surveyId);
     return(Client.DeleteAsync(InterviewsApiUri(surveyId, interviewId))
            .ContinueWith(
                responseMessageTask => responseMessageTask.Result.Content.ReadAsStringAsync().Result)
            .ContinueWith(stringResult =>
                          JsonConvert.DeserializeObject <BackgroundActivityStatus>(stringResult.Result).ActivityId)
            .ContinueWith(activityResult => ConnectionClient.GetActivityResultAsync <int>(activityResult.Result, "DeletedTotal"))
            .Unwrap()
            .FlattenExceptions());
 }
Example #12
0
        private void ConnectionCreated(ConnectionClient con)
        {
            if (con == null)
            {
                throw new ArgumentNullException(nameof(con));
            }

            m_ReconnectAttempts = MaxReconnectAttempts;
            TryInitPersistence(con);
            con.OnClientJoined += TryInitPersistence;
            con.OnDisconnected += ConnectionClosed;
        }
Example #13
0
        public void OnPeerConnected(NetPeer peer)
        {
            LiteNetConnection  network     = new LiteNetConnection(peer);
            RailNetPeerWrapper persistence = new RailNetPeerWrapper(network);
            ConnectionClient   connection  = new ConnectionClient(
                network,
                persistence,
                m_Session.World);

            m_Session.ConnectionCreated(connection);
            peer.Tag = connection;
        }
Example #14
0
        public void authenticateUser(string user, string password)
        {
            NetworkStream connection = ConnectionClient.getConnectionClient();

            /* LOGIN command */
            byte[] bytes;
            bytes = Encoding.ASCII.GetBytes("LOIN ");
            connection.Write(bytes, 0, bytes.Length);

            bytes = BitConverter.GetBytes(user.Length);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            connection.Write(bytes, 0, bytes.Length);

            bytes = Encoding.ASCII.GetBytes(user);
            connection.Write(bytes, 0, bytes.Length);

            bytes = BitConverter.GetBytes(password.Length);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            connection.Write(bytes, 0, bytes.Length);

            bytes = Encoding.ASCII.GetBytes(password);
            connection.Write(bytes, 0, bytes.Length);

            byte[] buffer    = new byte[100];
            int    bytesRead = connection.Read(buffer, 0, 4);
            string response  = "";

            for (int i = 0; i < bytesRead; i++)
            {
                if (!buffer[i].Equals(00))
                {
                    response += Convert.ToChar(buffer[i]);
                }
            }

            Console.WriteLine(response);
            if (response.ToUpper().Equals("LGGD"))
            {
                listener.onLoginSuccess();
            }
            else if (response.ToUpper().Equals("ERRO"))
            {
                bytesRead = connection.Read(buffer, 0, 5);
                listener.onLoginFail();
            }
        }
Example #15
0
        private void TryInitPersistence(ConnectionClient con)
        {
            if (con == null || con.State != EConnectionState.ClientConnected)
            {
                return;
            }

            if (m_Persistence == null)
            {
                m_Persistence = new PersistenceClient(new GameEnvironmentClient());
            }

            m_Persistence.SetConnection(con);
        }
        public void DownloadLog(string GuildName, ref int RegisteredUserCount, ref int ConnectedUserCount, ref int GuestUserCount, Dictionary <string, int> GuildmateTable, List <string> ChatLineList)
        {
            Dictionary <string, string> Values = new Dictionary <string, string>();

            Values.Add("id", LogId);
            Values.Add("guildname", GuildName);
            Values.Add("index", LastReadIndex.ToString());

            try
            {
                FormUrlEncodedContent Content = new FormUrlEncodedContent(Values);

                Task <HttpResponseMessage> PostTask = ConnectionClient.PostAsync(ConnectionAddress + "download_form.php", Content);
                if (PostTask.Wait(2000))
                {
                    HttpResponseMessage Response = PostTask.Result;

                    Task <string> ReadTask = Response.Content.ReadAsStringAsync();
                    if (ReadTask.Wait(2000))
                    {
                        string   Result = ReadTask.Result;
                        string[] Lines  = Result.Split('\n');

                        bool IsUserInfoParsed = false;
                        for (int i = 0; i < Lines.Length; i++)
                        {
                            string Line = Lines[i];
                            if (Line.Length < 1 || Line[0] != '*')
                            {
                                continue;
                            }
                            Line = Line.Substring(1);

                            if (!IsUserInfoParsed)
                            {
                                IsUserInfoParsed = true;
                                ParseUserInfo(Line, ref RegisteredUserCount, ref ConnectedUserCount, ref GuestUserCount, GuildmateTable);
                            }
                            else
                            {
                                ChatLineList.Add(Line);
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
    protected override void OnGUI()
    {
        DrawConnectionControls();
        DrawServerList();

        if (GUILayout.Button("Walk"))
        {
            ConnectionClient.SendData("Walk");
        }

        if (GUILayout.Button("Idle"))
        {
            ConnectionClient.SendData("Idle");
        }
    }
Example #18
0
        private void TryInitPersistence(ConnectionClient con)
        {
            if (con == null || con.State != EConnectionState.ClientPlaying)
            {
                return;
            }

            if (Persistence == null)
            {
                Persistence = new PersistenceClient(new GameEnvironmentClient());
                OnPersistenceInitialized?.Invoke(Persistence);
            }

            Persistence.SetConnection(con);
        }
Example #19
0
        protected virtual Task CloseAsync()
        {
            if (!Connected)
            {
                return(Task.FromResult(false));
            }

            Interlocked.CompareExchange(ref _connected, 0, 1);

            _cts.Cancel();
            _packetQueue.CompleteAdding();

            try
            {
                if (ConnectionClient != null)
                {
                    ConnectionClient.Disconnect(false);

                    if (ConnectionClient.Poll(10000, SelectMode.SelectRead))
                    {
                    }
                }
            }
            catch
            {
            }
            finally
            {
                EventHandler disconnected = Disconnected;
                if (disconnected != null)
                {
                    disconnected(this, EventArgs.Empty);
                }

                if (ConnectionClient != null)
                {
                    ConnectionClient.Close();
                    ConnectionClient = null;
                }

                if (Completed != null)
                {
                    Completed.SetResult(true);
                }
            }

            return(Task.FromResult(false));
        }
 public ConnectionClient_Test()
 {
     m_NetworkConnection
     .Setup(
         con => con.SendRaw(It.IsAny <ArraySegment <byte> >(), It.IsAny <EDeliveryMethod>()))
     .Callback(
         (ArraySegment <byte> arg, EDeliveryMethod eMethod) => m_SendRawParam = arg);
     m_GamePersistence = new Mock <IGameStatePersistence>();
     m_GamePersistence.Setup(per => per.Receive(It.IsAny <ArraySegment <byte> >()))
     .Callback(
         (ArraySegment <byte> arg) => m_PersistenceReceiveParam = arg);
     m_Connection = new ConnectionClient(
         m_NetworkConnection.Object,
         m_GamePersistence.Object,
         m_WorldData.Object);
 }
Example #21
0
        public async Task <object> Go(QueryContext context, ConnectionClient client, RegistryService registry)
        {
            var c = new Command();

            c.Commands.Add(context.Query);
            try
            {
                var res = await client.PostCommandAsync(c);

                return(new CommandResultViewModel(res));
            }
            catch (Exception err)
            {
                return(new CommandResultViewModel(err.Message));
            }
        }
Example #22
0
        public async Task <object> Go(QueryContext context, ConnectionClient client, RegistryService registry)
        {
            var from          = context.Query.Split("from", StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().TrimEnd(';')).ToList();
            var fromTableName = @from[1].Split(' ')[0];

            var select            = @from[0].Split("select", StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().TrimEnd(';')).ToList();
            var columnsOrWildcard = @select[0].Trim();

            string[] columns;

            if (columnsOrWildcard == "*")
            {
                if (fromTableName.ToLower().Equals("sqlite_master"))
                {
                    columns = Describe.DescribeMasterColumns.ToArray();
                }
                else
                {
                    columns = (await client.DescribeCommandAsync(new Describe()
                    {
                        TableName = fromTableName
                    })).Results.Select(DescribeResponse.GetName).ToArray();
                }
            }
            else
            {
                columns = @select[0].Split(',', StringSplitOptions.RemoveEmptyEntries);
            }

            var q = new Network.Server.Api.Db.Model.Query()
            {
                Select     = context.Query,
                Columns    = columns.Select(x => x?.Trim()).ToList(),
                Properties = columns.Select(x => x?.Trim()).ToList()
            };

            try
            {
                var res = await client.PostQueryAsync(q);

                return(new QueryResultViewModel(res, await registry.GetServices(), context.HttpContext.Request));
            }
            catch (Exception err)
            {
                return(new QueryResultViewModel(err.Message));
            }
        }
        private Task <int> ClearAsync(string surveyId, List <SampleFilter> filters, IEnumerable <string> columnsToClear)
        {
            var uri = new Uri(SurveySampleUrl(surveyId) + "Clear");

            var request = new ClearSurveySampleModel
            {
                Filters = filters,
                Columns = columnsToClear
            };

            return(Client.PutAsJsonAsync(uri, request)
                   .ContinueWith(responseMessageTask => responseMessageTask.Result.Content.ReadAsStringAsync().Result)
                   .ContinueWith(stringResult => JsonConvert.DeserializeObject <BackgroundActivityStatus>(stringResult.Result).ActivityId)
                   .ContinueWith(activityResult => ConnectionClient.GetActivityResultAsync <int>(activityResult.Result, "ClearTotal"))
                   .Unwrap()
                   .FlattenExceptions());
        }
Example #24
0
        /// <summary>
        /// Удалить запись физ.лиза
        /// </summary>
        /// <param name="Id">ИД Клиента</param>
        internal static void DeletePhysical(int Id)
        {
            try
            {
                string sql = string.Format($"DELETE FROM PhysicalClient WHERE Id = { Id}");
                ConnectionClient.ConOpen();
                using (SqlCommand cmd = new SqlCommand(sql, ConnectionClient.connection))
                {
                    cmd.ExecuteNonQuery();

                    ConnectionClient.ConClose();
                }
            }
            catch (SqlException e) { errorMes.ErrorSQL(e.Message); }
            catch (Exception e) { errorMes.ErrorSQL(e.Message); }
            finally { ConnectionClient.ConClose(); }
        }
Example #25
0
        private void App_StartupAsync(object sender, StartupEventArgs e)
        {
            if (ConnectionClient.ConnectionTest())
            {
                AccountViewModel viewModel = new AccountViewModel();
                MainWindow = new AccountView()
                {
                    DataContext = viewModel
                };
                MainWindow.Show();

                RepositoryAccount.LoadAsync();
            }
            else
            {
                MessageBox.Show("Отсутствует соединение с базой");
            }
        }
Example #26
0
        public void deleteFriend(string friend)
        {
            NetworkStream connection = ConnectionClient.getConnectionClient();

            /* DELETE FRIEND command */
            byte[] bytes;
            bytes = Encoding.ASCII.GetBytes("DELF ");
            connection.Write(bytes, 0, bytes.Length);

            bytes = BitConverter.GetBytes(friend.Length);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            connection.Write(bytes, 0, bytes.Length);

            bytes = Encoding.ASCII.GetBytes(friend);
            connection.Write(bytes, 0, bytes.Length);
        }
Example #27
0
        /// <summary>
        /// Загрузка данных по всем вкладам
        /// </summary>
        private static void LoadDeposit()
        {
            try
            {
                string sql       = "SELECT * FROM Deposit";
                int    itemcount = 0;
                lock (o)
                {
                    ConnectionClient.ConOpen();
                    using (SqlCommand commmand = new SqlCommand(sql, ConnectionClient.connection))
                    {
                        SqlDataReader reader1 = commmand.ExecuteReader();
                        itemcount = reader1.Cast <object>().Count();
                        reader1.Close();
                        int           count  = 0;
                        SqlDataReader reader = commmand.ExecuteReader();
                        while (reader.Read())
                        {
                            Deposit deposit = new Deposit((int)reader["Id"], (long)reader["AccountNumber"], (decimal)reader["Cash"], (decimal)reader["DepositAmount"], (int)reader["ClientId"],
                                                          (bool)reader["State"], (int)reader["MonthsPeriod"], (int)reader["Rate"], (DateTime)reader["OpenDate"],
                                                          (DateTime)reader["DateClose"], (bool)reader["Capitalization"], (int)reader["TypeId"], (decimal)reader["MoneyEarned"]);
                            //  Repository.GetDeposits.Add(deposit);
                            accounts.Add(AccountFactory.GetAccount(deposit));
                            count++;
                            countAccount++;

                            ProgressBar.GetValue("Загрузка вкладов", itemcount, count);
                        }
                    }
                    ConnectionClient.ConClose();
                }
            }
            catch (SqlException e)
            {
                errorMes.ErrorSQL(e.Message); ConnectionClient.ConClose();
            }
            catch (Exception e)
            {
                errorMes.ErrorSQL(e.Message); ConnectionClient.ConClose();
            }
            finally { ConnectionClient.ConClose(); }
        }
Example #28
0
 /// <summary>
 /// Загрузка данных по всем кредитам
 /// </summary>
 private static void LoadCredit()
 {
     try
     {
         string sql       = "SELECT * FROM Credits";
         int    itemcount = 0;
         Debug.WriteLine("Поток Крдиты");
         lock (o)
         {
             ConnectionClient.ConOpen();
             using (SqlCommand commmand = new SqlCommand(sql, ConnectionClient.connection))
             {
                 SqlDataReader reader1 = commmand.ExecuteReader();
                 itemcount = reader1.Cast <object>().Count();
                 reader1.Close();
                 int           count  = 0;
                 SqlDataReader reader = commmand.ExecuteReader();
                 while (reader.Read())
                 {
                     Credits credits = new Credits((int)reader["Id"], (long)reader["AccountNumber"], (decimal)reader["Cash"], (decimal)reader["RepayALoan"],
                                                   (decimal)reader["AmountIssue"], (int)reader["ClientId"], (int)reader["Rate"], (decimal)reader["MonthlyPayment"], (bool)reader["State"],
                                                   (int)reader["MonthsPeriod"], (DateTime)reader["OpenDate"], (DateTime)reader["NextDate"], (int)reader["TypeId"]);
                     // Repository.GetCredits.Add(credits);
                     accounts.Add(AccountFactory.GetAccount(credits));
                     count++;
                     countAccount++;
                     ProgressBar.GetValue("Загрузка счетов", itemcount, count);
                 }
             }
             ConnectionClient.ConClose();
         }
     }
     catch (SqlException e)
     {
         errorMes.ErrorSQL(e.Message); ConnectionClient.ConClose();
     }
     catch (Exception e)
     {
         errorMes.ErrorSQL(e.Message); ConnectionClient.ConClose();
     }
     finally { ConnectionClient.ConClose(); }
 }
Example #29
0
        static void Main(string[] args)
        {
            Console.Write(
                @"
New Features in version 1.0.0
  1. PersistentConnection
  2. Hub
New Features in version 2.1.0
  3. Hub<T>

Select sample you want to run: ");
            var sample = Console.ReadKey().KeyChar;

            Console.WriteLine();

            var url    = "http://localhost:46962/";
            var writer = Console.Out;

            switch (sample)
            {
            case '1':
                var client = new ConnectionClient(writer);
                client.RunAsync(url + "Connections/DemoPersistentConnection").Wait();
                break;

            case '2':
                var hubClient = new HubClient(writer);
                hubClient.RunAsync(url).Wait();
                break;

            case '3':
                var hubTClient = new HubTClient(writer);
                hubTClient.RunAsync(url).Wait();
                break;

            default:
                break;
            }

            Console.WriteLine("Sample completed. Press ENTER to finish program.");
            Console.ReadLine();
        }
        public Task <int> DeleteAsync(string surveyId, string respondentKey)
        {
            Ensure.ArgumentNotNullOrEmptyString(surveyId, nameof(surveyId));
            Ensure.ArgumentNotNullOrEmptyString(respondentKey, nameof(respondentKey));

            var uri     = SurveySampleUrl(surveyId);
            var filters = new List <SampleFilter>
            {
                new SampleFilter {
                    Name = RespondentKey, Op = "eq", Value = respondentKey
                }
            };

            return(Client.DeleteAsJsonAsync <IEnumerable <SampleFilter> >(uri, filters)
                   .ContinueWith(responseMessageTask => responseMessageTask.Result.Content.ReadAsStringAsync().Result)
                   .ContinueWith(stringResult => JsonConvert.DeserializeObject <BackgroundActivityStatus>(stringResult.Result).ActivityId)
                   .ContinueWith(activityResult => ConnectionClient.GetActivityResultAsync <int>(activityResult.Result, "DeletedTotal"))
                   .Unwrap()
                   .FlattenExceptions());
        }
Example #31
0
            public static void SetUp()
            {
                lock (Synchronise)
                {
                    RegistryClient = SqlDStart.NewClient().ConnectedTo(EndPoints.Registry);
                    EndPointMonitor.WaitUntil(RegistryClient.EndPoint, EndPointIs.Up);

                    AlphaClient = SqlDStart.NewClient().ConnectedTo(EndPoints.Alpha);
                    EndPointMonitor.WaitUntil(AlphaClient.EndPoint, EndPointIs.Up);

                    BetaClient = SqlDStart.NewClient().ConnectedTo(EndPoints.Beta);
                    EndPointMonitor.WaitUntil(BetaClient.EndPoint, EndPointIs.Up);

                    Free1Client = SqlDStart.NewClient().ConnectedTo(EndPoints.Free1);
                    EndPointMonitor.WaitUntil(Free1Client.EndPoint, EndPointIs.Up);

                    Free2Client = SqlDStart.NewClient().ConnectedTo(EndPoints.Free2);
                    EndPointMonitor.WaitUntil(Free2Client.EndPoint, EndPointIs.Up);
                }
            }
        /// <summary>
        /// Calls API Methods.
        /// </summary>
        /// <typeparam name="T">Type to which the response content will be converted.</typeparam>
        /// <param name="method">HTTPMethod (POST-GET-PUT-DELETE)</param>
        /// <param name="endpoint">Url endpoing.</param>
        /// <param name="isSigned">Specifies if the request needs a signature.</param>
        /// <param name="parameters">Request parameters.</param>
        /// <returns>returns raw JSON output as string</returns>
        public async Task <string> CallAsyncRaw(ApiMethod method, string endpoint, bool isSigned = false, string parameters = null)
        {
            var finalEndpoint = endpoint + (string.IsNullOrWhiteSpace(parameters) ? "" : $"?{parameters}");

            if (isSigned)
            {
                parameters += (!string.IsNullOrWhiteSpace(parameters) ? "&timestamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now);
                var signature = Utilities.GenerateSignature(APISecret, parameters);
                finalEndpoint = $"{endpoint}?{parameters}&signature={signature}";
            }

            var request = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint);

            var response = await ConnectionClient.SendAsync(request).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();

            var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(result);
        }
Example #33
0
        /// <summary>
        /// General method for sending messages. Sends single message to server and waits for any responses.
        /// </summary>
        /// <param name="message">XmlMessage to be sent.</param>
        /// <returns>All received messages as XMLDocuments.</returns>
        protected List<MessagePackage> SendMessage(IClusterMessage message)
        {
            var tcpClient = new ConnectionClient(ServerInfo);

            tcpClient.Connect();

            var responses = tcpClient.SendAndWaitForResponses(message);

            tcpClient.Close();

            return responses;
        }