private void EpConnectButton_Click(object sender, EventArgs e) { //Check if sessions exists; If yes > delete subscriptions and disconnect if (mySession != null && !mySession.Disposed) { try { //mySubscription.Delete(true); } catch { ; } myClientHelperAPI.Disconnect(); mySession = myClientHelperAPI.Session; ResetUI(); } else { try { //Register mandatory events (cert and keep alive) myClientHelperAPI.KeepAliveNotification += new KeepAliveEventHandler(Notification_KeepAlive); myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); //Check for a selected endpoint if (mySelectedEndpoint != null) { //Call connect myClientHelperAPI.Connect(mySelectedEndpoint, userPwButton.Checked, userTextBox.Text, pwTextBox.Text).Wait(); //Extract the session object for further direct session interactions mySession = myClientHelperAPI.Session; //UI settings epConnectServerButton.Text = "Disconnect from server"; browsePage.Enabled = true; monitoringPage.Enabled = true; myCertForm = null; } else { MessageBox.Show("Please select an endpoint before connecting", "Error"); return; } } catch (Exception ex) { myCertForm = null; ResetUI(); MessageBox.Show(ex.InnerException.Message, "Error"); } } }
/// <summary> /// Global OPC UA event handlers /// </summary> #region OpcEventHandlers private void Notification_ServerCertificate(CertificateValidator cert, CertificateValidationEventArgs e) { //Handle certificate here //To accept a certificate manually move it to the root folder (Start > mmc.exe > add snap-in > certificates) //Or handle via UAClientCertForm if (this.InvokeRequired) { this.BeginInvoke(new CertificateValidationEventHandler(Notification_ServerCertificate), cert, e); return; } try { //Search for the server's certificate in store; if found -> accept X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509CertificateCollection certCol = store.Certificates.Find(X509FindType.FindByThumbprint, e.Certificate.Thumbprint, true); store.Close(); if (certCol.Capacity > 0) { e.Accept = true; } //Show cert dialog if cert hasn't been accepted yet else { if (!e.Accept & myCertForm == null) { myCertForm = new UAClientCertForm(e); myCertForm.ShowDialog(); } } } catch { ; } }