Ejemplo n.º 1
0
        public Client(IEventAggregator ea)
        {
            this.EventAggregator = ea;

            this.config = ApplicationConfiguration.Load(null);
            config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(validateCerts);
        }
        private static async Task ConsoleServerAsync(string[] args)
        {
            var quitEvent = new ManualResetEvent(false);

            // init OPC configuration and tracing
            OpcApplicationConfiguration stationOpcApplicationConfiguration = new OpcApplicationConfiguration();

            Opc.Ua.ApplicationConfiguration stationApplicationConfiguration = await stationOpcApplicationConfiguration.ConfigureAsync();

            // allow canceling the connection process
            try
            {
                Console.CancelKeyPress += (sender, eArgs) =>
                {
                    quitEvent.Set();
                    eArgs.Cancel = true;
                };
            }
            catch
            {
            }

            // start the server.
            Logger.Information($"Starting server on endpoint {stationApplicationConfiguration.ServerConfiguration.BaseAddresses[0].ToString()} ...");
            Logger.Information($"Server simulation settings are:");
            Logger.Information($"Ideal cycle time of this station is {IdealCycleTimeDefault} msec");
            Logger.Information($"Power consumption when operating at ideal cycle time is {PowerConsumption} kW");
            Logger.Information($"{(GenerateAlerts ? "Periodically " : "Not ")}generating high pressure for alert simulation.");
            StationServer stationServer = new StationServer();

            stationServer.Start(stationApplicationConfiguration);
            Logger.Information("OPC UA Server started. Press CTRL-C to exit.");

            // wait for Ctrl-C
            quitEvent.WaitOne(Timeout.Infinite);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a new UA-binary transport channel if requested. Null otherwise.
        /// </summary>
        /// <param name="configuration">The application configuration.</param>
        /// <param name="description">The description for the endpoint.</param>
        /// <param name="endpointConfiguration">The configuration to use with the endpoint.</param>
        /// <param name="clientCertificate">The client certificate.</param>
        /// <param name="clientCertificateChain">The client certificate chain.</param>
        /// <param name="messageContext">The message context to use when serializing the messages.</param>
        /// <returns></returns>
        public static ITransportChannel CreateUaBinaryChannel(
            ApplicationConfiguration configuration,
            EndpointDescription description,
            EndpointConfiguration endpointConfiguration,
            X509Certificate2 clientCertificate,
            X509Certificate2Collection clientCertificateChain,
            IServiceMessageContext messageContext)
        {
            string uriScheme = new Uri(description.EndpointUrl).Scheme;

            switch (description.TransportProfileUri)
            {
            case Profiles.UaTcpTransport:
            {
                uriScheme = Utils.UriSchemeOpcTcp;
                break;
            }

            case Profiles.HttpsBinaryTransport:
            {
                uriScheme = Utils.UriSchemeHttps;
                break;
            }

            case Profiles.UaWssTransport:
            {
                uriScheme = Utils.UriSchemeOpcWss;
                break;
            }
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = TransportBindings.Channels.GetChannel(uriScheme);

            if (channel == null)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadProtocolVersionUnsupported,
                          "Unsupported transport profile for scheme {0}.", uriScheme);
            }

            // create a UA-TCP channel.
            TransportChannelSettings settings = new TransportChannelSettings {
                Description            = description,
                Configuration          = endpointConfiguration,
                ClientCertificate      = clientCertificate,
                ClientCertificateChain = clientCertificateChain
            };

            if (description.ServerCertificate != null && description.ServerCertificate.Length > 0)
            {
                settings.ServerCertificate = Utils.ParseCertificateBlob(description.ServerCertificate);
            }

            if (configuration != null)
            {
                settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
            }

            settings.NamespaceUris = messageContext.NamespaceUris;
            settings.Factory       = messageContext.Factory;

            channel.Initialize(new Uri(description.EndpointUrl), settings);
            channel.Open();

            return(channel);
        }
Ejemplo n.º 4
0
 public static BindingFactory Create(ApplicationConfiguration configuration)
 {
     return(Create(configuration, configuration.CreateMessageContext()));
 }
 /// <summary>
 /// Loads a collection of endpoints from a file and overrides the endpoint configuration.
 /// </summary>
 public static ConfiguredEndpointCollection Load(ApplicationConfiguration configuration, string filePath)
 {
     return(Load(configuration, filePath, false));
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Loads and validates the application configuration from a configuration section.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="applicationType">Type of the application.</param>
 /// <param name="systemType">Type of the system.</param>
 /// <returns>Application configuration</returns>
 public static async Task <ApplicationConfiguration> Load(FileInfo file, ApplicationType applicationType, Type systemType)
 {
     return(await ApplicationConfiguration.Load(file, applicationType, systemType, true));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a binding for to use for discovering servers.
        /// </summary>
        /// <param name="discoveryUrl">The discovery URL.</param>
        /// <param name="endpointConfiguration">The endpoint configuration.</param>
        /// /// <param name="applicationConfiguration">The application configuration.</param>
        /// <returns></returns>
        public static DiscoveryClient Create(Uri discoveryUrl, EndpointConfiguration endpointConfiguration, ApplicationConfiguration applicationConfiguration)
        {
            if (endpointConfiguration == null)
            {
                endpointConfiguration = EndpointConfiguration.Create();
            }

            // check if application configuration contains instance certificate.
            X509Certificate2 clientCertificate = null;

            try
            {
                if (applicationConfiguration != null &&
                    applicationConfiguration.SecurityConfiguration != null &&
                    applicationConfiguration.SecurityConfiguration.ApplicationCertificate != null)
                {
                    clientCertificate = applicationConfiguration.SecurityConfiguration.ApplicationCertificate.Find(true).Result;
                }
            }
            catch
            {
                //ignore erros
            }

            ITransportChannel channel = DiscoveryChannel.Create(discoveryUrl, endpointConfiguration, new ServiceMessageContext(), clientCertificate);

            return(new DiscoveryClient(channel));
        }
        /// <summary>
        /// Creates a new UA-binary transport channel if requested. Null otherwise.
        /// </summary>
        /// <param name="configuration">The application configuration.</param>
        /// <param name="description">The description for the endpoint.</param>
        /// <param name="endpointConfiguration">The configuration to use with the endpoint.</param>
        /// <param name="clientCertificate">The client certificate.</param>
        /// <param name="messageContext">The message context to use when serializing the messages.</param>
        /// <returns></returns>
        public static ITransportChannel CreateUaBinaryChannel(
            ApplicationConfiguration configuration,
            EndpointDescription description,
            EndpointConfiguration endpointConfiguration,
            X509Certificate2 clientCertificate,
            ServiceMessageContext messageContext)
        {
            bool useUaTcp = description.EndpointUrl.StartsWith(Utils.UriSchemeOpcTcp);
            bool useHttps = description.EndpointUrl.StartsWith(Utils.UriSchemeHttps);


            switch (description.TransportProfileUri)
            {
            case Profiles.UaTcpTransport:
            {
                useUaTcp = true;
                break;
            }

            case Profiles.HttpsBinaryTransport:
            {
                useHttps = true;
                break;
            }
            }

            // note: WCF channels are not supported
            if (!useUaTcp && !useHttps)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadServiceUnsupported,
                          "Unsupported transport profile\r\n");
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = null;

            // create a UA-TCP channel.
            TransportChannelSettings settings = new TransportChannelSettings();

            settings.Description       = description;
            settings.Configuration     = endpointConfiguration;
            settings.ClientCertificate = clientCertificate;

            if (description.ServerCertificate != null && description.ServerCertificate.Length > 0)
            {
                settings.ServerCertificate = Utils.ParseCertificateBlob(description.ServerCertificate);
            }

            if (configuration != null)
            {
                settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
            }

            settings.NamespaceUris = messageContext.NamespaceUris;
            settings.Factory       = messageContext.Factory;

            if (useUaTcp)
            {
                channel = new TcpTransportChannel();
            }
            else if (useHttps)
            {
                channel = new HttpsTransportChannel();
            }

            channel.Initialize(new Uri(description.EndpointUrl), settings);
            channel.Open();

            return(channel);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Loads and validates the application configuration from a configuration section.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="applicationType">Type of the application.</param>
 /// <param name="systemType">Type of the system.</param>
 /// <returns>Application configuration</returns>
 public static Task <ApplicationConfiguration> Load(FileInfo file, ApplicationType applicationType, Type systemType) =>
 ApplicationConfiguration.Load(file, applicationType, systemType, true);
Ejemplo n.º 10
0
        public void InitializeSinglePolicy(
            Type contractType,
            ApplicationConfiguration configuration,
            BindingFactory bindingFactory,
            EndpointConfiguration endpointConfiguration,
            List <EndpointDescription> endpoints,
            MessageSecurityMode securityMode,
            string securityPolicyUri)
        {
            // allow any url to match.
            System.ServiceModel.ServiceBehaviorAttribute behavoir = this.Description.Behaviors.Find <System.ServiceModel.ServiceBehaviorAttribute>();
            behavoir.AddressFilterMode = System.ServiceModel.AddressFilterMode.Any;

            // specify service credentials
            ServiceCredentials credentials = new ServiceCredentials();

            credentials.ClientCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
            credentials.ClientCertificate.Authentication.TrustedStoreLocation       = StoreLocation.LocalMachine;
            credentials.ClientCertificate.Authentication.RevocationMode             = X509RevocationMode.NoCheck;
            credentials.ClientCertificate.Authentication.CustomCertificateValidator = configuration.CertificateValidator.GetChannelValidator();

            if (configuration.SecurityConfiguration.ApplicationCertificate != null)
            {
                X509Certificate2 certificate = configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

                if (certificate != null)
                {
                    credentials.ServiceCertificate.Certificate = CertificateFactory.Load(certificate, true);
                }
            }

            this.Description.Behaviors.Add(credentials);

            // check if explicitly specified.
            ServiceThrottlingBehavior throttle = this.Description.Behaviors.Find <ServiceThrottlingBehavior>();

            if (throttle == null)
            {
                throttle = new ServiceThrottlingBehavior();

                throttle.MaxConcurrentCalls     = 1000;
                throttle.MaxConcurrentInstances = 100;
                throttle.MaxConcurrentSessions  = 100;

                this.Description.Behaviors.Add(throttle);
            }

            // add the endpoints for each base address.
            foreach (Uri baseAddress in this.BaseAddresses)
            {
                ServiceEndpoint endpoint = null;

                // find endpoint configuration.
                EndpointDescription description = null;

                foreach (EndpointDescription current in endpoints)
                {
                    if (new Uri(current.EndpointUrl) == baseAddress)
                    {
                        description = current;
                        break;
                    }
                }

                // skip endpoints without a matching base address.
                if (description == null)
                {
                    continue;
                }

                // set the supported profiles.
                description.TransportProfileUri = Profiles.WsHttpXmlOrBinaryTransport;

                // create the SOAP XML binding
                Binding binding = bindingFactory.Create(baseAddress.Scheme, description, endpointConfiguration);

                // add the session endpoint.
                endpoint = this.AddServiceEndpoint(contractType, binding, baseAddress, baseAddress);

                // set the protection level
                if (securityMode == MessageSecurityMode.Sign)
                {
                    endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;
                }

                // update the max items in graph (set to an low value by default).
                foreach (OperationDescription operation in endpoint.Contract.Operations)
                {
                    operation.Behaviors.Find <DataContractSerializerOperationBehavior>().MaxItemsInObjectGraph = Int32.MaxValue;
                }
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Loads and validates the application configuration from a configuration section.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="applicationType">Type of the application.</param>
 /// <param name="systemType">Type of the system.</param>
 /// <returns>Application configuration</returns>
 public static ApplicationConfiguration Load(FileInfo file, ApplicationType applicationType, Type systemType)
 {
     return(ApplicationConfiguration.Load(file, applicationType, systemType, true));
 }
        /// <summary>
        /// Creates a new UA-binary transport channel if requested. Null otherwise.
        /// </summary>
        /// <param name="configuration">The application configuration.</param>
        /// <param name="description">The description for the endpoint.</param>
        /// <param name="endpointConfiguration">The configuration to use with the endpoint.</param>
        /// <param name="clientCertificate">The client certificate.</param>
        /// <param name="messageContext">The message context to use when serializing the messages.</param>
        /// <returns></returns>
        public static ITransportChannel CreateUaBinaryChannel(
            ApplicationConfiguration configuration,
            EndpointDescription description,
            EndpointConfiguration endpointConfiguration,
            X509Certificate2 clientCertificate,
            ServiceMessageContext messageContext)
        {
            // check if the server if configured to use the ANSI C stack.
            bool useUaTcp = description.EndpointUrl.StartsWith(Utils.UriSchemeOpcTcp);
            bool useHttps = description.EndpointUrl.StartsWith(Utils.UriSchemeHttps);

            bool useAnsiCStack = false;

            switch (description.TransportProfileUri)
            {
            case Profiles.UaTcpTransport:
            {
                useUaTcp = true;

                if (configuration != null)
                {
                    useAnsiCStack = configuration.UseNativeStack;
                }

                break;
            }

            case Profiles.HttpsXmlTransport:
            case Profiles.HttpsBinaryTransport:
            case Profiles.HttpsXmlOrBinaryTransport:
            {
                useHttps = true;
                break;
            }
            }

            // note: WCF channels are not supported
            if (!useUaTcp && !useHttps)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadServiceUnsupported,
                          "Unsupported transport profile\r\n");
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = null;

            // create a UA-TCP channel.
            TransportChannelSettings settings = new TransportChannelSettings();

            settings.Description       = description;
            settings.Configuration     = endpointConfiguration;
            settings.ClientCertificate = clientCertificate;

            if (description.ServerCertificate != null && description.ServerCertificate.Length > 0)
            {
                settings.ServerCertificate = Utils.ParseCertificateBlob(description.ServerCertificate);
            }

            if (configuration != null)
            {
                settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
            }

            settings.NamespaceUris = messageContext.NamespaceUris;
            settings.Factory       = messageContext.Factory;

            if (useUaTcp)
            {
                Type type = null;

                if (useAnsiCStack)
                {
                    type = Type.GetType("Opc.Ua.NativeStack.NativeStackChannel,Opc.Ua.NativeStackWrapper");
                }

                if (useAnsiCStack && type != null)
                {
                    channel = (ITransportChannel)Activator.CreateInstance(type);
                }
                else
                {
                    channel = new Opc.Ua.Bindings.TcpTransportChannel();
                }
            }
            else if (useHttps)
            {
                channel = new Opc.Ua.Bindings.HttpsTransportChannel();
            }

            channel.Initialize(new Uri(description.EndpointUrl), settings);
            channel.Open();

            return(channel);
        }