Esempio n. 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;
            }
        }
Esempio n. 2
0
        /// <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);
        }
Esempio n. 3
0
        /// <summary>
        /// Updates an endpoint with information from the server's discovery endpoint.
        /// </summary>
        /// <param name="endpoint">The server endpoint</param>
        private void UpdateEndpoint(ConfiguredEndpoint endpoint)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                // create the binding factory if it has not been created yet.
                if (m_bindingFactory == null)
                {
                    m_bindingFactory = BindingFactory.Create(m_configuration);
                }

                endpoint.UpdateFromServer(m_bindingFactory);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Esempio n. 4
0
        private static void securelyUpdateEndpointConfiguration(ConfiguredEndpoint ep, ApplicationConfiguration applicationConfiguration)
        {
            // ep.UpdateFromServer(...) looks for matching endpoints on the server.
            // If there is no match with the same securityMode and securityPolicy, it will simply
            // _replace_ ep by one of the server endpoints, possibly lowering the security settings. Therefore:
            // save old settings - update from server - verify security settings -- and throw update from server away if security settings have changed.
            // note that ConfiguredEndpoints need a collection to live in. Note also that some settings of the configured endpoint may be changed nonetheless behind the scenes.
            ConfiguredEndpointCollection cepc = new ConfiguredEndpointCollection();
            EndpointDescription          epd  = (EndpointDescription)ep.Description.Clone();
            ConfiguredEndpoint           cep  = new ConfiguredEndpoint(cepc, epd);

            Opc.Ua.BindingFactory bindingFactory = BindingFactory.Create(applicationConfiguration, applicationConfiguration.CreateMessageContext());
            ep.UpdateFromServer(bindingFactory);

            if (ep.Description.SecurityMode != epd.SecurityMode || ep.Description.SecurityPolicyUri != epd.SecurityPolicyUri)
            {
                ep.Update(cep);
                throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "No endpoint with matching security configuration could be found during updated on connect.");
            }
        }
Esempio n. 5
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();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Runs the test in a background thread.
        /// </summary>
        private void DoTest(ConfiguredEndpoint endpoint)
        {
            PerformanceTestResult result = new PerformanceTestResult(endpoint, 100);

            result.Results.Add(1, -1);
            result.Results.Add(10, -1);
            result.Results.Add(50, -1);
            result.Results.Add(100, -1);
            result.Results.Add(250, -1);
            result.Results.Add(500, -1);

            try
            {
                // update the endpoint.
                if (endpoint.UpdateBeforeConnect)
                {
                    BindingFactory bindingFactory = BindingFactory.Create(m_configuration, m_messageContext);
                    endpoint.UpdateFromServer(bindingFactory);
                }

                SessionClient client = null;

                Uri url = new Uri(endpoint.Description.EndpointUrl);

                ITransportChannel channel = SessionChannel.Create(
                    m_configuration,
                    endpoint.Description,
                    endpoint.Configuration,
                    m_clientCertificate,
                    m_messageContext);

                client = new SessionClient(channel);

                List <int> requestSizes = new List <int>(result.Results.Keys);

                for (int ii = 0; ii < requestSizes.Count; ii++)
                {
                    // update the progress indicator.
                    TestProgress((ii * 100) / requestSizes.Count);

                    lock (m_lock)
                    {
                        if (!m_running)
                        {
                            break;
                        }
                    }

                    int count = requestSizes[ii];

                    // initialize request.
                    RequestHeader requestHeader = new RequestHeader();
                    requestHeader.ReturnDiagnostics = 5000;

                    ReadValueIdCollection nodesToRead = new ReadValueIdCollection(count);

                    for (int jj = 0; jj < count; jj++)
                    {
                        ReadValueId item = new ReadValueId();

                        item.NodeId      = new NodeId((uint)jj, 1);
                        item.AttributeId = Attributes.Value;

                        nodesToRead.Add(item);
                    }

                    // ensure valid connection.
                    DataValueCollection      results         = null;
                    DiagnosticInfoCollection diagnosticInfos = null;

                    client.Read(
                        requestHeader,
                        0,
                        TimestampsToReturn.Both,
                        nodesToRead,
                        out results,
                        out diagnosticInfos);

                    if (results.Count != count)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    // do test.
                    DateTime start = DateTime.UtcNow;

                    for (int jj = 0; jj < result.Iterations; jj++)
                    {
                        client.Read(
                            requestHeader,
                            0,
                            TimestampsToReturn.Both,
                            nodesToRead,
                            out results,
                            out diagnosticInfos);

                        if (results.Count != count)
                        {
                            throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                        }
                    }

                    DateTime finish = DateTime.UtcNow;

                    long    totalTicks          = finish.Ticks - start.Ticks;
                    decimal averageMilliseconds = ((((decimal)totalTicks) / ((decimal)result.Iterations))) / ((decimal)TimeSpan.TicksPerMillisecond);
                    result.Results[requestSizes[ii]] = (double)averageMilliseconds;
                }
            }
            finally
            {
                TestComplete(result);
            }
        }
Esempio n. 7
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>
        /// Runs the test in a background thread.
        /// </summary>
        private void DoTest(ConfiguredEndpoint endpoint)
        {
            PerformanceTestResult result = new PerformanceTestResult(endpoint, 100);

            result.Results.Add(1, -1);
            result.Results.Add(10, -1);
            result.Results.Add(50, -1);
            result.Results.Add(100, -1);
            result.Results.Add(250, -1);
            result.Results.Add(500, -1);

            try
            {
                // update the endpoint.
                if (endpoint.UpdateBeforeConnect)
                {
                    endpoint.UpdateFromServer();
                }

                SessionClient client = null;

                Uri url = new Uri(endpoint.Description.EndpointUrl);

                ITransportChannel channel = SessionChannel.Create(
                    m_configuration,
                    endpoint.Description,
                    endpoint.Configuration,
                    m_clientCertificate,
                    m_messageContext);

                client = new SessionClient(channel);

                List<int> requestSizes = new List<int>(result.Results.Keys);

                for (int ii = 0; ii < requestSizes.Count; ii++)
                {
                    // update the progress indicator.
                    TestProgress((ii * 100) / requestSizes.Count);

                    lock (m_lock)
                    {
                        if (!m_running)
                        {
                            break;
                        }
                    }

                    int count = requestSizes[ii];

                    // initialize request.
                    RequestHeader requestHeader = new RequestHeader();
                    requestHeader.ReturnDiagnostics = 5000;

                    ReadValueIdCollection nodesToRead = new ReadValueIdCollection(count);

                    for (int jj = 0; jj < count; jj++)
                    {
                        ReadValueId item = new ReadValueId();

                        item.NodeId = new NodeId((uint)jj, 1);
                        item.AttributeId = Attributes.Value;

                        nodesToRead.Add(item);
                    }

                    // ensure valid connection.
                    DataValueCollection results = null;
                    DiagnosticInfoCollection diagnosticInfos = null;

                    client.Read(
                        requestHeader,
                        0,
                        TimestampsToReturn.Both,
                        nodesToRead,
                        out results,
                        out diagnosticInfos);

                    if (results.Count != count)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    // do test.
                    DateTime start = DateTime.UtcNow;

                    for (int jj = 0; jj < result.Iterations; jj++)
                    {
                        client.Read(
                            requestHeader,
                            0,
                            TimestampsToReturn.Both,
                            nodesToRead,
                            out results,
                            out diagnosticInfos);

                        if (results.Count != count)
                        {
                            throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                        }
                    }

                    DateTime finish = DateTime.UtcNow;

                    long totalTicks = finish.Ticks - start.Ticks;
                    decimal averageMilliseconds = ((((decimal)totalTicks) / ((decimal)result.Iterations))) / ((decimal)TimeSpan.TicksPerMillisecond);
                    result.Results[requestSizes[ii]] = (double)averageMilliseconds;
                }
            }
            finally
            {
                TestComplete(result);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Create a session with the given UA server
        /// </summary>
        /// <param name="discoveryUrl"></param>
        /// <param name="configSection"></param>
        /// <returns></returns>
        public static Session CreateSession(string discoveryUrl, string configSection)
        {
            // Step 1 -- Load configuration
            ApplicationConfiguration configuration = ApplicationConfiguration.Load(configSection, ApplicationType.Client);

            ClientUtils.CheckApplicationInstanceCertificate(configuration);

            // Step 2 -- Select an endpoint
            // create the endpoint description
            EndpointDescription endpointDescription = ClientUtils.SelectEndpoint(discoveryUrl, false);

            endpointDescription.SecurityMode      = MessageSecurityMode.None;
            endpointDescription.SecurityPolicyUri = @"http://opcfoundation.org/UA/SecurityPolicy#None";

            // create the endpoint configuration
            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);

            // the default timeout for a requests sent using the channel.
            endpointConfiguration.OperationTimeout = 600000;
            // create the endpoint.
            ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);

            // choose the encoding strategy: true: BinaryEncoding; false: XmlEncoding
            endpoint.Configuration.UseBinaryEncoding = true;

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

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

                //Console.Error.WriteLine("Updated endpoint description for url: {0}\n", 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);

            // Step 3 -- Initialize the channel which will be created with the server.
            SessionChannel channel = SessionChannel.Create(
                configuration,
                endpointDescription,
                endpointConfiguration,
                bindingFactory,
                clientCertificate,
                null);

            // Step 4 -- Create a session
            Session session = new Session(channel, configuration, endpoint);

            session.ReturnDiagnostics = DiagnosticsMasks.All;
            string       sessionName = "SenderSession";
            UserIdentity identity    = new UserIdentity(); // anonymous

            session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);
            session.Open(sessionName, identity);
            return(session);
        }
Esempio n. 10
0
        /// <summary>
        /// Runs the testcases against the endpoint.
        /// </summary>
        /// <param name="endpoint">The endpoint to test.</param>
        /// <param name="testcases">The testcases to run.</param>
        public void Run(ConfiguredEndpoint endpoint, ServerTestConfiguration testConfiguration)
        {
            // save the test configuration.
            m_testConfiguration = testConfiguration;
            m_stopped = false;

            // create the binding factory.
            m_bindingFactory = BindingFactory.Create(m_configuration, m_messageContext);

            while (!m_stopped)
            {
                try
                { 
                    Report("Test run started.");

                    // update from server.
                    if (endpoint.UpdateBeforeConnect)
                    {
                        endpoint.UpdateFromServer(m_bindingFactory);
                        Report("Updated endpoint from the discovery endpoint.");
                    }
                    
                    // validate the server certificate.
                    byte[] certificateData = endpoint.Description.ServerCertificate;

                    try
                    {
                        X509Certificate2 certificate = CertificateFactory.Create(certificateData, true);
                        m_configuration.CertificateValidator.Validate(certificate);
                    }
                    catch (ServiceResultException e)
                    {
                        if (e.StatusCode != StatusCodes.BadCertificateUntrusted)
                        {
                            throw new ServiceResultException(e, StatusCodes.BadCertificateInvalid);
                        }
                        
                        // automatically trust the certificate if it is untrusted.
                        m_configuration.CertificateValidator.Update(m_configuration.SecurityConfiguration);
                    }

                    m_defaultEndpoint = endpoint;
                    
                    // fetch all endpoints from the server.
                    m_endpoints = GetEndpoints(endpoint);
                    Report("Fetched all endpoints supported by the server.");
                }
                catch (Exception e)
                {
                    Report(e, "Could not connect to server");
                    return;
                }

                m_endpointCount = 0;
                m_totalEndpointCount = 0;
                m_testCount = 0;
                m_failedTestCount = 0;
                m_iterationCount = 0;
                m_totalIterationCount = 0;

                uint totalCount = 0;
                uint failedCount = 0;
                uint endpointCount = 0;

                if (m_testConfiguration.EndpointSelection != EndpointSelection.Single)
                {
                    EndpointSelection selection = m_testConfiguration.EndpointSelection;

                    foreach (ConfiguredEndpoint current in m_endpoints.Endpoints)
                    {
                        if (IsEndpointSelected(current, selection, false))
                        {
                            m_totalEndpointCount++;
                        }

                        if (current.Description.EncodingSupport == BinaryEncodingSupport.Optional)
                        {
                            if (IsEndpointSelected(current, selection, true))
                            {
                                m_totalEndpointCount++;
                            }
                        }
                    }

                    foreach (ConfiguredEndpoint current in m_endpoints.Endpoints)
                    {
                        if (IsEndpointSelected(current, selection, false))
                        {
                            m_endpointCount++;

                            // check if test stopped.
                            if (m_stopped)
                            {
                                break;
                            }

                            DoTestForEndpoint(current, ref totalCount, ref failedCount);
                            endpointCount++;
                        }

                        if (current.Description.EncodingSupport == BinaryEncodingSupport.Optional)
                        {         
                            if (IsEndpointSelected(current, selection, true))
                            {                   
                                m_endpointCount++;
                             
                                // check if test stopped.
                                if (m_stopped)
                                {
                                    break;
                                }
                                
                                current.Configuration.UseBinaryEncoding = !current.Configuration.UseBinaryEncoding;
                                DoTestForEndpoint(current, ref totalCount, ref failedCount);
                                endpointCount++;
                            }
                        }
                    }
                }
                else
                {
                    m_endpointCount++;
                    m_totalEndpointCount = 1;

                    DoTestForEndpoint(m_defaultEndpoint, ref totalCount, ref failedCount);
                    endpointCount++;
                }

                if (failedCount > 0)
                {
                    Report("WARNING: {0} tests failed. {1} tests run.", failedCount, totalCount);
                }
                else
                {
                    Report("{0} tests completed successfully for {1} endpoints.", totalCount, endpointCount);
                    DumpPerfData();
                }

                if (!m_testConfiguration.Continuous)
                {
                    break;
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Updates an endpoint with information from the server's discovery endpoint.
        /// </summary>
        /// <param name="endpoint">The server endpoint</param>
        private void UpdateEndpoint(ConfiguredEndpoint endpoint)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                // create the binding factory if it has not been created yet.
                if (m_bindingFactory == null)
                {
                    m_bindingFactory = BindingFactory.Create(m_configuration);
                }

                endpoint.UpdateFromServer(m_bindingFactory);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// This method executes the test cases for the configured endpoint.
        /// In case of multiple channel test cases, this endpoint value is ignored and new
        /// endpoint is used to connect to the server specified in test configuration.
        /// </summary>
        /// <param name="endpoint">This parameter stores an endpoint of the server.</param>
        public void ExecuteTestSequence(ConfiguredEndpoint endpoint)
        {
            lock (m_lock)
            {
                m_cancel = false;
            }

            if (endpoint.UpdateBeforeConnect)
            {
                // create the binding factory if it has not been created yet.
                if (m_bindingFactory == null)
                {
                    m_bindingFactory = BindingFactory.Create(m_configuration, m_messageContext);
                }

                endpoint.UpdateFromServer(m_bindingFactory);
            }

            ChannelContext selectedChannelContext = null;

            selectedChannelContext = InitializeChannel(endpoint, m_logFilePath);

            try
            {
                foreach (TestCase testCase in m_sequenceToExecute.TestCase)
                {
                    if (testCase.SkipTest || testCase.Name.StartsWith(TestCases.SerializerDirect))
                    {
                        continue;
                    }

                    try
                    {
                        TestUtils.ValidateTestCase(testCase, (int)testCase.Start);
                    }
                    catch (Exception e)
                    {
                        selectedChannelContext.EventLogger.LogErrorEvent(testCase, (int)testCase.Start, e);

                        if (m_sequenceToExecute.HaltOnError)
                        {
                            throw;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    TestCaseContext testCaseContext = TestUtils.GetExecutionContext(testCase);

                    try
                    {
                        ValidateTestContext(testCaseContext, testCase);
                    }
                    catch (Exception e)
                    {
                        selectedChannelContext.EventLogger.LogErrorEvent(testCase, (int)testCase.Start, e);

                        if (m_sequenceToExecute.HaltOnError)
                        {
                            throw;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (testCase.Name != TestCases.MultipleChannels)
                    {
                        ExecuteTestCase(selectedChannelContext, testCaseContext, testCase);
                    }
                    else
                    {
                        Uri defaultUrl = new Uri(endpoint.Description.EndpointUrl);

                        // In case of multiple channel get endpoint urls from the test case file.
                        List <ChannelContext>     channelContextList     = new List <ChannelContext>();
                        List <ConfiguredEndpoint> configuredEndpointList = new List <ConfiguredEndpoint>();
                        for (int serverCnt = 0; serverCnt < testCaseContext.ServerDetails.Count; serverCnt++)
                        {
                            string serverURL = testCaseContext.ServerDetails[serverCnt].Url;
                            serverURL = serverURL.Replace("localhost", defaultUrl.DnsSafeHost);

                            //ConfiguredEndpointCollection endpointCollection = new ConfiguredEndpointCollection () ;
                            //ConfiguredEndpoint serverendpoint = endpointCollection.Create(serverURL);
                            ConfiguredEndpoint serverendpoint = (ConfiguredEndpoint)endpoint.Clone();

                            // slow systems may not be able to renew tokens fast enough when overloaded with channels.
                            serverendpoint.Configuration.SecurityTokenLifetime = 60000;

                            serverendpoint.Description.EndpointUrl = serverURL;
                            configuredEndpointList.Add(serverendpoint);

                            //For each channel get the log file name as <default file name>_<server name>_<channel index>.
                            for (int channelCnt = 0; channelCnt < testCaseContext.ChannelsPerServer; channelCnt++)
                            {
                                string logFileSuffix = "_" + testCaseContext.ServerDetails[serverCnt].Name + "_" + channelCnt.ToString();
                                string logFileName   = m_logFilePath.Replace(".xml", logFileSuffix) + ".xml";

                                ChannelContext channelContext = InitializeChannel(configuredEndpointList[serverCnt],
                                                                                  logFileName);
                                channelContextList.Add(channelContext);
                            }
                        }

                        try
                        {
                            WaitHandle[] waitHandles = new WaitHandle[channelContextList.Count];

                            for (int iCtr = 0; iCtr < channelContextList.Count; iCtr++)
                            {
                                waitHandles[iCtr] = channelContextList[iCtr].TestCaseComplete;
                                ThreadPool.QueueUserWorkItem(ExecuteTestCase, new object[] { channelContextList[iCtr], testCaseContext, testCase });
                            }

                            WaitHandle.WaitAll(waitHandles);
                        }
                        finally
                        {
                            for (int iCtr = 0; iCtr < channelContextList.Count; iCtr++)
                            {
                                WindupChannel(channelContextList[iCtr]);
                            }
                        }
                    }
                }
            }
            finally
            {
                WindupChannel(selectedChannelContext);
            }

            RaiseEvent(new TestSequenceEventArgs(0, "Done", 0));
        }
Esempio n. 13
0
        /// <summary>
        /// This method executes the test cases for the configured endpoint.
        /// In case of multiple channel test cases, this endpoint value is ignored and new
        /// endpoint is used to connect to the server specified in test configuration.
        /// </summary>
        /// <param name="endpoint">This parameter stores an endpoint of the server.</param>
        public void ExecuteTestSequence(ConfiguredEndpoint endpoint)
        {
            lock (m_lock)
            {
                m_cancel = false;
            }

            if (endpoint.UpdateBeforeConnect)
            {
                // create the binding factory if it has not been created yet.
                if (m_bindingFactory == null)
                {
                    m_bindingFactory = BindingFactory.Create(m_configuration, m_messageContext);
                }

                endpoint.UpdateFromServer(m_bindingFactory);
            }

            ChannelContext selectedChannelContext = null;

            selectedChannelContext = InitializeChannel(endpoint, m_logFilePath);

            try
            {
                foreach (TestCase testCase in m_sequenceToExecute.TestCase)
                {
                    if (testCase.SkipTest || testCase.Name.StartsWith(TestCases.SerializerDirect))
                    {
                        continue;
                    }
                    
                    try
                    {
                        TestUtils.ValidateTestCase(testCase, (int)testCase.Start);
                    }
                    catch (Exception e)
                    {
                        selectedChannelContext.EventLogger.LogErrorEvent(testCase, (int)testCase.Start, e);

                        if (m_sequenceToExecute.HaltOnError)
                        {
                            throw;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    TestCaseContext testCaseContext = TestUtils.GetExecutionContext(testCase);

                    try
                    {
                        ValidateTestContext(testCaseContext, testCase);
                    }
                    catch (Exception e)
                    {
                        selectedChannelContext.EventLogger.LogErrorEvent(testCase, (int)testCase.Start, e);

                        if (m_sequenceToExecute.HaltOnError)
                        {
                            throw;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (testCase.Name != TestCases.MultipleChannels)
                    {
                        ExecuteTestCase(selectedChannelContext, testCaseContext, testCase);
                    }
                    else
                    {
                        Uri defaultUrl = new Uri(endpoint.Description.EndpointUrl);

                        // In case of multiple channel get endpoint urls from the test case file.
                        List<ChannelContext> channelContextList = new List<ChannelContext>();
                        List<ConfiguredEndpoint> configuredEndpointList = new List<ConfiguredEndpoint>();
                        for (int serverCnt = 0; serverCnt < testCaseContext.ServerDetails.Count; serverCnt++)
                        {
                            string serverURL = testCaseContext.ServerDetails[serverCnt].Url;
                            serverURL = serverURL.Replace("localhost", defaultUrl.DnsSafeHost);

                            //ConfiguredEndpointCollection endpointCollection = new ConfiguredEndpointCollection () ;
                            //ConfiguredEndpoint serverendpoint = endpointCollection.Create(serverURL);
                            ConfiguredEndpoint serverendpoint = (ConfiguredEndpoint)endpoint.Clone();

                            // slow systems may not be able to renew tokens fast enough when overloaded with channels.
                            serverendpoint.Configuration.SecurityTokenLifetime = 60000;

                            serverendpoint.Description.EndpointUrl = serverURL;
                            configuredEndpointList.Add(serverendpoint);

                            //For each channel get the log file name as <default file name>_<server name>_<channel index>.
                            for (int channelCnt = 0; channelCnt < testCaseContext.ChannelsPerServer; channelCnt++)
                            {
                                string logFileSuffix = "_" + testCaseContext.ServerDetails[serverCnt].Name + "_" + channelCnt.ToString();
                                string logFileName = m_logFilePath.Replace(".xml", logFileSuffix) + ".xml";

                                ChannelContext channelContext = InitializeChannel(configuredEndpointList[serverCnt],
                                logFileName);
                                channelContextList.Add(channelContext);
                            }
                        }

                        try
                        {
                            WaitHandle[] waitHandles = new WaitHandle[channelContextList.Count];

                            for (int iCtr = 0; iCtr < channelContextList.Count; iCtr++)
                            {
                                waitHandles[iCtr] = channelContextList[iCtr].TestCaseComplete;
                                ThreadPool.QueueUserWorkItem(ExecuteTestCase, new object[] { channelContextList[iCtr], testCaseContext, testCase });
                            }

                            WaitHandle.WaitAll(waitHandles);
                        }
                        finally
                        {
                            for (int iCtr = 0; iCtr < channelContextList.Count; iCtr++)
                            {
                                WindupChannel(channelContextList[iCtr]);
                            }
                        }
                    }
                }
            }
            finally
            {
                WindupChannel(selectedChannelContext);
            }

            RaiseEvent(new TestSequenceEventArgs(0, "Done", 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 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>
        /// 建立与OPC UA的连接,该种方式需要用户名与密码形式
        /// </summary>
        /// <param name="Url">需要连接的Url地址信息</param>
        /// <param name="userName">用户名</param>
        /// <param name="userPwd">密码</param>
        public void Connect(string Url, String userName, String userPwd)
        {
            try
            {
                // Create the configuration.
                ApplicationConfiguration configuration = opcUA_Helper.CreateClientConfiguration();

                // Create the endpoint description.
                EndpointDescription endpointDescription = opcUA_Helper.CreateEndpointDescription(Url);

                // 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 = 300000;

                // Use the pure binary encoding on the wire.
                endpointConfiguration.UseBinaryEncoding = true;

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

                // Create the binding factory.
                BindingFactory bindingFactory = BindingFactory.Create(configuration);

                // Update endpoint description using the discovery endpoint.
                if (endpoint.UpdateBeforeConnect)
                {
                    endpoint.UpdateFromServer(bindingFactory);
                    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.
                SessionChannel channel = SessionChannel.Create(
                    configuration,
                    endpointDescription,
                    endpointConfiguration,
                    bindingFactory,
                    clientCertificate,
                    null);

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

                // Register keep alive callback.
                m_Session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);

                UserIdentity identity = new UserIdentity(userName, userPwd);


                // Create the session. This actually connects to the server.
                // Passing null for the user identity will create an anonymous session.
                m_Session.Open("625IIS - main session", identity);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 16
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();
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Runs the testcases against the endpoint.
        /// </summary>
        /// <param name="endpoint">The endpoint to test.</param>
        /// <param name="testcases">The testcases to run.</param>
        public void Run(ConfiguredEndpoint endpoint, ServerTestConfiguration testConfiguration)
        {
            // save the test configuration.
            m_testConfiguration = testConfiguration;
            m_stopped           = false;

            // create the binding factory.
            m_bindingFactory = BindingFactory.Create(m_configuration, m_messageContext);

            while (!m_stopped)
            {
                try {
                    Report("Test run started.");

                    // update from server.
                    if (endpoint.UpdateBeforeConnect)
                    {
                        endpoint.UpdateFromServer(m_bindingFactory);
                        Report("Updated endpoint from the discovery endpoint.");
                    }

                    // validate the server certificate.
                    byte[] certificateData = endpoint.Description.ServerCertificate;

                    try {
                        X509Certificate2 certificate = CertificateFactory.Create(certificateData, true);
                        m_configuration.CertificateValidator.Validate(certificate);
                    } catch (ServiceResultException e) {
                        if (e.StatusCode != StatusCodes.BadCertificateUntrusted)
                        {
                            throw new ServiceResultException(e, StatusCodes.BadCertificateInvalid);
                        }

                        // automatically trust the certificate if it is untrusted.
                        m_configuration.CertificateValidator.Update(m_configuration.SecurityConfiguration);
                    }

                    m_defaultEndpoint = endpoint;

                    // fetch all endpoints from the server.
                    m_endpoints = GetEndpoints(endpoint);
                    Report("Fetched all endpoints supported by the server.");
                } catch (Exception e) {
                    Report(e, "Could not connect to server");
                    return;
                }

                m_endpointCount       = 0;
                m_totalEndpointCount  = 0;
                m_testCount           = 0;
                m_failedTestCount     = 0;
                m_iterationCount      = 0;
                m_totalIterationCount = 0;

                uint totalCount    = 0;
                uint failedCount   = 0;
                uint endpointCount = 0;

                if (m_testConfiguration.EndpointSelection != EndpointSelection.Single)
                {
                    EndpointSelection selection = m_testConfiguration.EndpointSelection;

                    foreach (ConfiguredEndpoint current in m_endpoints.Endpoints)
                    {
                        if (IsEndpointSelected(current, selection, false))
                        {
                            m_totalEndpointCount++;
                        }

                        if (current.Description.EncodingSupport == BinaryEncodingSupport.Optional)
                        {
                            if (IsEndpointSelected(current, selection, true))
                            {
                                m_totalEndpointCount++;
                            }
                        }
                    }

                    foreach (ConfiguredEndpoint current in m_endpoints.Endpoints)
                    {
                        if (IsEndpointSelected(current, selection, false))
                        {
                            m_endpointCount++;

                            // check if test stopped.
                            if (m_stopped)
                            {
                                break;
                            }

                            DoTestForEndpoint(current, ref totalCount, ref failedCount);
                            endpointCount++;
                        }

                        if (current.Description.EncodingSupport == BinaryEncodingSupport.Optional)
                        {
                            if (IsEndpointSelected(current, selection, true))
                            {
                                m_endpointCount++;

                                // check if test stopped.
                                if (m_stopped)
                                {
                                    break;
                                }

                                current.Configuration.UseBinaryEncoding = !current.Configuration.UseBinaryEncoding;
                                DoTestForEndpoint(current, ref totalCount, ref failedCount);
                                endpointCount++;
                            }
                        }
                    }
                }
                else
                {
                    m_endpointCount++;
                    m_totalEndpointCount = 1;

                    DoTestForEndpoint(m_defaultEndpoint, ref totalCount, ref failedCount);
                    endpointCount++;
                }

                if (failedCount > 0)
                {
                    Report("WARNING: {0} tests failed. {1} tests run.", failedCount, totalCount);
                }
                else
                {
                    Report("{0} tests completed successfully for {1} endpoints.", totalCount, endpointCount);
                    DumpPerfData();
                }

                if (!m_testConfiguration.Continuous)
                {
                    break;
                }
            }
        }
Esempio n. 18
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);
        }
        /// <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;
        }