Create() public static method

Creates a new communication session with a server by invoking the CreateSession service
public static Create ( ApplicationConfiguration configuration, ConfiguredEndpoint endpoint, bool updateBeforeConnect, bool checkDomain, string sessionName, uint sessionTimeout, IUserIdentity identity, IList preferredLocales ) : Session
configuration ApplicationConfiguration The configuration for the client application.
endpoint ConfiguredEndpoint The endpoint for the server.
updateBeforeConnect bool If set to true the discovery endpoint is used to update the endpoint description before connecting.
checkDomain bool If set to true then the domain in the certificate must match the endpoint used.
sessionName string The name to assign to the session.
sessionTimeout uint The timeout period for the session.
identity IUserIdentity The user identity to associate with the session.
preferredLocales IList The preferred locales.
return Session
        private static async Task RunClient(string address)
        {
            var clientApp = new ApplicationInstance
            {
                ApplicationName   = "OPC UA StackOverflow Example Client",
                ApplicationType   = ApplicationType.Client,
                ConfigSectionName = "Opc.Client"
            };

            // load the application configuration.
            var clientConfig = await clientApp.LoadApplicationConfiguration(true);

            var haveClientAppCertificate = await clientApp.CheckApplicationInstanceCertificate(true, 0);

            if (!haveClientAppCertificate)
            {
                throw new Exception("Application instance certificate invalid!");
            }
            var endpointConfiguration = EndpointConfiguration.Create(clientConfig);
            var selectedEndpoint      = CoreClientUtils.SelectEndpoint(address, true, 15000);
            var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);

            using (var session = await Session.Create(clientConfig, endpoint, false, clientConfig.ApplicationName, 60000, new UserIdentity(new AnonymousIdentityToken()), null))
            {
                Console.WriteLine("Client connected");
                var rootFolders = await session.BrowseAsync(ObjectIds.ObjectsFolder);

                Console.WriteLine("Received root folders");
                var childFolders = await Task.WhenAll(
                    from root in rootFolders
                    select session.BrowseAsync(ExpandedNodeId.ToNodeId(root.NodeId, session.NamespaceUris)));

                foreach (var childFolder in childFolders.SelectMany(x => x).OrderBy(c => c.BrowseName.Name))
                {
                    Console.WriteLine(childFolder.BrowseName.Name);
                }
                Console.WriteLine("Client disconnecting");
                session.Close();
                Console.WriteLine("Client disconnected");
            }
            Console.WriteLine("Client disposed");
        }
Example #2
0
        public async Task EndpointConnect()
        {
            var endpointCollection = DiscoverEndpoints(Module.Configuration, ServerUrl, 60);
            var selectedEndpoints  = new List <EndpointDescription>();

            // Select endpoints
            foreach (EndpointDescription endpoint in endpointCollection)
            {
                if (endpoint.TransportProfileUri == Profiles.UaTcpTransport &&
                    endpoint.SecurityLevel >= MinimumSecurityLevel &&
                    endpoint.SecurityMode >= MinimumSecurityMode)
                {
                    // patch endpoint to set the original host name we want to connect to.
                    var url = new UriBuilder(endpoint.EndpointUrl);
                    url.Host             = ServerUrl.Host;
                    endpoint.EndpointUrl = url.ToString();
                    selectedEndpoints.Add(endpoint);
                }
            }

            //
            // Sort, but descending with highest level first i.e. return
            // < 0 if x is less than y
            // > 0 if x is greater than y
            //   0 if x and y are equal
            //
            selectedEndpoints.Sort((y, x) => x.SecurityLevel - y.SecurityLevel);

            // Do not emit all exceptions as they occur, only throw them all when no connection can be made.
            var exceptions = new List <Exception>(selectedEndpoints.Count);

            foreach (EndpointDescription endpoint in selectedEndpoints)
            {
                ConfiguredEndpoint configuredEndpoint = new ConfiguredEndpoint(
                    endpoint.Server, EndpointConfiguration.Create(Module.Configuration));
                configuredEndpoint.Update(endpoint);
                try
                {
                    Console.WriteLine($"Opc.Ua.Client.SampleModule: Trying to create session with mode: {endpoint.SecurityMode}, level:{endpoint.SecurityLevel} to {configuredEndpoint.EndpointUrl}...");
                    _session = await Session.Create(
                        Module.Configuration,
                        configuredEndpoint,
                        true,
                        false,
                        Module.Configuration.ApplicationName,
                        60000,
                        // TODO: Make user identity configurable, plus add dedicated security policy
                        new UserIdentity(new AnonymousIdentityToken()),
                        null);

                    if (_session != null)
                    {
                        var subscription = new Subscription(_session.DefaultSubscription);
                        subscription.PublishingInterval = PublishingInterval;

                        // TODO: Make other subscription settings configurable...
                        subscription.AddItems(MonitoredItems);
                        _session.AddSubscription(subscription);
                        subscription.Create();

                        Console.WriteLine($"Opc.Ua.Client.SampleModule: Session with mode: {endpoint.SecurityMode}, level:{endpoint.SecurityLevel} to {configuredEndpoint.EndpointUrl} established!");
                        _session.KeepAlive += new KeepAliveEventHandler(StandardClient_KeepAlive);

                        // Done
                        return;
                    }
                    exceptions.Add(new Exception($"ERROR: Create session to endpoint {endpoint.ToString()} returned null."));
                }
                catch (AggregateException ae)
                {
                    exceptions.AddRange(ae.InnerExceptions);
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }

                //  ... try another endpoint until we do not have any more...
                Console.WriteLine($"Opc.Ua.Client.SampleModule: WARNING Could not create session to endpoint {endpoint.ToString()}...");
            }
            throw new AggregateException("Failed to find acceptable endpoint to connect to.", exceptions);
        }