/// <summary> /// Creates a session with the endpoint. /// </summary> public Session Connect(ConfiguredEndpoint endpoint) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } // check if the endpoint needs to be updated. if (endpoint.UpdateBeforeConnect) { endpoint = new ConfiguredServerDlg().ShowDialog(endpoint, m_configuration); if (endpoint == null) { return(null); } } m_endpoint = endpoint; // copy the message context. m_messageContext = m_configuration.CreateMessageContext(); // create the channel. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true), m_messageContext); // create the session. return(Connect(endpoint, channel)); }
public async Task TryConnectAsync() { await _mutex.WaitAsync(_cancellationToken).ConfigureAwait(false); try { if (Connected) { return; } try { var endpointDescription = await GetEndpointAsync(EndpointUrl, true).ConfigureAwait(false); ConfiguredEndpoint.Update(endpointDescription); ConfiguredEndpoint.Configuration.UseBinaryEncoding = endpointDescription.EncodingSupport == BinaryEncodingSupport.Optional || endpointDescription.EncodingSupport == BinaryEncodingSupport.Required; TransportChannel = SessionChannel.Create(Configuration, ConfiguredEndpoint.Description, ConfiguredEndpoint.Configuration, Configuration.SecurityConfiguration.ApplicationCertificate.Certificate, Configuration.CreateMessageContext()); Open(_sessionName, null); NotifyPropertyChanged("Connected"); Trace.TraceInformation("Success connecting to endpoint '{0}'. ", ConfiguredEndpoint); } catch (ServiceResultException ex) { Trace.TraceError("Error connecting to endpoint '{0}'. {1}", ConfiguredEndpoint, ex.Message); } } finally { _mutex.Release(); } }
/// <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; } }
private void OkBTN_Click(object sender, EventArgs e) { try { EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration); configuration.OperationTimeout = (int)OperationTimeoutNC.Value; configuration.UseBinaryEncoding = UseBinaryEncodingCK.Checked; configuration.MaxMessageSize = (int)MaxMessageSizeNC.Value; configuration.MaxArrayLength = (int)MaxArrayLengthNC.Value; configuration.MaxStringLength = (int)MaxStringLengthNC.Value; configuration.MaxByteStringLength = (int)MaxByteStringLengthNC.Value; ITransportChannel channel = SessionChannel.Create( m_configuration, m_endpoints[EndpointCB.SelectedIndex], configuration, m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true), m_messageContext); // create the channel. // open the channel. Cursor = Cursors.WaitCursor; m_channel = channel; // close the dialog. DialogResult = DialogResult.OK; } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } finally { Cursor = Cursors.Default; } }
/// <summary>Establishes the connection to an OPC UA server.</summary> /// <param name="url">The Url of the endpoint.</param> /// <returns>Result code.</returns> /// <exception cref="Exception">Throws and forwards any exception with short error description.</exception> public void Connect(EndpointDescription endpointDescription) { try { // Create the configuration. ApplicationConfiguration configuration = opcUA_Helper.CreateClientConfiguration(); // 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); 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(); // Create the session. This actually connects to the server. // Passing null for the user identity will create an anonymous session. m_Session.Open("Siemens OPC UA sample client - main session", identity); } catch (Exception e) { throw e; } }
/// <summary> /// Connects to the UA server identfied by the CLSID. /// </summary> /// <param name="clsid">The CLSID.</param> /// <returns>The UA server.</returns> private async Task <Session> Connect(Guid clsid) { // load the endpoint information. ConfiguredEndpoint endpoint = m_endpoint = LoadConfiguredEndpoint(clsid); if (endpoint == null) { throw new ServiceResultException(StatusCodes.BadConfigurationError); } // update security information. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(); // check if halted while waiting for a response. if (!m_running) { throw new ServiceResultException(StatusCodes.BadServerHalted); } } // look up the client certificate. X509Certificate2 clientCertificate = await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true); // create a message context to use with the channel. ServiceMessageContext messageContext = m_configuration.CreateMessageContext(); // create the channel. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, clientCertificate, messageContext); // create the session. Session session = new Session(channel, m_configuration, endpoint, clientCertificate); // create a session name that is useful for debugging. string sessionName = Utils.Format("COM Client (Host={0}, CLSID={1})", System.Net.Dns.GetHostName(), clsid); // open the session. session.Open(sessionName, null); // return the new session. return(session); }
/// <summary> /// Creates a session. /// </summary> private Session CreateSession( ApplicationConfiguration configuration, BindingFactory bindingFactory, ConfiguredEndpoint endpoint, IUserIdentity identity) { Report("Creating new Session with URL = {0}", endpoint.EndpointUrl); // Initialize the channel which will be created with the server. ITransportChannel channel = SessionChannel.Create( configuration, endpoint.Description, endpoint.Configuration, configuration.SecurityConfiguration.ApplicationCertificate.Find(true), configuration.CreateMessageContext()); // Wrap the channel with the session object. Session session = new Session(channel, configuration, endpoint, null); session.ReturnDiagnostics = DiagnosticsMasks.All; // register keep alive callback. session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // create the user identity. if (identity == null) { if (endpoint.Description.UserIdentityTokens.Count > 0) { identity = CreateUserIdentity(endpoint.Description.UserIdentityTokens[0]); } } // Create the session. This actually connects to the server. session.Open(Guid.NewGuid().ToString(), identity); Report("Successfully created new Session."); // return the session. return(session); }
/// <summary> /// Connects to an endpoint of a server and returns its channel context /// </summary> /// <param name="endpoint">This parameter stores an endpoint of the server.</param> /// <param name="logFileName">File name for logging.</param> /// <returns>This object will contain the channel related information.</returns> private ChannelContext InitializeChannel(ConfiguredEndpoint endpoint, string logFileName) { ChannelContext channelContext = new ChannelContext(); channelContext.PendingAsycnTests = 0; channelContext.AsyncTestsComplete = new AutoResetEvent(false); channelContext.TestCaseComplete = new AutoResetEvent(false); // load random number file. channelContext.Random = new PseudoRandom(m_randomFilePath); // create the proxy. channelContext.Channel = SessionChannel.Create( Configuration, endpoint.Description, endpoint.Configuration, m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true), m_messageContext); channelContext.MessageContext = m_messageContext; channelContext.EndpointDescription = endpoint.Description; // wrap the channel. channelContext.ClientSession = new SessionClient(channelContext.Channel); // open log file. channelContext.EventLogger = new Logger(logFileName, (TestLogDetailMasks)m_sequenceToExecute.LogDetailLevel); channelContext.EventLogger.Open(String.Empty, m_testFilePath, channelContext.Random.FilePath); if (m_testLogEventHandler != null) { channelContext.EventLogger.TestLogEvent += m_testLogEventHandler; } return(channelContext); }
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(); } }
/// <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); } }
/// <summary> /// Creates a session with the endpoint. /// </summary> public Session Connect(ConfiguredEndpoint endpoint) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } EndpointDescriptionCollection availableEndpoints = null; // check if the endpoint needs to be updated. if (endpoint.UpdateBeforeConnect) { ConfiguredServerDlg configurationDialog = new ConfiguredServerDlg(); endpoint = configurationDialog.ShowDialog(endpoint, m_configuration); if (endpoint == null) { return(null); } availableEndpoints = configurationDialog.AvailableEnpoints; } m_endpoint = endpoint; // copy the message context. m_messageContext = m_configuration.CreateMessageContext(); X509Certificate2 clientCertificate = null; X509Certificate2Collection clientCertificateChain = null; if (endpoint.Description.SecurityPolicyUri != SecurityPolicies.None) { if (m_configuration.SecurityConfiguration.ApplicationCertificate == null) { throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified."); } clientCertificate = m_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>(); //m_configuration.CertificateValidator.GetIssuers(clientCertificate, issuers); //for (int i = 0; i < issuers.Count; i++) //{ // clientCertificateChain.Add(issuers[i].Certificate); //} } // create the channel. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, //clientCertificateChain, clientCertificate, m_messageContext); // create the session. return(Connect(endpoint, channel, availableEndpoints)); }
/// <summary> /// Connects to a server. /// </summary> /// <param name="endpoint">The server endpoint</param> /// <param name="oldlvi">null if a new connection. non-null if an existing disconnected connection</param> public void Connect(ConfiguredEndpoint endpoint, ListViewItem oldlvi) { try { if (endpoint == null) { return; } if (ServerListView.Items.ContainsKey(endpoint.ToString())) { MessageBox.Show("endpoint already in use"); return; } ServerConnection connection = new ServerConnection(endpoint); if (connection.m_Endpoint.UpdateBeforeConnect) { UpdateEndpoint(connection.m_Endpoint); } // create the channel. connection.m_channel = SessionChannel.Create( m_configuration, connection.m_Endpoint.Description, connection.m_Endpoint.Configuration, m_bindingFactory, m_configuration.SecurityConfiguration.ApplicationCertificate.Find(), null); connection.m_session = new Session(connection.m_channel, m_configuration, connection.m_Endpoint); connection.m_session.ReturnDiagnostics = DiagnosticsMasks.All; // Set up good defaults connection.m_session.DefaultSubscription.PublishingInterval = 1000; connection.m_session.DefaultSubscription.KeepAliveCount = 3; connection.m_session.DefaultSubscription.Priority = 0; connection.m_session.DefaultSubscription.PublishingEnabled = true; connection.m_session.DefaultSubscription.DefaultItem.SamplingInterval = 1000; if (new SessionOpenDlg().ShowDialog(connection.m_session, new List <string>()) == true) { NodeId ServerStartTimeNodeId = new NodeId(Variables.Server_ServerStatus_StartTime); NodeId ServerCurrentTimeNodeId = new NodeId(Variables.Server_ServerStatus_CurrentTime); NodeId ServerStateNodeId = new NodeId(Variables.Server_ServerStatus_State); // Save in the map m_Connections.Add(connection.m_Endpoint.Description.EndpointUrl.ToString(), connection); // Add to list control ListViewItem lvi = ServerListView.Items.Add(connection.m_session.SessionId.ToString(), "", -1); lvi.SubItems.Add("").Name = ServerStartTimeNodeId.Identifier.ToString(); lvi.SubItems.Add("").Name = ServerCurrentTimeNodeId.Identifier.ToString(); lvi.SubItems.Add("").Name = ServerStateNodeId.Identifier.ToString(); lvi.SubItems.Add(""); lvi.SubItems.Add(""); lvi.SubItems.Add(""); lvi.SubItems.Add(""); lvi.Tag = connection; if (oldlvi != null) { ServerListView.Items.Remove(oldlvi); } connection.m_session.KeepAlive += new KeepAliveEventHandler(StandardClient_KeepAlive); connection.m_Subscription = new Subscription(connection.m_session.DefaultSubscription); connection.m_Subscription.DisplayName = connection.m_session.ToString(); bool bResult = connection.m_session.AddSubscription(connection.m_Subscription); connection.m_Subscription.Create(); MonitoredItem startTimeItem = new MonitoredItem(connection.m_Subscription.DefaultItem); INode node = connection.m_session.NodeCache.Find(ServerStartTimeNodeId); startTimeItem.DisplayName = connection.m_session.NodeCache.GetDisplayText(node); startTimeItem.StartNodeId = ServerStartTimeNodeId; startTimeItem.NodeClass = (NodeClass)node.NodeClass; startTimeItem.AttributeId = Attributes.Value; connection.m_Subscription.AddItem(startTimeItem); startTimeItem.Notification += m_ItemNotification; MonitoredItem currentTimeItem = new MonitoredItem(connection.m_Subscription.DefaultItem); INode currentTimeNode = connection.m_session.NodeCache.Find(ServerCurrentTimeNodeId); currentTimeItem.DisplayName = connection.m_session.NodeCache.GetDisplayText(currentTimeNode); currentTimeItem.StartNodeId = ServerCurrentTimeNodeId; currentTimeItem.NodeClass = (NodeClass)currentTimeNode.NodeClass; currentTimeItem.AttributeId = Attributes.Value; connection.m_Subscription.AddItem(currentTimeItem); currentTimeItem.Notification += m_ItemNotification; MonitoredItem stateItem = new MonitoredItem(connection.m_Subscription.DefaultItem); INode stateNode = connection.m_session.NodeCache.Find(ServerStateNodeId); stateItem.DisplayName = connection.m_session.NodeCache.GetDisplayText(stateNode); stateItem.StartNodeId = ServerStateNodeId; stateItem.NodeClass = (NodeClass)stateNode.NodeClass; stateItem.AttributeId = Attributes.Value; connection.m_Subscription.AddItem(stateItem); connection.m_Subscription.ApplyChanges(); stateItem.Notification += m_ItemNotification; } } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <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 var configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configSection + ".Config.xml"); var configFileInfo = new FileInfo(configFilePath); ApplicationConfiguration configuration = ApplicationConfiguration.Load(configFileInfo, ApplicationType.Client, null).Result; //ApplicationConfiguration configuration = ApplicationConfiguration.Load(configSection, ApplicationType.Client).Result; 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().Result; configuration.SecurityConfiguration.RejectSHA1SignedCertificates = false; ushort minimumKeySize = CertificateFactory.defaultKeySize / 2; configuration.SecurityConfiguration.MinimumCertificateKeySize = minimumKeySize; configuration.CertificateValidator.Update(configuration.SecurityConfiguration); // 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. var channel = SessionChannel.Create( configuration, endpointDescription, endpointConfiguration, //bindingFactory, clientCertificate, new ServiceMessageContext()); // Step 4 -- Create a session Session session = new Session(channel, configuration, endpoint, clientCertificate) { ReturnDiagnostics = DiagnosticsMasks.All }; string sessionName = "SenderSession"; UserIdentity identity = new UserIdentity(); // anonymous session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); session.Open(sessionName, identity); return(session); }
/// <summary> /// Creates a session with the endpoint. /// </summary> public async Task <Session> Connect(ConfiguredEndpoint endpoint) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } // check if the endpoint needs to be updated. if (endpoint.UpdateBeforeConnect) { ConfiguredServerDlg configurationDialog = new ConfiguredServerDlg(); endpoint = await configurationDialog.ShowDialog(endpoint, m_configuration); } if (endpoint == null) { return(null); } m_endpoint = endpoint; // copy the message context. m_messageContext = m_configuration.CreateMessageContext(); X509Certificate2 clientCertificate = null; if (endpoint.Description.SecurityPolicyUri != SecurityPolicies.None) { if (m_configuration.SecurityConfiguration.ApplicationCertificate == null) { throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified."); } clientCertificate = await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true); if (clientCertificate == null) { throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found."); } } // create the channel. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, clientCertificate, m_messageContext); try { // create the session. Session session = new Session(channel, m_configuration, endpoint, null); session.ReturnDiagnostics = DiagnosticsMasks.All; SessionOpenDlg sessiondlg = new SessionOpenDlg(); session = await sessiondlg.ShowDialog(session, PreferredLocales); if (session != null) { // session now owns the channel. channel = null; // add session to tree. AddNode(session); return(session); } } finally { // ensure the channel is closed on error. if (channel != null) { channel.Close(); channel = null; } } return(null); }
public async Task <Session> CreateSession(OPCUAServer server, string sessionName) { try { lock (dicOfSession) { if (dicOfSession.ContainsKey(sessionName)) { return(dicOfSession[sessionName]); } } #region OPCUAServer UAServer objUAServer = new UAServer(); objUAServer.Protocol = server.protocol; objUAServer.SecurityMode = server.securityMode; objUAServer.SecurityPolicy = server.securityMode; objUAServer.SecurityPolicy = server.securityPolicy; objUAServer.UserIdentityString = server.UserIdentityString; objUAServer.ServerName = server.serverName; try { objUAServer.UserIdentity = (UserIdentityType)Enum.Parse(typeof(UserIdentityType), objUAServer.UserIdentityString); } catch { if (objUAServer.UserIdentityString.Equals("Anonymous")) { objUAServer.UserIdentity = UserIdentityType.Anonymous; } else if (objUAServer.UserIdentityString.Equals("UserName")) { objUAServer.UserIdentity = UserIdentityType.UserName; } else { objUAServer.UserIdentity = UserIdentityType.Certificate; } } if (objUAServer.UserIdentity.Equals(UserIdentityType.Certificate)) { objUAServer.IsSecurityStoreEnabled = false; objUAServer.CertificationPath = server.certificationPath; objUAServer.CertificationPassword = server.certificationPassword; } else if (objUAServer.UserIdentity.Equals(UserIdentityType.UserName)) { objUAServer.UserName = server.userName; objUAServer.UserPassword = server.userPassword; } #endregion await CheckAndLoadConfiguration(); // Create the configuration. ApplicationConfiguration configuration = _appConfiguration; // Helpers.CreateClientConfiguration(myServer); // Create the endpoint description. EndpointDescription endpointDescription = Helpers.CreateEndpointDescription(objUAServer); // 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. //OA-2018-04-11 // endpointConfiguration.UseBinaryEncoding = true; if (objUAServer.MessageEncoding.ToLower().Equals("binary")) { endpointConfiguration.UseBinaryEncoding = true; } else { endpointConfiguration.UseBinaryEncoding = false; } IUserIdentity identity; var t = _appConfiguration.SecurityConfiguration.ApplicationCertificate.Find(true); X509Certificate2 clientCertificate = t.Result; UserTokenPolicy poly; if (objUAServer.UserIdentity.Equals(UserIdentityType.UserName)) { identity = new UserIdentity(objUAServer.UserName, objUAServer.UserPassword); poly = new UserTokenPolicy(UserTokenType.UserName); //added by kais wali bool exist = false; foreach (UserTokenPolicy poltemp in endpointDescription.UserIdentityTokens) { if (poltemp.TokenType.ToString() == poly.TokenType.ToString()) { exist = true; break; } } if (!exist) { endpointDescription.UserIdentityTokens.Add(poly); } } else if (objUAServer.UserIdentity.Equals(UserIdentityType.Certificate)) { CertificateIdentifier certificateIdentifier = new CertificateIdentifier(); X509Certificate2 currentCertificate; certificateIdentifier.StoreType = CertificateStoreType.Directory; currentCertificate = new X509Certificate2(objUAServer.CertificationPath, objUAServer.CertificationPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); if (currentCertificate == null) { throw ServiceResultException.Create(StatusCodes.BadCertificateInvalid, "Could not find certificate: {0}", certificateIdentifier.SubjectName); } identity = new UserIdentity(currentCertificate); // poly = new UserTokenPolicy(UserTokenType.Certificate); //added by kais wali bool exist = false; foreach (UserTokenPolicy poltemp in endpointDescription.UserIdentityTokens) { if (poltemp.TokenType.ToString() == poly.TokenType.ToString()) { exist = true; break; } } if (!exist) { endpointDescription.UserIdentityTokens.Add(poly); } } else { identity = new UserIdentity(); poly = new UserTokenPolicy(UserTokenType.Anonymous); //added by kais wali bool exist = false; foreach (UserTokenPolicy poltemp in endpointDescription.UserIdentityTokens) { if (poltemp.TokenType.ToString() == poly.TokenType.ToString()) { exist = true; break; } } if (!exist) { endpointDescription.UserIdentityTokens.Add(poly); } } // Create the endpoint. ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); // Update endpoint description using the discovery endpoint. // create message context. ServiceMessageContext messageContext = configuration.CreateMessageContext(); //Set to true in default configuration (If the user have not configured an OPC UA Server in the ONBS) endpoint.UpdateBeforeConnect = false; // update endpoint description using the discovery endpoint. //OA-2018-06-19 Commented /*if (endpoint.UpdateBeforeConnect) * { * BindingFactory bindingFactory = BindingFactory.Create(configuration, messageContext); * endpoint.UpdateFromServer(bindingFactory); * * endpointDescription = endpoint.Description; * endpointConfiguration = endpoint.Configuration; * }*/ // 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, //clientCertificateChain, clientCertificate, messageContext); // create the session object. //OA-2017-08-15 Session m_session = new Session(channel, configuration, endpoint, clientCertificate); //m_session = new Session(channel, configuration, endpoint, null); //OA-2017-09-20 byte[] certificateData = endpoint.Description.ServerCertificate; //islem Commented serverCertificate if (certificateData != null) //OA-2018-04-27 //serverCertificate = Utils.ParseCertificateBlob(certificateData); // { m_session.ReturnDiagnostics = DiagnosticsMasks.All; } // Register keep alive callback. //islem Commented KeepAlive // m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // create the session. try { m_session.Open(sessionName, 60000, identity, null); dicOfSession.Add(sessionName, m_session);//OA-2017-09-20 } catch (Exception e) { } return(m_session); } catch (Exception e) { return(null); } }
public void connect() { clearSession(); #region Server var lServers = getServersDescr(mDiscovery); ApplicationDescription lApplication = null; foreach (var lServer in lServers) { if (mServerName.Equals(lServer.ApplicationName.ToString(), StringComparison.Ordinal)) { lApplication = lServer; break; } } if (lApplication == null) { throw new InvalidOperationException("Unable to find server. "); } var lEndpoints = DiscoveryClient.Create(new Uri(lApplication.DiscoveryUrls[0])).GetEndpoints(null); EndpointDescription lEndpoint = null; foreach (var lEP in lEndpoints) { try { if (getTransport(lEP.EndpointUrl) == mTransport && lEP.SecurityMode == MessageSecurityMode.None) { lEndpoint = lEP; break; } } catch { } } if (lEndpoint == null) { throw new InvalidOperationException("Unable to find suitable endpoint. "); } mHost = mDiscovery.Split(':')[1].Substring(2); lEndpoint.EndpointUrl = lEndpoint.EndpointUrl.Replace("localhost", mHost); #endregion #region ApplicationConfiguration var lAppConfig = new ApplicationConfiguration(); lAppConfig.ApplicationName = "Process Simulator 2"; lAppConfig.ApplicationType = ApplicationType.Client; lAppConfig.ApplicationUri = "http://localhost/VendorId/ApplicationId/InstanceId"; lAppConfig.ProductUri = "http://VendorId/ProductId/VersionId"; lAppConfig.SecurityConfiguration = new SecurityConfiguration(); lAppConfig.SecurityConfiguration.ApplicationCertificate = new CertificateIdentifier(); lAppConfig.SecurityConfiguration.ApplicationCertificate.StoreType = CertificateStoreType.Windows; lAppConfig.SecurityConfiguration.ApplicationCertificate.StorePath = "LocalMachine\\My"; lAppConfig.SecurityConfiguration.ApplicationCertificate.SubjectName = lAppConfig.ApplicationName; lAppConfig.SecurityConfiguration.TrustedPeerCertificates.StoreType = CertificateStoreType.Windows; lAppConfig.SecurityConfiguration.TrustedPeerCertificates.StorePath = "LocalMachine\\My"; var lClientCertificate = lAppConfig.SecurityConfiguration.ApplicationCertificate.Find(true); if (lClientCertificate == null) { lClientCertificate = CertificateFactory.CreateCertificate( lAppConfig.SecurityConfiguration.ApplicationCertificate.StoreType, lAppConfig.SecurityConfiguration.ApplicationCertificate.StorePath, lAppConfig.ApplicationUri, lAppConfig.ApplicationName, null, null, 1024, 120); } lAppConfig.TransportConfigurations.Add(new TransportConfiguration(Opc.Ua.Utils.UriSchemeOpcTcp, typeof(Opc.Ua.Bindings.UaTcpBinding))); lAppConfig.TransportConfigurations.Add(new TransportConfiguration(Opc.Ua.Utils.UriSchemeHttp, typeof(Opc.Ua.Bindings.UaSoapXmlBinding))); lAppConfig.TransportQuotas = new TransportQuotas(); lAppConfig.TransportQuotas.OperationTimeout = 360000; lAppConfig.TransportQuotas.MaxStringLength = 67108864; lAppConfig.ServerConfiguration = new ServerConfiguration(); lAppConfig.ClientConfiguration = new ClientConfiguration(); lAppConfig.ClientConfiguration.DefaultSessionTimeout = 36000; lAppConfig.Validate(ApplicationType.Client); #endregion #region Session var lEndpointConfig = EndpointConfiguration.Create(lAppConfig); lEndpointConfig.OperationTimeout = 300000; lEndpointConfig.UseBinaryEncoding = true; var lConfiguredEndpoint = new ConfiguredEndpoint(null, lEndpoint, lEndpointConfig); var lBindingFactory = BindingFactory.Create(lAppConfig, new ServiceMessageContext()); lAppConfig.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = true; }; var lChannel = SessionChannel.Create(lAppConfig, lEndpoint, lEndpointConfig, lBindingFactory, lClientCertificate, null); mSession = new Session(lChannel, lAppConfig, lConfiguredEndpoint); mSession.ReturnDiagnostics = DiagnosticsMasks.All; mSession.KeepAlive += MSession_KeepAlive; mSession.Notification += MSession_Notification; mSession.PublishError += MSession_PublishError; if (String.IsNullOrWhiteSpace(mLogin) == false && String.IsNullOrWhiteSpace(mPassword) == false) { mSession.Open("Process Simulator 2 session", new UserIdentity(mLogin, mPassword)); } else { mSession.Open("Process Simulator 2 session", null); } #endregion #region Namespace var lNewNamespaces = getNamespaces(); if (mNamespaces != null && NumberOfItems > 0) { int lIndex; int[] lNsChanges = new int[mNamespaces.Length]; bool lNeedChanges = false; for (int i = 0; i < mNamespaces.Length; i++) { lIndex = StringUtils.getIndex(lNewNamespaces, mNamespaces[i]); if (lIndex == -1) { throw new InvalidOperationException("Namespace '" + mNamespaces[i] + "' is missing. "); } lNsChanges[i] = lIndex; if (i != lIndex) { lNeedChanges = true; } } if (lNeedChanges) { foreach (DataItem lItem in mItemList) { if (lItem.mNodeId.NamespaceIndex != lNsChanges[lItem.mNodeId.NamespaceIndex]) { lItem.mNodeId = new NodeId(lItem.mNodeId.Identifier, (ushort)lNsChanges[lItem.mNodeId.NamespaceIndex]); } } mNamespaces = lNewNamespaces; } } else { mNamespaces = lNewNamespaces; } #endregion #region Subscription mSubscription = new Subscription(mSession.DefaultSubscription); mSubscription.DisplayName = "Subscription"; mSubscription.PublishingEnabled = true; mSubscription.PublishingInterval = mPublishingInterval; mSubscription.KeepAliveCount = 10; mSubscription.LifetimeCount = 100; mSubscription.MaxNotificationsPerPublish = 100; mSession.AddSubscription(mSubscription); mSubscription.Create(); byte lAccess; object lValue; StatusCode lStatusCode; string lType; bool lArray; int lNotOKItemsCount = 0; foreach (DataItem lItem in mItemList) { try { checkVariable(lItem.mNodeId, out lAccess, out lValue, out lStatusCode, out lType, out lArray); lItem.setAccess(lAccess); lItem.StatusCode = lStatusCode; if ((lAccess == AccessLevels.CurrentRead || lAccess == AccessLevels.CurrentReadOrWrite) && StatusCode.IsGood(lStatusCode) && lValue != null) { lItem.mValue = lValue; } else { lItem.initValue(lType, lArray); } addItemToSubscription(lItem); } catch (Exception lExc) { lItem.setAccess(AccessLevels.None); lNotOKItemsCount = lNotOKItemsCount + 1; Log.Error("Data item '" + lItem.mNodeId.ToString() + "' activation error. " + lExc.Message, lExc.ToString()); } } mSubscription.ApplyChanges(); #endregion mConnected = true; raiseConnectionState(); #region Update Item Values if (mItemList.Count > lNotOKItemsCount) { foreach (DataItem lItem in mItemList) { if (lItem.Access.HasFlag(EAccess.READ)) { lItem.raiseValueChanged(); } } } #endregion if (lNotOKItemsCount > 0) { throw new InvalidOperationException("Unable to activate " + StringUtils.ObjectToString(lNotOKItemsCount) + " data item(s). "); } }
/// <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> /// 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); }