示例#1
0
        public WindowsServiceClient(string connectionString)
        {
            // Initialize status cache members.
            string statusBufferSize;

            if (connectionString.ParseKeyValuePairs().TryGetValue("statusBufferSize", out statusBufferSize))
                m_statusBufferSize = int.Parse(statusBufferSize);
            else
                m_statusBufferSize = 8192;

            m_cachedStatus = string.Empty;

            // Initialize remoting client socket.
            m_remotingClient = new TcpClient();
            m_remotingClient.ConnectionString = connectionString;
            m_remotingClient.SharedSecret = "openPDC";
            m_remotingClient.Handshake = true;
            m_remotingClient.PayloadAware = true;
            m_remotingClient.MaxConnectionAttempts = -1;

            // Initialize windows service client.
            m_clientHelper = new ClientHelper();
            m_clientHelper.RemotingClient = m_remotingClient;
            m_clientHelper.ReceivedServiceUpdate += ClientHelper_ReceivedServiceUpdate;
        }
示例#2
0
        /// <summary>
        /// Creates an instance of <see cref="WindowsServiceClient"/>.
        /// </summary>
        /// <param name="connectionString">Connection information such as server ip address and port where windows service is running.</param>
        public WindowsServiceClient(string connectionString)
        {
            // Initialize status cache members.
            Dictionary<string, string> settings = connectionString.ParseKeyValuePairs();
            string setting;

            if (settings.TryGetValue("statusBufferSize", out setting) && !string.IsNullOrWhiteSpace(setting))
                m_statusBufferSize = int.Parse(setting);
            else
                m_statusBufferSize = 8192;

            m_cachedStatus = string.Empty;

            // Initialize remoting client socket.
            m_remotingClient = new TcpClient();
            m_remotingClient.ConnectionString = connectionString;

            // See if user wants to connect to remote service using integrated security
            if (settings.TryGetValue("integratedSecurity", out setting) && !string.IsNullOrWhiteSpace(setting))
                m_remotingClient.IntegratedSecurity = setting.ParseBoolean();

            m_remotingClient.PayloadAware = true;
            m_remotingClient.MaxConnectionAttempts = -1;

            // Initialize windows service client.
            m_clientHelper = new ClientHelper();
            m_clientHelper.RemotingClient = m_remotingClient;
            m_clientHelper.ReceivedServiceUpdate += ClientHelper_ReceivedServiceUpdate;
        }
示例#3
0
文件: ClientBase.cs 项目: avs009/gsf
        /// <summary>
        /// Create a communications client
        /// </summary>
        /// <remarks>
        /// Note that typical connection string should be prefixed with a "protocol=tcp", "protocol=udp", "protocol=serial" or "protocol=file"
        /// </remarks>
        /// <returns>A communications client.</returns>
        /// <param name="connectionString">Connection string for the client.</param>
        public static IClient Create(string connectionString)
        {
            Dictionary<string, string> connectionData = connectionString.ParseKeyValuePairs();
            IClient client = null;
            string protocol;

            if (connectionData.TryGetValue("protocol", out protocol))
            {
                connectionData.Remove("protocol");
                StringBuilder settings = new StringBuilder();

                foreach (string key in connectionData.Keys)
                {
                    settings.Append(key);
                    settings.Append("=");
                    settings.Append(connectionData[key]);
                    settings.Append(";");
                }

                switch (protocol.ToLower())
                {
                    case "tcp":
                        client = new TcpClient(settings.ToString());
                        break;
                    case "udp":
                        client = new UdpClient(settings.ToString());
                        break;
                    case "file":
                        client = new FileClient(settings.ToString());
                        break;
                    case "serial":
                        client = new SerialClient(settings.ToString());
                        break;
                    default:
                        throw new ArgumentException(protocol + " is not a valid transport protocol.");
                }
            }
            else
            {
                throw new ArgumentException("Transport protocol must be specified.");
            }

            return client;
        }
示例#4
0
        /// <summary>
        /// Initializes <see cref="DataSubscriber"/>.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            Dictionary<string, string> settings = Settings;
            string setting;
            double interval;

            // Setup connection to data publishing server with or without authentication required
            if (settings.TryGetValue("requireAuthentication", out setting))
                m_requireAuthentication = setting.ParseBoolean();
            else
                m_requireAuthentication = false;

            if (m_requireAuthentication)
            {
                if (!settings.TryGetValue("sharedSecret", out m_sharedSecret) && !string.IsNullOrWhiteSpace(m_sharedSecret))
                    throw new ArgumentException("The \"sharedSecret\" setting must defined when authentication is required.");

                if (!settings.TryGetValue("authenticationID", out m_authenticationID) && !string.IsNullOrWhiteSpace(m_authenticationID))
                    throw new ArgumentException("The \"authenticationID\" setting must defined when authentication is required.");
            }

            // Check if synchronize metadata is disabled.
            if (settings.TryGetValue("synchronizeMetadata", out setting))
                m_synchronizeMetadata = setting.ParseBoolean();
            else
                m_synchronizeMetadata = true;   // by default, we will always perform this.

            // Check if measurements for this connection should be marked as "internal" - i.e., owned and allowed for proxy
            if (settings.TryGetValue("internal", out setting))
                m_internal = setting.ParseBoolean();

            // See if user has opted for different operational modes
            if (!(settings.TryGetValue("operationalModes", out setting) && Enum.TryParse(setting, true, out m_operationalModes)))
                m_operationalModes = DefaultOperationalModes;

            // Check if we should be using the alternate binary format for communications with the publisher
            if (settings.TryGetValue("operationalModes", out setting))
                m_operationalModes = (OperationalModes)uint.Parse(setting);

            // Check if user wants to request that publisher use millisecond resolution to conserve bandwidth
            if (settings.TryGetValue("useMillisecondResolution", out setting))
                m_useMillisecondResolution = setting.ParseBoolean();

            // Define auto connect setting
            if (settings.TryGetValue("autoConnect", out setting))
                m_autoConnect = setting.ParseBoolean();

            // Define data loss interval
            if (settings.TryGetValue("dataLossInterval", out setting) && double.TryParse(setting, out interval))
                DataLossInterval = interval;

            if (m_autoConnect)
            {
                // Connect to local events when automatically engaging connection cycle
                ConnectionAuthenticated += DataSubscriber_ConnectionAuthenticated;
                MetaDataReceived += DataSubscriber_MetaDataReceived;

                // If active measurements are defined, attempt to defined desired subscription points from there
                if (DataSource != null && (object)DataSource.Tables != null && DataSource.Tables.Contains("ActiveMeasurements"))
                {
                    try
                    {
                        // Filter to points associated with this subscriber that have been requested for subscription, are enabled and not owned locally
                        DataRow[] filteredRows = DataSource.Tables["ActiveMeasurements"].Select("Subscribed <> 0");
                        List<IMeasurement> subscribedMeasurements = new List<IMeasurement>();
                        MeasurementKey key;
                        Guid signalID;

                        foreach (DataRow row in filteredRows)
                        {
                            // Create a new measurement for the provided field level information
                            Measurement measurement = new Measurement();

                            // Parse primary measurement identifier
                            signalID = row["SignalID"].ToNonNullString(Guid.Empty.ToString()).ConvertToType<Guid>();

                            // Set measurement key if defined
                            if (MeasurementKey.TryParse(row["ID"].ToString(), signalID, out key))
                                measurement.Key = key;

                            // Assign other attributes
                            measurement.ID = signalID;
                            measurement.TagName = row["PointTag"].ToNonNullString();
                            measurement.Multiplier = double.Parse(row["Multiplier"].ToString());
                            measurement.Adder = double.Parse(row["Adder"].ToString());

                            subscribedMeasurements.Add(measurement);
                        }

                        if (subscribedMeasurements.Count > 0)
                        {
                            // Combine subscribed output measurement with any existing output measurement and return unique set
                            if (OutputMeasurements == null)
                                OutputMeasurements = subscribedMeasurements.ToArray();
                            else
                                OutputMeasurements = subscribedMeasurements.Concat(OutputMeasurements).Distinct().ToArray();
                        }
                    }
                    catch (Exception ex)
                    {
                        // Errors here may not be catastrophic, this simply limits the auto-assignment of input measurement keys desired for subscription
                        OnProcessException(new InvalidOperationException(string.Format("Failed to define subscribed measurements: {0}", ex.Message), ex));
                    }
                }
            }

            // Create a new TCP client
            TcpClient commandChannel = new TcpClient();

            // Initialize default settings
            commandChannel.ConnectionString = "server=localhost:6165";
            commandChannel.PayloadAware = true;
            commandChannel.PersistSettings = false;
            commandChannel.MaxConnectionAttempts = 1;

            // Assign command channel client reference and attach to needed events
            this.CommandChannel = commandChannel;

            // Get proper connection string - either from specified command channel
            // or from base connection string
            if (settings.TryGetValue("commandChannel", out setting))
                commandChannel.ConnectionString = setting;
            else
                commandChannel.ConnectionString = ConnectionString;

            // Register subscriber with the statistics engine
            StatisticsEngine.Register(this, "Subscriber", "SUB");

            Initialized = true;
        }
示例#5
0
 /// <summary>
 /// Releases the unmanaged resources used by the <see cref="DataSubscriber"/> object and optionally releases the managed resources.
 /// </summary>
 /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
 protected override void Dispose(bool disposing)
 {
     if (!m_disposed)
     {
         try
         {
             if (disposing)
             {
                 DataLossInterval = 0.0D;
                 CommandChannel = null;
                 DataChannel = null;
                 DisposeLocalConcentrator();
             }
         }
         finally
         {
             m_disposed = true;          // Prevent duplicate dispose.
             base.Dispose(disposing);    // Call base class Dispose().
         }
     }
 }
示例#6
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="WindowsServiceClient"/> object and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                try
                {
                    if (disposing)
                    {
                        if (m_clientHelper != null)
                            m_clientHelper.ReceivedServiceUpdate -= ClientHelper_ReceivedServiceUpdate;
                        m_clientHelper = null;

                        if (m_remotingClient != null)
                        {
                            m_remotingClient.MaxConnectionAttempts = 0;

                            if (m_remotingClient.CurrentState == ClientState.Connected)
                                m_remotingClient.Disconnect();

                            m_remotingClient.Dispose();
                        }
                        m_remotingClient = null;
                    }
                }
                finally
                {
                    m_disposed = true;  // Prevent duplicate dispose.
                }
            }
        }
示例#7
0
文件: ClientBase.cs 项目: avs009/gsf
        /// <summary>
        /// Create a communications client
        /// </summary>
        /// <remarks>
        /// Note that typical connection string should be prefixed with a "protocol=tcp", "protocol=udp", "protocol=serial" or "protocol=file"
        /// </remarks>
        /// <returns>A communications client.</returns>
        /// <param name="connectionString">Connection string for the client.</param>
        public static IClient Create(string connectionString)
        {
            Dictionary<string, string> connectionSettings = connectionString.ParseKeyValuePairs();
            IClient client = null;
            string protocol;

            if (connectionSettings.TryGetValue("protocol", out protocol))
            {
                connectionSettings.Remove("protocol");
                StringBuilder settings = new StringBuilder();

                foreach (string key in connectionSettings.Keys)
                {
                    settings.Append(key);
                    settings.Append("=");
                    settings.Append(connectionSettings[key]);
                    settings.Append(";");
                }

                // Create a client instance for the specified protocol.
                switch (protocol.ToLower())
                {
                    case "tcp":
                        client = new TcpClient(settings.ToString());
                        break;
                    case "udp":
                        client = new UdpClient(settings.ToString());
                        break;
                    case "file":
                        client = new FileClient(settings.ToString());
                        break;
                    case "serial":
                        client = new SerialClient(settings.ToString());
                        break;
                    default:
                        throw new ArgumentException(protocol + " is not a valid transport protocol");
                }

                // Apply client settings from the connection string to the client.
                foreach (KeyValuePair<string, string> setting in connectionSettings)
                {
                    PropertyInfo property = client.GetType().GetProperty(setting.Key);
                    if (property != null)
                        property.SetValue(client, Convert.ChangeType(setting.Value, property.PropertyType), null);
                }
            }
            else
            {
                throw new ArgumentException("Transport protocol must be specified");
            }

            return client;
        }
示例#8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DataListener"/> class.
        /// </summary>
        public DataListener()
            : base()
        {
            m_id = DefaultID;
            m_server = DefaultServer;
            m_port = DefaultPort;
            m_protocol = DefaultProtocol;
            m_connectToServer = DefaultConnectToServer;
            m_initializeData = DefaultInitializeData;
            m_initializeDataTimeout = DefaultInitializeDataTimeout;
            m_persistSettings = DefaultPersistSettings;
            m_settingsCategory = DefaultSettingsCategory;
            m_data = new List<IDataPoint>();
            m_initializeWaitHandle = new AutoResetEvent(false);

            m_parser = new PacketParser();
            m_parser.DataParsed += PacketParser_DataParsed;

            m_tcpClient = new TcpClient();
            m_tcpClient.ConnectionAttempt += ClientSocket_ConnectionAttempt;
            m_tcpClient.ConnectionEstablished += ClientSocket_ConnectionEstablished;
            m_tcpClient.ConnectionTerminated += ClientSocket_ConnectionTerminated;
            m_tcpClient.ReceiveDataComplete += ClientSocket_ReceiveDataComplete;

            m_udpClient = new UdpClient();
            m_udpClient.ConnectionAttempt += ClientSocket_ConnectionAttempt;
            m_udpClient.ConnectionEstablished += ClientSocket_ConnectionEstablished;
            m_udpClient.ConnectionTerminated += ClientSocket_ConnectionTerminated;
            m_udpClient.ReceiveDataComplete += ClientSocket_ReceiveDataComplete;

            m_tcpServer = new TcpServer();
            m_tcpServer.ServerStarted += ServerSocket_ServerStarted;
            m_tcpServer.ServerStopped += ServerSocket_ServerStopped;
            m_tcpServer.ReceiveClientDataComplete += ServerSocket_ReceiveClientDataComplete;

            m_dataInitClient = new TcpClient();
            m_dataInitClient.ConnectionString = "Server={0}:1003";
            m_dataInitClient.PayloadAware = true;
            m_dataInitClient.MaxConnectionAttempts = 10;
            m_dataInitClient.ReceiveDataComplete += DataInitClient_ReceiveDataComplete;
        }
示例#9
0
文件: ServiceHost.cs 项目: avs009/gsf
        private void ServiceHelper_ServiceStarted(object sender, EventArgs e)
        {
            // Initialize config.
            ConfigurationFile config = ConfigurationFile.Current;
            CategorizedSettingsElementCollection settings = config.Settings["SystemSettings"];

            // Connect to source.
            m_source = new TcpClient();
            m_source.ConnectionString = string.Format("Server={0}", settings["Source"].Value);
            m_source.ConnectionAttempt += SourceClient_ConnectionAttempt;
            m_source.ConnectionEstablished += SourceClient_ConnectionEstablished;
            m_source.ConnectionTerminated += SourceClient_ConnectionTerminated;
            m_source.ReceiveDataComplete += SourceClient_ReceiveDataComplete;
            m_source.ConnectAsync();
            m_serviceHelper.ServiceComponents.Add(m_source);

            // Connect to target.
            m_targets = new List<TcpClient>();
            foreach (string item in settings["Target"].Value.Replace(',', ';').Split(';'))
            {
                TcpClient target = new TcpClient();
                target.ConnectionString = string.Format("Server={0}", item.Trim());
                target.ConnectionAttempt += TargetClient_ConnectionAttempt;
                target.ConnectionEstablished += TargetClient_ConnectionEstablished;
                target.ConnectionTerminated += TargetClient_ConnectionTerminated;
                target.ReceiveDataException += TargetClient_ReceiveDataException;
                target.ConnectAsync();
                m_serviceHelper.ServiceComponents.Add(target);
            }
        }