Пример #1
1
    static void Main(string[] args)
    {
        // Setup Credentials and Server Information
        ConnectionInfo ConnNfo = new ConnectionInfo("10.141.3.110",22,"root",
            new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("root","ismail"),

            }
        );

        // Execute (SHELL) Commands
        using (var sshclient = new SshClient(ConnNfo)){
            sshclient.Connect();

            // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
            Console.WriteLine("telnet localhost 6571");
            Console.WriteLine("denemeeeeeee");
            //Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
            //Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
            //Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
            sshclient.Disconnect();
        }
        Console.ReadKey();
    }
Пример #2
0
 public void Disconnect()
 {
     CheckConnected();
     ((IActorClientProxy)_actor).Close();
     _actor = null;
     _connectionInfo = null;
 }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _netConfSessionMock = new Mock<INetConfSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object);

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _netConfClient.OperationTimeout))
                .Returns(_netConfSessionMock.Object);
            _netConfSessionMock.InSequence(sequence).Setup(p => p.Connect());
            _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
            _netConfSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _netConfSessionMock.InSequence(sequence).Setup(p => p.Dispose());

            _netConfClient.Connect();
            _netConfClient.Dispose();
        }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Loose);
            _sessionMock = new Mock<ISession>(MockBehavior.Loose);
            _netConfSessionMock = new Mock<INetConfSession>(MockBehavior.Loose);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object);

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _netConfClient.OperationTimeout))
                .Returns(_netConfSessionMock.Object);
            _netConfSessionMock.InSequence(sequence).Setup(p => p.Connect());

            _netConfClient.Connect();
            _netConfClient = null;

            // we need to dereference all other mocks as they might otherwise hold the target alive
            _sessionMock = null;
            _connectionInfo = null;
            _serviceFactoryMock = null;

        }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Loose);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10));
            _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sftpClient.OperationTimeout = _operationTimeout;

            _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.Setup(p => p.Connect());
            _serviceFactoryMock.Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns(_sftpSessionMock.Object);
            _sftpSessionMock.Setup(p => p.Connect());

            _sftpClient.Connect();
            _sftpClient = null;

            _serviceFactoryMock.Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns((ISftpSession)  null);
            _serviceFactoryMock.ResetCalls();

            // we need to dereference all other mocks as they might otherwise hold the target alive
            _sessionMock = null;
            _connectionInfo = null;
            _serviceFactoryMock = null;
        }
Пример #6
0
        protected Connection(ConnectionInfo connectionInfo)
        {
            Ensure.That(connectionInfo, "connectionInfo").IsNotNull();

            HttpClient = CreateHttpClient(connectionInfo);
            IsDisposed = false;
        }
Пример #7
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            int DoctorID;
            DoctorID = Convert.ToInt32(cbDoctor.SelectedValue.ToString());
            ReportDocument reportDocument = new ReportDocument();
            ParameterField paramField = new ParameterField();
            ParameterFields paramFields = new ParameterFields();
            ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
            string ReportPath = ConfigurationManager.AppSettings["ReportPath"];

            paramField.Name = "@DoctorID";

            paramDiscreteValue.Value = DoctorID;
            reportDocument.Load(ReportPath + "Report\\DoctorCrystalReport.rpt");

            ConnectionInfo connectionInfo = new ConnectionInfo();
            connectionInfo.DatabaseName = "DB_MedicalShop_02Sept20159PM";
            //connectionInfo.UserID = "wms";
            //connectionInfo.Password = "******";
            connectionInfo.IntegratedSecurity = true;
            SetDBLogonForReport(connectionInfo, reportDocument);

            reportDocument.SetParameterValue("@DoctorID", DoctorID);
            DoctorCrystalRpt.ReportSource = reportDocument;

            DoctorCrystalRpt.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.None;
        }
Пример #8
0
 private static void SaveExportFile(string fileName, ConnectionsSaver.Format saveFormat, SaveFilter saveFilter, ConnectionInfo exportTarget)
 {
     try
     {
         ISerializer<string> serializer;
         switch (saveFormat)
         {
             case ConnectionsSaver.Format.mRXML:
                 var factory = new CryptographyProviderFactory();
                 var cryptographyProvider = factory.CreateAeadCryptographyProvider(mRemoteNG.Settings.Default.EncryptionEngine, mRemoteNG.Settings.Default.EncryptionBlockCipherMode);
                 cryptographyProvider.KeyDerivationIterations = Settings.Default.EncryptionKeyDerivationIterations;
                 serializer = new XmlConnectionsSerializer(cryptographyProvider);
                 ((XmlConnectionsSerializer) serializer).SaveFilter = saveFilter;
                 break;
             case ConnectionsSaver.Format.mRCSV:
                 serializer = new CsvConnectionsSerializerMremotengFormat();
                 ((CsvConnectionsSerializerMremotengFormat)serializer).SaveFilter = saveFilter;
                 break;
             default:
                 throw new ArgumentOutOfRangeException(nameof(saveFormat), saveFormat, null);
         }
         var serializedData = serializer.Serialize(exportTarget);
         var fileDataProvider = new FileDataProvider(fileName);
         fileDataProvider.Save(serializedData);
     }
     catch (Exception ex)
     {
         Runtime.MessageCollector.AddExceptionStackTrace($"Export.SaveExportFile(\"{fileName}\") failed.", ex);
     }
     finally
     {
         Runtime.RemoteConnectionsSyncronizer?.Enable();
     }
 }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10));
            _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sftpClient.OperationTimeout = _operationTimeout;

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns(_sftpSessionMock.Object);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect());
            _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _sessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sessionMock.InSequence(sequence).Setup(p => p.Dispose());

            _sftpClient.Connect();
            _sftpClient.Disconnect();
        }
		public DefaultMongoAbstractFactory(ConnectionInfo connectionInfo)
		{
			RepositoryFactory = new DefaultMongoRepositoryFactory(connectionInfo);
			ErrorHandlingFactory = new DefaultMongoErrorHandlingFactory();
			IdGeneratorFactory = new DefaultMongoIdGeneratorFactory(connectionInfo);
			HashGeneratorFactory = new DefaultMongoHashGeneratorFactory();
		}
Пример #11
0
        public async void Run(
           int messageCount,
           bool interceptors,
           bool batchSending,
           ConnectionInfoTypes type)
        {

            var queueName = GenerateQueueName.Create();
            var logProvider = LoggerShared.Create(queueName, GetType().Name);
            var producer = new ProducerAsyncShared();
            var connectionString = new ConnectionInfo(type).ConnectionString;
            using (
                var queueCreator =
                    new QueueCreationContainer<RedisQueueInit>(
                        serviceRegister => serviceRegister.Register(() => logProvider, LifeStyles.Singleton)))
            {
                try
                {
                    await producer.RunTest<RedisQueueInit, FakeMessage>(queueName,
                       connectionString, interceptors, messageCount, logProvider, Helpers.GenerateData,
                        Helpers.Verify, batchSending);
                }
                finally
                {
                    using (
                        var oCreation =
                            queueCreator.GetQueueCreation<RedisQueueCreation>(queueName,
                                connectionString)
                        )
                    {
                        oCreation.RemoveQueue();
                    }
                }
            }
        }
 /// <summary>
 /// Gets the connection info. (some fields of <see cref="T:System.Data.Odbc.OdbcConnection"/>)
 /// If specified <c>odbcConnectionString</c> doesn`t work empty strings are returned in
 /// result fields.
 /// </summary>
 /// <param name="odbcConnectionString">The ODBC connection string.</param>
 /// <param name="boxIdentity">The box identity.</param>
 /// <returns>
 /// <see cref="Ferda.Modules.Boxes.DataMiningCommon.Database.ConnectionInfo"/>
 /// </returns>
 public static ConnectionInfo GetConnectionInfo(string odbcConnectionString, string boxIdentity)
 {
     ConnectionInfo result = new ConnectionInfo();
     try
     {
         OdbcConnection conn = Ferda.Modules.Helpers.Data.OdbcConnections.GetConnection(odbcConnectionString, boxIdentity);
         result.databaseName = conn.Database;
         result.dataSource = conn.DataSource;
         result.driver = conn.Driver;
         try
         {
             result.serverVersion = conn.ServerVersion;
         }
         catch (InvalidOperationException)
         {
             result.serverVersion = String.Empty;
         }
     }
     catch (Ferda.Modules.BadParamsError ex)
     {
         if (ex.restrictionType != Ferda.Modules.restrictionTypeEnum.DbConnectionString)
             throw ex;
         result.databaseName = String.Empty;
         result.dataSource = String.Empty;
         result.driver = String.Empty;
         result.serverVersion = String.Empty;
     }
     return result;
 }
Пример #13
0
        private void AcceptCallback(IAsyncResult result)
        {
            ConnectionInfo connection = new ConnectionInfo();
            try
            {
                // Завершение операции Accept
                Socket s = (Socket)result.AsyncState;

                connection.Socket = s.EndAccept(result);
                connection.Buffer = new byte[255];
                lock (_connections) _connections.Add(connection);
                Console.WriteLine("New connection. Count of clients = " + _connections.Count);
                // Начало операции Receive и новой операции Accept
                connection.Socket.BeginReceive(connection.Buffer,
                    0, connection.Buffer.Length, SocketFlags.None,
                    new AsyncCallback(ReceiveCallback),
                    connection);
                _serverSocket.BeginAccept(new AsyncCallback(
                    AcceptCallback), result.AsyncState);
            }
            catch (SocketException exc)
            {
                CloseConnection(connection);
                Console.WriteLine("Socket exception: " +
                    exc.SocketErrorCode);
            }
            catch (Exception exc)
            {
                CloseConnection(connection);
                Console.WriteLine("Exception: " + exc);
            }
        }
 public virtual void Uninitialize()
 {
     _features = default(FeatureReferences<FeatureInterfaces>);
     if (_request != null)
     {
         UninitializeHttpRequest(_request);
         _request = null;
     }
     if (_response != null)
     {
         UninitializeHttpResponse(_response);
         _response = null;
     }
     if (_authenticationManager != null)
     {
         UninitializeAuthenticationManager(_authenticationManager);
         _authenticationManager = null;
     }
     if (_connection != null)
     {
         UninitializeConnectionInfo(_connection);
         _connection = null;
     }
     if (_websockets != null)
     {
         UninitializeWebSocketManager(_websockets);
         _websockets = null;
     }
 }
 public XElement SerializeConnectionInfo(ConnectionInfo connectionInfo)
 {
     var element = new XElement(XName.Get("Node", ""));
     SetElementAttributes(element, connectionInfo);
     SetInheritanceAttributes(element, connectionInfo);
     return element;
 }
Пример #16
0
        private void LaunchSelected()
        {
            if (listView1.SelectedIndices.Count == 0)
                return;

            if (listView1.SelectedIndices[0] > _filtered.Count() - 1)
                return;

            var selected = _filtered[listView1.SelectedIndices[0]];
            var info = new ConnectionInfo {
                Mppass = selected.Mppass,
                Ip = selected.Ip,
                Port = selected.Port,
                Username = _service.Username
            };

            ClassicalSharp.Launch(info);

            if (Preferences.Settings.Launcher.RememberServers) {
                Preferences.Settings.Launcher.ResumeUrl = string.Format("mc://{0}:{1}/{2}/{3}", info.Ip, info.Port,
                    info.Username, info.Mppass);

                Preferences.Save();
            }

            if (!Preferences.Settings.Launcher.KeepLauncherOpen)
                Application.Exit();
        }
 private ConnectionTreeModel SetupConnectionTreeModel()
 {
     /*
      * Root
      * |--- con0
      * |--- folder1
      * |    L--- con1
      * L--- folder2
      *      |--- con2
      *      L--- folder3
      *           |--- con3
      *           L--- con4
      */
     var connectionTreeModel = new ConnectionTreeModel();
     var rootNode = new RootNodeInfo(RootNodeType.Connection);
     var folder1 = new ContainerInfo { Name = "folder1" };
     var folder2 = new ContainerInfo { Name = "folder2" };
     var folder3 = new ContainerInfo { Name = "folder3" };
     var con0 = new ConnectionInfo { Name = "con0" };
     var con1 = new ConnectionInfo { Name = "con1" };
     var con2 = new ConnectionInfo { Name = "con2" };
     var con3 = new ConnectionInfo { Name = "con3" };
     var con4 = new ConnectionInfo { Name = "con4" };
     rootNode.AddChild(folder1);
     rootNode.AddChild(folder2);
     rootNode.AddChild(con0);
     folder1.AddChild(con1);
     folder2.AddChild(con2);
     folder2.AddChild(folder3);
     folder3.AddChild(con3);
     folder3.AddChild(con4);
     connectionTreeModel.AddRootNode(rootNode);
     return connectionTreeModel;
 }
Пример #18
0
        private void FormSupplierPayment_Print_Load(object sender, EventArgs e)
        {
            try
            {
                // int TransactionID;
                //SaleTransactionID = Convert.ToInt32(cbSupplier.SelectedValue.ToString());
                ReportDocument reportDocument = new ReportDocument();
                ParameterField paramField = new ParameterField();
                ParameterFields paramFields = new ParameterFields();
                ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
                string ReportPath = ConfigurationManager.AppSettings["ReportPath"];

                paramField.Name = "@SupplierPaymentID";

                paramDiscreteValue.Value = @SupplierPaymentID;
                reportDocument.Load(ReportPath+"SupplierPay_Print_CrystalReport.rpt");

                ConnectionInfo connectionInfo = new ConnectionInfo();
                connectionInfo.DatabaseName = "DB_MedicalShop_02Sept20159PM";
                //connectionInfo.UserID = "wms";
                //connectionInfo.Password = "******";
                connectionInfo.IntegratedSecurity = true;
                SetDBLogonForReport(connectionInfo, reportDocument);

                reportDocument.SetParameterValue("@SupplierPaymentID", SupplierPaymentID);
                SupplierPyCrystalPrint.ReportSource = reportDocument;

                SupplierPyCrystalPrint.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.None;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        private ToolStripDropDownItem CreateMenuItem(ConnectionInfo node)
        {
            var menuItem = new ToolStripMenuItem
            {
                Text = node.Name,
                Tag = node
            };

            var nodeAsContainer = node as ContainerInfo;
            if (nodeAsContainer != null)
            {
                menuItem.Image = Resources.Folder;
                menuItem.Tag = nodeAsContainer;
                AddSubMenuNodes(nodeAsContainer.Children, menuItem);
            }
            else if (node.GetTreeNodeType() == TreeNodeType.PuttySession)
            {
                menuItem.Image = Resources.PuttySessions;
                menuItem.Tag = node;
            }
            else if (node.GetTreeNodeType() == TreeNodeType.Connection)
            {
                menuItem.Image = Resources.Pause;
                menuItem.Tag = node;
            }

            menuItem.MouseUp += MouseUpEventHandler;
            return menuItem;
        }
Пример #20
0
        /// <summary>
        /// Request user to provide server details and returns the result as a <see cref="ConnectionInfo"/> object. Performs the necessary validation and prevents code duplication across examples.
        /// </summary>
        /// <param name="connectionInfo"></param>
        public static void GetServerDetails(out ConnectionInfo connectionInfo)
        {
            if (lastServerIPEndPoint != null)
                Console.WriteLine("Please enter the destination IP and port. To reuse '{0}:{1}' use r:", lastServerIPEndPoint.Address, lastServerIPEndPoint.Port);
            else
                Console.WriteLine("Please enter the destination IP address and port, e.g. '192.168.0.1:10000':");

            while (true)
            {
                try
                {
                    //Parse the provided information
                    string userEnteredStr = Console.ReadLine();

                    if (userEnteredStr.Trim() == "r" && lastServerIPEndPoint != null)
                        break;
                    else
                    {
                        lastServerIPEndPoint = IPTools.ParseEndPointFromString(userEnteredStr);
                        break;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to determine host IP address and port. Check format and try again:");
                }
            }

            connectionInfo = new ConnectionInfo(lastServerIPEndPoint);
        }
Пример #21
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            int GroupId;
            GroupId = Convert.ToInt32(cbgroupNames.SelectedValue.ToString());

            ReportDocument reportDocument = new ReportDocument();
            ParameterField paramField = new ParameterField();
            ParameterFields paramFields = new ParameterFields();
            ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
            string ReportPath = ConfigurationManager.AppSettings["ReportPath"];

            paramField.Name = "@GroupId";
            paramDiscreteValue.Value = 1;
            reportDocument.Load(ReportPath + "Reports\\GroupWise_CrystalReport.rpt");

            ConnectionInfo connectionInfo = new ConnectionInfo();
            connectionInfo.DatabaseName = "DB_LoanApplication";
            //connectionInfo.UserID = "wms";
            //connectionInfo.Password = "******";
            connectionInfo.IntegratedSecurity = true;
            SetDBLogonForReport(connectionInfo, reportDocument);

            reportDocument.SetParameterValue("@GroupId", GroupId);
            GroupWisecrystalReport.ReportSource = reportDocument;
            GroupWisecrystalReport.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.None;
        }
Пример #22
0
        private ConnectionTreeModel SetupConnectionTreeModel()
        {
            /*
             * Tree:
             * Root
             * |--- folder1
             * |    |--- con1
             * |    L--- con2
             * |--- folder2
             * |    |--- con3
             * |    L--- con4
             * L--- con5
             *
             */
            var connectionTreeModel = new ConnectionTreeModel();
            var root = new RootNodeInfo(RootNodeType.Connection);
            _folder1 = new ContainerInfo { Name = "folder1"};
            _con1 = new ConnectionInfo { Name = "con1"};
            _con2 = new ConnectionInfo { Name = "con2"};
            _folder2 = new ContainerInfo { Name = "folder2" };
            _con3 = new ConnectionInfo { Name = "con3" };
            _con4 = new ConnectionInfo { Name = "con4" };
            _con5 = new ConnectionInfo { Name = "con5" };

            connectionTreeModel.AddRootNode(root);
            root.AddChildRange(new [] { _folder1, _folder2, _con5 });
            _folder1.AddChildRange(new [] { _con1, _con2 });
            _folder2.AddChildRange(new[] { _con3, _con4 });

            return connectionTreeModel;
        }
Пример #23
0
        private void AcceptCallback(IAsyncResult result)
        {
            ConnectionInfo connection = new ConnectionInfo();
            try
            {
            // Завершение операции Accept
            Socket s = (Socket)result.AsyncState;
            connection.Socket = s.EndAccept(result);
            connection.Buffer = new byte[255];
            lock (_connections) _connections.Add(connection);

            // Начало операции Receive и новой операции Accept // запрашиваем выполнение операции асинхронного чтения
            //(читаем данные из сокета без явного опроса сокета или создания потока)
              connection.Socket.BeginReceive(connection.Buffer,0, connection.Buffer.Length, SocketFlags.None,
              new AsyncCallback(ReceiveCallback),connection);

            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), result.AsyncState);
            }
            catch (SocketException exc)
            {
            CloseConnection(connection);
            Console.WriteLine("Socket exception: " +
                exc.SocketErrorCode);
            }
            catch (Exception exc)
            {
            CloseConnection(connection);
            Console.WriteLine("Exception: " + exc);
            }
        }
Пример #24
0
        private void frmReport_Load(object sender, EventArgs e)
        {
            TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
            ConnectionInfo crConnectionInfo = new ConnectionInfo();
            Tables CrTables;
            string[] Account = help.GetAccount().Split(' ');
            crConnectionInfo.ServerName = Account[0];
            crConnectionInfo.DatabaseName = Account[1];
            crConnectionInfo.UserID = Account[2];
            object pwd = Account[3];
            crConnectionInfo.Password=(pwd.ToString());
            //---------Xét account truy cập vào các table
            CrTables = rpt.Database.Tables;
            foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
            {
                crtableLogoninfo = CrTable.LogOnInfo;
                crtableLogoninfo.ConnectionInfo = crConnectionInfo;
                CrTable.ApplyLogOnInfo(crtableLogoninfo);
            }
            //----------set resource---------------

              rpt.SetParameterValue("tu",tu);
              rpt.SetParameterValue("den", den);
            cryRViewer.ReportSource = rpt;
            cryRViewer.Refresh();
        }
Пример #25
0
        public void DeleteNode(ConnectionInfo connectionInfo)
        {
            if (connectionInfo is RootNodeInfo)
                return;

            connectionInfo?.RemoveParent();
        }
Пример #26
0
    void MainMenu()
    {
        float stdW = 100;
        float stdH = 20;
        float currY = 0;
        if (GUI.Button(new Rect(0, currY, stdW, stdH), "Host Game"))
        {
            SendMessage("StartServer");
            SendMessage("GoToNextScene");
        }
        currY += stdH;

        GUI.Label(new Rect(0, currY, stdW, stdH), "IP Address");
        currY += stdH;

        ipAddress = GUI.TextArea(new Rect(0, currY, stdW, stdH), ipAddress);
        currY += stdH;

        portNumber = GUI.TextArea(new Rect(0, currY, stdW, stdH), portNumber);
        currY += stdH;

        if (GUI.Button(new Rect(0, currY, stdW, stdH), "Connect to Server"))
        {
            ConnectionInfo info = new ConnectionInfo();
            info.ipAddress = ipAddress;
            int iPortNum = 0;
            if (Int32.TryParse(portNumber, out iPortNum))
            {
                info.port = iPortNum;
            }

            SendMessage("ConnectToServer", info);
        }
    }
Пример #27
0
 public void CopyingAConnectionInfoAlsoCopiesItsInheritance()
 {
     _connectionInfo.Inheritance.Username = true;
     var secondConnection = new ConnectionInfo {Inheritance = {Username = false}};
     secondConnection.CopyFrom(_connectionInfo);
     Assert.That(secondConnection.Inheritance.Username, Is.True);
 }
        public ConnectionTreeNode(ProjectSchemaTreeNode parent, ConnectionInfo connectionInfo)
            : base(parent)
        {
            this.ConnectionInfo = connectionInfo;

            Initialize();
        }
        protected void Arrange()
        {
            var random = new Random();
            _fileName = CreateTemporaryFile(new byte[] {1});
            _connectionInfo = new ConnectionInfo("host", 22, "user", new PasswordAuthenticationMethod("user", "pwd"));
            _fileInfo = new FileInfo(_fileName);
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _uploadingRegister = new List<ScpUploadEventArgs>();

            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _pipeStreamMock = new Mock<PipeStream>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Open());
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(false);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _pipeStreamMock.As<IDisposable>().InSequence(sequence).Setup(p => p.Dispose());

            _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args);
            _scpClient.Connect();
        }
        protected void Arrange()
        {
            _serverEndPoint = new IPEndPoint(IPAddress.Loopback, 8122);
            _connectionInfo = new ConnectionInfo(
                _serverEndPoint.Address.ToString(),
                _serverEndPoint.Port,
                "user",
                new PasswordAuthenticationMethod("user", "password"));
            _connectionInfo.Timeout = TimeSpan.FromMilliseconds(200);
            _actualException = null;

            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);

            _serverListener = new AsyncSocketListener(_serverEndPoint);
            _serverListener.Connected += (socket) =>
                {
                    _serverSocket = socket;

                    socket.Send(Encoding.ASCII.GetBytes("\r\n"));
                    socket.Send(Encoding.ASCII.GetBytes("WELCOME banner\r\n"));
                    socket.Send(Encoding.ASCII.GetBytes("SSH-2.0-SshStub\r\n"));
                };
            _serverListener.BytesReceived += (received, socket) =>
                {
                    var badPacket = new byte[] {0x0a, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05};
                    _serverSocket.Send(badPacket, 0, badPacket.Length, SocketFlags.None);
                    _serverSocket.Shutdown(SocketShutdown.Send);
                };
            _serverListener.Start();
        }
            /// <summary>
            /// The connection has been closed remotely or disconnected locally. Check data.State for details.
            /// </summary>
            public override void OnDisconnected(Connection connection, ConnectionInfo data)
            {
                Console.WriteLine($" - OnDisconnected");

                base.OnDisconnected(connection, data);
            }
Пример #32
0
 public void SetUp()
 {
     provider       = (MockProvider) new MockProviderFactory().CreateProvider(new Uri("mock://localhost"));
     connectionInfo = new ConnectionInfo(new Id("ID:TEST:1"));
 }
Пример #33
0
 public PostDataAccess(ConnectionInfo connectionInfo, IMongoDataAccessAbstractFactory factories)
     : base(connectionInfo, factories)
 {
 }
Пример #34
0
        public override ProcessOutput ExecuteCcm(string args, bool throwOnProcessError = true)
        {
            var executable = GetExecutable(ref args);

            Trace.TraceInformation(executable + " " + args);

            var output = new ProcessOutput();

            if (_sshClient == null)
            {
                Trace.TraceInformation("Connecting ssh client...");
                var kauth = new KeyboardInteractiveAuthenticationMethod(_user);
                var pauth = new PasswordAuthenticationMethod(_user, _password);

                var connectionInfo = new ConnectionInfo(_ip, _port, _user, kauth, pauth);

                kauth.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                {
                    foreach (var prompt in e.Prompts)
                    {
                        if (prompt.Request.ToLowerInvariant().StartsWith("password"))
                        {
                            prompt.Response = _password;
                        }
                    }
                };

                if (!string.IsNullOrEmpty(_privateKeyFilePath))
                {
                    var privateKeyAuth = new PrivateKeyAuthenticationMethod(_user, new PrivateKeyFile[]
                    {
                        new PrivateKeyFile(_privateKeyFilePath)
                    });
                    connectionInfo = new ConnectionInfo(_ip, _port, _user, privateKeyAuth);
                }

                _sshClient = new SshClient(connectionInfo);
            }
            if (!_sshClient.IsConnected)
            {
                _sshClient.Connect();
            }

            var result = _sshClient.RunCommand(string.Format(@"{0} {1}", executable, args));

            output.ExitCode = result.ExitStatus;
            if (result.Error != null)
            {
                output.OutputText.Append(result.Error);
            }
            else
            {
                output.OutputText.Append(result.Result);
            }

            if (throwOnProcessError)
            {
                ValidateOutput(output);
            }
            return(output);
        }
Пример #35
0
 public TCPIPSocket(ConnectionInfo info) : base(info)
 {
     this.Create();
 }
Пример #36
0
        public static async Task <IDbConnection> OpenDbConnectionAsync(this IDbConnectionFactory dbFactory, ConnectionInfo connInfo)
        {
            if (dbFactory is IDbConnectionFactoryExtended dbFactoryExt && connInfo != null)
            {
                if (connInfo.ConnectionString != null)
                {
                    return(connInfo.ProviderName != null
                        ? await dbFactoryExt.OpenDbConnectionStringAsync(connInfo.ConnectionString, connInfo.ProviderName)
                        : await dbFactoryExt.OpenDbConnectionStringAsync(connInfo.ConnectionString));
                }

                if (connInfo.NamedConnection != null)
                {
                    return(await dbFactoryExt.OpenDbConnectionAsync(connInfo.NamedConnection));
                }
            }
            return(await dbFactory.OpenAsync());
        }
Пример #37
0
        public static IDbConnection OpenDbConnection(this IDbConnectionFactory dbFactory, ConnectionInfo connInfo)
        {
            if (dbFactory is IDbConnectionFactoryExtended dbFactoryExt && connInfo != null)
            {
                if (connInfo.ConnectionString != null)
                {
                    return(connInfo.ProviderName != null
                        ? dbFactoryExt.OpenDbConnectionString(connInfo.ConnectionString, connInfo.ProviderName)
                        : dbFactoryExt.OpenDbConnectionString(connInfo.ConnectionString));
                }

                if (connInfo.NamedConnection != null)
                {
                    return(dbFactoryExt.OpenDbConnection(connInfo.NamedConnection));
                }
            }
            return(dbFactory.Open());
        }
Пример #38
0
        private bool AttemptSshPortForward()
        {
            context.Splash.SetLabel("Überprüfe Verfügbarkeit des SSH-Proxy...");

            string hostname = context.Ini["sshProxy"]["host"];
            ushort port     = Convert.ToUInt16(context.Ini["sshProxy"]["port"]);
            bool   tcpProbe = TcpProbe(hostname, port);

            if (!tcpProbe)
            {
                return(false);
            }

            context.Splash.SetLabel("Versuche über SSH-Proxy mit Datenbank zu verbinden...");
            string sshHost     = context.Ini["sshProxy"]["host"];
            int    sshPort     = Convert.ToInt32(context.Ini["sshProxy"]["port"]);
            string sshUser     = context.Ini["sshProxy"]["username"];
            string sshPassword = null;

            if (context.Ini["sshProxy"].ContainsKey("password"))
            {
                sshPassword = context.Ini["sshProxy"]["password"];
            }

            List <AuthenticationMethod> authenticationMethods = new List <AuthenticationMethod>();

            authenticationMethods.Add(new NoneAuthenticationMethod(sshUser));

            if (File.Exists("ssh.key"))
            {
                authenticationMethods.Add(
                    new PrivateKeyAuthenticationMethod(sshUser, new PrivateKeyFile[] { new PrivateKeyFile("ssh.key") }));
            }

            if (string.IsNullOrEmpty(sshPassword) && authenticationMethods.Count == 1)
            {
                context.Splash.Invoke((MethodInvoker) delegate
                {
                    sshPassword =
                        TextInputForm.PromptPassword(String.Format("Passwort für {0} auf {1}?", sshUser, sshHost),
                                                     context.Splash);
                });
            }

            if (!string.IsNullOrEmpty(sshPassword) && authenticationMethods.Count == 1)
            {
                authenticationMethods.Add(new PasswordAuthenticationMethod(sshUser, sshPassword));
            }

            if (authenticationMethods.Count > 1)
            {
                context.Splash.SetLabel("Verbinde mit SSH Server...");
                ConnectionInfo sshConnectionInfo =
                    new ConnectionInfo(sshHost, sshPort, sshUser, authenticationMethods.ToArray());
                context.SSH = new SshClient(sshConnectionInfo);
                if (!context.SSH.IsConnected)
                {
                    context.SSH.Connect();
                }

                context.Splash.SetLabel("Starte Port-Forwarding...");
                uint          localPort = (uint)AzusaContext.FindFreePort();
                ForwardedPort sqlPort   = new ForwardedPortLocal("127.0.0.1", localPort, context.Ini["postgresql"]["server"], Convert.ToUInt16(context.Ini["postgresql"]["port"]));
                context.SSH.AddForwardedPort(sqlPort);
                sqlPort.Start();
                bool worksWithForward = TcpProbe("127.0.0.1", (int)localPort);
                if (worksWithForward)
                {
                    context.Ini["postgresql"]["server"] = "127.0.0.1";
                    context.Ini["postgresql"]["port"]   = localPort.ToString();
                    return(true);
                }
                else
                {
                    context.SSH.Disconnect();
                    context.SSH = null;
                }
            }

            return(false);
        }
Пример #39
0
        private void PopulateConnectionInfoFromDatarow(DataRow dataRow, ConnectionInfo connectionInfo)
        {
            connectionInfo.Name       = (string)dataRow["Name"];
            connectionInfo.ConstantID = (string)dataRow["ConstantID"];
            //connectionInfo.Parent.ConstantID = (string)dataRow["ParentID"];
            //connectionInfo is ContainerInfo ? ((ContainerInfo)connectionInfo).IsExpanded.ToString() : "" = dataRow["Expanded"];
            connectionInfo.Description                       = (string)dataRow["Description"];
            connectionInfo.Icon                              = (string)dataRow["Icon"];
            connectionInfo.Panel                             = (string)dataRow["Panel"];
            connectionInfo.Username                          = (string)dataRow["Username"];
            connectionInfo.Domain                            = (string)dataRow["DomainName"];
            connectionInfo.Password                          = (string)dataRow["Password"];
            connectionInfo.Hostname                          = (string)dataRow["Hostname"];
            connectionInfo.Protocol                          = (ProtocolType)Enum.Parse(typeof(ProtocolType), (string)dataRow["Protocol"]);
            connectionInfo.PuttySession                      = (string)dataRow["PuttySession"];
            connectionInfo.Port                              = (int)dataRow["Port"];
            connectionInfo.UseConsoleSession                 = (bool)dataRow["ConnectToConsole"];
            connectionInfo.UseCredSsp                        = (bool)dataRow["UseCredSsp"];
            connectionInfo.RenderingEngine                   = (HTTPBase.RenderingEngine)Enum.Parse(typeof(HTTPBase.RenderingEngine), (string)dataRow["RenderingEngine"]);
            connectionInfo.ICAEncryptionStrength             = (ProtocolICA.EncryptionStrength)Enum.Parse(typeof(ProtocolICA.EncryptionStrength), (string)dataRow["ICAEncryptionStrength"]);
            connectionInfo.RDPAuthenticationLevel            = (ProtocolRDP.AuthenticationLevel)Enum.Parse(typeof(ProtocolRDP.AuthenticationLevel), (string)dataRow["RDPAuthenticationLevel"]);
            connectionInfo.LoadBalanceInfo                   = (string)dataRow["LoadBalanceInfo"];
            connectionInfo.Colors                            = (ProtocolRDP.RDPColors)Enum.Parse(typeof(ProtocolRDP.RDPColors), (string)dataRow["Colors"]);
            connectionInfo.Resolution                        = (ProtocolRDP.RDPResolutions)Enum.Parse(typeof(ProtocolRDP.RDPResolutions), (string)dataRow["Resolution"]);
            connectionInfo.AutomaticResize                   = (bool)dataRow["AutomaticResize"];
            connectionInfo.DisplayWallpaper                  = (bool)dataRow["DisplayWallpaper"];
            connectionInfo.DisplayThemes                     = (bool)dataRow["DisplayThemes"];
            connectionInfo.EnableFontSmoothing               = (bool)dataRow["EnableFontSmoothing"];
            connectionInfo.EnableDesktopComposition          = (bool)dataRow["EnableDesktopComposition"];
            connectionInfo.CacheBitmaps                      = (bool)dataRow["CacheBitmaps"];
            connectionInfo.RedirectDiskDrives                = (bool)dataRow["RedirectDiskDrives"];
            connectionInfo.RedirectPorts                     = (bool)dataRow["RedirectPorts"];
            connectionInfo.RedirectPrinters                  = (bool)dataRow["RedirectPrinters"];
            connectionInfo.RedirectSmartCards                = (bool)dataRow["RedirectSmartCards"];
            connectionInfo.RedirectSound                     = (ProtocolRDP.RDPSounds)Enum.Parse(typeof(ProtocolRDP.RDPSounds), (string)dataRow["RedirectSound"]);
            connectionInfo.SoundQuality                      = (ProtocolRDP.RDPSoundQuality)Enum.Parse(typeof(ProtocolRDP.RDPSoundQuality), (string)dataRow["SoundQuality"]);
            connectionInfo.RedirectKeys                      = (bool)dataRow["RedirectKeys"];
            connectionInfo.PleaseConnect                     = (bool)dataRow["Connected"];
            connectionInfo.PreExtApp                         = (string)dataRow["PreExtApp"];
            connectionInfo.PostExtApp                        = (string)dataRow["PostExtApp"];
            connectionInfo.MacAddress                        = (string)dataRow["MacAddress"];
            connectionInfo.UserField                         = (string)dataRow["UserField"];
            connectionInfo.ExtApp                            = (string)dataRow["ExtApp"];
            connectionInfo.VNCCompression                    = (ProtocolVNC.Compression)Enum.Parse(typeof(ProtocolVNC.Compression), (string)dataRow["VNCCompression"]);
            connectionInfo.VNCEncoding                       = (ProtocolVNC.Encoding)Enum.Parse(typeof(ProtocolVNC.Encoding), (string)dataRow["VNCEncoding"]);
            connectionInfo.VNCAuthMode                       = (ProtocolVNC.AuthMode)Enum.Parse(typeof(ProtocolVNC.AuthMode), (string)dataRow["VNCAuthMode"]);
            connectionInfo.VNCProxyType                      = (ProtocolVNC.ProxyType)Enum.Parse(typeof(ProtocolVNC.ProxyType), (string)dataRow["VNCProxyType"]);
            connectionInfo.VNCProxyIP                        = (string)dataRow["VNCProxyIP"];
            connectionInfo.VNCProxyPort                      = (int)dataRow["VNCProxyPort"];
            connectionInfo.VNCProxyUsername                  = (string)dataRow["VNCProxyUsername"];
            connectionInfo.VNCProxyPassword                  = (string)dataRow["VNCProxyPassword"];
            connectionInfo.VNCColors                         = (ProtocolVNC.Colors)Enum.Parse(typeof(ProtocolVNC.Colors), (string)dataRow["VNCColors"]);
            connectionInfo.VNCSmartSizeMode                  = (ProtocolVNC.SmartSizeMode)Enum.Parse(typeof(ProtocolVNC.SmartSizeMode), (string)dataRow["VNCSmartSizeMode"]);
            connectionInfo.VNCViewOnly                       = (bool)dataRow["VNCViewOnly"];
            connectionInfo.RDGatewayUsageMethod              = (ProtocolRDP.RDGatewayUsageMethod)Enum.Parse(typeof(ProtocolRDP.RDGatewayUsageMethod), (string)dataRow["RDGatewayUsageMethod"]);
            connectionInfo.RDGatewayHostname                 = (string)dataRow["RDGatewayHostname"];
            connectionInfo.RDGatewayUseConnectionCredentials = (ProtocolRDP.RDGatewayUseConnectionCredentials)Enum.Parse(typeof(ProtocolRDP.RDGatewayUseConnectionCredentials), (string)dataRow["RDGatewayUseConnectionCredentials"]);
            connectionInfo.RDGatewayUsername                 = (string)dataRow["RDGatewayUsername"];
            connectionInfo.RDGatewayPassword                 = (string)dataRow["RDGatewayPassword"];
            connectionInfo.RDGatewayDomain                   = (string)dataRow["RDGatewayDomain"];

            connectionInfo.Inheritance.CacheBitmaps             = (bool)dataRow["InheritCacheBitmaps"];
            connectionInfo.Inheritance.Colors                   = (bool)dataRow["InheritColors"];
            connectionInfo.Inheritance.Description              = (bool)dataRow["InheritDescription"];
            connectionInfo.Inheritance.DisplayThemes            = (bool)dataRow["InheritDisplayThemes"];
            connectionInfo.Inheritance.DisplayWallpaper         = (bool)dataRow["InheritDisplayWallpaper"];
            connectionInfo.Inheritance.EnableFontSmoothing      = (bool)dataRow["InheritEnableFontSmoothing"];
            connectionInfo.Inheritance.EnableDesktopComposition = (bool)dataRow["InheritEnableDesktopComposition"];
            connectionInfo.Inheritance.Domain                   = (bool)dataRow["InheritDomain"];
            connectionInfo.Inheritance.Icon                              = (bool)dataRow["InheritIcon"];
            connectionInfo.Inheritance.Panel                             = (bool)dataRow["InheritPanel"];
            connectionInfo.Inheritance.Password                          = (bool)dataRow["InheritPassword"];
            connectionInfo.Inheritance.Port                              = (bool)dataRow["InheritPort"];
            connectionInfo.Inheritance.Protocol                          = (bool)dataRow["InheritProtocol"];
            connectionInfo.Inheritance.PuttySession                      = (bool)dataRow["InheritPuttySession"];
            connectionInfo.Inheritance.RedirectDiskDrives                = (bool)dataRow["InheritRedirectDiskDrives"];
            connectionInfo.Inheritance.RedirectKeys                      = (bool)dataRow["InheritRedirectKeys"];
            connectionInfo.Inheritance.RedirectPorts                     = (bool)dataRow["InheritRedirectPorts"];
            connectionInfo.Inheritance.RedirectPrinters                  = (bool)dataRow["InheritRedirectPrinters"];
            connectionInfo.Inheritance.RedirectSmartCards                = (bool)dataRow["InheritRedirectSmartCards"];
            connectionInfo.Inheritance.RedirectSound                     = (bool)dataRow["InheritRedirectSound"];
            connectionInfo.Inheritance.SoundQuality                      = (bool)dataRow["InheritSoundQuality"];
            connectionInfo.Inheritance.Resolution                        = (bool)dataRow["InheritResolution"];
            connectionInfo.Inheritance.AutomaticResize                   = (bool)dataRow["InheritAutomaticResize"];
            connectionInfo.Inheritance.UseConsoleSession                 = (bool)dataRow["InheritUseConsoleSession"];
            connectionInfo.Inheritance.UseCredSsp                        = (bool)dataRow["InheritUseCredSsp"];
            connectionInfo.Inheritance.RenderingEngine                   = (bool)dataRow["InheritRenderingEngine"];
            connectionInfo.Inheritance.Username                          = (bool)dataRow["InheritUsername"];
            connectionInfo.Inheritance.ICAEncryptionStrength             = (bool)dataRow["InheritICAEncryptionStrength"];
            connectionInfo.Inheritance.RDPAuthenticationLevel            = (bool)dataRow["InheritRDPAuthenticationLevel"];
            connectionInfo.Inheritance.LoadBalanceInfo                   = (bool)dataRow["InheritLoadBalanceInfo"];
            connectionInfo.Inheritance.PreExtApp                         = (bool)dataRow["InheritPreExtApp"];
            connectionInfo.Inheritance.PostExtApp                        = (bool)dataRow["InheritPostExtApp"];
            connectionInfo.Inheritance.MacAddress                        = (bool)dataRow["InheritMacAddress"];
            connectionInfo.Inheritance.UserField                         = (bool)dataRow["InheritUserField"];
            connectionInfo.Inheritance.ExtApp                            = (bool)dataRow["InheritExtApp"];
            connectionInfo.Inheritance.VNCCompression                    = (bool)dataRow["InheritVNCCompression"];
            connectionInfo.Inheritance.VNCEncoding                       = (bool)dataRow["InheritVNCEncoding"];
            connectionInfo.Inheritance.VNCAuthMode                       = (bool)dataRow["InheritVNCAuthMode"];
            connectionInfo.Inheritance.VNCProxyType                      = (bool)dataRow["InheritVNCProxyType"];
            connectionInfo.Inheritance.VNCProxyIP                        = (bool)dataRow["InheritVNCProxyIP"];
            connectionInfo.Inheritance.VNCProxyPort                      = (bool)dataRow["InheritVNCProxyPort"];
            connectionInfo.Inheritance.VNCProxyUsername                  = (bool)dataRow["InheritVNCProxyUsername"];
            connectionInfo.Inheritance.VNCProxyPassword                  = (bool)dataRow["InheritVNCProxyPassword"];
            connectionInfo.Inheritance.VNCColors                         = (bool)dataRow["InheritVNCColors"];
            connectionInfo.Inheritance.VNCSmartSizeMode                  = (bool)dataRow["InheritVNCSmartSizeMode"];
            connectionInfo.Inheritance.VNCViewOnly                       = (bool)dataRow["InheritVNCViewOnly"];
            connectionInfo.Inheritance.RDGatewayUsageMethod              = (bool)dataRow["InheritRDGatewayUsageMethod"];
            connectionInfo.Inheritance.RDGatewayHostname                 = (bool)dataRow["InheritRDGatewayHostname"];
            connectionInfo.Inheritance.RDGatewayUseConnectionCredentials = (bool)dataRow["InheritRDGatewayUseConnectionCredentials"];
            connectionInfo.Inheritance.RDGatewayUsername                 = (bool)dataRow["InheritRDGatewayUsername"];
            connectionInfo.Inheritance.RDGatewayPassword                 = (bool)dataRow["InheritRDGatewayPassword"];
            connectionInfo.Inheritance.RDGatewayDomain                   = (bool)dataRow["InheritRDGatewayDomain"];
        }
 public string Serialize(ConnectionInfo serializationTarget)
 {
     return(SerializeConnectionsData(serializationTarget));
 }
        public List <API.Common.Model.ChargePoint> Process(CoreReferenceData coreRefData)
        {
            List <ChargePoint> outputList = new List <ChargePoint>();

            var submissionStatus  = coreRefData.SubmissionStatusTypes.First(s => s.ID == 100);//imported and published
            var operationalStatus = coreRefData.StatusTypes.First(os => os.ID == 50);
            var unknownStatus     = coreRefData.StatusTypes.First(os => os.ID == 0);
            var usageTypePublic   = coreRefData.UsageTypes.First(u => u.ID == 1);
            var usageTypePrivate  = coreRefData.UsageTypes.First(u => u.ID == 2);
            var usageTypePrivateForStaffAndVisitors = coreRefData.UsageTypes.First(u => u.ID == 6); //staff and visitors
            var operatorUnknown = coreRefData.Operators.First(opUnknown => opUnknown.ID == 1);

            int itemCount = 0;

            string jsonString = "{ \"data\": " + InputData + "}";

            JObject o        = JObject.Parse(jsonString);
            var     dataList = o.Values()["list"].Values().ToArray();

            foreach (var item in dataList)
            {
                ChargePoint cp = new ChargePoint();
                cp.DataProvider = new DataProvider()
                {
                    ID = this.DataProviderID
                };                                                                 //AddEnergie
                cp.DataProvidersReference = item["StationID"].ToString();
                cp.DateLastStatusUpdate   = DateTime.UtcNow;

                cp.AddressInfo = new AddressInfo();

                cp.AddressInfo.Title           = item["ParkName"].ToString();
                cp.AddressInfo.AddressLine1    = item["Address"].ToString().Trim();
                cp.AddressInfo.Town            = item["City"].ToString().Trim();
                cp.AddressInfo.StateOrProvince = item["StateOrProvince"].ToString().Trim();
                cp.AddressInfo.Postcode        = item["PostalOrZipCode"].ToString().Trim();
                cp.AddressInfo.Latitude        = double.Parse(item["Latitude"].ToString());
                cp.AddressInfo.Longitude       = double.Parse(item["Longitude"].ToString());

                //default to canada
                //cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(c => c.ISOCode.ToLower() == "ca");
                //todo: detect country

                //set network operators
                if (this.SelectedNetworkType == NetworkType.ReseauVER)
                {
                    cp.OperatorInfo = new OperatorInfo {
                        ID = 89
                    };
                }

                if (this.SelectedNetworkType == NetworkType.LeCircuitElectrique)
                {
                    cp.OperatorInfo = new OperatorInfo {
                        ID = 90
                    };
                }

                bool isPublic = bool.Parse(item["IsPublic"].ToString());
                if (isPublic)
                {
                    cp.UsageType = usageTypePublic;
                }
                else
                {
                    cp.UsageType = usageTypePrivate;
                }

                cp.NumberOfPoints = int.Parse(item["NumPorts"].ToString());
                cp.StatusType     = operationalStatus;

                //populate connectioninfo from Ports
                foreach (var port in item["Ports"].ToArray())
                {
                    ConnectionInfo cinfo = new ConnectionInfo()
                    {
                    };
                    ConnectionType cType = new ConnectionType {
                        ID = 0
                    };

                    cinfo.Amps    = int.Parse(port["Current"].ToString());
                    cinfo.Voltage = int.Parse(port["Voltage"].ToString());
                    cinfo.PowerKW = double.Parse(port["KiloWatts"].ToString());
                    cinfo.Level   = new ChargerType()
                    {
                        ID = int.Parse(port["Level"].ToString())
                    };
                    //cinfo.Comments = (port["Make"]!=null?port["Make"].ToString()+" ":"") + (port["Model"]!=null?port["Model"].ToString():"");

                    if (port["ConnectorType"].ToString() == "J1772")
                    {
                        cType = coreRefData.ConnectionTypes.FirstOrDefault(c => c.ID == 1);
                    }
                    else if (port["ConnectorType"].ToString().ToUpper() == "CHADEMO")
                    {
                        cType = coreRefData.ConnectionTypes.FirstOrDefault(c => c.ID == 2);//CHADEMO
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Unmatched connector" + port["ConnectorType"].ToString());
                    }

                    cinfo.ConnectionType = cType;

                    if (cp.Connections == null)
                    {
                        cp.Connections = new List <ConnectionInfo>();
                        if (!IsConnectionInfoBlank(cinfo))
                        {
                            cp.Connections.Add(cinfo);
                        }
                    }
                }

                if (cp.DataQualityLevel == null)
                {
                    cp.DataQualityLevel = 4;
                }

                cp.SubmissionStatus = submissionStatus;

                outputList.Add(cp);
                itemCount++;
            }

            return(outputList);
        }
Пример #42
0
        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            // 初始化RenderControl控件
            IPropertySet ps = new PropertySet();

            ps.SetProperty("RenderSystem", gviRenderSystem.gviRenderOpenGL);
            this.axRenderControl1.Initialize(true, ps);
            this.axRenderControl1.Camera.FlyTime = 1;

            rootId = this.axRenderControl1.ObjectManager.GetProjectTree().RootID;

            // 设置天空盒

            if (System.IO.Directory.Exists(strMediaPath))
            {
                string  tmpSkyboxPath = strMediaPath + @"\skybox";
                ISkyBox skybox        = this.axRenderControl1.ObjectManager.GetSkyBox(0);
                skybox.SetImagePath(gviSkyboxImageIndex.gviSkyboxImageBack, tmpSkyboxPath + "\\1_BK.jpg");
                skybox.SetImagePath(gviSkyboxImageIndex.gviSkyboxImageBottom, tmpSkyboxPath + "\\1_DN.jpg");
                skybox.SetImagePath(gviSkyboxImageIndex.gviSkyboxImageFront, tmpSkyboxPath + "\\1_FR.jpg");
                skybox.SetImagePath(gviSkyboxImageIndex.gviSkyboxImageLeft, tmpSkyboxPath + "\\1_LF.jpg");
                skybox.SetImagePath(gviSkyboxImageIndex.gviSkyboxImageRight, tmpSkyboxPath + "\\1_RT.jpg");
                skybox.SetImagePath(gviSkyboxImageIndex.gviSkyboxImageTop, tmpSkyboxPath + "\\1_UP.jpg");
            }
            else
            {
                MessageBox.Show("请不要随意更改SDK目录名");
                return;
            }

            #region 加载FDB场景
            try
            {
                IConnectionInfo ci = new ConnectionInfo();
                ci.ConnectionType = gviConnectionType.gviConnectionFireBird2x;
                string tmpFDBPath = (strMediaPath + @"\SDKDEMO.FDB");
                ci.Database = tmpFDBPath;
                IDataSourceFactory dsFactory = new DataSourceFactory();
                IDataSource        ds        = dsFactory.OpenDataSource(ci);
                string[]           setnames  = (string[])ds.GetFeatureDatasetNames();
                if (setnames.Length == 0)
                {
                    return;
                }
                IFeatureDataSet dataset = ds.OpenFeatureDataset(setnames[0]);
                string[]        fcnames = (string[])dataset.GetNamesByType(gviDataSetType.gviDataSetFeatureClassTable);
                if (fcnames.Length == 0)
                {
                    return;
                }
                fcMap = new Hashtable(fcnames.Length);
                foreach (string name in fcnames)
                {
                    IFeatureClass fc = dataset.OpenFeatureClass(name);
                    // 找到空间列字段
                    List <string>        geoNames   = new List <string>();
                    IFieldInfoCollection fieldinfos = fc.GetFields();
                    for (int i = 0; i < fieldinfos.Count; i++)
                    {
                        IFieldInfo fieldinfo = fieldinfos.Get(i);
                        if (null == fieldinfo)
                        {
                            continue;
                        }
                        IGeometryDef geometryDef = fieldinfo.GeometryDef;
                        if (null == geometryDef)
                        {
                            continue;
                        }
                        geoNames.Add(fieldinfo.Name);
                    }
                    fcMap.Add(fc, geoNames);
                }
            }
            catch (COMException ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
                return;
            }

            // CreateFeautureLayer
            bool hasfly = false;
            foreach (IFeatureClass fc in fcMap.Keys)
            {
                List <string> geoNames = (List <string>)fcMap[fc];
                foreach (string geoName in geoNames)
                {
                    if (!geoName.Equals("Geometry"))
                    {
                        continue;
                    }

                    IFeatureLayer featureLayer = this.axRenderControl1.ObjectManager.CreateFeatureLayer(
                        fc, geoName, null, null, rootId);

                    if (!hasfly)
                    {
                        IFieldInfoCollection fieldinfos  = fc.GetFields();
                        IFieldInfo           fieldinfo   = fieldinfos.Get(fieldinfos.IndexOf(geoName));
                        IGeometryDef         geometryDef = fieldinfo.GeometryDef;
                        IEnvelope            env         = geometryDef.Envelope;
                        if (env == null || (env.MaxX == 0.0 && env.MaxY == 0.0 && env.MaxZ == 0.0 &&
                                            env.MinX == 0.0 && env.MinY == 0.0 && env.MinZ == 0.0))
                        {
                            continue;
                        }
                        IEulerAngle angle = new EulerAngle();
                        angle.Set(0, -20, 0);
                        this.axRenderControl1.Camera.LookAt(env.Center, 500, angle);
                    }
                    hasfly = true;
                }
            }
            #endregion 加载FDB场景

            {
                this.helpProvider1.SetShowHelp(this.axRenderControl1, true);
                this.helpProvider1.SetHelpString(this.axRenderControl1, "");
                this.helpProvider1.HelpNamespace = "SightlineAnalysis.html";
            }

            this.btnFlyToSourcePoint.Enabled = false;
            this.btnFlyToTargetPoint.Enabled = false;
        }
Пример #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Repository&lt;TId, T&gt;"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="helper">The helper.</param>
 public LogRepository(ConnectionInfo connectionInfo, IDatabase db)
     : base(connectionInfo, db)
 {
 }
Пример #44
0
 /// <summary>
 /// Initialize the rowmapper
 /// </summary>
 public override void Init(ConnectionInfo connectionInfo, IDatabase db)
 {
     base.Init(connectionInfo, db);
     this.RowMapper = new LogRowMapper();
 }
Пример #45
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo = null;
                switch (ParameterSetName)
                {
                case "NoKey":
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                            {
                                prompt.Response = _credential.GetNetworkCredential().Password;
                            }
                        }
                    };
                    break;

                case "Key":
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_keyfile, out provider);
                    var          localfullPath = pathinfo[0];
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               localfullPath,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                case "KeyString":
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keystring,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                default:
                    break;
                }

                //Ceate instance of SSH Client with connection info
                BaseClient client;
                if (Protocol == "SSH")
                {
                    client = new SshClient(connectInfo);
                }
                else
                {
                    client = new SftpClient(connectInfo);
                }


                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                        }

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            e.CanTrust = _sshHostKeys[computer1] == fingerPrint;
                            if (e.CanTrust && MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            else
                            {
                                if (!_acceptkey)
                                {
                                    var choices = new Collection <ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };
                                    e.CanTrust = 0 == Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                else // User specified he would accept the key so we can just add it to our list.
                                {
                                    e.CanTrust = true;
                                }
                                if (e.CanTrust)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                }
                            }
                        }
                    };
                }
                try
                {
                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Set Keepalive for connections
                    client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval);

                    // Connect to host using Connection info
                    client.Connect();

                    if (Protocol == "SSH")
                    {
                        WriteObject(SshModHelper.AddToSshSessionCollection(client as SshClient, SessionState), true);
                    }
                    else
                    {
                        WriteObject(SshModHelper.AddToSftpSessionCollection(client as SftpClient, SessionState), true);
                    }
                }
                catch (SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }

                // Renci.SshNet.Common.SshOperationTimeoutException when host is not alive or connection times out.
                // Renci.SshNet.Common.SshConnectionException when fingerprint mismatched
                // Renci.SshNet.Common.SshAuthenticationException Bad password
            }
        } // End process record
Пример #46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Repository&lt;TId, T&gt;"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="helper">The helper.</param>
 public LogRepository(ConnectionInfo connectionInfo) : base(connectionInfo)
 {
 }
Пример #47
0
 internal TcpQuery(ConnectionInfo conInfo)
     : base(conInfo, ProtocolType.Tcp)
 {
     _conInfo = conInfo;
 }
Пример #48
0
 private static void BuildConnectionInterfaceController(ConnectionInfo ConnectionInfo, ProtocolBase newProtocol, Control connectionContainer)
 {
     newProtocol.InterfaceControl = new InterfaceControl(connectionContainer, newProtocol, ConnectionInfo);
 }
Пример #49
0
        private void OnReceieve(SocketToken token, BufferSegment seg)
        {
            var connection = _connectionPool.Find(x => x.sToken.tokenId == token.tokenId);

            if (connection == null)
            {
                connection = new ConnectionInfo()
                {
                    sToken = token
                };

                _connectionPool.Add(connection);
            }

            if (connection.IsHandShaked == false)
            {
                var serverFrame = new WebsocketFrame();

                var access = serverFrame.GetHandshakePackage(seg);
                connection.IsHandShaked = access.IsHandShaked();

                if (connection.IsHandShaked == false)
                {
                    CloseAndRemove(connection);
                    return;
                }
                connection.ConnectedTime = DateTime.Now;

                var rsp = serverFrame.RspAcceptedFrame(access);

                this._token.SendAsync(token, rsp);

                connection.accessInfo = access;

                if (onAccept != null)
                {
                    onAccept(token);
                }
            }
            else
            {
                RefreshTimeout(token);

                WebsocketFrame packet = new WebsocketFrame();
                bool           isOk   = packet.DecodingFromBytes(seg, true);
                if (isOk == false)
                {
                    return;
                }

                if (packet.opCode == 0x01)//text
                {
                    if (onRecieveString != null)
                    {
                        onRecieveString(token, _encoding.GetString(seg.buffer,
                                                                   seg.offset, seg.count));
                    }

                    return;
                }
                else if (packet.opCode == 0x08)//close
                {
                    CloseAndRemove(connection);
                    return;
                }
                else if (packet.opCode == 0x09)//ping
                {
                    SendPong(token, seg);
                }
                else if (packet.opCode == 0x0A)//pong
                {
                    //  SendPing(session.sToken);
                }

                if (onReceieve != null && packet.payload.count > 0)
                {
                    onReceieve(token, packet.payload);
                }
            }
        }
Пример #50
0
 private bool Remove(ConnectionInfo info)
 {
     return(_connectionPool.Remove(info));
 }
Пример #51
0
 private static bool checkFileName(string remoteFileName, string remoteDirectory, ConnectionInfo connectionInfo)
 {
     using (SftpClient client = new SftpClient(connectionInfo))
     {
         client.Connect();
         if (client.IsConnected)
         {
             var files = client.ListDirectory(remoteDirectory);
             foreach (var file in files)
             {
                 if (file.Name.Contains(remoteFileName))
                 {
                     return(true);
                 }
             }
         }
         return(false);
     }
 }
        public static void RunExample()
        {
            NetworkComms.ConnectionEstablishTimeoutMS = 600000;

            IPAddress localIPAddress = IPAddress.Parse("::1");

            Console.WriteLine("Please select mode:");
            Console.WriteLine("1 - Server (Listens for connections)");
            Console.WriteLine("2 - Client (Creates connections to server)");

            //Read in user choice
            if (Console.ReadKey(true).Key == ConsoleKey.D1)
            {
                serverMode = true;
            }
            else
            {
                serverMode = false;
            }

            if (serverMode)
            {
                NetworkComms.PacketHandlerCallBackDelegate <byte[]> callback = (header, connection, data) =>
                {
                    if (data == null)
                    {
                        Console.WriteLine("Received null array from " + connection.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Received data (" + data + ") from " + connection.ToString());
                    }
                };

                //NetworkComms.AppendGlobalIncomingPacketHandler("Data", callback);

                NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
                RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, "somePassword!!");

                ConnectionListenerBase listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled);
                listener.AppendIncomingPacketHandler("Data", callback);

                Connection.StartListening(listener, new IPEndPoint(localIPAddress, 10000), true);

                Console.WriteLine("\nListening for UDP messages on:");
                foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.UDP))
                {
                    Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
                }

                Console.WriteLine("\nPress any key to quit.");
                ConsoleKeyInfo key = Console.ReadKey(true);
            }
            else
            {
                ConnectionInfo serverInfo = new ConnectionInfo(new IPEndPoint(localIPAddress, 10000));

                SendReceiveOptions customOptions = (SendReceiveOptions)NetworkComms.DefaultSendReceiveOptions.Clone();

                //customOptions.DataProcessors.Add(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>());
                //RijndaelPSKEncrypter.AddPasswordToOptions(customOptions.Options, "somePassword!!");

                customOptions.DataProcessors.Add(DPSManager.GetDataProcessor <SharpZipLibCompressor.SharpZipLibGzipCompressor>());

                //customOptions.DataProcessors.Add(DPSManager.GetDataProcessor<DataPadder>());
                //DataPadder.AddPaddingOptions(customOptions.Options, 10240, DataPadder.DataPaddingType.Random, false);

                //customOptions.UseNestedPacket = true;

                Connection conn = TCPConnection.GetConnection(serverInfo, customOptions);

                sendArray = null;
                conn.SendObject("Data", sendArray);

                Console.WriteLine("Sent data to server.");

                Console.WriteLine("\nClient complete. Press any key to quit.");
                Console.ReadKey(true);
            }
        }
Пример #53
0
 public PostDataAccess(ConnectionInfo connectionInfo)
     : this(connectionInfo, new DefaultMongoAbstractFactory(connectionInfo))
 {
 }
Пример #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StatusUpdateRepository"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="db">Database to use.</param>
 public StatusUpdateRepository(ConnectionInfo connectionInfo, IDatabase db)
     : base(connectionInfo, db)
 {
     this.RowMapper = new StatusUpdateRowMapper();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Repository&lt;TId, T&gt;"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="helper">The helper.</param>
 public CategoryRepository(ConnectionInfo connectionInfo, IDatabase db)
     : base(connectionInfo, db)
 {
 }
            public override void OnConnectionChanged(Connection connection, ConnectionInfo data)
            {
                Console.WriteLine($"[Socket{Socket}][connection:{connection}][data.Identity:{data.Identity}] [data.State:{data.State}]");

                base.OnConnectionChanged(connection, data);
            }
 /// <summary>
 /// Initializes a new instance of the <see cref="Repository&lt;TId, T&gt;"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="helper">The helper.</param>
 public CategoryRepository(ConnectionInfo connectionInfo) : base(connectionInfo)
 {
 }
 public override void OnConnecting(Connection connection, ConnectionInfo data)
 {
     Console.WriteLine($" - OnConnecting");
     base.OnConnecting(connection, data);
 }
        private void SetConnectionInfoParameter(ConnectionInfo connectionInfo, string key, string value)
        {
            switch (key.ToLower())
            {
            case "full address":
                var uri = new Uri("dummyscheme" + Uri.SchemeDelimiter + value);
                if (!string.IsNullOrEmpty(uri.Host))
                {
                    connectionInfo.Hostname = uri.Host;
                }
                if (uri.Port != -1)
                {
                    connectionInfo.Port = uri.Port;
                }
                break;

            case "server port":
                connectionInfo.Port = Convert.ToInt32(value);
                break;

            case "username":
                connectionInfo.Username = value;
                break;

            case "domain":
                connectionInfo.Domain = value;
                break;

            case "session bpp":
                switch (value)
                {
                case "8":
                    connectionInfo.Colors = ProtocolRDP.RDPColors.Colors256;
                    break;

                case "15":
                    connectionInfo.Colors = ProtocolRDP.RDPColors.Colors15Bit;
                    break;

                case "16":
                    connectionInfo.Colors = ProtocolRDP.RDPColors.Colors16Bit;
                    break;

                case "24":
                    connectionInfo.Colors = ProtocolRDP.RDPColors.Colors24Bit;
                    break;

                case "32":
                    connectionInfo.Colors = ProtocolRDP.RDPColors.Colors32Bit;
                    break;
                }
                break;

            case "bitmapcachepersistenable":
                connectionInfo.CacheBitmaps = value == "1";
                break;

            case "screen mode id":
                connectionInfo.Resolution = value == "2" ? ProtocolRDP.RDPResolutions.Fullscreen : ProtocolRDP.RDPResolutions.FitToWindow;
                break;

            case "connect to console":
                connectionInfo.UseConsoleSession = value == "1";
                break;

            case "disable wallpaper":
                connectionInfo.DisplayWallpaper = value == "1";
                break;

            case "disable themes":
                connectionInfo.DisplayThemes = value == "1";
                break;

            case "allow font smoothing":
                connectionInfo.EnableFontSmoothing = value == "1";
                break;

            case "allow desktop composition":
                connectionInfo.EnableDesktopComposition = value == "1";
                break;

            case "redirectsmartcards":
                connectionInfo.RedirectSmartCards = value == "1";
                break;

            case "redirectdrives":
                connectionInfo.RedirectDiskDrives = value == "1";
                break;

            case "redirectcomports":
                connectionInfo.RedirectPorts = value == "1";
                break;

            case "redirectprinters":
                connectionInfo.RedirectPrinters = value == "1";
                break;

            case "audiomode":
                switch (value)
                {
                case "0":
                    connectionInfo.RedirectSound = ProtocolRDP.RDPSounds.BringToThisComputer;
                    break;

                case "1":
                    connectionInfo.RedirectSound = ProtocolRDP.RDPSounds.LeaveAtRemoteComputer;
                    break;

                case "2":
                    connectionInfo.RedirectSound = ProtocolRDP.RDPSounds.DoNotPlay;
                    break;
                }
                break;
            }
        }
 static List <Coord> GetPath(ConnectionInfo connection)
 {
     return(connection.tileA.GetLineTo(connection.tileB));
 }