Dispose() protected method

Closes the session and the underlying channel.
protected Dispose ( bool disposing ) : void
disposing bool
return void
Example #1
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();
            }
        }
Example #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;
        }
        /// <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;
        }
Example #4
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;
        }
        /// <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;
        }