Example #1
0
        public Task Send(RpcRequest request)
        {
            ServerInfo server = _loadBalance.GetServer(request.AppName);

            IChannel channel = _connector.Connect(server.Host, server.Port);

            return(DoSend(channel, request));
        }
Example #2
0
        public static void Register(IConnector connector)
        {
            var result = connectors.Add(connector);

            if (result && ChannelInfo.IsConnecting)
            {
                connector.Connect(ChannelInfo.channel);
            }
        }
Example #3
0
 /// <summary>
 /// 连接到服务器
 /// </summary>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 public void Connect(string ip, int port)
 {
     if (connector == null)
     {
         Debug.LogError("Connector为空!!!");
         return;
     }
     connector.Connect(ip, port);
 }
Example #4
0
        public void Setup()
        {
            m_WebDavConnector = new WebDavConnectorImplementation(eEmailServerType.Exchange2007WebDAV);
            m_WebDavConnector.Init(m_Logger, m_sExchangeServerAddress, m_sFolder, m_sDomain, m_sUsername, m_bDebugAll);
            m_WebDavConnector.Connect(m_sPassword);

            m_EwsConnector = new EwsConnectorImplementation();
            m_EwsConnector.Init(m_Logger, m_sExchangeServerAddress, m_sFolder, m_sDomain, m_sUsername, m_bDebugAll);
            m_EwsConnector.Connect(m_sPassword);
        }
Example #5
0
        private void InitializeConnection(Client client)
        {
            var clientWrapper = CreateConnection(client);

            _registredConnections.Add(clientWrapper);
            if (client.Enabled)
            {
                Connector.Connect(client);
            }
        }
Example #6
0
        /// <summary>
        /// 创建连接
        /// </summary>
        /// <returns></returns>
        private T createConnection()
        {
            connCount++;
            var connection = connector.Connect(connectorConfig);

            lock (map.SyncRoot)
            {
                map[connection] = DateTime.Now;
            }
            return(connection);
        }
Example #7
0
        public int ConnectServer(IPAddress ipAddress, int nPort, out string strException)
        {
            strException = string.Empty;

            if (!_connector.Connect(ipAddress, nPort, out strException))
            {
                return(-1);
            }

            m_nType = 1;
            return(0);
        }
        public PartsService(IConnector plmConnector)
        {
            if (_plmConnector == null)
            {
                _plmConnector = plmConnector;
            }

            _plmConnector.Connect();

            var kamInnovatorItem = new KamInnovatorItem(_plmConnector.ServerConnection);

            _inn = kamInnovatorItem.Inn;
        }
        async void Connect()
        {
            try
            {
                await connector.Connect("127.0.0.1", port, 1000);

                Debug.LogFormat("连接成功");
            }
            catch (Exception e)
            {
                Debug.LogFormat("连接异常:{0}", e);
            }
        }
Example #10
0
        protected static void setup(TestContext context)
        {
            connector.Connect(ConnectorUnitTests.GetTestConnectionDictionary());

            if (connector.IsConnected == false)
            {
                throw new InvalidConnectionException("Unable to connect to Connector during ClassSetup");
            }

            var metadataProvider = connector.GetMetadataProvider();

            if (metadataProvider == null)
            {
                throw new InvalidConnectionException("Null MetadataProvider during ClassSetup");
            }
        }
        public static void Startup(TestContext context)
        {
            var connectionProperties = new Dictionary <string, string>();

            //setup the initial parameters for data connection
            connectionProperties.Add("Provider", "SQLNCLI10");
            connectionProperties.Add("Server", "localhost");
            connectionProperties.Add("Database", "ScribeSampleRSSource");
            connectionProperties.Add("UserName", "sa");
            //encrypt the connection password using the shared key
            string encryptedPassword = Encryptor.Encrypt_AesManaged("sa", CryptoKey);

            connectionProperties.Add("Password", encryptedPassword);
            //open a new connection to the datasource
            _rsTargetConnector.Connect(connectionProperties);
        }
        private void ConnectMenuItemClick(object sender, EventArgs e)
        {
            var menuItem   = (MenuItem)sender;
            var connection = GetConnection(menuItem);

            if (connection == null)
            {
                _notifyIcon.ShowBalloonTip(5000, Messages.ConnectionChecking, Messages.ConnectionNotFound, ToolTipIcon.Info);
                return;
            }

            var connectResult = _connector.Connect(connection);

            if (connectResult)
            {
                _notifyIcon.ShowBalloonTip(5000, Messages.Connection, string.Format(Messages.SuccesfulConnection, connection.Name), ToolTipIcon.Info);
            }
            else
            {
                _notifyIcon.ShowBalloonTip(5000, Messages.Connection, string.Format(Messages.NonSuccesfulConnection, connection.Name), ToolTipIcon.Error);
            }
        }
Example #13
0
        /// <inheritdoc/>
        public ConnectResult Connect(out IPEndPoint endpoint, out IListener listener)
        {
            var result = inner.Connect(out endpoint, out listener);

            if (result != ConnectResult.Accept)
            {
                return(result);
            }

            lock (syncRoot)
            {
                if (random.NextDouble() < configuration.Reject.Percentage)
                {
                    OnRejected();
                    return(ConnectResult.Reject);
                }

                listener = new ChaosListener(listener, configuration, random, this);
            }

            return(ConnectResult.Accept);
        }
Example #14
0
        public void AddConnection(EndPoint remoteAddress, bool keepAlive, bool stream)
        {
            IServiceHandler serviceHandler;

            if (keepAlive && !stream)
            {
                serviceHandler = new TcpVarData_SockServiceHandler(reactor, true, 5000);
            }
            else if (!keepAlive && !stream)
            {
                serviceHandler = new TcpVarData_SockServiceHandler(reactor, false, 0);
            }
            else
            {
                serviceHandler = new TcpEoLData_SockServiceHandler(reactor);
            }

            ISocket socket = SocketFactory.CreateNonBlockingTcpSocket();

            serviceHandler.Handle = socket;
            serviceHandler.ConnectionNotification += ConnectNotification;
            connector.Connect(serviceHandler, remoteAddress, Connection_Mode.ASYNC);
        }
Example #15
0
        private void SerialConnectButton_Click(object sender, RoutedEventArgs e)
        {
            object     device    = null;
            IConnector connector = Serialcon;

            if (!SerialPortCombo.Text.Trim().StartsWith("COM"))
            {
                Log.warn("没有可用串口!");
                return;
            }
            if (SerialConnectButton.Content.ToString() == "连接")
            {
                string        SerialComName = SerialPortCombo.Text.Trim();
                GetSerialInfo SerialInfo    = GetSerialInfo.Get(SerialComName);
                device = new SerialPort(SerialComName, 768000);
                SerialConnectButton.Content = "正在连接";
                Log.info("正在连接......");
                connector.Connect(device);
            }
            else
            {
                connector.Disconnect();
            }
        }
 public bool Connect(string telemetryServerConnectionString)
 {
     return(_connector.Connect(telemetryServerConnectionString));
 }
        private void DoConnectCmd()
        {
            if (_connector.ConnectionState == ConnectionStates.Connected)
            {
                _messageManager.ProceedAnswer("already connected.");
                return;
            }

            _connector.Connected += () =>
            {
                _messageManager.ProceedAnswer("connected (success), loading securities, pls wait...");
                _dataManager = new DataManager(_connector);
            };

            _connector?.Connect();

            Task.Run(() =>
            {
                try
                {
                    Thread.Sleep(5000); //dunno what to do

                    var tempSecurityMap      = new SynchronizedDictionary <string, Security>();
                    var cannotReadCounter    = 0;
                    var alreadyLoadedCounter = 0;

                    _connector.Securities.ForEach(s =>
                    {
                        if (s.ExpiryDate == null || s.Type != SecurityTypes.Future && s.Type != SecurityTypes.Option)
                        {
                            cannotReadCounter++;
                            return;
                        }

                        var key = _dataManager.GetSecurityStringRepresentation(s);

                        if (tempSecurityMap.ContainsKey(key))
                        {
                            alreadyLoadedCounter++;
                        }
                        else
                        {
                            tempSecurityMap.Add(key, s);
                        }
                    });

                    _dataManager.MappedSecurities = tempSecurityMap;

                    _messageManager.ProceedAnswer($"couldn't read instruments: {cannotReadCounter}", ConsoleColor.Red, false);
                    _messageManager.ProceedAnswer($"attempts to load more than twice: {alreadyLoadedCounter}", ConsoleColor.Red, false);

                    _dataManager.UnderlyingAsset = _dataManager.LookupThroughExistingSecurities(
                        ConfigManager.GetInstance().GetSettingValue(UserConfigs.Asset.ToString()));

                    _dataManager.RegisterMappedUndAssetsSecuruties();

                    _messageManager.ProceedAnswer($"{_dataManager.MappedSecurities.Count} securities loaded.");

                    _connector.NewMyTrade += mt =>
                    {
                        var secCode = mt.Trade.Security.Code;
                        var price   = mt.Trade.Price;
                        var size    = mt.Trade.Volume;
                        var side    = mt.Order.Direction;

                        if (!_userPositions.ContainsKey(secCode))
                        {
                            var userPosNew = new UserPosition(secCode);
                            _userPositions.Add(secCode, userPosNew);
                        }

                        _userPositions[secCode].AddNewDeal(side, price, size);

                        UserPosition.SaveToXml(_userPositions.Values.ToList());

                        _messageManager.ProceedAnswer(MessageManager.AlignString(new string[]
                        {
                            "NEW TRADE [",
                            $"side: {mt.Order.Direction}",
                            $"size: {mt.Trade.Volume}",
                            $"price: {mt.Trade.Price}",
                            $"sec: {mt.Trade.Security.Code}",
                            " ], deal saved"
                        }), ConsoleColor.Magenta);
                    };

                    _messageManager.ProceedAnswer("Print 'timer' to enable/disable auto-print-information about positions.", ConsoleColor.Yellow);
                    DoStatusCmd();
                }
                catch (Exception e1)
                {
                    _messageManager.ProceedAnswer($"unknown exception: {e1.Message}", ConsoleColor.Red);
                }
            });
        }
Example #18
0
 public async Task Start()
 {
     await _connector.Connect();
 }
Example #19
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            var isDde = IsDde.IsChecked == true;

            if (isDde && Path.Text.IsEmpty())
            {
                MessageBox.Show(this, LocalizedStrings.Str2969);
                return;
            }

            if (Connector != null && !(Connector is FakeConnector))
            {
                return;
            }

            PosChart.Positions.Clear();
            PosChart.AssetPosition = null;
            PosChart.Refresh(1, 1, default(DateTimeOffset), default(DateTimeOffset));

            // создаем подключение
            Connector = new QuikTrader(Path.Text)
            {
                IsDde = isDde
            };

            if (isDde)
            {
                // изменяем метаданные так, чтобы начали обрабатывать дополнительные колонки опционов
                var columns = ((QuikTrader)Connector).SecuritiesTable.Columns;
                columns.Add(DdeSecurityColumns.Strike);
                columns.Add(DdeSecurityColumns.ImpliedVolatility);
                columns.Add(DdeSecurityColumns.UnderlyingSecurity);
                columns.Add(DdeSecurityColumns.TheorPrice);
                columns.Add(DdeSecurityColumns.OptionType);
                columns.Add(DdeSecurityColumns.ExpiryDate);
            }

            //_trader = new PlazaTrader { IsCGate = true };
            //_trader.Tables.Add(_trader.TableRegistry.Volatility);

            Portfolio.Connector = Connector;

            PosChart.MarketDataProvider = Connector;
            PosChart.SecurityProvider   = Connector;

            // добавляем базовые активы в список
            Connector.NewSecurities += securities =>
                                       _assets.AddRange(securities.Where(s => s.Type == SecurityTypes.Future));

            Connector.SecuritiesChanged += securities =>
            {
                if ((PosChart.AssetPosition != null && securities.Contains(PosChart.AssetPosition.Security)) || PosChart.Positions.Cache.Select(p => p.Security).Intersect(securities).Any())
                {
                    _isDirty = true;
                }
            };

            // подписываемся на событие новых сделок чтобы обновить текущую цену фьючерса
            Connector.NewTrades += trades =>
            {
                var assetPos = PosChart.AssetPosition;
                if (assetPos != null && trades.Any(t => t.Security == assetPos.Security))
                {
                    _isDirty = true;
                }
            };

            Connector.NewPositions += positions => this.GuiAsync(() =>
            {
                var asset = SelectedAsset;

                if (asset == null)
                {
                    return;
                }

                var assetPos = positions.FirstOrDefault(p => p.Security == asset);
                var newPos   = positions.Where(p => p.Security.UnderlyingSecurityId == asset.Id).ToArray();

                if (assetPos == null && newPos.Length == 0)
                {
                    return;
                }

                if (assetPos != null)
                {
                    PosChart.AssetPosition = assetPos;
                }

                if (newPos.Length > 0)
                {
                    PosChart.Positions.AddRange(newPos);
                }

                RefreshChart();
            });

            Connector.PositionsChanged += positions => this.GuiAsync(() =>
            {
                if ((PosChart.AssetPosition != null && positions.Contains(PosChart.AssetPosition)) || positions.Intersect(PosChart.Positions.Cache).Any())
                {
                    RefreshChart();
                }
            });

            Connector.Connect();
        }
Example #20
0
        public void TestTransport(IAcceptor acc, IConnector conn, string address, string port)
        {
            acceptor = acc;
            connector = conn;

            acceptor.Start();
            acceptor.NewTransportAccepted += SetupServer;
            acceptorThread = new Thread(RunAcceptor);
            acceptorThread.Name = "Acceptor";
            acceptorThread.IsBackground = true;
            acceptorThread.Start();

            client = connector.Connect(address, port, new Dictionary<string, string>());
            Assert.IsNotNull(client);
            client.PacketReceived += ClientReceivedPacket;

            for (int i = 0; i < 10; i++)
            {
                sourceData[0] = (byte)i;
                Debug("client: sending packet#" + i + ": "
                    + ByteUtils.DumpBytes(sourceData, 0, sourceData.Length));
                client.SendPacket(new TransportPacket(sourceData));
                if (failure.Length != 0)
                {
                    Assert.Fail(failure);
                }
                Thread.Sleep(500);
                client.Update();
            }
            Assert.AreEqual(10, serverPacketCount);
            Assert.AreEqual(10, clientPacketCount);

            try
            {
                client.SendPacket(new TransportPacket(new byte[client.MaximumPacketSize * 2]));
                Assert.Fail("Transport allowed sending packets exceeding its capacity");
            }
            catch (ContractViolation) { /* expected */ }
        }
Example #21
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            if (_connector == null)
            {
                if (IsQuik.IsChecked == true)
                {
                    var isDde = IsDde.IsChecked == true;

                    if (isDde && Path.Text.IsEmpty())
                    {
                        MessageBox.Show(this, LocalizedStrings.Str2969);
                        return;
                    }

                    // создаем подключение
                    var trader = new QuikTrader(Path.Text)
                    {
                        IsDde = isDde
                    };

                    if (isDde)
                    {
                        // изменяем метаданные так, чтобы начали обрабатывать дополнительные колонки опционов
                        var columns = trader.SecuritiesTable.Columns;
                        columns.Add(DdeSecurityColumns.Strike);
                        columns.Add(DdeSecurityColumns.ImpliedVolatility);
                        columns.Add(DdeSecurityColumns.UnderlyingSecurity);
                        columns.Add(DdeSecurityColumns.TheorPrice);
                        columns.Add(DdeSecurityColumns.OptionType);
                        columns.Add(DdeSecurityColumns.ExpiryDate);
                    }

                    _connector = trader;
                }
                else
                {
                    var trader = new PlazaTrader
                    {
                        Address = Address.Text.To <EndPoint>(),
                        IsCGate = IsCGate.IsChecked == true
                    };

                    trader.Tables.Add(trader.TableRegistry.Volatility);

                    if (IsAutorization.IsChecked == true)
                    {
                        trader.Login    = Login.Text;
                        trader.Password = Password.Password;
                    }

                    _connector = trader;
                }

                Desk.MarketDataProvider = _connector;
                Desk.SecurityProvider   = _connector;
                Desk.CurrentTime        = null;

                // добавляем в выпадающий список только фьючерсы
                _connector.NewSecurities += securities =>
                                            this.GuiAsync(() =>
                {
                    _assets.AddRange(securities.Where(s => s.Type == SecurityTypes.Future));

                    if (SelectedAsset == null && _assets.Count > 0)
                    {
                        SelectedAsset = _assets.First();
                    }

                    if (SelectedAsset != null)
                    {
                        var newStrikes = securities
                                         .Where(s => s.Type == SecurityTypes.Option && s.UnderlyingSecurityId.CompareIgnoreCase(SelectedAsset.Id))
                                         .ToArray();

                        if (newStrikes.Length > 0)
                        {
                            _options.AddRange(newStrikes);
                            Desk.Options = _options;
                            Desk.RefreshOptions();
                        }
                    }
                });

                _connector.SecuritiesChanged += securities =>
                {
                    this.GuiAsync(() =>
                    {
                        if (SelectedAsset == null)
                        {
                            return;
                        }

                        var newStrikes = securities
                                         .Where(s => s.Type == SecurityTypes.Option && s.UnderlyingSecurityId.CompareIgnoreCase(SelectedAsset.Id))
                                         .Where(s => !_options.Contains(s))
                                         .ToArray();

                        if (newStrikes.Length > 0)
                        {
                            _options.AddRange(newStrikes);
                            Desk.Options = _options;
                            Desk.RefreshOptions();
                        }

                        if (Desk.Options.Intersect(securities).Any())
                        {
                            Desk.RefreshOptions();
                        }
                    });
                };

                // подписываемся на событие новых сделок чтобы обновить текущую цену фьючерса
                _connector.NewTrades += trades => this.GuiAsync(() =>
                {
                    var asset = SelectedAsset;
                    if (asset == null)
                    {
                        return;
                    }

                    if (asset.LastTrade != null)
                    {
                        LastPrice.Text = asset.LastTrade.Price.To <string>();
                    }
                });

                _connector.Connected += () =>
                {
                    var trader = _connector as QuikTrader;
                    if (trader != null && trader.IsDde)
                    {
                        var quikTrader = trader;
                        quikTrader.StartExport(new[] { quikTrader.SecuritiesTable, quikTrader.TradesTable });
                    }
                    else
                    {
                        _connector.StartExport();
                    }
                };
            }

            if (_connector.ConnectionState == ConnectionStates.Connected)
            {
                _connector.Disconnect();
            }
            else
            {
                _connector.Connect();
            }
        }
Example #22
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            if (Connector != null && !(Connector is FakeConnector))
            {
                return;
            }

            PosChart.Positions.Clear();
            PosChart.AssetPosition = null;
            PosChart.Refresh(1, 1, default(DateTimeOffset), default(DateTimeOffset));

            // create connection
            Connector = new QuikTrader();

            //_trader = new PlazaTrader { IsCGate = true };
            //_trader.Tables.Add(_trader.TableRegistry.Volatility);

            Portfolio.Portfolios = new PortfolioDataSource(Connector);

            PosChart.MarketDataProvider = Connector;
            PosChart.SecurityProvider   = Connector;

            // fill underlying asset's list
            Connector.NewSecurity += security =>
            {
                if (security.Type == SecurityTypes.Future)
                {
                    _assets.Add(security);
                }
            };

            Connector.SecurityChanged += security =>
            {
                if ((PosChart.AssetPosition != null && PosChart.AssetPosition.Security == security) || PosChart.Positions.Cache.Select(p => p.Security).Contains(security))
                {
                    _isDirty = true;
                }
            };

            // subscribing on tick prices and updating asset price
            Connector.NewTrade += trade =>
            {
                var assetPos = PosChart.AssetPosition;
                if (assetPos != null && trade.Security == assetPos.Security)
                {
                    _isDirty = true;
                }
            };

            Connector.NewPosition += position => this.GuiAsync(() =>
            {
                var asset = SelectedAsset;

                if (asset == null)
                {
                    return;
                }

                var assetPos = position.Security == asset;
                var newPos   = position.Security.UnderlyingSecurityId == asset.Id;

                if (!assetPos && !newPos)
                {
                    return;
                }

                if (assetPos)
                {
                    PosChart.AssetPosition = position;
                }

                if (newPos)
                {
                    PosChart.Positions.Add(position);
                }

                RefreshChart();
            });

            Connector.PositionChanged += position => this.GuiAsync(() =>
            {
                if ((PosChart.AssetPosition != null && PosChart.AssetPosition == position) || PosChart.Positions.Cache.Contains(position))
                {
                    RefreshChart();
                }
            });

            Connector.Connect();
        }
Example #23
0
		private void ConnectClick(object sender, RoutedEventArgs e)
		{
			var isDde = IsDde.IsChecked == true;

			if (isDde && Path.Text.IsEmpty())
			{
				MessageBox.Show(this, LocalizedStrings.Str2969);
				return;
			}

			if (Connector != null && !(Connector is FakeConnector))
				return;

			PosChart.Positions.Clear();
			PosChart.AssetPosition = null;
			PosChart.Refresh(1, 1, default(DateTimeOffset), default(DateTimeOffset));

			// создаем подключение
			Connector = new QuikTrader(Path.Text)
			{
				IsDde = isDde
			};

			if (isDde)
			{
				// изменяем метаданные так, чтобы начали обрабатывать дополнительные колонки опционов
				var columns = ((QuikTrader)Connector).SecuritiesTable.Columns;
				columns.Add(DdeSecurityColumns.Strike);
				columns.Add(DdeSecurityColumns.ImpliedVolatility);
				columns.Add(DdeSecurityColumns.UnderlyingSecurity);
				columns.Add(DdeSecurityColumns.TheorPrice);
				columns.Add(DdeSecurityColumns.OptionType);
				columns.Add(DdeSecurityColumns.ExpiryDate);
			}

			//_trader = new PlazaTrader { IsCGate = true };
			//_trader.Tables.Add(_trader.TableRegistry.Volatility);

			Portfolio.Connector = Connector;

			PosChart.MarketDataProvider = Connector;
			PosChart.SecurityProvider = Connector;

			// добавляем базовые активы в список
			Connector.NewSecurities += securities =>
				_assets.AddRange(securities.Where(s => s.Type == SecurityTypes.Future));

			Connector.SecuritiesChanged += securities =>
			{
				if ((PosChart.AssetPosition != null && securities.Contains(PosChart.AssetPosition.Security)) || PosChart.Positions.Cache.Select(p => p.Security).Intersect(securities).Any())
					_isDirty = true;
			};

			// подписываемся на событие новых сделок чтобы обновить текущую цену фьючерса
			Connector.NewTrades += trades =>
			{
				var assetPos = PosChart.AssetPosition;
				if (assetPos != null && trades.Any(t => t.Security == assetPos.Security))
					_isDirty = true;
			};

			Connector.NewPositions += positions => this.GuiAsync(() =>
			{
				var asset = SelectedAsset;

				if (asset == null)
					return;

				var assetPos = positions.FirstOrDefault(p => p.Security == asset);
				var newPos = positions.Where(p => p.Security.UnderlyingSecurityId == asset.Id).ToArray();

				if (assetPos == null && newPos.Length == 0)
					return;

				if (assetPos != null)
					PosChart.AssetPosition = assetPos;

				if (newPos.Length > 0)
					PosChart.Positions.AddRange(newPos);

				RefreshChart();
			});

			Connector.PositionsChanged += positions => this.GuiAsync(() =>
			{
				if ((PosChart.AssetPosition != null && positions.Contains(PosChart.AssetPosition)) || positions.Intersect(PosChart.Positions.Cache).Any())
					RefreshChart();
			});

			Connector.Connect();
		}
 public bool DownloadUpdates()
 {
     connector.Connect("updater");
     Debug.WriteLine("Downloading updates");
     return(true);
 }
Example #25
0
 public LoginWindow(IUpdater updater, IConnector connector)
 {
     InitializeComponent();
     connector.Connect("login");
     updater.DownloadUpdates();
 }
Example #26
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     //object o = Assembly.LoadFrom("C:\\Program Files\\NinjaTrader 7\\bin\\NinjaTrader.Hosted.dll").CreateInstance("NinjaTrader.Hosted.Loader");
     SetStatus("Connecting...", Color.LightSalmon);
     m_connector.Connect(txtHost.Text, (int)txtPort.Value);
 }
 public MainWindow(IConnector connector)
 {
     InitializeComponent();
     connector.Connect("client");
 }
Example #28
0
 /// <summary>
 /// Открыть соединение со slave-устройством.
 /// </summary>
 public void Connect() => _connector.Connect();
 public void Setup()
 {
     m_connector = new EwsConnectorImplementation();
     m_connector.Init(m_Logger, m_sExchangeServerAddress, m_sFolder, m_sDomain, m_sUsername, m_bDebugAll);
     m_connector.Connect(m_sPassword);
 }
Example #30
0
        public void SetUp()
        {
            acceptor = new UdpAcceptor(IPAddress.Any, 8765,
                new TransportFactory<UdpHandle>(BaseUdpTransport.SequencedProtocolDescriptor,
                    h => new UdpSequencedServerTestTransport(h),
                    t => t is UdpSequencedServerTestTransport));
            connector = new UdpConnector(
                new TransportFactory<UdpClient>(BaseUdpTransport.SequencedProtocolDescriptor,
                    h => new UdpSequencedClientTestTransport(h),
                    t => t is UdpSequencedClientTestTransport));

            acceptor.NewTransportAccepted += delegate(ITransport transport, IDictionary<string, string> capabilities)
            {
                serverTransport = (UdpSequencedServerTestTransport)transport;
            };
            acceptor.Start();
            Thread acceptorThread = new Thread(delegate()
            {
                for (int i = 0; serverTransport == null && i < 100; i++)
                {
                    try
                    {
                        acceptor.Update();
                        Thread.Sleep(50);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Acceptor Thread: " + e);
                    }
                }
            });
            acceptorThread.IsBackground = true;
            acceptorThread.Name = "Acceptor Thread";
            acceptorThread.Start();
            Thread.Sleep(50);

            clientTransport = (UdpSequencedClientTestTransport)connector.Connect("127.0.0.1", "8765", new Dictionary<string, string>());
            acceptorThread.Join();
            Assert.IsNotNull(clientTransport);
            Assert.IsNotNull(serverTransport);

            acceptor.Dispose();
            connector.Dispose();
        }
Example #31
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="connector">The connector being connected.</param>
 public virtual void Connect(IConnector connector)
 {
     decoratedConnector.Connect(connector);
 }
Example #32
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            if (Connector != null && !(Connector is FakeConnector))
            {
                return;
            }

            PosChart.Positions.Clear();
            PosChart.AssetPosition = null;
            PosChart.Refresh(1, 1, default(DateTimeOffset), default(DateTimeOffset));

            // create connection
            Connector = new QuikTrader();

            //_trader = new PlazaTrader { IsCGate = true };
            //_trader.Tables.Add(_trader.TableRegistry.Volatility);

            Portfolio.Portfolios = new PortfolioDataSource(Connector);

            PosChart.MarketDataProvider = Connector;
            PosChart.SecurityProvider   = Connector;

            // fill underlying asset's list
            Connector.NewSecurities += securities =>
                                       _assets.AddRange(securities.Where(s => s.Type == SecurityTypes.Future));

            Connector.SecuritiesChanged += securities =>
            {
                if ((PosChart.AssetPosition != null && securities.Contains(PosChart.AssetPosition.Security)) || PosChart.Positions.Cache.Select(p => p.Security).Intersect(securities).Any())
                {
                    _isDirty = true;
                }
            };

            // subscribing on tick prices and updating asset price
            Connector.NewTrades += trades =>
            {
                var assetPos = PosChart.AssetPosition;
                if (assetPos != null && trades.Any(t => t.Security == assetPos.Security))
                {
                    _isDirty = true;
                }
            };

            Connector.NewPositions += positions => this.GuiAsync(() =>
            {
                var asset = SelectedAsset;

                if (asset == null)
                {
                    return;
                }

                var assetPos = positions.FirstOrDefault(p => p.Security == asset);
                var newPos   = positions.Where(p => p.Security.UnderlyingSecurityId == asset.Id).ToArray();

                if (assetPos == null && newPos.Length == 0)
                {
                    return;
                }

                if (assetPos != null)
                {
                    PosChart.AssetPosition = assetPos;
                }

                if (newPos.Length > 0)
                {
                    PosChart.Positions.AddRange(newPos);
                }

                RefreshChart();
            });

            Connector.PositionsChanged += positions => this.GuiAsync(() =>
            {
                if ((PosChart.AssetPosition != null && positions.Contains(PosChart.AssetPosition)) || positions.Intersect(PosChart.Positions.Cache).Any())
                {
                    RefreshChart();
                }
            });

            Connector.Connect();
        }