Code examples OPC UA Toolkits

The integration of OPC UA Toolkits is very easy and user-friendly. 
In the following examples will show you the most importent functionality.

You will find other documentations with more code examples in our example application in the downloadpackage or online:

 http://www.demo.plccom.de/help_opcua_toolkit/help/index.html

Discover OPC UA Server

The endpoints provided an OPC UA server can be determined with the command GetDiscoveryUrls.

A simple example when the OPC UA server has registered its endpoints with a Discovery server:
string[] Endpoints = OpcUaClient.GetDiscoveryUrls("127.0.0.1");

or directly determine the endpoints on a server without a discovery server:
string[] Endpoints = OpcUaClient.GetDiscoveryUrls("127.0.0.1", 50520);

Please see the following complete working sample:

  • C#
  • Visual Basic
using PLCcom.Opc.Ua;
using PLCcom.Opc.Ua.Toolkit;
using System;

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        p.Start();
    }

    void Start()
    {
        try
        {
            Console.WriteLine("Start discover discovery server");
            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')");
            string Hostname = Console.ReadLine();
            if (string.IsNullOrEmpty(Hostname))
            {
                Hostname = "localhost";
            }

            Console.WriteLine("setting hostname to " + Hostname);

            Console.WriteLine("please enter the port number (nothing when discover discovery server)");
            string Port = Console.ReadLine();
            int iPort = 4840;
            string[] DiscoveryEndpoints;
            if (int.TryParse(Port, out iPort) && iPort > 0)
            {
                DiscoveryEndpoints = OpcUaClient.GetDiscoveryUrls(Hostname, iPort);
            }
            else
            {
                DiscoveryEndpoints = OpcUaClient.GetDiscoveryUrls(Hostname);
            }

            if (DiscoveryEndpoints.Length > 0)
            {
                Console.WriteLine("Discovery endpoints found:");
                int counter = 0;
                foreach (string Endpoint in DiscoveryEndpoints)
                {
                    Console.WriteLine(counter++.ToString() + " => " + Endpoint);
                }
            }
            else
            {
                Console.WriteLine("no discovery endpoints found");
            }

            Console.WriteLine("End discover discovery server");
            Console.WriteLine();

            Console.WriteLine("Start getting Endports by Opc Ua application");
            Console.WriteLine("please enter the port number from application)");
            Port = Console.ReadLine();
            if (int.TryParse(Port, out iPort) && iPort > 0)
            {
                EndpointDescriptionCollection Endpoints = null;
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort);
                int counter = 0;
                foreach (EndpointDescription Endpoint in Endpoints)
                {
                    Console.WriteLine(counter++.ToString() + " => " + Endpoint.ToString());
                }
            }
            else
            {
                Console.WriteLine("invalid port number");
            }

            Console.WriteLine("End getting Endports from UA Application");

            Console.WriteLine();
            Console.WriteLine("press enter for exit");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("press enter for exit");
            Console.ReadLine();
        }
    }

}
Imports PLCcom.Opc.Ua
Imports PLCcom.Opc.Ua.Toolkit

Module Program
    Sub Main()
        Try
            Console.WriteLine("Start discover discovery server")
            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')")
            Dim Hostname As String = Console.ReadLine()
            If String.IsNullOrEmpty(Hostname) Then
                Hostname = "localhost"
            End If

            Console.WriteLine(Convert.ToString("setting hostname to ") & Hostname)

            Console.WriteLine("please enter the port number (nothing when discover discovery server)")
            Dim Port As String = Console.ReadLine()
            Dim iPort As Integer = 4840
            Dim DiscoveryEndpoints As String()
            If Integer.TryParse(Port, iPort) AndAlso iPort > 0 Then
                DiscoveryEndpoints = OpcUaClient.GetDiscoveryUrls(Hostname, iPort)
            Else
                DiscoveryEndpoints = OpcUaClient.GetDiscoveryUrls(Hostname)
            End If

            If DiscoveryEndpoints.Length > 0 Then
                Console.WriteLine("Discovery endpoints found:")
                Dim counter As Integer = 0
                For Each Endpoint As String In DiscoveryEndpoints
                    Console.WriteLine(Convert.ToString(System.Math.Max(System.Threading.Interlocked.Increment(counter), counter - 1).ToString() + " => ") & Endpoint)
                Next
            Else
                Console.WriteLine("no discovery endpoints found")
            End If

            Console.WriteLine("End discover discovery server")
            Console.WriteLine()

            Console.WriteLine("Start getting Endports by Opc Ua application")
            Console.WriteLine("please enter the port number from application)")
            Port = Console.ReadLine()
            If Integer.TryParse(Port, iPort) AndAlso iPort > 0 Then
                Dim Endpoints As EndpointDescriptionCollection = Nothing
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort)
                Dim counter As Integer = 0
                For Each Endpoint As EndpointDescription In Endpoints
                    Console.WriteLine(System.Math.Max(System.Threading.Interlocked.Increment(counter), counter - 1).ToString() + " => " + Endpoint.ToString())
                Next
            Else
                Console.WriteLine("invalid port number")
            End If

            Console.WriteLine("End getting Endports from UA Application")

            Console.WriteLine()
            Console.WriteLine("press enter for exit")
            Console.ReadLine()
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.WriteLine("press enter for exit")
            Console.ReadLine()
        End Try
    End Sub
End Module

Example: Discover OPC UA Server

Connect to endpoint

 

Connecting an OPC UA server can be performed automatically or manually.

By default, a client automatically connects to the server when a connection is required. The reconnect after a connection break also takes place automatically.

The behavior can be set using the AutoConnect property of the client object.

DataAccessClient client = new DataAccessClient("<Enter your UserName here>", "<Enter your Serial here>", sessionConfiguration, false);
oder
client.AutoConnect = false;

Please see the following complete working sample:

  • C#
  • Visual Basic
using PLCcom.Opc.Ua.Toolkit;
using System;
using PLCcom.Opc.Ua.Client;
using PLCcom.Opc.Ua;

class Program
{
    static void Main(string[] args)
    {
        Program program = new Program();
        program.Start();
    }
    void Start()
    {
        try
        {
            //TODO
            //Submit your license information from your license e-mail
            //Note: with invalid license information the client will be disconnected after 15 minutes
            string LicenseUserName = "<Enter your UserName here>";
            string LicenseSerial = "<Enter your Serial here>";


            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')");
            string Hostname = Console.ReadLine();
            if (string.IsNullOrEmpty(Hostname))
            {
                Hostname = "localhost";
                Console.WriteLine("localhost");
            }

            Console.WriteLine("please enter the port number (nothing when discover discovery server)");
            string Port = Console.ReadLine();
            Console.WriteLine("");
            int iPort = 4840;

            EndpointDescriptionCollection Endpoints = null;
            if (int.TryParse(Port, out iPort) && iPort > 0)
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort);
            }
            else
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname);
            }

            if (Endpoints.Count > 0)
            {
                Console.WriteLine("endpoints found:");
                int counter = 0;
                foreach (EndpointDescription Endpoint in Endpoints)
                {
                    Console.WriteLine(counter++.ToString() + " => " + Endpoint.ToString());
                }

                Console.WriteLine("please enter index of desired endpoint");
                string NumberOfEndpoint = Console.ReadLine();
                int iNumberOfEndpoint = -1;
                if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count)
                {
                    //create a a SessionConfiguration with the selected endpoint and application name
                    SessionConfiguration sessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, 
                                                                                            Endpoints[iNumberOfEndpoint]);

                    //output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath);

                    //Create a new opc client instance and pass your license information
                    DataAccessClient client = new DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration, false);
                    Console.WriteLine("Info: license state => " + client.GetLicenceMessage());

                    //register events
                    client.ServerConnectionLost += Client_ServerConnectionLost;
                    client.ServerConnected += Client_ServerConnected;
                    client.InternalSubscription_StateChanged += InternalSubscription_StateChanged;
                    client.KeepAlive += Client_KeepAlive;
                    try
                    {
                        //connect client
                        client.AutoConnect = false;
                        client.ConnectSession();
                        Console.WriteLine(client.GetSessionState().ToString());

                        Console.WriteLine();
                        Console.WriteLine("press enter for exit");
                        Console.ReadLine();
                        return;
                    }
                    finally
                    {
                        if (client.GetSessionState() == SessionState.Connected) client.DisconnectSession();
                    }

                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("invalid number of Endpoint");
                }
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("no endpoints found");
            }

            Console.WriteLine();
            Console.WriteLine("press enter for exit");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("press enter for exit");
            Console.ReadLine();
        }

    }
    private void InternalSubscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " State of InternalSubscription changed to => " + e.Status.ToString());
    }

    private void Client_ServerConnected(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected");
    }

    private void Client_ServerConnectionLost(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost");
    }

    void Client_KeepAlive(Session session, KeepAliveEventArgs e)
    {
        //catch the keepalive event
    }
}
Imports PLCcom.Opc.Ua.Toolkit
Imports PLCcom.Opc.Ua.Client
Imports PLCcom.Opc.Ua

Module Program
    Sub Main()
        Try

            'TODO
            'Submit your license information from your license e-mail
            'Note: with invalid license information the client will be disconnected after 15 minutes
            Dim LicenseUserName As String = "<Enter your UserName here>"
            Dim LicenseSerial As String = "<Enter your Serial here>"

            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')")
            Dim Hostname As String = Console.ReadLine()
            If String.IsNullOrEmpty(Hostname) Then
                Hostname = "localhost"
                Console.WriteLine("localhost")
            End If

            Console.WriteLine("please enter the port number (nothing when discover discovery server)")
            Dim Port As String = Console.ReadLine()
            Console.WriteLine("")
            Dim iPort As Integer = 4840

            Dim Endpoints As EndpointDescriptionCollection = Nothing
            If Integer.TryParse(Port, iPort) AndAlso iPort > 0 Then
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort)
            Else
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname)
            End If

            If Endpoints.Count > 0 Then
                Console.WriteLine("endpoints found:")
                Dim counter As Integer = 0
                For Each Endpoint As EndpointDescription In Endpoints
                    Console.WriteLine(counter.ToString() & " => " & Endpoint.ToString)
                    counter += 1
                Next

                Console.WriteLine("please enter index of desired endpoint")
                Dim NumberOfEndpoint As String = Console.ReadLine()
                Console.WriteLine("")

                Dim iNumberOfEndpoint As Integer = -1
                If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then
                    'create a a SessionConfiguration with the selected endpoint and application name
                    Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint))

                    'output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath)

                    'Create a New opc client instance and pass your license information
                    Dim client As New DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration, False)
                    Console.WriteLine("Info: license state => " & client.GetLicenceMessage())

                    'register events
                    AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost
                    AddHandler client.ServerConnected, AddressOf Client_ServerConnected
                    AddHandler client.InternalSubscription_StateChanged, AddressOf InternalSubscription_StateChanged
                    AddHandler client.KeepAlive, AddressOf Client_KeepAlive

                    Try
                        'connect client
                        client.ConnectSession()

                        Console.WriteLine(client.GetSessionState().ToString())
                        Console.WriteLine()
                        Console.WriteLine("press enter for exit")
                        Console.ReadLine()
                    Finally
                        If Not IsNothing(client) AndAlso client.GetSessionState().Equals(SessionState.Connected) Then
                            client.DisconnectSession()
                        End If
                    End Try
                Else
                    Console.WriteLine("invalid number of Endpoint")
                    Console.WriteLine("press enter for exit")
                    Console.ReadLine()
                End If
            Else
                Console.WriteLine("no endpoints found")
                Console.WriteLine("press enter for exit")
                Console.ReadLine()
            End If
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.WriteLine("press enter for exit")
            Console.ReadLine()
        End Try

    End Sub
    Private Sub InternalSubscription_StateChanged(subscription As Subscription, e As SubscriptionStateChangedEventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " State of InternalSubscription changed to => " & e.Status.ToString())
    End Sub

    Private Sub Client_ServerConnected(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connected")
    End Sub

    Private Sub Client_ServerConnectionLost(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connection lost")
    End Sub

    Private Sub Client_KeepAlive(session As Session, e As KeepAliveEventArgs)
        'catch the keepalive event
    End Sub
End Module

Example: Connect to endpoint

Browse nodes

The nodes of an OPC UA server can be browsed with the "Browse" command.

Simple Example:
ReferenceDescription rd = client.Browse("Objects.Server.Data.Static") ;

Please see the following complete working sample:

  • C#
  • Visual Basic
using PLCcom.Opc.Ua;
using PLCcom.Opc.Ua.Toolkit;
using System;
using PLCcom.Opc.Ua.Client;

class Program
{

    static void Main(string[] args)
    {
        Program program = new Program();
        program.Start();
    }
    void Start()
    {
        try
        {

            //TODO
            //Submit your license information from your license e-mail
            //Note: with invalid license information the client will be disconnected after 15 minutes
            string LicenseUserName = "<Enter your UserName here>";
            string LicenseSerial = "<Enter your Serial here>";

            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')");
            string Hostname = Console.ReadLine();
            if (string.IsNullOrEmpty(Hostname))
            {
                Hostname = "localhost";
                Console.WriteLine("localhost");
            }
            Console.WriteLine("please enter the port number (nothing when discover discovery server)");
            string Port = Console.ReadLine();
            Console.WriteLine("");
            int iPort = 4840;

            EndpointDescriptionCollection Endpoints = null;
            if (int.TryParse(Port, out iPort) && iPort > 0)
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort);
            }
            else
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname);
            }

            if (Endpoints.Count > 0)
            {
                Console.WriteLine("endpoints found:");
                int counter = 0;
                foreach (EndpointDescription Endpoint in Endpoints)
                {
                    Console.WriteLine(counter++.ToString() + " => " + Endpoint);
                }

                Console.WriteLine("please enter index of desired endpoint");
                string NumberOfEndpoint = Console.ReadLine();
                Console.WriteLine("");
                int iNumberOfEndpoint = -1;
                if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count)
                {
                    //create a a SessionConfiguration with the selected endpoint and application name
                    SessionConfiguration sessionConfiguration =  SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name,
                                                                                            Endpoints[iNumberOfEndpoint]);

                    //output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath);

                    //Create a new opc client instance and pass your license information
                    using (DataAccessClient client = new DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration))
                    {
                        Console.WriteLine("Info: license state => " + client.GetLicenceMessage());

                        //register events
                        client.ServerConnectionLost += Client_ServerConnectionLost;
                        client.ServerConnected += Client_ServerConnected;
                        client.InternalSubscription_StateChanged += InternalSubscription_StateChanged;
                        client.KeepAlive += Client_KeepAlive;

                        string browsePath = string.Empty;
                        do
                        {
                            Console.WriteLine("");
                            Console.WriteLine("please enter browse path (nothing for root or 'exit' for exit program)");
                            browsePath = Console.ReadLine();
                            if (!browsePath.ToUpper().Equals("EXIT"))
                            {
                                try
                                {
                                    //Browse the server
                                    foreach (ReferenceDescription rd in client.Browse(browsePath))
                                    {
                                        Console.WriteLine("Child NodeID found => " + rd.NodeId + " " +
                                            rd.DisplayName.ToString() + " NodeClass => " + rd.NodeClass.ToString() +
                                            " FullPath => " + client.GetPathFromNodeId(rd.NodeId)[0]);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);
                                }
                            }
                        }
                        while (!browsePath.ToUpper().Equals("EXIT"));
                    }
                }
                else
                {
                    Console.WriteLine("invalid number of Endpoint");
                    Console.WriteLine();
                    Console.WriteLine("press enter for exit");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("no endpoints found");
                Console.WriteLine();
                Console.WriteLine("press enter for exit");
                Console.ReadLine();
            }


        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("press enter for exit");
            Console.ReadLine();
        }

    }

    private void InternalSubscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " State of InternalSubscription changed to => " + e.Status.ToString());
    }

    private void Client_ServerConnected(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected");
    }

    private void Client_ServerConnectionLost(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost");
    }

    void Client_KeepAlive(Session session, KeepAliveEventArgs e)
    {
        //catch the keepalive event
    }

}
Imports PLCcom.Opc.Ua
Imports PLCcom.Opc.Ua.Client
Imports PLCcom.Opc.Ua.Toolkit

Module Program

#Region "private member"
    Private client As DataAccessClient = Nothing
#End Region

    Sub Main()
        Try

            'TODO
            'Submit your license information from your license e-mail
            'Note: with invalid license information the client will be disconnected after 15 minutes
            Dim LicenseUserName As String = "<Enter your UserName here>"
            Dim LicenseSerial As String = "<Enter your Serial here>"

            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')")
            Dim Hostname As String = Console.ReadLine()
            If String.IsNullOrEmpty(Hostname) Then
                Hostname = "localhost"
                Console.WriteLine("localhost")
            End If
            Console.WriteLine("please enter the port number (nothing when discover discovery server)")
            Dim Port As String = Console.ReadLine()
            Console.WriteLine("")
            Dim iPort As Integer = 4840

            Dim Endpoints As EndpointDescriptionCollection = Nothing
            If Integer.TryParse(Port, iPort) AndAlso iPort > 0 Then
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort)
            Else
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname)
            End If

            If Endpoints.Count > 0 Then
                Console.WriteLine("endpoints found:")
                Dim counter As Integer = 0
                For Each Endpoint As EndpointDescription In Endpoints
                    Console.WriteLine(counter.ToString() & " => " & Endpoint.ToString)
                    counter += 1
                Next

                Console.WriteLine("please enter index of desired endpoint")
                Dim NumberOfEndpoint As String = Console.ReadLine()
                Console.WriteLine("")

                Dim iNumberOfEndpoint As Integer = -1
                If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then
                    'create a a SessionConfiguration with the selected endpoint and application name
                    Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint))

                    'output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath)

                    'Create a New opc client instance and pass your license information
                    client = New DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration)
                    Console.WriteLine("Info: license state => " & client.GetLicenceMessage())

                    'register events
                    AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost
                    AddHandler client.ServerConnected, AddressOf Client_ServerConnected
                    AddHandler client.InternalSubscription_StateChanged, AddressOf InternalSubscription_StateChanged
                    AddHandler client.KeepAlive, AddressOf Client_KeepAlive

                    Console.WriteLine(client.GetSessionState().ToString())
                    Console.WriteLine()

                    Dim browsePath As String = String.Empty
                    Do

                        Console.WriteLine("please enter browse path (nothing for root or 'exit' for exit program)")
                        browsePath = Console.ReadLine()
                        If Not browsePath.ToUpper().Equals("EXIT") Then
                            Try
                                For Each rd As ReferenceDescription In client.Browse(browsePath)
                                    Console.WriteLine(("Child NodeID found => " & rd.NodeId.ToString() & " " & rd.DisplayName.ToString() & " NodeClass => " & rd.NodeClass.ToString() & " FullPath => ") + client.GetPathFromNodeId(rd.NodeId)(0))
                                Next
                            Catch ex As Exception
                                Console.WriteLine(ex.Message)
                            End Try
                        End If
                    Loop While Not browsePath.ToUpper().Equals("EXIT")
                Else
                    Console.WriteLine("invalid number of Endpoint")
                    Console.WriteLine()
                    Console.WriteLine("press enter for exit")
                    Console.ReadLine()
                End If
            Else
                Console.WriteLine("no endpoints found")
                Console.WriteLine()
                Console.WriteLine("press enter for exit")
                Console.ReadLine()


            End If
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.WriteLine("press enter for exit")
            Console.ReadLine()
        Finally
            If Not IsNothing(client) AndAlso client.GetSessionState().Equals(SessionState.Connected) Then
                client.DisconnectSession()
            End If
        End Try

    End Sub

    Private Sub InternalSubscription_StateChanged(subscription As Subscription, e As SubscriptionStateChangedEventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " State of InternalSubscription changed to => " & e.Status.ToString())
    End Sub

    Private Sub Client_ServerConnected(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connected")
    End Sub

    Private Sub Client_ServerConnectionLost(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connection lost")
    End Sub

    Private Sub Client_KeepAlive(session As Session, e As KeepAliveEventArgs)
        'catch the keepalive event
    End Sub
End Module

Example: Browse nodes

Read or write values

Reading or writing of values can take place either via the NodeId or directly over the complete name / path of the node:

Example for reading a node:
DataValue value = client.ReadValue("Objects.Server.Data.Static.Scalar.Int64Value");

Example for writing the value 123 to a node:
StatusCode sc = client.Write("Objects.Server.Data.Static.Scalar.Int64Value",123);

Please see the following complete working sample:

  • C#
  • Visual Basic
using System;
using PLCcom.Opc.Ua.Toolkit;
using PLCcom.Opc.Ua.Client;
using PLCcom.Opc.Ua;

class Program
{

    static void Main(string[] args)
    {
        Program program = new Program();
        program.Start();
    }
    void Start()
    {
        try
        {
            //TODO
            //Submit your license information from your license e-mail
            //Note: with invalid license information the client will be disconnected after 15 minutes
            string LicenseUserName = "<Enter your UserName here>";
            string LicenseSerial = "<Enter your Serial here>";

            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')");
            string Hostname = Console.ReadLine();
            if (string.IsNullOrEmpty(Hostname))
            {
                Hostname = "localhost";
                Console.WriteLine("localhost");
            }
            Console.WriteLine("please enter the port number (nothing when discover discovery server)");
            string Port = Console.ReadLine();
            Console.WriteLine("");
            int iPort = 4840;

            EndpointDescriptionCollection Endpoints = null;
            if (int.TryParse(Port, out iPort) && iPort > 0)
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort);
            }
            else
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname);
            }

            if (Endpoints.Count > 0)
            {
                Console.WriteLine("endpoints found:");
                int counter = 0;
                foreach (EndpointDescription Endpoint in Endpoints)
                {
                    Console.WriteLine(counter++.ToString() + " => " + Endpoint);
                }

                Console.WriteLine("please enter index of desired endpoint");
                string NumberOfEndpoint = Console.ReadLine();
                Console.WriteLine("");
                int iNumberOfEndpoint = -1;
                if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count)
                {
                    //create a a SessionConfiguration with the selected endpoint and application name
                    SessionConfiguration sessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name,
                                                                                          Endpoints[iNumberOfEndpoint]);

                    //output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath);

                    //Create a new opc client instance and pass your license information
                    using (DataAccessClient client = new DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration))
                    {
                        Console.WriteLine("Info: license state => " + client.GetLicenceMessage());
                        Console.WriteLine("");

                        //register events
                        client.ServerConnectionLost += Client_ServerConnectionLost;
                        client.ServerConnected += Client_ServerConnected;
                        client.InternalSubscription_StateChanged += InternalSubscription_StateChanged;
                        client.KeepAlive += Client_KeepAlive;

                        string browsePath = string.Empty;
                        string mode = string.Empty;
                        do
                        {
                            Console.WriteLine("please enter 'r' for read or 'w' for write or return for exit");
                            mode = Console.ReadLine();
                            if (string.IsNullOrEmpty(mode)) break;
                            try
                            {
                                switch (mode.ToLower())
                                {
                                    case "r":
                                        Console.WriteLine("please enter browse path (e.g. 'Objects.Server.Data.Static.Scalar.Int64Value')");
                                        browsePath = Console.ReadLine();
                                        if (!string.IsNullOrEmpty(browsePath)) Console.WriteLine(browsePath + " Value => " + client.ReadValue(browsePath));
                                        break;
                                    case "w":
                                        Console.WriteLine("please enter browse path (e.g. 'Objects.Server.Data.Static.Scalar.Int64Value') ");
                                        browsePath = Console.ReadLine();
                                        if (!string.IsNullOrEmpty(browsePath))
                                        {
                                            Console.WriteLine("please input value for writing");
                                            string value = Console.ReadLine();
                                            Console.WriteLine(browsePath + " Result => " + client.Write(browsePath, value));
                                        }
                                        break;
                                    default:
                                        Console.WriteLine("unknown command " + mode);
                                        break;
                                }
                                Console.WriteLine();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        }
                        while (!string.IsNullOrEmpty(mode));
                    }
                }
                else
                {
                    Console.WriteLine("invalid number of Endpoint");
                    Console.WriteLine();
                    Console.WriteLine("press enter for exit");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("no endpoints found");
                Console.WriteLine();
                Console.WriteLine("press enter for exit");
                Console.ReadLine();
            }


        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("press enter for exit");
            Console.ReadLine();
        }

    }

    private void InternalSubscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " State of InternalSubscription changed to => " + e.Status.ToString());
    }

    private void Client_ServerConnected(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected");
    }

    private void Client_ServerConnectionLost(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost");
    }

    void Client_KeepAlive(Session session, KeepAliveEventArgs e)
    {
        //catch the keepalive event
    }

}
Imports PLCcom.Opc.Ua.Toolkit
Imports PLCcom.Opc.Ua.Client
Imports PLCcom.Opc.Ua

Module Program

    Sub Main()
        Try

            'TODO
            'Submit your license information from your license e-mail
            'Note: with invalid license information the client will be disconnected after 15 minutes
            Dim LicenseUserName As String = "<Enter your UserName here>"
            Dim LicenseSerial As String = "<Enter your Serial here>"

            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')")
            Dim Hostname As String = Console.ReadLine()
            If String.IsNullOrEmpty(Hostname) Then
                Hostname = "localhost"
                Console.WriteLine("localhost")
            End If
            Console.WriteLine("please enter the port number (nothing when discover discovery server)")
            Dim Port As String = Console.ReadLine()
            Console.WriteLine("")
            Dim iPort As Integer = 4840

            Dim Endpoints As EndpointDescriptionCollection = Nothing
            If Integer.TryParse(Port, iPort) AndAlso iPort > 0 Then
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort)
            Else
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname)
            End If

            If Endpoints.Count > 0 Then
                Console.WriteLine("endpoints found:")
                Dim counter As Integer = 0
                For Each Endpoint As EndpointDescription In Endpoints
                    Console.WriteLine(counter.ToString() & " => " & Endpoint.ToString)
                    counter += 1
                Next

                Console.WriteLine("please enter index of desired endpoint")
                Dim NumberOfEndpoint As String = Console.ReadLine()
                Console.WriteLine("")

                Dim iNumberOfEndpoint As Integer = -1
                If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then
                    'create a a SessionConfiguration with the selected endpoint and application name
                    Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint))

                    'output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath)

                    'Create a New opc client instance and pass your license information
                    Using client As New DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration)
                        Console.WriteLine("Info: license state => " & client.GetLicenceMessage())
                        Console.WriteLine("")

                        'register events
                        AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost
                        AddHandler client.ServerConnected, AddressOf Client_ServerConnected
                        AddHandler client.InternalSubscription_StateChanged, AddressOf InternalSubscription_StateChanged
                        AddHandler client.KeepAlive, AddressOf Client_KeepAlive

                        Dim browsePath As String = String.Empty
                        Dim mode As String = String.Empty
                        Do
                            Console.WriteLine("please enter 'r' for read or 'w' for write or return for exit")
                            mode = Console.ReadLine()
                            If String.IsNullOrEmpty(mode) Then
                                Exit Do
                            End If
                            Try
                                Select Case mode.ToLower()
                                    Case "r"
                                        Console.WriteLine("please enter browse path (e.g. 'Objects.Server.Data.Static.Scalar.Int64Value')")
                                        browsePath = Console.ReadLine()
                                        If Not String.IsNullOrEmpty(browsePath) Then
                                            Console.WriteLine(browsePath & " Value => " & client.ReadValue(browsePath).ToString())
                                        End If
                                        Exit Select
                                    Case "w"
                                        Console.WriteLine("please enter browse path (e.g. 'Objects.Server.Data.Static.Scalar.Int64Value') ")
                                        browsePath = Console.ReadLine()
                                        If Not String.IsNullOrEmpty(browsePath) Then
                                            Console.WriteLine("please input value for writing")
                                            Dim value As String = Console.ReadLine()
                                            Console.WriteLine(browsePath & " Result => " & client.Write(browsePath, value).ToString())
                                        End If
                                        Exit Select
                                    Case Else
                                        Console.WriteLine("unknown command " & mode)
                                        Exit Select

                                End Select
                                Console.WriteLine()
                            Catch ex As Exception
                                Console.WriteLine(ex.Message)
                            End Try
                        Loop While Not String.IsNullOrEmpty(mode)
                    End Using

                Else
                    Console.WriteLine("invalid number of Endpoint")
                    Console.WriteLine()
                    Console.WriteLine("press enter for exit")
                    Console.ReadLine()
                End If
            Else
                Console.WriteLine("no endpoints found")
                Console.WriteLine()
                Console.WriteLine("press enter for exit")
                Console.ReadLine()


            End If
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.WriteLine("press enter for exit")
            Console.ReadLine()
        End Try

    End Sub


    Private Sub InternalSubscription_StateChanged(subscription As Subscription, e As SubscriptionStateChangedEventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " State of InternalSubscription changed to => " & e.Status.ToString())
    End Sub

    Private Sub Client_ServerConnected(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connected")
    End Sub

    Private Sub Client_ServerConnectionLost(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connection lost")
    End Sub

    Private Sub Client_KeepAlive(session As Session, e As KeepAliveEventArgs)
        'catch the keepalive event
    End Sub

End Module

Example: Read or write values

Monitoring items

The monitoring of items can be done either via the NodeId or directly over the complete name / path of the node:

Beispiel:
...
//create and register monitoring item
client.StartMonitoringItem("Objects.Server.Data.Dynamic.Scalar.Int64Value", Client_MonitorNotification);
...

//catch the monitoring event
private void Client_MonitorNotification(string Identifier, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
{
MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
Console.WriteLine(Identifier + " " + monitoredItem.StartNodeId + " Value: " + notification.Value + " Status: " + notification.Value.StatusCode.ToString());
}
 
Please see the following complete working sample:
  • C#
  • Visual Basic
using System;
using PLCcom.Opc.Ua;
using PLCcom.Opc.Ua.Client;
using PLCcom.Opc.Ua.Toolkit;

class Program
{
    static void Main(string[] args)
    {
        Program program = new Program();
        program.Start();
    }
    void Start()
    {
        try
        {
            //TODO
            //Submit your license information from your license e-mail
            //Note: with invalid license information the client will be disconnected after 15 minutes
            string LicenseUserName = "<Enter your UserName here>";
            string LicenseSerial = "<Enter your Serial here>";

            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')");
            string Hostname = Console.ReadLine();
            if (string.IsNullOrEmpty(Hostname))
            {
                Hostname = "localhost";
                Console.WriteLine("localhost");
            }
            Console.WriteLine("please enter the port number (nothing when discover discovery server)");
            string Port = Console.ReadLine();
            Console.WriteLine("");
            int iPort = 4840;

            EndpointDescriptionCollection Endpoints = null;
            if (int.TryParse(Port, out iPort) && iPort > 0)
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort);
            }
            else
            {
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname);
            }


            if (Endpoints.Count > 0)
            {
                Console.WriteLine("endpoints found:");
                int counter = 0;
                foreach (EndpointDescription Endpoint in Endpoints)
                {
                    Console.WriteLine(counter++.ToString() + " => " + Endpoint);
                }

                Console.WriteLine("please enter index of desired endpoint");
                string NumberOfEndpoint = Console.ReadLine();
                Console.WriteLine("");

                int iNumberOfEndpoint = -1;
                if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count)
                {
                    //create a a SessionConfiguration with the selected endpoint and application name
                    SessionConfiguration sessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name,
                                                                                         Endpoints[iNumberOfEndpoint]);

                    //output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath);

                    //Create a new opc client instance and pass your license information
                    using (DataAccessClient client = new DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration))
                    {
                        Console.WriteLine("Info: license state => " + client.GetLicenceMessage());
                        Console.WriteLine("");

                        //register events
                        client.ServerConnectionLost += Client_ServerConnectionLost;
                        client.ServerConnected += Client_ServerConnected;
                        client.InternalSubscription_StateChanged += InternalSubscription_StateChanged;
                        client.KeepAlive += Client_KeepAlive;
                        client.ConnectSession();

                        string browsePath = string.Empty;

                        Console.WriteLine("please enter browse path (e.g. 'Objects.Topics.S7_1500.DataBlocks.Datenbaustein_3.dword12_bitleiste') or return for exit");
                        browsePath = Console.ReadLine();
                        if (!string.IsNullOrEmpty(browsePath))
                        {
                            try
                            {
                                client.StartMonitoringItem(browsePath, Client_MonitorNotification);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        }

                        Console.WriteLine();
                        Console.WriteLine("press enter for exit");
                        Console.ReadLine();
                    }
                }
                else
                {
                    Console.WriteLine("invalid number of Endpoint");

                }
            }
            else
            {
                Console.WriteLine("no endpoints found");
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("press enter for exit");
            Console.ReadLine();
        }
    }

    private void Client_MonitorNotification(string Identifier,
                                            MonitoredItem monitoredItem,
                                            MonitoredItemNotificationEventArgs e)
    {
        MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
        Console.WriteLine(Identifier + " " + monitoredItem.StartNodeId + " Value: " + notification.Value + " Status: " + notification.Value.StatusCode.ToString());
    }

    private void InternalSubscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " State of InternalSubscription changed to => " + e.Status.ToString());
    }

    private void Client_ServerConnected(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected");
    }

    private void Client_ServerConnectionLost(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost");
    }

    void Client_KeepAlive(Session session, KeepAliveEventArgs e)
    {
        //catch the keepalive event
    }

}
Imports PLCcom.Opc.Ua
Imports PLCcom.Opc.Ua.Client
Imports PLCcom.Opc.Ua.Toolkit

Module Program

#Region "private member"
    Private client As DataAccessClient = Nothing
#End Region

    Sub Main()
        Try

            'TODO
            'Submit your license information from your license e-mail
            'Note: with invalid license information the client will be disconnected after 15 minutes
            Dim LicenseUserName As String = "<Enter your UserName here>"
            Dim LicenseSerial As String = "<Enter your Serial here>"

            Console.WriteLine("please enter the IP address or hostname (nothing for 'localhost')")
            Dim Hostname As String = Console.ReadLine()
            If String.IsNullOrEmpty(Hostname) Then
                Hostname = "localhost"
                Console.WriteLine("localhost")
            End If
            Console.WriteLine("please enter the port number (nothing when discover discovery server)")
            Dim Port As String = Console.ReadLine()
            Console.WriteLine("")
            Dim iPort As Integer = 4840

            Dim Endpoints As EndpointDescriptionCollection = Nothing
            If Integer.TryParse(Port, iPort) AndAlso iPort > 0 Then
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname, iPort)
            Else
                Endpoints = OpcUaClient.GetAllEndpoints(Hostname)
            End If

            If Endpoints.Count > 0 Then
                Console.WriteLine("endpoints found:")
                Dim counter As Integer = 0
                For Each Endpoint As EndpointDescription In Endpoints
                    Console.WriteLine(counter.ToString() & " => " & Endpoint.ToString)
                    counter += 1
                Next

                Console.WriteLine("please enter index of desired endpoint")
                Dim NumberOfEndpoint As String = Console.ReadLine()
                Console.WriteLine("")

                Dim iNumberOfEndpoint As Integer = -1
                If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then
                    'create a a SessionConfiguration with the selected endpoint and application name
                    Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint))

                    'output certificate store path
                    Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath)

                    'Create a New opc client instance and pass your license information
                    Using client As New DataAccessClient(LicenseUserName, LicenseSerial, sessionConfiguration)

                        Console.WriteLine("Info: license state => " & client.GetLicenceMessage())
                        Console.WriteLine("")

                        'register events
                        AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost
                        AddHandler client.ServerConnected, AddressOf Client_ServerConnected
                        AddHandler client.InternalSubscription_StateChanged, AddressOf InternalSubscription_StateChanged
                        AddHandler client.KeepAlive, AddressOf Client_KeepAlive

                        Dim browsePath As String = String.Empty

                        Console.WriteLine("please enter browse path (e.g. 'Objects.Server.Data.Dynamic.Scalar.Int64Value') or return for exit")
                        browsePath = Console.ReadLine()
                        If Not String.IsNullOrEmpty(browsePath) Then
                            Try
                                client.StartMonitoringItem(browsePath, AddressOf Client_MonitorNotification)
                            Catch ex As Exception
                                Console.WriteLine(ex.Message)
                            End Try
                        End If

                        Console.WriteLine()
                        Console.WriteLine("press enter for exit")
                        Console.ReadLine()
                    End Using
                Else

                    Console.WriteLine("invalid number of Endpoint")
                End If
            Else
                Console.WriteLine("no endpoints found")
            End If

        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.WriteLine("press enter for exit")
            Console.ReadLine()
        Finally
            If Not IsNothing(client) AndAlso client.GetSessionState().Equals(SessionState.Connected) Then
                client.DisconnectSession()
            End If
        End Try

    End Sub

    Private Sub Client_MonitorNotification(Identifier As String, monitoredItem As MonitoredItem, e As MonitoredItemNotificationEventArgs)
        Dim notification As MonitoredItemNotification = TryCast(e.NotificationValue, MonitoredItemNotification)
        Console.WriteLine((Identifier & " " & Convert.ToString(monitoredItem.StartNodeId).ToString() & " Value: ") + notification.Value.ToString() & " Status: " & notification.Value.StatusCode.ToString())
    End Sub

    Private Sub InternalSubscription_StateChanged(subscription As Subscription, e As SubscriptionStateChangedEventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " State of InternalSubscription changed to => " & e.Status.ToString())
    End Sub

    Private Sub Client_ServerConnected(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connected")
    End Sub

    Private Sub Client_ServerConnectionLost(sender As Object, e As EventArgs)
        Console.WriteLine(DateTime.Now.ToLocalTime() & " Session connection lost")
    End Sub

    Private Sub Client_KeepAlive(session As Session, e As KeepAliveEventArgs)
        'catch the keepalive event
    End Sub

End Module

Example: Monitoring items