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(/* TODOBindingFactory.Default*/);
// 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 ({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;
}