/// <inheritdoc />
        public void Initialize()
        {
            _portConfig = ConfigManager.GetConfiguration <PortConfig>();

            _hostingContainer = new WindsorContainer();

            var hostBuilder = Host.CreateDefaultBuilder()
                              .UseWindsorContainerServiceProvider(_hostingContainer)
                              .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(options =>
                {
                    options.Listen(new IPAddress(0), _portConfig.HttpPort);
                }).ConfigureLogging(builder =>
                {
                    builder.ClearProviders();
                }).UseStartup(Startup);
            });

            _host = hostBuilder.Build();

            // Missing registrations
            _hostingContainer.Register(Component.For <EndpointCollector>());

            _host.Start();
        }
Example #2
0
        private void OnEdit()
        {
            if (dgConfig.SelectedRows == null || dgConfig.SelectedRows.Count <= 0)
            {
                MsgBox.Show(this.Text, "Vui lòng chọn 1 cấu hình kết nối để sửa.", IconType.Information);
                return;
            }

            DataGridViewRow row        = dgConfig.SelectedRows[0];
            string          id         = row.Cells[0].Value.ToString();
            PortConfig      portConfig = Global.PortConfigCollection.GetPortConfigById(id);

            if (portConfig == null)
            {
                return;
            }
            dlgAddPortConfig dlg = new dlgAddPortConfig(portConfig);

            if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                row.Cells[1].Value = dlg.PortConfig.TenMayXetNghiem;
                row.Cells[2].Value = dlg.PortConfig.LoaiMay.ToString();
                row.Cells[3].Value = dlg.PortConfig.PortName;
                Global.PortConfigCollection.Serialize(Global.PortConfigPath);
            }
        }
        /// <inheritdoc />
        public void Initialize()
        {
            LoggerManagement.ActivateLogging(this);

            _container  = new LocalContainer();
            _portConfig = ConfigManager.GetConfiguration <PortConfig>();

            _container.Register <IVersionService, VersionService>(nameof(VersionService), LifeCycle.Transient);
            _container.Register <EndpointCollector, EndpointCollector>();
            var collector = _container.Resolve <EndpointCollector>();

            _container.Extend <WcfFacility>();
            _container.Register <ITypedHostFactory, TypedHostFactory>();

            var factory = _container.Resolve <ITypedHostFactory>();

            var host       = new ConfiguredServiceHost(factory, Logger, collector, _portConfig);
            var hostConfig = new HostConfig
            {
                Endpoint        = "endpoints",
                MetadataEnabled = true
            };

            host.Setup(typeof(IVersionService), hostConfig);
            host.Start();
        }
Example #4
0
 /* ----------------------------------------------------------------- */
 ///
 /// Create
 ///
 /// <summary>
 /// Creates a new instance of the Port class from the specified
 /// configuration.
 /// </summary>
 ///
 /// <param name="src">Port configuration.</param>
 ///
 /// <returns>Port object.</returns>
 ///
 /* ----------------------------------------------------------------- */
 public static Port Create(this PortConfig src) =>
 new Port(src.Name, src.MonitorName)
 {
     FileName         = src.FileName,
     Arguments        = src.Arguments,
     WorkingDirectory = src.WorkingDirectory,
     WaitForExit      = src.WaitForExit
 };
Example #5
0
        private void init()
        {
            var config = XmlHelper.LoadFromXml(this.portFile, typeof(PortConfig)) as PortConfig;

            if (config != null)
            {
                this.portConfig = config;
            }

            this.portNames = SerialPort.GetPortNames().ToList();
            this.cbSerialPort.ItemsSource = this.portNames;
            if (this.portConfig != null)
            {
                this.cbSerialPort.SelectedItem = this.portConfig.serialName;
            }
            else
            {
                this.cbSerialPort.SelectedIndex = 0;
            }
            this.cbBitRate.ItemsSource = bitRateList;
            if (this.portConfig != null)
            {
                this.cbBitRate.SelectedItem = this.portConfig.baudRate;
            }
            else
            {
                this.cbBitRate.SelectedIndex = 5;//默认9600
            }
            this.cbDataBit.ItemsSource = dataBitList;
            if (this.portConfig != null)
            {
                this.cbDataBit.SelectedItem = this.portConfig.dataBit;
            }
            else
            {
                this.cbDataBit.SelectedIndex = 3;//默认8
            }
            this.cbStopBit.ItemsSource = stopBitList;
            if (this.portConfig != null)
            {
                this.cbStopBit.SelectedItem = this.portConfig.stopBit;
            }
            else
            {
                this.cbStopBit.SelectedIndex = 0;//默认1
            }
            this.cbParity.ItemsSource = parityList;
            if (this.portConfig != null)
            {
                this.cbParity.SelectedItem = this.portConfig.parityBit;
            }
            else
            {
                this.cbParity.SelectedIndex = 1;//默认奇校验
            }

            this.lbLog.ItemsSource = LogHelper.LogList;
        }
        /// <summary>
        /// 网站启动事件
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            PortConfig.ReloadPortConfig();
            Application.Add(nameof(Log), Log.CreateAppLog());
        }
Example #7
0
        public TcpServerPort(PortConfig portConfig, IPPortEndpointConfig serverPortEndpointConfig)
            : base(portConfig, new IPPortEndpointConfig("", new IPEndPoint(IPAddress.None, 0)), "TcpServerPort")
        {
            serverEPConfig = serverPortEndpointConfig;

            PortBehavior = new PortBehaviorStorage()
            {
                DataDeliveryBehavior = DataDeliveryBehavior.ByteStream, IsNetworkPort = true, IsServerPort = true
            };
        }
        public ConfiguredServiceHost(ITypedHostFactory factory, IModuleLogger parentLogger, EndpointCollector endpointCollector, PortConfig portConfig)
        {
            _factory    = factory;
            _collector  = endpointCollector;
            _portConfig = portConfig;

            if (parentLogger != null)
            {
                _logger = parentLogger.GetChild("WcfHosting", GetType());
            }
        }
Example #9
0
 public dlgAddPortConfig(PortConfig portConfig)
 {
     InitializeComponent();
     _isNew      = false;
     _portConfig = portConfig;
     InitData();
     this.Text = "Sua cau hinh ket noi";
     txtTenMayXetNghiem.Text  = _portConfig.TenMayXetNghiem;
     cboLoaiMay.SelectedIndex = (int)_portConfig.LoaiMay;
     cboCOM.Text = portConfig.PortName;
 }
Example #10
0
        private void SetData()
        {
            if (_isNew)
            {
                _portConfig    = new PortConfig();
                _portConfig.Id = Guid.NewGuid().ToString();
            }

            _portConfig.TenMayXetNghiem = txtTenMayXetNghiem.Text;
            _portConfig.LoaiMay         = (LoaiMayXN)cboLoaiMay.SelectedIndex;
            _portConfig.PortName        = cboCOM.Text;
        }
Example #11
0
        public void Properties()
        {
            var src = new PortConfig();

            Assert.That(src.Name, Is.Empty);
            Assert.That(src.MonitorName, Is.Empty);
            Assert.That(src.Proxy, Is.Empty);
            Assert.That(src.Application, Is.Empty);
            Assert.That(src.Arguments, Is.Empty);
            Assert.That(src.Temp, Is.Empty);
            Assert.That(src.WaitForExit, Is.False);
            Assert.That(src.RunAsUser, Is.True);
        }
Example #12
0
        public TcpClientPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig, string className)
            : base(portConfig, className)
        {
            targetEPConfig = ipPortEndpointConfig;

            PortBehavior = new PortBehaviorStorage()
            {
                DataDeliveryBehavior = DataDeliveryBehavior.ByteStream, IsNetworkPort = true, IsClientPort = true
            };

            PrivateBaseState = new BaseState(false, true);
            PublishBaseState("object constructed");
        }
Example #13
0
            public SerialEchoTracker(string portPartID, string portTargetSpec, double[] binBoundariesArray, SerialEchoPerformancePartConfig config, INotifyable notifyOnDone, Logging.IBasicLogger logger)
            {
                PortTargetSpec = portTargetSpec;
                Config         = config;
                NotifyOnDone   = notifyOnDone;
                Logger         = logger;

                h = new Histogram(binBoundariesArray);

                timeoutCountGPI = new MDRF.Writer.GroupPointInfo()
                {
                    Name = "timeoutCount", ValueCST = ContainerStorageType.UInt64, VC = new ValueContainer(0L)
                };
                failureCountGPI = new MDRF.Writer.GroupPointInfo()
                {
                    Name = "failureCount", ValueCST = ContainerStorageType.UInt64, VC = new ValueContainer(0L)
                };

                hGrp = new MDRFHistogramGroupSource("{0}".CheckedFormat(portPartID),
                                                    h,
                                                    (ulong)config.AggregateGroupsFileIndexUserRowFlagBits,
                                                    extraClientNVS: new NamedValueSet()
                {
                    { "SerialEcho" }, { "PortTargetSpec", PortTargetSpec }
                },
                                                    extraGPISet: new[] { timeoutCountGPI, failureCountGPI });

                try
                {
                    portConfig = new PortConfig(portPartID, portTargetSpec)
                    {
                        TxLineTerm          = LineTerm.None,
                        RxLineTerm          = LineTerm.CR,
                        ConnectTimeout      = (2.0).FromSeconds(),
                        WriteTimeout        = (1.0).FromSeconds(),
                        ReadTimeout         = (1.0).FromSeconds(),
                        IdleTime            = (1.0).FromSeconds(),
                        EnableAutoReconnect = true,
                    };

                    port = MosaicLib.SerialIO.Factory.CreatePort(portConfig);

                    portGetNextPacketAction = port.CreateGetNextPacketAction();
                    portFlushAction         = port.CreateFlushAction();
                    portWriteAction         = port.CreateWriteAction(portWriteActionParam = new WriteActionParam());
                }
                catch (System.Exception ex)
                {
                    Logger.Error.Emit("Port setup for '{0}' failed: {1}", portTargetSpec, ex.ToString(ExceptionFormat.TypeAndMessage));
                }
            }
Example #14
0
        public ComPort(PortConfig portConfig, ComPortConfig comPortConfig)
            : base(portConfig, "ComPort")
        {
            this.comPortConfig = comPortConfig;
            PortBehavior       = new PortBehaviorStorage()
            {
                DataDeliveryBehavior = DataDeliveryBehavior.ByteStream, IsClientPort = true
            };

            PrivateBaseState = new BaseState(false, true);
            PublishBaseState("object constructed");

            CreatePort();
        }
Example #15
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (this.cbSerialPort.SelectedItem == null)
            {
                LogHelper.WriteLog(LogType.ERROR, "没有选择串口!");
                return;
            }
            this.portConfig            = new PortConfig();
            this.portConfig.serialName = this.cbSerialPort.SelectedItem.ToString();
            this.portConfig.baudRate   = this.cbBitRate.SelectedItem.ToString();
            this.portConfig.dataBit    = this.cbDataBit.SelectedItem.ToString();
            this.portConfig.stopBit    = this.cbStopBit.SelectedItem.ToString();
            this.portConfig.parityBit  = this.cbParity.SelectedItem.ToString();

            XmlHelper.SaveToXml(this.portFile, this.portConfig);
        }
        /// <inheritdoc />
        public void Initialize()
        {
            LoggerManagement.ActivateLogging(this);

            _container = new LocalContainer();
            var factoryConfig = ConfigManager.GetConfiguration <HostFactoryConfig>();

            _portConfig = ConfigManager.GetConfiguration <PortConfig>();

            // In minimal core setups with no WCF service this can be disabled
            if (factoryConfig.VersionServiceDisabled)
            {
                return;
            }

            var hostConfig = new HostConfig
            {
                BindingType     = ServiceBindingType.BasicHttp,
                Endpoint        = "ServiceVersions",
                MetadataEnabled = true
            };

            _container.Register <IVersionService, VersionService>(nameof(VersionService), LifeCycle.Transient);
            _container.Register <IEndpointCollector, EndpointCollector>();
            var collector = _container.Resolve <IEndpointCollector>();

            _container.Extend <WcfFacility>();
            _container.Register <ITypedHostFactory, TypedHostFactory>();

            var factory = _container.Resolve <ITypedHostFactory>();
            var host    = new ConfiguredServiceHost(factory, Logger, collector, _portConfig);

            host.Setup <IVersionService>(hostConfig);
            host.Start();

            hostConfig = new HostConfig
            {
                Endpoint        = "ServiceVersionsWeb",
                MetadataEnabled = true
            };

            host = new ConfiguredServiceHost(factory, Logger, collector, _portConfig);
            host.Setup <IVersionService>(hostConfig);
            host.Start();
        }
Example #17
0
        private void init()
        {
            var list = XmlHelper.LoadFromXml(this.dataFile, typeof(ObservableCollection <Battery>)) as ObservableCollection <Battery>;

            if (list != null)
            {
                this.batteryList = list;
            }

            var config = XmlHelper.LoadFromXml(this.portFile, typeof(PortConfig)) as PortConfig;

            if (config != null)
            {
                this.portConfig = config;
            }

            chart1.Series.Clear();
            var ds = new Visifire.Charts.DataSeries();

            ds.RenderAs     = Visifire.Charts.RenderAs.Column;
            ds.LabelEnabled = true;
            ds.DataPoints.Add(new Visifire.Charts.DataPoint()
            {
                AxisXLabel = "未启动任务", YValue = this.batteryList.Where(i => i.isEnabled == "否").Count()
            });
            ds.DataPoints.Add(new Visifire.Charts.DataPoint()
            {
                AxisXLabel = "已启动任务", YValue = this.batteryList.Where(i => i.isEnabled == "是").Count()
            });
            chart1.Series.Add(ds);

            tbTotal.Text    = this.batteryList.Count.ToString();
            tbDisabled.Text = this.batteryList.Where(i => i.isEnabled == "否").Count().ToString();
            tbEnabled.Text  = this.batteryList.Where(i => i.isEnabled == "是").Count().ToString();
            // 串口配置
            if (this.portConfig != null)
            {
                tbPort.Text    = this.portConfig.serialName;
                tbBitRate.Text = this.portConfig.baudRate;
                tbDataBit.Text = this.portConfig.dataBit;
                tbStopBit.Text = this.portConfig.stopBit;
                tbParity.Text  = this.portConfig.parityBit;
            }
        }
Example #18
0
        private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPort port       = (SerialPort)sender;
                PortConfig portConfig = Global.PortConfigCollection.GetPortConfigByPortName(port.PortName);
                if (portConfig == null)
                {
                    return;
                }

                LoadConfig();

                string data = port.ReadExisting();

                if (portConfig.LoaiMay == LoaiMayXN.Hitachi917)
                {
                    List <TestResult_Hitachi917> testResults = ParseTestResult_Hitachi917(data, port.PortName);
                    Result result = XetNghiem_Hitachi917Bus.InsertKQXN(testResults);
                    if (!result.IsOK)
                    {
                        Utility.WriteToTraceLog(result.GetErrorAsString("XetNghiem_Hitachi917Bus.InsertKQXN"));
                    }
                }
                else if (portConfig.LoaiMay == LoaiMayXN.CellDyn3200)
                {
                    List <TestResult_CellDyn3200> testResults = ParseTestResult_CellDyn3200(data, port.PortName);
                    Result result = XetNghiem_CellDyn3200Bus.InsertKQXN(testResults);
                    if (!result.IsOK)
                    {
                        Utility.WriteToTraceLog(result.GetErrorAsString("XetNghiem_CellDyn3200Bus.InsertKQXN"));
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.WriteToTraceLog(string.Format("Serial Port: {0}", ex.Message));
            }
        }
Example #19
0
        public TaskRT(List <Battery> batteryList, PortConfig portConfig)
        {
            this.batteryList = batteryList.Where(i => i.isEnabled == "是").OrderBy(i => i.uid).ToList();
            this.portConfig  = portConfig;

            // 数据表结构
            dataTable = CSVFileHelper.OpenCSV(dataFile);
            if (dataTable == null)
            {
                dataTable = new DataTable();
                DataColumn dc = new DataColumn("采集时间");
                dataTable.Columns.Add(dc);

                int len = this.batteryList.Count * 24;
                for (var i = 0; i < len; i++)
                {
                    DataColumn col = new DataColumn("单体电压" + (i + 1));
                    dataTable.Columns.Add(col);
                }
                CSVFileHelper.SaveCSV(dataTable, dataFile);
            }
        }
Example #20
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, EventArgs e)
        {
            PortConfig port = new PortConfig();

            port.Name     = this.Name_ed.Text;
            port.PortName = (PortIndex)Enum.Parse(typeof(PortIndex), this.PortName.SelectedItem.ToString());
            port.BaudRate = int.Parse(this.BaudRate.Text);
            port.DataBits = (int)this.DataBits.SelectedItem;
            port.Parity   = (Parity)Enum.Parse(typeof(Parity), this.Parity.SelectedItem.ToString());
            port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), this.StopBits.SelectedItem.ToString());

            var result = Data.SQLiteProvider.SavePortInfo(port);

            if (result == string.Empty)
            {
                //ok
                this.Close();
            }
            else
            {
                MessageBox.Show(result);
            }
        }
Example #21
0
 /// <summary>
 /// 根据id获取串口信息
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public static PortConfig GetPortItemsByID(long id)
 {
     try
     {
         PortConfig result     = new PortConfig();
         var        sqlite     = Helper.SQLiteDBHelper.sqliteHelper;
         var        queryTable = sqlite.Select($"select * from PortConfig where id == {id}");
         var        query      = Helper.DataSetToEntityHelper.DataTableToEntityList <PortConfig>(queryTable, 0);
         if (query.Count == 1)
         {
             return(query.First());
         }
         else
         {
             throw new Exception("查询数据出现错误,不是唯一值");
         }
     }
     catch (Exception ex)
     {
         Helper.NLogHelper.log.Error(ex.Message);
     }
     return(null);
 }
Example #22
0
        public Task(List <Battery> batteryList, PortConfig portConfig)
        {
            this.batteryList = batteryList;
            this.portConfig  = portConfig;

            // 数据表结构
            dataTable = CSVFileHelper.OpenCSV(dataFile);
            if (dataTable == null)
            {
                dataTable = new DataTable();
                DataColumn dc = new DataColumn("采集时间");
                dataTable.Columns.Add(dc);
                DataColumn dc2 = new DataColumn("地址");
                dataTable.Columns.Add(dc2);

                for (var i = 0; i < 24; i++)
                {
                    DataColumn col = new DataColumn("单体电压" + (i + 1));
                    dataTable.Columns.Add(col);
                }
                CSVFileHelper.SaveCSV(dataTable, dataFile);
            }
        }
Example #23
0
        /// <summary>
        /// 保存串口信息.
        /// 返回的string为string.Empty则为成功,否则为错误内容。
        /// </summary>
        /// <param name="portInfo">串口信息</param>
        /// <param name="isEdit">是否为修改。默认false新增,true修改</param>
        /// <returns>返回的string为string.Empty则为成功,否则为错误内容。</returns>
        public static string SavePortInfo(PortConfig portInfo, bool isEdit = false)
        {
            string result = string.Empty;
            var    sqlite = Helper.SQLiteDBHelper.sqliteHelper;

            sqlite.BeginTransaction();
            try
            {
                int affectRow;

                if (isEdit)
                {
                    affectRow = sqlite.Update("PortConfig", Helper.EntityToDictionary.ToMap(portInfo), "id", portInfo.Id);
                }
                else
                {
                    affectRow = sqlite.Insert("PortConfig", Helper.EntityToDictionary.ToMap(portInfo, "id"));
                }

                if (affectRow == 1)
                {
                    result = string.Empty;
                }
                else
                {
                    throw new Exception("受影响的行数有误!执行回滚操作。");
                }
                sqlite.Commit();
            }
            catch (Exception ex)
            {
                sqlite.Rollback();
                result = ex.Message;
                Helper.NLogHelper.log.Error(ex.Message);
            }
            return(result);
        }
Example #24
0
 /// <summary>
 /// Standard constructor.  Accepts PortConfig and IPPortEndpointConfig (parsed from PortConfig.SpecStr).
 /// </summary>
 public UdpClientPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig)
     : base(portConfig, ipPortEndpointConfig, "UdpClientPort")
 {
 }
Example #25
0
        public TcpServerPort(PortConfig portConfig, IPPortEndpointConfig serverPortEndpointConfig)
            : base(portConfig, new IPPortEndpointConfig("", new IPEndPoint(IPAddress.None, 0)), "TcpServerPort")
        {
            serverEPConfig = serverPortEndpointConfig;

            PortBehavior = new PortBehaviorStorage() { DataDeliveryBehavior = DataDeliveryBehavior.ByteStream, IsNetworkPort = true, IsServerPort = true };
        }
Example #26
0
 public static IPort CreateTcpServerPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig)
 {
     return new TcpServerPort(portConfig, ipPortEndpointConfig);
 }
Example #27
0
        public TcpClientPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig, string className)
            : base(portConfig, className)
        {
            targetEPConfig = ipPortEndpointConfig;

            PortBehavior = new PortBehaviorStorage() { DataDeliveryBehavior = DataDeliveryBehavior.ByteStream, IsNetworkPort = true, IsClientPort = true };

            PrivateBaseState = new BaseState(false, true);
            PublishBaseState("object constructed");
        }
Example #28
0
 public TcpClientPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig)
     : this(portConfig, ipPortEndpointConfig, "TcpClientPort")
 {
 }
Example #29
0
 public static IPort CreateTcpServerPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig)
 {
     return(new TcpServerPort(portConfig, ipPortEndpointConfig));
 }
Example #30
0
 /// <summary>
 /// static factory method used to create a UdpClientPort from the given portConfig and ipPortEndpointConfig
 /// </summary>
 public static IPort CreateUdpClientPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig)
 {
     return new UdpClientPort(portConfig, ipPortEndpointConfig);
 }
Example #31
0
 public void StorePortConfig(PortIdentifier port, PortConfig config) => _collector.StorePortConfig(port, config);
Example #32
0
 /// <summary>Creates a Com type IPort implementation from the given portConfig and comPortConfig</summary>
 /// <param name="portConfig">Provides all configuration details for the port to be created.</param>
 /// <param name="comPortConfig">Provides the ComPort specific configuration information.  Typically derived by parsing the portConfig.SpecStr.</param>
 /// <returns>the created Com type IPort object.</returns>
 public static IPort CreateComPort(PortConfig portConfig, ComPortConfig comPortConfig)
 {
     return new ComPort(portConfig, comPortConfig);
 }
Example #33
0
        public ComPort(PortConfig portConfig, ComPortConfig comPortConfig)
            : base(portConfig, "ComPort")
        {
            this.comPortConfig = comPortConfig;
            PortBehavior = new PortBehaviorStorage() { DataDeliveryBehavior = DataDeliveryBehavior.ByteStream, IsClientPort = true };

            PrivateBaseState = new BaseState(false, true);
            PublishBaseState("object constructed");

            CreatePort();
        }
Example #34
0
 public void StorePortConfig(PortIdentifier port, PortConfig config) => _portConfigCache[port] = config;
Example #35
0
 public TcpClientPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig) : this(portConfig, ipPortEndpointConfig, "TcpClientPort")
 {
 }
Example #36
0
 /// <summary>
 /// Standard constructor.  Accepts PortConfig and IPPortEndpointConfig (parsed from PortConfig.SpecStr).
 /// </summary>
 public UdpClientPort(PortConfig portConfig, IPPortEndpointConfig ipPortEndpointConfig)
     : base(portConfig, ipPortEndpointConfig, "UdpClientPort")
 {
 }
        public void TestProcessMockSessionStartExisting()
        {
            var session = new PortSession(new PortConfig {
                AutoStart = false
            });

            // Try no variable.
            var startResult = session.Start();

            Assert.AreEqual(false, startResult.Success);

            // Try junk variable.
            Environment.SetEnvironmentVariable(Util.X3270Port, "junk");
            startResult = session.Start();
            Assert.AreEqual(false, startResult.Success);

            // Set up an explicit config to shorten the retry delay.
            var config = new PortConfig
            {
                ConnectRetryMsec = 10,
                AutoStart        = false
            };

            // Try an unused port.
            // We guarantee an unused port by binding a socket to port 0 (letting the
            // system pick one) and then *not* listening on it.
            using (var noListenSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                noListenSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
                Environment.SetEnvironmentVariable(Util.X3270Port, ((IPEndPoint)noListenSocket.LocalEndPoint).Port.ToString());
                session     = new PortSession(config);
                startResult = session.Start();
                Assert.AreEqual(false, startResult.Success);
            }

            // Try again, without the connect retry override.
            // This is frustratingly slow, but needed to exercise the default timeout of 3x1000ms.
            config.ConnectRetryMsec = null;
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            startResult = session.Start();
            Assert.AreEqual(false, startResult.Success);
            stopwatch.Stop();
            Assert.IsTrue(stopwatch.ElapsedMilliseconds >= 3000);

            // Verify that we can't set a ConnectRetryMsec < 0.
            Assert.Throws <ArgumentOutOfRangeException>(() => { var config2 = new PortConfig {
                                                                    ConnectRetryMsec = -3
                                                                }; });

            // Create a mock server thread by hand, so we can connect to it manually.
            using (var listener = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                listener.Listen(1);
                var mockServer = new Server();
                var server     = Task.Run(() => mockServer.Ws3270(listener));

                // Now connect to it, which should be successful.
                // We also put the port in the config, to exercise that path.
                config.Port = ((IPEndPoint)listener.LocalEndPoint).Port;
                startResult = session.Start();
                Assert.AreEqual(true, startResult.Success);

                // All done, close the client side and wait for the mock server to complete.
                session.Close();
                server.Wait();
            }
        }
Example #38
0
 /// <summary>Creates a Com type IPort implementation from the given portConfig and comPortConfig</summary>
 /// <param name="portConfig">Provides all configuration details for the port to be created.</param>
 /// <param name="comPortConfig">Provides the ComPort specific configuration information.  Typically derived by parsing the portConfig.SpecStr.</param>
 /// <returns>the created Com type IPort object.</returns>
 public static IPort CreateComPort(PortConfig portConfig, ComPortConfig comPortConfig)
 {
     return(new ComPort(portConfig, comPortConfig));
 }