Open() public method

Establishes a session with the server.
public Open ( string sessionName, IUserIdentity identity ) : void
sessionName string The name to assign to the session.
identity IUserIdentity The user identity.
return void
Beispiel #1
0
        /// <summary>
        /// Creates a new session.
        /// </summary>
        private Session CreateSession()
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                ServiceMessageContext messageContext = m_configuration.CreateMessageContext();
                BindingFactory bindingFactory = BindingFactory.Create(m_configuration, messageContext);

                ConfiguredEndpoint endpoint = this.EndpointsCTRL.SelectedEndpoint;
                
                endpoint.UpdateFromServer(bindingFactory);
                                
                // Initialize the channel which will be created with the server.
                ITransportChannel channel = SessionChannel.Create(
                    m_configuration,
                    endpoint.Description,
                    endpoint.Configuration,
                    m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true),
                    messageContext);

                // Wrap the channel with the session object.
                Session session = new Session(channel, m_configuration, endpoint, null);

                // Create the session. This actually connects to the server.
                session.Open(Guid.NewGuid().ToString(), null);

                return session;
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Recreates a session based on a specified template.
        /// </summary>
        /// <param name="template">The Session object to use as template</param>
        /// <returns>The new session object.</returns>
        public static Session Recreate(Session template)
        {
            // create the channel object used to connect to the server.
            ITransportChannel channel = SessionChannel.Create(
                template.m_configuration,
                template.m_endpoint.Description,
                template.m_endpoint.Configuration,
                template.m_instanceCertificate,
                template.m_configuration.CreateMessageContext());

            // create the session object.
            Session session = new Session(channel, template, true);

            try
            {
                // open the session.
                session.Open(
                    template.m_sessionName,
                    (uint)template.m_sessionTimeout,
                    template.m_identity,
                    template.m_preferredLocales);

                // create the subscriptions.
                foreach (Subscription subscription in session.Subscriptions)
                {
                    subscription.Create();
                }
            }
            catch (Exception e)
            {
                session.Dispose();
                throw ServiceResultException.Create(StatusCodes.BadCommunicationError, e, "Could not recreate session. {0}", template.m_sessionName);
            }

            return session;
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            VariableBrowsePaths = new List<string>();
            VariableBrowsePaths.Add("/6:Data/6:Dynamic/6:Scalar/6:Int32Value");
            // VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1");
            // VariableBrowsePaths.Add("/7:MatrikonOPC Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int2");


            try
            { 
                // create the configuration.     
                ApplicationConfiguration configuration = Helpers.CreateClientConfiguration();

                // create the endpoint description.
                EndpointDescription endpointDescription = Helpers.CreateEndpointDescription();

                // create the endpoint configuration (use the application configuration to provide default values).
                EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);

                // the default timeout for a requests sent using the channel.
                endpointConfiguration.OperationTimeout = 600000;

                // use the pure XML encoding on the wire.
                endpointConfiguration.UseBinaryEncoding = true;

                // create the endpoint.
                ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);

                // create the binding factory.
                ServiceMessageContext messageContext = configuration.CreateMessageContext();
                BindingFactory bindingFactory = BindingFactory.Create(configuration, messageContext);

                // update endpoint description using the discovery endpoint.
                if (endpoint.UpdateBeforeConnect)
                {
                    endpoint.UpdateFromServer(bindingFactory);

                    Console.WriteLine("Updated endpoint description for url: {0}", endpointDescription.EndpointUrl);

                    endpointDescription = endpoint.Description;
                    endpointConfiguration = endpoint.Configuration;
                }

                X509Certificate2 clientCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find();

                // set up a callback to handle certificate validation errors.
                configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);

                // Initialize the channel which will be created with the server.
                ITransportChannel channel = SessionChannel.Create(
                    configuration,
                    endpointDescription,
                    endpointConfiguration,
                    clientCertificate,
                    messageContext);

                // Wrap the channel with the session object.
                // This call will fail if the server does not trust the client certificate.
                Session session = new Session(channel, configuration, endpoint, null);
                
                session.ReturnDiagnostics = DiagnosticsMasks.All;

                // register keep alive callback.
                // session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);

                // passing null for the user identity will create an anonymous session.
                UserIdentity identity = null; // new UserIdentity("iamuser", "password");        

                // create the session. This actually connects to the server.
                session.Open("My Session Name", identity);

                //Read some history values:
                string str = "";
                do
                {
                    Console.WriteLine("Select action from the menu:\n");
                    Console.WriteLine("\t 0 - Browse");
                    Console.WriteLine("\t 1 - Update");
                    Console.WriteLine("\t 2 - ReadRaw");
                    Console.WriteLine("\t 3 - ReadProcessed");
                    Console.WriteLine("\t 4 - ReadAtTime");
                    Console.WriteLine("\t 5 - ReadAttributes");
                    Console.WriteLine("\t 6 - DeleteAtTime");
                    Console.WriteLine("\t 7 - DeleteRaw");


                    Console.WriteLine("\n\tQ - exit\n\n");

                    str = Console.ReadLine();
                    Console.WriteLine("\n");

                    try
                    {
                        if (str == "0")
                        {
                            Browse(session);
                        }
                        else if (str == "1")
                            HistoryUpdate(session);
                        else if (str == "2")
                            HistoryReadRaw(session);
                        else if (str == "3")
                            HistoryReadProcessed(session);
                        else if (str == "4")
                            HistoryReadAtTime(session);
                        else if (str == "5")
                            HistoryReadAttributes(session);
                        else if (str == "6")
                            HistoryDeleteAtTime(session);
                        else if (str == "7")
                            HistoryDeleteRaw(session);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception occured: " + e.Message);
                    }

                } while (str != "Q" && str != "q");


                // Display some friendly info to the console and then wait for the ENTER key to be pressed.
                Console.WriteLine( "Connected to {0}.\nPress ENTER to disconnect to end.", DefaultServerUrl);
                Console.ReadLine();

                // Close and Dispose of our session, effectively disconnecting us from the UA Server.
                session.Close();
                session.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine( "Unexpected exception: {0}.\nPress ENTER to disconnect to end.", e.Message);
                Console.ReadLine();
                Console.WriteLine();
                Console.WriteLine("========================================================================================");
                Console.WriteLine();
            }
        }
Beispiel #4
0
        /// <summary>
        /// Connects to the UA server identfied by the CLSID.
        /// </summary>
        /// <param name="clsid">The CLSID.</param>
        /// <returns>The UA server.</returns>
        private Session Connect(Guid clsid)
        {
            // load the endpoint information.
            ConfiguredEndpoint endpoint = m_endpoint = LoadConfiguredEndpoint(clsid);

            if (endpoint == null)
            {
                throw new ServiceResultException(StatusCodes.BadConfigurationError);
            }

            // update security information.
            if (endpoint.UpdateBeforeConnect)
            {
                endpoint.UpdateFromServer(BindingFactory.Default);

                // check if halted while waiting for a response.
                if (!m_running)
                {
                    throw new ServiceResultException(StatusCodes.BadServerHalted);
                }
            }

            // look up the client certificate.
            X509Certificate2 clientCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

            // create a message context to use with the channel.
            ServiceMessageContext messageContext = m_configuration.CreateMessageContext();

            // create the channel.
            ITransportChannel channel = SessionChannel.Create(
                m_configuration,
                endpoint.Description,
                endpoint.Configuration,
                clientCertificate,
                messageContext);

            // create the session.
            Session session = new Session(channel, m_configuration, endpoint, clientCertificate);
            
            // create a session name that is useful for debugging.
            string sessionName = Utils.Format("COM Client ({0})", System.Net.Dns.GetHostName());

            // open the session.
            Opc.Ua.UserIdentity identity = null;

            if (endpoint.UserIdentity != null)
            {
                // need to decode password.
                UserNameIdentityToken userNameToken = endpoint.UserIdentity as UserNameIdentityToken;

                if (userNameToken != null)
                {
                    UserNameIdentityToken copy = new UserNameIdentityToken();
                    copy.PolicyId = userNameToken.PolicyId;
                    copy.DecryptedPassword = new UTF8Encoding().GetString(userNameToken.Password);
                    copy.UserName = userNameToken.UserName;
                    copy.EncryptionAlgorithm = userNameToken.EncryptionAlgorithm;
                    identity = new Opc.Ua.UserIdentity(copy);
                }

                // create the identity object.
                else
                {
                    identity = new Opc.Ua.UserIdentity(endpoint.UserIdentity);
                }
            }

            session.Open(sessionName, identity);

            // return the new session.
            return session;
        }
Beispiel #5
0
        /// <summary>
        /// Creates a new communication session with a server by invoking the CreateSession service
        /// </summary>
        /// <param name="configuration">The configuration for the client application.</param>
        /// <param name="endpoint">The endpoint for the server.</param>
        /// <param name="updateBeforeConnect">If set to <c>true</c> the discovery endpoint is used to update the endpoint description before connecting.</param>
        /// <param name="checkDomain">If set to <c>true</c> then the domain in the certificate must match the endpoint used.</param>
        /// <param name="sessionName">The name to assign to the session.</param>
        /// <param name="sessionTimeout">The timeout period for the session.</param>
        /// <param name="identity">The user identity to associate with the session.</param>
        /// <param name="preferredLocales">The preferred locales.</param>
        /// <returns>The new session object.</returns>
        public static Session Create( 
            ApplicationConfiguration configuration,
            ConfiguredEndpoint       endpoint,
            bool                     updateBeforeConnect,
            bool                     checkDomain,
            string                   sessionName,
            uint                     sessionTimeout,
            IUserIdentity            identity,
            IList<string>            preferredLocales)
        {
            endpoint.UpdateBeforeConnect = updateBeforeConnect;

            EndpointDescription endpointDescription = endpoint.Description;

            // create the endpoint configuration (use the application configuration to provide default values).
            EndpointConfiguration endpointConfiguration = endpoint.Configuration;
            
            if (endpointConfiguration == null)
            {
                endpoint.Configuration = endpointConfiguration = EndpointConfiguration.Create(configuration);
            }

            // create message context.
            ServiceMessageContext messageContext = configuration.CreateMessageContext();
            
            // update endpoint description using the discovery endpoint.
            if (endpoint.UpdateBeforeConnect)
            {
                BindingFactory bindingFactory = BindingFactory.Create(configuration, messageContext);
                endpoint.UpdateFromServer(bindingFactory);

                endpointDescription = endpoint.Description;
                endpointConfiguration = endpoint.Configuration;
            }

            // checks the domains in the certificate.
            if (checkDomain && endpoint.Description.ServerCertificate != null && endpoint.Description.ServerCertificate.Length > 0)
            {
                CheckCertificateDomain(endpoint);
            }

            X509Certificate2 clientCertificate = null;
			//X509Certificate2Collection clientCertificateChain = null;

            if (endpointDescription.SecurityPolicyUri != SecurityPolicies.None)
            {
                if (configuration.SecurityConfiguration.ApplicationCertificate == null)
                {
                    throw ServiceResultException.Create( StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified." );
                }

                clientCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find( true );

				if( clientCertificate == null )
				{
                    throw ServiceResultException.Create( StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found." );
                }

                //load certificate chain
                //clientCertificateChain = new X509Certificate2Collection(clientCertificate);
                //List<CertificateIdentifier> issuers = new List<CertificateIdentifier>();
                //configuration.CertificateValidator.GetIssuers(clientCertificate, issuers);
                //for (int i = 0; i < issuers.Count; i++)
                //{
                //    clientCertificateChain.Add(issuers[i].Certificate);
                //}
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = SessionChannel.Create(
                 configuration,
                 endpointDescription,
                 endpointConfiguration,
                 //clientCertificateChain,
                 clientCertificate,
                 messageContext);

            // create the session object.
            Session session = new Session(channel, configuration, endpoint, null);

            // create the session.
			try
			{
				session.Open( sessionName, sessionTimeout, identity, preferredLocales, checkDomain );
			}
			catch
			{
				session.Dispose();
				throw;
			}

            return session;
        }
Beispiel #6
0
        /// <summary>
        /// Creates a new session.
        /// </summary>
        private Session CreateSession(Guid clsid)
        {
            // lookup the cached configuration information.
            ConfiguredEndpoint endpoint = null;
            bool previouslyConnected = true;

            if (!m_verifiedEndpoints.TryGetValue(clsid, out endpoint))
            {
                endpoint = LoadConfiguredEndpoint(clsid);

                if (endpoint != null)
                {
                    Utils.Trace("Loaded endpoint with URL: {0}", endpoint.EndpointUrl);
                    previouslyConnected = false;
                }
            } 
            
            if (endpoint == null)
            { 
                endpoint = m_endpointCache.Create(DefaultServerUrl);
            }
            
            // Initialize the client configuration.
            // Fetch the current configuration information by connecting to the server's discovery endpoint.
            // This method assumes that the discovery endpoint can be constructed by appending "/discovery" to the URL.
            if (endpoint.UpdateBeforeConnect && !previouslyConnected)
            {
                endpoint.UpdateFromServer(BindingFactory.Default);
                Utils.Trace("Updated endpoint from server: {0}", endpoint.EndpointUrl);
            }

            // Need to specify that the server is trusted by the client application.
            if (!previouslyConnected)
            {
                m_configuration.SecurityConfiguration.AddTrustedPeer(endpoint.Description.ServerCertificate);
            }

            // Set the session keep alive to 600 seconds.
            m_configuration.ClientConfiguration.DefaultSessionTimeout = 600000;

            ServiceMessageContext messageContext = m_configuration.CreateMessageContext();

            // Initialize the channel which will be created with the server.
            ITransportChannel channel = SessionChannel.Create(
                m_configuration,
                endpoint.Description,
                endpoint.Configuration,
                m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true),
                messageContext);

              // Wrap the channel with the session object.
            Session session = new Session(channel, m_configuration, endpoint, null);
            session.ReturnDiagnostics = DiagnosticsMasks.SymbolicId;
            
            // The user login credentials must be provided when opening a session.
            IUserIdentity identity = null;

            if (endpoint.UserIdentity != null)
            {
                identity = new Opc.Ua.UserIdentity(endpoint.UserIdentity);
            }

            // Create the session. This actually connects to the server.
            session.Open("COM Client Session", identity);
        
            // need to fetch the references in order use the node cache.
            session.FetchTypeTree(ReferenceTypeIds.References);

            // save the updated information.
            if (!previouslyConnected)
            {
                try
                {
                    SaveConfiguredEndpoint(clsid, endpoint);
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Could not save SaveConfiguredEndpoint in registry."); 
                }

                m_verifiedEndpoints.Add(clsid, endpoint);
            }
            
            return session;
        }
        /// <summary>
        /// Connects to the UA server identfied by the CLSID.
        /// </summary>
        /// <param name="clsid">The CLSID.</param>
        /// <returns>The UA server.</returns>
        private async Task<Session> Connect(Guid clsid)
        {
            // load the endpoint information.
            ConfiguredEndpoint endpoint = m_endpoint = LoadConfiguredEndpoint(clsid);

            if (endpoint == null)
            {
                throw new ServiceResultException(StatusCodes.BadConfigurationError);
            }

            // update security information.
            if (endpoint.UpdateBeforeConnect)
            {
                endpoint.UpdateFromServer();

                // check if halted while waiting for a response.
                if (!m_running)
                {
                    throw new ServiceResultException(StatusCodes.BadServerHalted);
                }
            }

            // look up the client certificate.
            X509Certificate2 clientCertificate = await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

            // create a message context to use with the channel.
            ServiceMessageContext messageContext = m_configuration.CreateMessageContext();

            // create the channel.
            ITransportChannel channel = SessionChannel.Create(
                m_configuration,
                endpoint.Description,
                endpoint.Configuration,
                clientCertificate,
                messageContext);

            // create the session.
            Session session = new Session(channel, m_configuration, endpoint, clientCertificate);

            // create a session name that is useful for debugging.
            string sessionName = Utils.Format("COM Client (Host={0}, CLSID={1})", System.Net.Dns.GetHostName(), clsid);

            // open the session.
            session.Open(sessionName, null);

            // return the new session.
            return session;
        }
        /// <summary>
        /// Creates a session.
        /// </summary>
        private Session CreateSession(
            ApplicationConfiguration configuration, 
            BindingFactory           bindingFactory,
            ConfiguredEndpoint       endpoint,
            IUserIdentity            identity)
        {
            Report("Creating new Session with URL = {0}", endpoint.EndpointUrl);

            // Initialize the channel which will be created with the server.
            ITransportChannel channel = SessionChannel.Create(
                configuration,
                endpoint.Description,
                endpoint.Configuration,
                configuration.SecurityConfiguration.ApplicationCertificate.Find(true),
                configuration.CreateMessageContext());

            // Wrap the channel with the session object.
            Session session = new Session(channel, configuration, endpoint, null);
            session.ReturnDiagnostics = DiagnosticsMasks.All;
            
            // register keep alive callback.
            session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);
            
            // create the user identity.            
            if (identity == null)
            {
                if (endpoint.Description.UserIdentityTokens.Count > 0)
                {
                    identity = CreateUserIdentity(endpoint.Description.UserIdentityTokens[0]);
                }
            }

            // Create the session. This actually connects to the server.
            session.Open(Guid.NewGuid().ToString(), identity);

            Report("Successfully created new Session.");

            // return the session.
            return session;
        }
        /// <summary>
        /// Creates a new communication session with a server by invoking the CreateSession service
        /// </summary>
        /// <param name="configuration">The configuration for the client application.</param>
        /// <param name="endpoint">The endpoint for the server.</param>
        /// <param name="updateBeforeConnect">If set to <c>true</c> the discovery endpoint is used to update the endpoint description before connecting.</param>
        /// <param name="checkDomain">If set to <c>true</c> then the domain in the certificate must match the endpoint used.</param>
        /// <param name="sessionName">The name to assign to the session.</param>
        /// <param name="sessionTimeout">The timeout period for the session.</param>
        /// <param name="identity">The user identity to associate with the session.</param>
        /// <param name="preferredLocales">The preferred locales.</param>
        /// <returns>The new session object.</returns>
        public static async Task<Session> Create(
            ApplicationConfiguration configuration,
            ConfiguredEndpoint endpoint,
            bool updateBeforeConnect,
            bool checkDomain,
            string sessionName,
            uint sessionTimeout,
            IUserIdentity identity,
            IList<string> preferredLocales)
        {
            endpoint.UpdateBeforeConnect = updateBeforeConnect;

            EndpointDescription endpointDescription = endpoint.Description;

            // create the endpoint configuration (use the application configuration to provide default values).
            EndpointConfiguration endpointConfiguration = endpoint.Configuration;

            if (endpointConfiguration == null)
            {
                endpoint.Configuration = endpointConfiguration = EndpointConfiguration.Create(configuration);
            }

            // create message context.
            ServiceMessageContext messageContext = configuration.CreateMessageContext();

            // update endpoint description using the discovery endpoint.
            if (endpoint.UpdateBeforeConnect)
            {
                BindingFactory bindingFactory = BindingFactory.Create(configuration, messageContext);
                endpoint.UpdateFromServer(bindingFactory);

                endpointDescription = endpoint.Description;
                endpointConfiguration = endpoint.Configuration;
            }

            // checks the domains in the certificate.
            if (checkDomain && endpoint.Description.ServerCertificate != null && endpoint.Description.ServerCertificate.Length > 0)
            {
                bool domainFound = false;

                X509Certificate2 serverCertificate = new X509Certificate2(endpoint.Description.ServerCertificate);

                // check the certificate domains.
                IList<string> domains = Utils.GetDomainsFromCertficate(serverCertificate);

                if (domains != null)
                {
                    string hostname = endpoint.EndpointUrl.DnsSafeHost;

                    if (hostname == "localhost" || hostname == "127.0.0.1")
                    {
                        hostname = Utils.GetHostName();
                    }

                    for (int ii = 0; ii < domains.Count; ii++)
                    {
                        if (String.Compare(hostname, domains[ii], StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            domainFound = true;
                            break;
                        }
                    }
                }

                if (!domainFound)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateHostNameInvalid);
                }
            }

            X509Certificate2 clientCertificate = null;

            if (endpointDescription.SecurityPolicyUri != SecurityPolicies.None)
            {
                if (configuration.SecurityConfiguration.ApplicationCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified.");
                }

                clientCertificate = await configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

                if (clientCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found.");
                }
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = SessionChannel.Create(
                 configuration,
                 endpointDescription,
                 endpointConfiguration,
                 //clientCertificateChain,
                 clientCertificate,
                 messageContext);

            // create the session object.
            Session session = new Session(channel, configuration, endpoint, null);

            // create the session.
            try
            {
                session.Open(sessionName, sessionTimeout, identity, preferredLocales);
            }
            catch
            {
                session.Dispose();
                throw;
            }

            return session;
        }
        /// <summary>
        /// Creates a new communication session with a server by invoking the CreateSession service
        /// </summary>
        /// <param name="configuration">The configuration for the client application.</param>
        /// <param name="endpoint">The endpoint for the server.</param>
        /// <param name="updateBeforeConnect">If set to <c>true</c> the discovery endpoint is used to update the endpoint description before connecting.</param>
        /// <param name="checkDomain">If set to <c>true</c> then the domain in the certificate must match the endpoint used.</param>
        /// <param name="sessionName">The name to assign to the session.</param>
        /// <param name="sessionTimeout">The timeout period for the session.</param>
        /// <param name="identity">The user identity to associate with the session.</param>
        /// <param name="preferredLocales">The preferred locales.</param>
        /// <returns>The new session object.</returns>
        public static async Task<Session> Create(
            ApplicationConfiguration configuration,
            ConfiguredEndpoint endpoint,
            bool updateBeforeConnect,
            bool checkDomain,
            string sessionName,
            uint sessionTimeout,
            IUserIdentity identity,
            IList<string> preferredLocales)
        {
            endpoint.UpdateBeforeConnect = updateBeforeConnect;

            EndpointDescription endpointDescription = endpoint.Description;

            // create the endpoint configuration (use the application configuration to provide default values).
            EndpointConfiguration endpointConfiguration = endpoint.Configuration;

            if (endpointConfiguration == null)
            {
                endpoint.Configuration = endpointConfiguration = EndpointConfiguration.Create(configuration);
            }

            // create message context.
            ServiceMessageContext messageContext = configuration.CreateMessageContext();

            // update endpoint description using the discovery endpoint.
            if (endpoint.UpdateBeforeConnect)
            {
                endpoint.UpdateFromServer();

                endpointDescription = endpoint.Description;
                endpointConfiguration = endpoint.Configuration;
            }

            // checks the domains in the certificate.
            if (checkDomain && endpoint.Description.ServerCertificate != null && endpoint.Description.ServerCertificate.Length > 0)
            {
                CheckCertificateDomain(endpoint);
            }

            X509Certificate2 clientCertificate = null;

            if (endpointDescription.SecurityPolicyUri != SecurityPolicies.None)
            {
                if (configuration.SecurityConfiguration.ApplicationCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified.");
                }

                clientCertificate = await configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

                if (clientCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found.");
                }
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = SessionChannel.Create(
                 configuration,
                 endpointDescription,
                 endpointConfiguration,
                 clientCertificate,
                 messageContext);

            // create the session object.
            Session session = new Session(channel, configuration, endpoint, null);

            // create the session.
            try
            {
                session.Open(sessionName, sessionTimeout, identity, preferredLocales, checkDomain);
            }
            catch (Exception e)
            {
                session.Dispose();
                throw e;
            }

            return session;
        }