public async Task <IActionResult> OpenSession(string sessionName, OPCUAServer uaSever) { try { bool bSession = await _uaClient.CheckSession(sessionName); if (bSession) { return(BadRequest(new { error = $"A session with the same name {sessionName} is already created" })); } else { var session = await _uaClient.CreateSession(uaSever, sessionName); if (session == null) { return(BadRequest(new { error = $"Failed to create session {sessionName}" })); } else { return(Ok($"Session {sessionName} is created successfully")); } } } catch (Exception e) { return(BadRequest(new { error = $"Failed to create session {sessionName}:{e.Message}" })); } }
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); } }