Clientace Manual
Clientace Manual
Table of Contents
1
User Manual 1
Table of Contents 2
Contents 5
Overview 5
Runtime Requirements 7
EndPointIdentifier Class 8
PkiCertificate Class 9
toDER Method 10
fromDER Method 11
toWindowsStore Method 12
toWindowsStoreWithPrivateKey Method 14
fromWindowsStore Method 15
fromWindowsStoreWithPrivateKey Method 18
ServerIdentifier Class 20
ServerCategory Enumeration 21
WinStoreLocation Enumeration 21
OpcServerEnum Object 21
ClsidFromProgID Method 22
EnumComServer Method 23
getCertificateForEndpoint Method 25
getEndpoints Method 27
Kepware.ClientAce.OpcDaClient Namespace 28
BrowseElement Class 29
ConnectInfo Class 29
DaServerMgt Class 32
ItemIdentifier Class 32
ItemResultCallback Class 33
ItemProperty Class 33
ItemValue Class 33
ItemValueCallback Class 34
QualityID Class 35
ResultID Class 36
UserIdentityToken Class 38
www. ptc.com
3 ClientAce
UserIdentityTokenCertificate Class 39
UserIdentityTokenIssuedToken Class 39
UserIdentityTokenUserPassword Class 39
BrowseFilter Enumeration 39
Property ID Enumeration 39
ServerState Enumeration 41
ReturnCode Enumeration 41
UserTokenType Enumeration 41
DaServerMgt Object 42
AccessRights Enumerated Values 42
DataChanged Event 43
ReadCompleted Event 45
ServerStateChanged Event 48
WriteCompleted Event 49
Browse Method 51
Connect Method 56
Disconnect Method 60
Get Properties Method 60
Read Method 62
ReadAsync Method 68
Subscribe Method 71
SubscriptionModify Method 74
SubscriptionAddItems Method 76
SubscriptionCancel Method 78
SubscriptionRemoveItems Method 79
Write Method 81
WriteAsync Method 86
IsConnected Property 88
ServerState Property 88
ClientAceDA_Junction 89
Project Setup 91
DA Junction Configuration Window 91
A Sample Project Using DA Junction with VB.NET or C# 96
Item Update Rate 106
Disabling DataChange While the Control Has Focus 108
www. ptc.com
ClientAce 4
Troubleshooting 144
CoInitializeSecurity 144
Removing Blank Toolbar Options after Uninstalling ClientAce (VS 2005) 156
Appendix 158
Index 162
www. ptc.com
5 ClientAce
Contents
Overview
System and Application Requirements
ClientAce .NET API Assembly
ClientAceDA_Junction
Additional Controls
Data Types Description
Applying ClientAce
Troubleshooting
Appendix
ClientAce and KEPServerEX are trademarks of Kepware Technologies. Other company and product names
mentioned herein are the trademarks or registered trademarks of their respective owners.
Overview
ClientAce provides tools to help developers easily build an OPC client application. ClientAce consists of two
main parts: the .NET Application Programming Interface (API) and the DA Junction. Descriptions of the parts
are as follows:
l ClientAce .NET API: The ClientAce .NET API provides C# and Visual Basic .NET language users with a
simple, intuitive, and optimized class library to quickly develop OPC client applications for accessing
OPC servers. For more information, refer to ClientAce .NET API Assembly.
l ClientAceDA Junction: The ClientAce DA Junction is a customized .NET control that enables Visual
Basic .NET or C# programmers to develop OPC client applications that can access a variety of OPC
servers. No detailed knowledge of OPC Data Access (DA) interfaces is required. The DA Junction will
perform the connection handling procedure between the custom client application and the OPC
server, and will monitor and reconnect when necessary. For more information, refer to ClientAceDA_
Junction.
Note: When building advanced custom OPC client applications that require more control over OPC
functionality, the ClientAce .NET API is recommended.
Additional Controls
For more information on other controls that can be used in the Visual Studio Environment, refer to Additional
Controls.
www. ptc.com
ClientAce 6
Hardware Requirements
100 MB available disk space is required. For additional hardware requirements, refer to the Microsoft .NET
Framework documentation of the version that will be used in the Visual Studio project.
l Visual Studio 2003 with the .NET 2.0 Framework (ClientAce Version 1.0)
l Visual Studio 2005 with the .NET 2.0 Framework (ClientAce Version 1.0)
l Visual Studio 2008 SP1 with the .NET 3.5 Framework (ClientAce Version 3.5)
l Visual Studio 2010 with the .NET 4.0/4.5 Framework (ClientAce Version 4.0)
l Visual Studio 2012 with the .NET 4.0/4.5 Framework (ClientAce Version 4.0)
l Visual Studio 2013 with the .NET 4.0/4.5 Framework (ClientAce Version 4.0)
For the installation to complete, the following Visual Studio Environment Settings are required:
Notes:
2. Only Windows Applications (EXEs) can be signed. If DLLs are created, the application must be signed.
The user running the sign process must have permissions to modify the application being signed."
l OPC DA 2.0
l OPC DA 2.05A
l OPC DA 3.0
l OPC Unified Architecture (UA)*
l OPC XML-DA
*ClientAce currently supports OPC UA for use with the OPC DA information model.
Note: Other OPC specifications are not supported at this time.
www. ptc.com
7 ClientAce
Runtime Requirements
.NET Framework Requirements
When deploying the custom client applications created using ClientAce, the .NET Framework requirements
depend on the version of Visual Studio that was used for development. For more information, refer to
Deploying Your Client Application.
www. ptc.com
ClientAce 8
l A simple, intuitive .NET interface that does not require knowledge of the different OPC DA, UA, and
XML-DA interfaces.
l An API that covers the different OPC base technologies (such as COM and DCOM). It also manages
the connection handling to multiple OPC Servers, including connection establishment, connection
monitoring, and reconnection after errors.
l Simple development of OPC Client applications with C# or Visual Basic .NET.
l Conversion of OPC data from different OPC DA, UA, and XML-DA interfaces into .NET data types.
l Fast searching for both local and remote OPC COM servers.
l High performance and optimized client/server communication through kernel functionality
(implemented in C++).
EndPointIdentifier Class
OPC UA servers require more connection information than traditional OPC servers do, especially for
secured connections. The EndPointIdentifer Class specifies secured connection information, such as server
certificates, the security policy, and the message security mode used for UA communication. Its values may
be entered manually or obtained through the OpcServerEnum.EnumComServer Method when a UA
discovery server is used or the OpcServerEnum.getEndpoints Method when receiving connection
information directly from the endpoint.
Data
Property Description
Type
ApplicationName String The name of the application.
ApplicationUri String The URI of the application.
The mode of method security. Possible message security mode values
are as follows:
MessageSecurityMode Byte
None = 1
Sign = 2
SignAndEncrypt = 3
ProductUri String The product URI.
The URI of the security policy. Valid policy URI strings used for UA
communications are as follows:
SecurityPolicyUri String
http://opcfoundation.org/UA/SecurityPolicy#None
http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15
http://opcfoundation.org/UA/SecurityPolicy#Basic256
ServerCertificate Byte[] The server certificate.
This class is similar to ServerIdentifer. For more information, refer to ServerIdentifier Class.
www. ptc.com
9 ClientAce
PkiCertificate Class
New Class Constructor With Eleven Overloads
New(
URI As String,
HostIP As String,
DNS As String,
timeValid As Integer,
commonName As String,
organization As String,
organizationUnit As String,
locality As String,
state As String,
country As String,
keyStrength as Integer
)
Properties
The PkiCertificate Class allows the creation and encapsulation of an X509 certificate, and provides methods
for loading and saving certificates through the WindowsCertificateStore. Once constructed, the certificate's
properties are Read Only.
Example Code
[Visual Basic]
' Declare our Pki Certificate
Dim clientCertificate As Kepware.ClientAce.OpcCmn.PkiCertificate
' Create a new Pki Certificate with constructor
clientCertificate = New Kepware.ClientAce.OpcCmn.PkiCertificate( _
"OPCUA Sample Application:Kepware:OpcUaSampleApplication", _
www. ptc.com
ClientAce 10
"127.0.0.1", _
"", _
31536000, _
"CERT_TEST", _
"Kepware Technologies", _
"Development", _
"Portland", _
"Maine", _
"United States", _
1028)
' If a problem occurred we will receive a null certificate
if IsNothing(clientCertificate) Then
MsgBox("A problem occurred when attempting to create a certificate")
End If
[C#]
// Create a new Pki Certificate with constructor
PkiCertificate clientCert = new Kepware.ClientAce.OpcCmn.PkiCertificate(
"OPCUA Sample Application:Kepware:OpcUaSampleApplication",
"127.0.0.1",
"",
31536000,
"CERT_TEST",
"Kepware Technologies",
"Development",
"Portland",
"Maine",
"United States",
1028);
// If a problem occurred we will receive a null certificate
if (clientCert == null)
{
MessageBox.Show("A problem occurred when attempting to create a certificate");
}
toDER Method
Method
toDER() As/Returns Byte()
Properties
This method outputs a DER-encoded byte array that contains the PkiCertificate. This format is used in the
EndpointIndentifier and ConnectInfo classes.
Example Code
[Visual Basic]
' Declare our Application URI needed to search for the certificate
Dim URI As String = "OPCUA Sample Application:Kepware:OpcUaSampleApplication"
www. ptc.com
11 ClientAce
[C#]
// Declare our Application URI needed to search for the certificate
String URI = "OPCUA Sample Application:Kepware:OpcUaSampleApplication";
// Declare our ConnectInfo object
Kepware.ClientAce.OpcDaClient.ConnectInfo connectInfo = null;
// Declare our certificate
Kepware.ClientAce.OpcCmn.PkiCertificate clientCertificate = null;
// Grab our certificate with private key from the Windows Certificate Store
clientCertificate =
Kepware.ClientAce.OpcCmn.PkiCertificate.fromWindowsStoreWithPrivateKey
(Kepware.ClientAce.OpcCmn.WinStoreLocation.LocalMachine,
"UA Applications",
URI);
// Use the toDER method to pass the certificate to the connectInfo object
connectInfo.ClientCertificate = clientCertificate.toDER();
fromDER Method
Method
fromDER(
DERdata as byte()
) As/Returns Kepware.ClientAce.OpcCmn.PkiCertificate
Properties
This static method creates a PkiCertificate object from a DER-encoded byte array that contains a certificate.
If the fromDER Method fails, a certificate that contains properties as null strings will be returned.
Example Code
[Visual Basic]
' Our DER encoded byte array containing our certificate
www. ptc.com
ClientAce 12
[C#]
// Our DER encoded byte array containing our certificate
Byte[] DERdata;
// Creating a PKI Certificate from our DER encoded byte array
Kepware.ClientAce.OpcCmn.PkiCertificate certificate;
certificate = Kepware.ClientAce.OpcCmn.PkiCertificate.fromDER(DERdata);
toWindowsStore Method
Method
toWindowsStore(
WindowsCertificateStore as Kepware.ClientAce.OpcCmn.WinStoreLocation,
storeName as String
)
Properties
This method exports the PkiCertificate to the WindowsCertificateStore without the Private Key.
Note: When a secure UA connection is needed, the Private Key must be supplied to the ConnectInfo
Object.
Note: Additional permissions and/or configuration may be necessary when specifying a Windows Store
Location besides "Current User" and "Local Computer".
Example Code
[Visual Basic]
www. ptc.com
13 ClientAce
[C#]
// Create a certificate
Kepware.ClientAce.OpcCmn.PkiCertificate clientCertificate =
new Kepware.ClientAce.OpcCmn.PkiCertificate(
"OPCUA Sample Application:Kepware:OpcUaSampleApplication",
"127.0.0.1",
"",
31536000,
"ClientAce UA Sample Application",
"Kepware Technologies",
"Development",
"Portland",
"Maine",
"United States",
1028);
// Specify a Windows Store location
Kepware.ClientAce.OpcCmn.WinStoreLocation
winStoreLocation = Kepware.ClientAce.OpcCmn.WinStoreLocation.CurrentUser;
// Specify a store name. Most UA applications will use the "UA Applications" location.
string storeName = "UA Applications";
// Export Certificate to the Windows Store
clientCertificate.toWindowsStore(winStoreLocation, storeName);
www. ptc.com
ClientAce 14
toWindowsStoreWithPrivateKey Method
Method
toWindowsStoreWithPrivateKey(
WindowsCertificateStore as Kepware.ClientAce.OpcCmn.WinStoreLocation,
storeName as String
)
Properties
This method exports the PkiCertificate (including the Private Key) to the WindowsCertificateStore.
Note: Additional permissions and/or configuration may be necessary when specifying a Windows Store
Location besides "Current User" and "Local Computer".
Example Code
[Visual Basic]
' Create a certificate
Dim clientCertificate As New Kepware.ClientAce.OpcCmn.PkiCertificate( _
"OPCUA Sample Application:Kepware:OpcUaSampleApplication", _
"127.0.0.1", _
"", _
31536000, _
"ClientAce UA Sample Application", _
"Kepware Technologies", _
"Development", _
"Portland", _
www. ptc.com
15 ClientAce
"Maine", _
"United States", _
1028)
' Specify a Windows Store Location
Dim winStoreLocation As Kepware.ClientAce.OpcCmn.WinStoreLocation = _
Kepware.ClientAce.OpcCmn.WinStoreLocation.CurrentUser
' Specify a store name. Most UA applications will use the "UA Applications" location.
Dim storeName As String = "UA Applications"
' Export Certificate to the Windows Store
clientCertificate.toWindowsStoreWithPrivateKey(winStoreLocation, storeName)
[C#]
// Create a certificate
Kepware.ClientAce.OpcCmn.PkiCertificate clientCertificate =
new Kepware.ClientAce.OpcCmn.PkiCertificate(
"OPCUA Sample Application:Kepware:OpcUaSampleApplication",
"127.0.0.1",
"",
31536000,
"ClientAce UA Sample Application",
"Kepware Technologies",
"Development",
"Portland",
"Maine",
"United States",
1028);
// Specify a Windows Store location
Kepware.ClientAce.OpcCmn.WinStoreLocation
winStoreLocation = Kepware.ClientAce.OpcCmn.WinStoreLocation.CurrentUser;
// Specify a store name. Most UA applications will use the "UA Applications" location.
string storeName = "UA Applications";
// Export Certificate to the Windows Store
clientCertificate.toWindowsStoreWithPrivateKey (winStoreLocation, storeName);
fromWindowsStore Method
Method
fromWindowsStore(
winStoreLocation as Kepware.ClientAce.OpcCmn.WinStoreLocation,
storeName as String,
thumbprint as Byte[]
) As/returns Kepware.ClientAce.OpcCmn.PkiCertificate
Properties
www. ptc.com
ClientAce 16
This method retrieves a certificate from a specific location within the Windows Certificate Store by
referencing its thumbprint.
Note: When a secure UA connection is needed, the Private Key must be supplied to the ConnectInfo
Object. The fromWindowsStoreWithPrivateKey Method is recommended when there are no other private key
storage/retrieval methods being used within the client application. For more information, refer to
fromWindowsStoreWithPrivateKey Method.
Example Code
[Visual Basic]
Private Function RetrieveCertificateFromStore(ByRef thumbprint() As Byte)
' Declare a certificate for our return value
Dim certificate As Kepware.ClientAce.OpcCmn.PkiCertificate
' Specify a Windows Store Location
Dim winStoreLocation As Kepware.ClientAce.OpcCmn.WinStoreLocation = _
Kepware.ClientAce.OpcCmn.WinStoreLocation.CurrentUser
www. ptc.com
17 ClientAce
' Specify a store name. Most UA applications will use the "UA Applications" location.
Dim storeName As String = "UA Applications"
Try
' Retrieve the certificate form the windows store
certificate = Kepware.ClientAce.OpcCmn.PkiCertificate.fromWindowsStore( _
winStoreLocation, _
storeName, _
thumbprint)
' Return the certificate from the function
Return certificate
Catch ex As Exception
MsgBox("A handled exception was caught when attempting to retrieve the certificate Form the
WindowsFormsSection store: " _
& ex.ToString())
' If an exception occurred, return nothing
Return Nothing
End Try
End Function
[C#]
private PkiCertificate retrieveCertificateFromStore(byte[] thumbprint)
{
// Declare a certificate for our return value
PkiCertificate certificate;
// Specify a Windows Store location
Kepware.ClientAce.OpcCmn.WinStoreLocation
winStoreLocation = Kepware.ClientAce.OpcCmn.WinStoreLocation.CurrentUser;
// Specify a store name. Most UA applications will use the "UA Applications" location.
string storeName = "UA Applications";
try
{
// Retrieve the certificate form the windows store
certificate = PkiCertificate.fromWindowsStore(winStoreLocation,
storeName,
thumbprint);
// Return the certificate
return certificate;
}
catch (Exception ex)
{
MessageBox.Show("A handled exception was caught when attempting to retrieve the certificate
Form the WindowsFormsSection store: "
+ ex.ToString());
// If an exception occurred, return null
return null;
}
}
www. ptc.com
ClientAce 18
fromWindowsStoreWithPrivateKey Method
Method One
fromWindowsStoreWithPrivateKey(
winStoreLocation as Kepware.ClientAce.OpcCmn.WinStoreLocation,
storeName as String,
thumbprint as Byte[]
) As/returns Kepware.ClientAce.OpcCmn.PkiCertificate
Method Two
fromWindowsStoreWithPrivateKey(
winStoreLocation as Kepware.ClientAce.OpcCmn.WinStoreLocation,
storeName as String,
applicationURI as String
) As/returns Kepware.ClientAce.OpcCmn.PkiCertificate
Properties
This method retrieves a certificate with the private key from a specific location within the Windows
Certificate Store by referencing the certificate's thumbprint or application URI.
www. ptc.com
19 ClientAce
within the
Windows MMC
Certificate
snap-in.
If desired, a
string that
contains the
application URI
can be used
applicationURI Input-2 String instead of the
thumbprint to
retrieve the
certificate from
the Windows
store.
Example Code
[Visual Basic]
Private Function RetrieveCertificateFromStore(ByRef thumbprint() As Byte)
' Declare a certificate for our return value
Dim certificate As Kepware.ClientAce.OpcCmn.PkiCertificate
' Specify a Windows Store Location
Dim winStoreLocation As Kepware.ClientAce.OpcCmn.WinStoreLocation = _
Kepware.ClientAce.OpcCmn.WinStoreLocation.CurrentUser
' Specify a store name. Most UA applications will use the "UA Applications" location.
Dim storeName As String = "UA Applications"
Try
' Retrieve the certificate form the windows store
certificate = Kepware.ClientAce.OpcCmn.PkiCertificate.fromWindowsStoreWithPrivateKey ( _
winStoreLocation, _
storeName, _
thumbprint)
' Return the certificate from the function
Return certificate
Catch ex As Exception
MsgBox("A handled exception was caught when attempting to retrieve the certificate Form the
WindowsFormsSection store: " _
& ex.ToString())
' If an exception occurred, return nothing
Return Nothing
End Try
End Function
[C#]
private PkiCertificate retrieveCertificateFromStore(byte[] thumbprint)
{
// Declare a certificate for our return value
PkiCertificate certificate;
www. ptc.com
ClientAce 20
ServerIdentifier Class
The ServerIdentifier class is used to instance the server identifiers that are used by the DAServerObject for
OPC connections.
Properties
www. ptc.com
21 ClientAce
ServerIdentifier objects are returned by the EnumComServers Method and contain information that
describe the OPC servers installed on the specified machine.
ServerCategory Enumeration
The ServerCategory enumerator is used to specify the type of OPC server.
Note: Because OPC XML-DA servers are not registered like COM OPC servers, they cannot be found using
the OpcServerEnum object. To connect to an OPC XML-DA server, the URL must be known.
WinStoreLocation Enumeration
The WinStoreLocation enumerator is an enumerated object that specifies WinStoreLocation values.
OpcServerEnum Object
The Kepware.ClientAce.OpcCmn.OpcServerEnum object enumerates the OPC servers installed on a given
machine. It also determines the CLSID from an OPC server's ProgID.
www. ptc.com
ClientAce 22
[Visual Basic]
Dim opcServerEnum As New Kepware.ClientAce.OpcCmn.OpcServerEnum
[C#]
OpcServerEnum opcServerEnum = new
Kepware.ClientAce.OpcCmn.OpcServerEnum ();
ClsidFromProgID Method
Method
ClsidFromProgId (
ByVal nodeName As String,
ByVal progID As String,
ByRef clsid As String
)
Properties
The ClsidFromProgID Method is used to obtain an OPC server's Class ID from its Program ID. The server's
host machine must be accessible from the client.
Example Code
[Visual Basic]
' Declare variables
Dim opcServerEnum As Kepware.ClientAce.OpcCmn.OpcServerEnum = Nothing
Dim nodeName As String = "localhost"
Dim progId As String = "KEPware.KEPServerEx.V5"
Dim clsid As String = Nothing
Try
' Call ClsidFromProgId API method
opcServerEnum.ClsidFromProgId(nodeName, progId, clsid)
' Handle result
Console.WriteLine("CLSID: " & clsid)
Catch ex As Exception
Console.WriteLine("ClsidFromProgID exception. Reason: " & _
ex.Message)
www. ptc.com
23 ClientAce
End Try
[C#]
// Declare variables
OpcServerEnum opcEnum = new OpcServerEnum();
string nodeName = "localhost";
string progId = "KEPware.KEPServerEx.V5";
string clsid;
try
{
// Call ClsidFromProgId API method
opcEnum.ClsidFromProgId(nodeName, progId, out clsid);
// Handle result
Console.WriteLine("CLSID: {0}", clsid);
}
catch (Exception ex)
{
Console.WriteLine("ClsidFromProgId exception. Reason: {0}", ex);
}
EnumComServer Method
Method
EnumComServer (
ByVal nodeName As String,
ByVal returnAllServers As Boolean,
ByVal serverCategories() As Kepware.ClientAce.OpcCmn.ServerCategory,
ByRef servers() As Kepware.ClientAce.OpcCmn.ServerIdentifier
)
Properties
The EnumComServer Method is used to determine the OPC servers that are accessible to a ClientAce
application. These servers can exist on the same computer as the client application, or on any machine
accessible on the network. The results can be filtered according to OPC server category. For more
information, refer to ServerCategory Enumeration.
www. ptc.com
ClientAce 24
Example Code
These examples browse for all OPCDA servers installed on localhost.
[ Visual Basic]
' Declare parameters
Dim opcEnum As Kepware.ClientAce.OpcCmn.OpcServerEnum = Nothing
Dim nodeName As String = "localhost"
Dim returnAllServers As Boolean = False
Dim serverCatagories(0) As Kepware.ClientAce.OpcCmn.ServerCategory
serverCatagories(0) = New Kepware.ClientAce.OpcCmn.ServerCategory
serverCatagories(0) = Kepware.ClientAce.OpcCmn.ServerCategory.OPCDA
Dim servers() As Kepware.ClientAce.OpcCmn.ServerIdentifier = Nothing
Try
' Call EnumComServer API method
opcEnum.EnumComServer( _
nodeName, _
returnAllServers, _
serverCatagories, _
servers)
' Handle results
Dim server As Kepware.ClientAce.OpcCmn.ServerIdentifier
For Each server In servers
Dim progID As String = server.ProgID
Dim url As String = server.Url
Console.WriteLine("ProgID: " & progID & " url: " & url)
Next
Catch ex As Exception
Console.WriteLine("Handled EnumComServer exception. Reason: " _
& ex.Message)
End Try
[C#]
// Declare parameters
string nodeName = "localhost";
bool returnAllServers = false;
OpcServerEnum opcEnum = new OpcServerEnum();
ServerCategory[] serverCategories = new ServerCategory[1];
serverCategories[0] = new ServerCategory();
serverCategories[0] = ServerCategory.OPCDA;
ServerIdentifier[] servers;
try
{
// Call EnumComServer API method
opcEnum.EnumComServer(nodeName, returnAllServers, serverCategories, out servers);
// Handle results
foreach (ServerIdentifier server in servers)
{
string progID = server.ProgID;
www. ptc.com
25 ClientAce
getCertificateForEndpoint Method
Method
getCertificateForEndpoint( _
endpointUrl As String, _
securityPolicyUri As String, _
messageSecurityMode As Byte, _
ByRef serverCertificate() As Byte _
)
Properties
The getCertificateForEndpoint Method retrieves the certificates for a specified OPC UA Server EndPoint.
Data
Parameter Use Description
Type
endpointUrl Input String The URL of the Endpoint.
The URI of the security policy. Valid policy URI strings used
for UA communications are as follows:
Example Code
[VB]
' Create a new OPC Server Enum object to call the getCertificateForEndpoint method
Dim opcEnum As Kepware.ClientAce.OpcCmn.OpcServerEnum = _
New Kepware.ClientAce.OpcCmn.OpcServerEnum
' Specify a server endpoint
Dim endpointURL As String = "opc.tcp://localhost:49320"
' Specify a security policy URI
www. ptc.com
ClientAce 26
[C#]
// Create a new OPC Server Enum object to call the getCertificateForEndpoint method
Kepware.ClientAce.OpcCmn.OpcServerEnum opcEnum =
new Kepware.ClientAce.OpcCmn.OpcServerEnum();
// Specify a server endpoint
string endpointURL = "opc.tcp://localhost:49320";
// specify a security policy URI
string securityPolicyURI = "http://opcfoundation.org/UA/SecurityPolicy#None";
// Specify a message security mode
byte messageSecurityMode = 1;
// Create a byte array which will contain our returned certificate
byte[] serverCertificate;
try
{
// Make the method call
opcEnum.getCertificateForEndpoint(endpointURL,
securityPolicyURI,
messageSecurityMode,
out serverCertificate);
}
catch(Exception ex)
{
MessageBox.Show("An error occurred when attempting to retrieve the certificate from the
following endpoint: "
+ endpointURL
+ ex.ToString());
}
www. ptc.com
27 ClientAce
getEndpoints Method
Method
getEndpoints(
discoveryURL as string,
endpoints() as Kepware.ClientAce.OpcCmn.EndpointIdentifier
)
Properties
The getEndpoints Method is used to retrieve connection information from an OPC UA server when an OPC
UA Discovery Server is not installed on the remote machine. Because port numbers can vary widely,
searching for OPC UA endpoints may be very communication-intensive. As such, it should not be done using
standard server enumeration methods like EnumComServer(). If an OPC Discovery Server is installed and
running on the remote machine, the EnumComServer Method will return any OPC servers residing on the
remote machine, including all OPC UA endpoints. Otherwise, the getEndpoints Method will allow the client to
retrieve UA-specific connection information.
Note: When using the getEndpoints Method, the Endpoint URL must contain the OPC UA server's full
address, including the port number. For example, "opc.tcp://[IP Address]:[Port]" and
"opc.tcp://localhost:49320".
Example Code
The examples below show how to retrieve pertinent connection information for a remote OPC UA server.
[Visual Basic]
'Declare our serverEnum object instance
Dim opcServerEnum As New Kepware.ClientAce.OpcCmn.OpcServerEnum()
'Create an array of endpoint identifiers for our return values
Dim endpoints(0) As Kepware.ClientAce.OpcCmn.EndpointIdentifier
endpoints(0) = New Kepware.ClientAce.OpcCmn.EndpointIdentifier()
'Specify a valid OPC UA endpoint URL
Dim discoveryURL As String = "opc.tcp://localhost:49320"
Try
'Make the method call
opcServerEnum.getEndpoints(discoveryURL, endpoints)
Catch ex As Exception
MsgBox("An error occurred when attempting to retrieve endpoint information" _
& ex.ToString())
End Try
[C#]
//Declare our serverEnum object instance
Kepware.ClientAce.OpcCmn.OpcServerEnum opcServerEnum =
www. ptc.com
ClientAce 28
new Kepware.ClientAce.OpcCmn.OpcServerEnum();
//Create an array of endpoint identifiers for our return values
Kepware.ClientAce.OpcCmn.EndpointIdentifier[] endpoints =
new Kepware.ClientAce.OpcCmn.EndpointIdentifier[0];
//Specify a valid OPC UA endpoint URL
string discoveryURL = "opc.tcp://localhost:49320";
try
{
//Make the method call
opcServerEnum.getEndpoints(discoveryURL, out endpoints);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(
"An error occurred when attempting to retrieve endpoint information" +
ex.ToString());
}
Kepware.ClientAce.OpcDaClient Namespace
The DaServerMgt Object provides the following features in the Kepware.ClientAce.OpcDaClient namespace:
l OPC Server Connection: The Connect Method is used to connect to the OPC Server; the Disconnect
Method is used to release the connection. Because the connection is monitored by ClientAce, the
client will be notified of any changes in connection status through ServerStateChanged Events.
l Data Change Notification: To avoid cyclic reading, ClientAce API provides tools that notify the client
of changes in values. Items can be registered for monitoring through the Subscribe Method,
subscriptions can be canceled through the SubscriptionCancel Method, and notifications of changed
values are made by the DataChanged Event.
Note: Items can be added or removed from a subscription at any time through the
SubscriptionAddItems and SubscriptionRemoveItems Methods. Subscription properties can also be
changed at any time through the SubscriptionModify Method.
l OPC Data Access Items Read / Write: The OPC items' values can be changed using the
asynchronous WriteAsync and synchronous Write Methods. When subscription is not appropriate, the
values can be obtained through the asynchronous ReadAsync and synchronous Read Methods.
l Information on the Address Space: The address space Browse Method can be used to search for
OPC items. The GetProperties Method can be used to obtain the properties of OPC items.
BrowseElement Class
ConnectInfo Class
DaServerMgt Class
ItemIdentifier Class
ItemResultCallback Class
ItemProperty Class
ItemValue Class
ItemValueCallback Class
QualityID Class
www. ptc.com
29 ClientAce
ResultID Class
UserIdentityToken Class
UserIdentityTokenCertificate Class
UserIdentityTokenIssuedToken Class
UserIdentityTokenUserPassword Class
BrowseFilter Enumeration
Property ID Enumeration
ServerState Enumeration
ReturnCode Enumeration
UserTokenType Enumeration
BrowseElement Class
The BrowseElement Class contains all the information that was obtained by using the Browse method.
ConnectInfo Class
Constructor
ConnectInfo(
localID As String,
retryInitialConnection As Boolean,
retryAfterConnectionError As Boolean,
keepAliveTime As Integer
)
Properties
A ConnectInfo object is used to pass connection related options to the API. This information determines how
the API will monitor and maintain connections, and will also provide language-dependent strings.
www. ptc.com
ClientAce 30
www. ptc.com
31 ClientAce
http://opcfoundation.org/UA/SecurityPolicy#None
SecurityPolicyURI Sting http://opcfoundation.org/UA/SecurityPolicy#Basic12-
8Rsa15
http://opcfoundation.org/UA/SecurityPolicy#Basic25-
6
ServerCertificate Byte[] The server's certificate.
The timeout used for each UA Service call. This is
the amount of time the UA interface waits for a
UACallTimeout Integer
response from the server. Default is 10000
milliseconds.
UserTokenTyp- This defines the type of user authentication for the
UserIdentity
e connection.**
*The DefaultNamespaceUri for KEPServerEX version 5 is "KEPServerEX". The Namespace URIs can be found
within the Server Namespace Array when browsing the server's address space.
**For more information, refer to UserTokenType Enumeration.
www. ptc.com
ClientAce 32
Note: Changes in the connection status should be monitored using a ServerStateChanged event handler.
Connect is the only method in the DaServerMgt namespace that can be called prior to establishing a
connection. This can be tested at any time with the IsConnected Property.
DaServerMgt Class
The DaServerMgt Class allows access to an OPC Data Access Server. For a more information on the
ClientAce API and its methods, refer to DaServerMgt Object.
ItemIdentifier Class
The ItemIdentifier Class is a required parameter of the following methods:
l GetProperties
l Read
l ReadAsync
l Subscribe
l SubscriptionAddItems
l SubscriptionRemoveItems
l Write
l WriteAsync
ItemIdentifier objects are used to identify OPC items within a server. These objects are passed by reference
(in/out) in all method calls so that ClientAce may update the properties described below.
www. ptc.com
33 ClientAce
The API will set this value when the ItemIdentifier is first used. The
ServerHandle Integer API can use the ServerHandle to optimize future calls to the OPC
server.
ItemResultCallback Class
The ItemResultCallback Class is used in the WriteCompleted event.
Data
Property Description
Type
This is the client handle of the item specified in the call to WriteAsync. The
ClientHandle Object client uses this handle to access the appropriate storage object for the
received data.
The class ResultID provides the error code (int), the name (string) and a
language-dependent description (string) for the item represented by the
ResultID ResultID* ClientHandle. Thus, certain activities can be programmed to react on
occurring errors. It is also possible to display the error on the user interface
(message box).
ItemProperty Class
ItemProperty objects are used to describe a single property of an OPC item.
ItemValue Class
The ItemValue Class contains an OPC item's value, quality, and timestamp. It is used in the following
methods:
l Read: This method takes an array of ItemValue objects as an output parameter. The API will allocate
and fill the array with the requested item values during the read.
www. ptc.com
ClientAce 34
l Write: This method takes an array of ItemValue objects as an input parameter. This array must be
filled with the values that will be written to the items specified in the corresponding array of
ItemIdentifier objects.
l WriteAsync: This method takes an array of ItemValue objects as an input parameter. This array must
be filled with the values that will be written to the items specified in the corresponding array of
ItemIdentifier objects.
Data
Property Description
Type
The OPC quality of the associated Value. The class QualityID provides the
Quality QualityID* quality code (int), the name (string), and the description (string). It is Read Only,
and will be set by the API during reads.
The timestamp of the associated Value. It is Read Only, and will be set by the
Timestamp Date
API during reads.
The value of the item. As an object, it can contain any data type. The value is
Value Object generally the same type as requested by the corresponding ItemIdentifier. If no
type was specified, the value will be provided in its canonical form.
ItemValueCallback Class
ItemValueCallback is derived from the ItemValue Class and is used in DataChanged and ReadCompleted
events.
Data
Property Description
Type
The client handle of the item specified in the call to Subscribe or ReadAsync.
ClientHandle Object The client uses this handle to access the appropriate storage object for the
received data.
The quality associated with the value when it was acquired from the data
source. The class QualityID provides the quality code (int), the name (string),
Quality QualityID*
and the description (string). It is Read Only, and will be set by the API during
reads.
The class ResultID provides the error code (int), the name (string), and a
language-dependent description (string) for the item represented by the
ResultID ResultID** ClientHandle. Certain activity can be programmed to react on eventually
occurring errors. It is also possible to display the error on the user interface
(message box).
The timestamp of the associated Value. It is Read Only, and will be set by the
Timestamp Date
API during reads.
The value of the item. As an object, it can contain any data type. The value is
Value Object generally the same type as requested by the corresponding ItemIdentifier. If
no type was specified, the value will be provided in its canonical form.
www. ptc.com
35 ClientAce
Tip: Quality, Timestamp, and Value are shared from the base class.
QualityID Class
A QualityID object is used to describe the OPC quality of an item's value.
Data
Property Description
Type
Description String The description of the quality code. The language depends on the locale.
FullCode Integer The full code sent by the server.
This property will be True if the value has "good" quality. If False, detailed
IsGood Boolean information about the quality of the value can be determined from the other
properties.
The limit portion of the code sent by the server.*
*For more information on OPC Quality based on the OPC specifications, refer to Deconstructing the
OPC Quality Field.
String Definitions
QualityID.Name QualityID.Code Description
OPC_QUALITY_BAD 0 (0x00) Bad quality. Reason unknown.
Bad quality. Communications have
OPC_QUALITY_COMM_FAILURE 24 (0x18) failed and there is no last known
value.
Bad quality. There is as server
OPC_QUALITY_CONFIG_ERROR 4 (0x04) configuration problem, such as the
item in question has been deleted.
OPC_QUALITY_DEVICE_FAILURE 12 (0x0C) Bad quality. Device failure detected.
Uncertain quality. The returned value
OPC_QUALITY_EGU_EXCEEDED 84 (0x54) is outside the EGU limits defined for
item.
OPC_QUALITY_GOOD 192 (0xC0) Good quality.
Bad quality. Communications have
OPC_QUALITY_LAST_KNOWN 20 (0x14) failed but there is a last known value
available.
Uncertain quality. A data source has
not provided the server with a data
OPC_QUALITY_LAST_USABLE 68 (0x44)
update within the expected time
period. The last known value is
www. ptc.com
ClientAce 36
returned.*
Good quality. The value has been
overridden. This may indicate that an
OPC_QUALITY_LOCAL_OVERRIDE 216 (0xD8) input has been disconnected and
that the returned value has been
manually "forced".
Bad quality. It has been determined
that an input is disconnected, or that
OPC_QUALITY_NOT_CONNECTED 8 (0x08)
no value has been provided by data
source yet.
Bad quality. The item is off scan,
OPC_QUALITY_OUT_OF_SERVICE 28 (0x1C)
locked, or inactive.
Uncertain quality. The value has
either exceeded the sensor's limits
OPC_QUALITY_SENSOR_CAL 80 (0x50) (limit bits should be set to 1 or 2), or
the sensor is out of calibration (limit
bits should be 0).
Bad quality. A sensor failure has
OPC_QUALITY_SENSOR_FAILURE 16 (0x10) been detected. Lth limit bits may
provide additional information.
Uncertain quality. The value is
derived from multiple sources, and
OPC_QUALITY_SUB_NORMAL 88 (0x58)
fewer than the required number are
good.
Uncertain quality. No specific reason
OPC_QUALITY_UNCERTAIN 64 (0x40)
is known.
Bad quality. No value has been
OPC_QUALITY_WAITING_FOR_INITIAL_DATA 32 (0x20)
provided to the server yet.
*This is different from the OPC_QUALITY_LAST_KNOWN quality, which is used when the server is unable to
read a value from a device. In this case, a data source has failed to write a value to the server in an
unsolicited manner.
ResultID Class
ResultID objects are used to describe the result of an operation on an OPC item, such as read, write, and
subscribe. ResultID objects will contain the error code provided by the server, its string representation, and a
description of the error code. Each item will have its own ResultID, because requests that contain multiple
items may succeed for some items and fail for other items.
Data
Property Description
Type
Code Integer The code sent by the server for the particular action.
Description String The description of the error. The language depends on the locale.
Name String The string representation of the code.
www. ptc.com
37 ClientAce
This property will be True if the operation was a success for the item. If the
Succeeded Boolean operation failed, it will be False and the specific reason for that failure can be
determined by examining the other properties.
String Definitions
ResultID.Name ResultID.Code Description
-1073479674 The item's access rights do not allow
OPC_E_BADRIGHTS
(0xC0040006) the operation.
The server cannot convert the data
-1073479676 between the specified format and/or
OPC_E_BADTYPE
(0xC0040004) requested data type and the
canonical data type.
-1073478656 The item's deadband has not been
OPC_E_DEADBANDNOTSET
(0xC0040400) set.
-1073478655 The item does not support
OPC_E_DEADBANDNOTSUPPORTED
(0xC0040401) deadband.
-1073479668
OPC_E_DUPLICATENAME Duplicate name not allowed.
(0xC004000C)
-1073479165 The specified Property ID is not valid
OPC_E_INVALID_PID
(0xC0040203) for the item.
-1073479664 The server's configuration file is an
OPC_E_INVALIDCONFIGFILE
(0xC0040010) invalid format.
-1073478653
OPC_E_INVALIDCONTINUATIONPOINT The continuation point is not valid.
(0xC0040403)
-1073479671
OPC_E_INVALIDFILTER The filter string is not valid.
(0xC0040009)
-1073479679
OPC_E_INVALIDHANDLE The handle value is not valid.
(0xC0040001)
-1073479672 The Item ID does not conform to the
OPC_E_INVALIDITEMID
(0xC0040008) server's syntax.
The server does not support the
-1073478654 buffering of data items that are
OPC_E_NOBUFFERING
(0xC0040402) collected at a faster rate than the
group update rate.
-1073479663 The requested object (such as a
OPC_E_NOTFOUND
(0xC0040011) public group) was not found.
-1073478650 The server does not support the
OPC_E_NOTSUPPORTED
(0xC0040406) writing of quality and/or timestamp.
-1073479675 The requested operation cannot be
OPC_E_PUBLIC
(0xC0040005) done on a public group.
-1073479669
OPC_E_RANGE The value is out of range.
(0xC004000B)
-1073478651 There is no sampling rate set for the
OPC_E_RATENOTSET
(0xC0040405) specified item.
OPC_E_UNKNOWNITEMID -1073479673 The Item ID was refused by the
www. ptc.com
ClientAce 38
(0xC0040007) server.
-1073479670 The item's access path is not known
OPC_E_UNKNOWNPATH
(0xC004000A) to the server.
A value passed to write was
-1073479666
OPC_S_CLAMP accepted, but the output was
(0x0004000E)
clamped.
Not every detected change has been
-1073478652 returned since the server's buffer
OPC_S_DATAQUEUEOVERFLOW
(0xC0040404) reached its limit and had to purge
the oldest data.
The operation cannot be performed
-1073479665
OPC_S_INUSE because the object is being
(0xC004000F)
referenced.
The server does not support the
-1073479667
OPC_S_UNSUPPORTEDRATE requested data rate but will use the
(0xC004000D)
closest available rate.
-2147220991
WIN_CONNECT_E_ADVISELIMIT Advise limit exceeded for this object.
(0x80040201)
-2147220992
WIN_CONNECT_E_NOCONNECTION The client has no callback registered.
(0x80040200)
-2147220990
WIN_CONNECT_E_CANNOTCONNECT The client cannot connect.
(0x80040202)
-2147352571
WIN_DISP_E_TYPEMISMATCH Type mismatch.
(0x80020005)
-2147467259
WIN_E_FAIL Unknown error.
(0x80004005)
-2147024809 An invalid parameter was passed to
WIN_E_INVALIDARG
(0x80070057) a method call.
-2147023170
WIN_RPC_S_CALL_FAILED Remote procedure call failed.
(0x800706BE)
-2147023174 The RPC server is currently not
WIN_RPC_S_SERVER_UNAVAILABLE
(0x800706BA) available.
WIN_S_FALSE 1 (0x00000001) The function was partially successful.
WIN_S_OK 0 (0x00000000) The operation succeeded.
UserIdentityToken Class
This is the base class for the UserIdentity Tokens.
www. ptc.com
39 ClientAce
UserIdentityTokenCertificate Class
The UserIdentityTokenCertificate Class defines the UserIdentityToken that will pass an X509v3 certificate for
User Authentication.
UserIdentityTokenIssuedToken Class
The UserIdentityTokenIssuedToken Class defines the UserIdentityToken for authentication based on a WS-
Security compliant token (such as a Kerberos token).
UserIdentityTokenUserPassword Class
The UserIdentityTokenUserPassword Class defines the user name and password used with User
Authentication.
BrowseFilter Enumeration
The BrowseFilter Enumeration is used to specify the type of child elements returned by the Browse method.
Property ID Enumeration
The values shown below are the enumeration of all the Item Property ID values.
www. ptc.com
ClientAce 40
www. ptc.com
41 ClientAce
ServerState Enumeration
Changes in server connection state (as indicated in ServerStateChanged events) may contain one of the
enumerated values described in the table below.
ReturnCode Enumeration
Most ClientAce API methods will return a code that indicates the operation's level of success. The code may
take one of the enumerated values described in the table below. An exception will be thrown in the event
that the function cannot satisfy the request (due to invalid arguments or unexpected errors).
UserTokenType Enumeration
The UserTokenType Enumeration identifies the type of User Authentication that will be used when
connecting to the server.
www. ptc.com
ClientAce 42
DaServerMgt Object
The DaServerMgt Object is a class that is used to connect to an OPC server to collect and manage its data.
The object supports OPC DA, OPC XML-DA, and OPC UA server connections. For more information on a
specific topic, select a link from the list below.
[Visual Basic]
Dim WithEvents daServerMgt As New Kepware.ClientAce.OpcDaClient.DAServerMgt
[C#]
DaServerMgt daServerMgt = new Kepware.ClientAce.OpcDaClient.DaServerMgt ();
www. ptc.com
43 ClientAce
DataChanged Event
Event
DataChanged(
ByVal clientSubscription As Integer,
ByVal allQualitiesGood As Boolean,
ByVal noErrors As Boolean,
ByVal itemValues() As Kepware.ClientAce.OpcDaClient.ItemValueCallback
) Handles daServerMgt.DataChanged
Properties
A DataChanged Event will occur when the value or quality of one or more items in a subscription changes.
To receive the new item values, implement a DataChanged event handler.
Parameter Functionality
clientSubscription This is the handle given to the subscription when created with the Subscribe method.
This flag will be set True if all values included in the data changed notification have
allQualitiesGood
good quality.
This flag will be set True if there are no item errors (as indicated by the ResultID) in
noErrors the values included in the data changed notification. If this flag is False, all ItemValue.
ResultID objects should be examined to determine which items are in error and why.
This array contains the value, quality, and timestamp that have changed. The
itemValues ItemValue elements also contain ResultID objects that are used to indicate possible
item-specific errors.
BeginInvoke(New
Kepware.ClientAce.OpcDaClient.DaServerMgt.DataChangedEventHandler(AddressOf
DataChanged), New Object() {clientSubscription, allQualitiesGood, noErrors, itemValues})
End Sub
www. ptc.com
ClientAce 44
Note: Users must forward the callback to the main thread of the application when accessing the GUI
directly from the callback. This is recommended even if the application is running in the background.
3. Create a subroutine called "Sub 1" to handles the event. Then, create a subroutine or function called
"Sub 2" that will act on the event by updating fields or controls within a form, storing values in a
cache, and so forth.
6. Finally, within the same BeginInvoke Method, pass an array of objects as the last parameter that
contain the relevant arguments from the event (which will become the parameters of Sub 2) to Sub 2.
Example Code
[Visual Basic]
Try
Dim itemValue As Kepware.ClientAce.OpcDaClient.ItemValueCallback
For Each itemValue In itemValues
If itemValue.ResultID.Succeeded = True Then
Console.WriteLine( _
"Item: " & itemValue.ClientHandle & _
"Value: " & itemValue.Value & _
"Quality: " & itemValue.Quality.Name & _
"Timestamp: " & itemValue.TimeStamp)
Else
Console.WriteLine("Item error")
End If
Next
Catch ex As Exception
www. ptc.com
45 ClientAce
[C#]
private void DataChanged (int clientSubscription, bool allQualitiesGood, bool noErrors,
ItemValueCallback[] itemValues)
{
try
{
foreach (ItemValueCallback itemValue in itemValues)
{
if (itemValue.ResultID.Succeeded)
{
Console.WriteLine(
"Item: {0}
Value: {1},
Quality: {2},
Timestamp: {3}",
itemValue.ClientHandle,
itemValue.Value,
itemValue.Quality.Name,
itemValue.TimeStamp);
}
else
{
Console.WriteLine("Item error");
}
}
}
catch (Exception ex)
{
Console.WriteLine("DataChanged exception. Reason: {0}", ex);
}
}
ReadCompleted Event
Event
[Visual Basic]
ReadCompleted( _
ByVal transactionHandle As Integer, _
ByVal allQualitiesGood As Boolean, _
ByVal noErrors As Boolean, _
ByVal itemValues() As Kepware.ClientAce.OpcDaClient.ItemValueCallback _
) Handles daServerMgt.ReadCompleted
Properties
A ReadCompleted Event will occur when the API has completed an asynchronous read request.
www. ptc.com
ClientAce 46
Parameter Functionality
transactionHandle This is the handle for the read transaction passed to ReadAsync.
This flag will be set True if all values included in the read completed notification have
allQualitiesGood
good quality.
This flag will be set True if there are no item errors (as indicated by the ResultID) in
the values included in the read completed notification. If this flag is False, users
noErrors
should examine all ItemValue.ResultID objects to determine which items are in error
and why.
This array contains the value, quality, and timestamp of the items specified in the
itemValues ReadAsync request. The ItemValue elements also contain ResultID objects that are
used to indicate possible item-specific errors.
BeginInvoke(New
Kepware.ClientAce.OpcDaClient.DaServerMgt.ReadCompletedEventHandler(AddressOf
ReadCompleted), New Object() {transactionHandle, allQualitiesGood, noErrors, itemValues})
End Sub
Note: Users must forward the callback to the main thread of the application when accessing the GUI
directly from the callback. This is recommended even if the application is running in the background.
3. Create a subroutine called "Sub 1" to handles the event. Then, create a subroutine or function called
"Sub 2" that will act on the event by updating fields or controls within a form, storing values in a
cache, and so forth.
www. ptc.com
47 ClientAce
6. Finally, within the same BeginInvoke Method, pass an array of objects as the last parameter that
contain the relevant arguments from the event (which will become the parameters of Sub 2) to Sub 2.
Example Code
[Visual Basic]
Try
Dim itemValue As Kepware.ClientAce.OpcDaClient.ItemValueCallback
For Each itemValue In itemValues
If itemValue.ResultID.Succeeded = True Then Console.WriteLine( _
"Item: " & itemValue.ClientHandle & _
"Value: " & itemValue.Value & _
"Quality: " & itemValue.Quality.Name & _
"Timestamp: " & itemValue.TimeStamp)
Else
Console.WriteLine("Item error")
End If
Next
Catch ex As Exception
Console.WriteLine("ReadCompleted exception. Reason: " & ex.Message)
End Try
[C#]
private void ReadCompleted (int transactionHandle, bool allQualitiesGood, bool noErrors,
ItemValueCallback[] itemValues)
{
try
{
foreach (ItemValueCallback itemValue in itemValues)
{
if (itemValue.ResultID.Succeeded)
{
Console.WriteLine(
"Item: {0}
Value: {1},
Quality: {2},
Timestamp: {3}",
www. ptc.com
ClientAce 48
itemValue.ClientHandle,
itemValue.Value,
itemValue.Quality.Name,
itemValue.TimeStamp);
}
else
{
Console.WriteLine("Item error");
}
}
}
catch (Exception ex)
{
Console.WriteLine("ReadCompleted exception. Reason: {0}", ex);
}
}
ServerStateChanged Event
Event
ServerStateChanged(
ByVal clientHandle As Integer,
ByVal state As Kepware.ClientAce.OpcDaClient.ServerState
) Handles daServerMgt.ServerStateChanged
Properties
A ServerStateChanged Event will occur when the API has detected that the connection state with a server
has changed. To monitor these changes and take appropriate action in response, implement a
ServerStateChanged Event Handler in the client application.
Parameter Functionality
This is the client handle associated with the particular server connection for a state
clientHandle
change notification. This handle is provided by the client though the Connect Method.
state The current status of the connection.*
BeginInvoke(New
Kepware.ClientAce.OpcDaClient.DaServerMgt.ServerStateChangedEventHandler(AddressOf
ServerStateChanged), New Object() {clientHandle, state})
End Sub
www. ptc.com
49 ClientAce
Note: Users must forward the callback to the main thread of the application when accessing the GUI
directly from the callback. This is recommended even if the application is running in the background.
3. Create a subroutine called "Sub 1" to handles the event. Then, create a subroutine or function called
"Sub 2" that will act on the event by updating fields or controls within a form, storing values in a
cache, and so forth.
6. Finally, within the same BeginInvoke Method, pass an array of objects as the last parameter that
contain the relevant arguments from the event (which will become the parameters of Sub 2) to Sub 2.
WriteCompleted Event
Event
WriteCompleted(
ByVal transaction As Integer,
ByVal noErrors As Boolean,
ByVal itemResults() As Kepware.ClientAce.OpcDaClient.ItemResultCallback
) Handles daServerMgt.WriteCompleted
Properties
A WriteCompleted Event will occur when the API has completed an asynchronous write request.
www. ptc.com
ClientAce 50
Parameter Functionality
transaction The handle for the read transaction passed to WriteAsync.
This flag will be set True if there are no item errors (as indicated by the ResultID) in the
items included in the write completed notification. If this flag is False, users should
noErrors
examine all ItemResultCallback. ResultID objects to determine which items are in error
and why.
itemResults This array contains the ClientHandle value and ResultID object for every written item.
BeginInvoke(New
Kepware.ClientAce.OpcDaClient.DaServerMgt.WriteCompletedEventHandler(AddressOf
WriteCompleted), New Object() {transaction, noErrors, itemResults})
End Sub
Users must forward the callback to the main thread of the application when accessing the GUI directly
from the callback. This is recommended even if the application is running in the background.
3. Create a subroutine called "Sub 1" to handles the event. Then, create a subroutine or function called
"Sub 2" that will act on the event by updating fields or controls within a form, storing values in a
cache, and so forth.
www. ptc.com
51 ClientAce
6. Finally, within the same BeginInvoke Method, pass an array of objects as the last parameter that
contain the relevant arguments from the event (which will become the parameters of Sub 2) to Sub 2.
Example Code
[Visual Basic]
Try
Dim result As Kepware.ClientAce.OpcDaClient.ItemResultCallback
For Each result In itemResults
If result.ResultID.Succeeded = False Then
Console.WriteLine("Write failed for item: " & _
result.ClientHandle)
End If
Next
Catch ex As Exception
Console.WriteLine("WriteCompleted exception. Reason: " & ex.Message)
End Try
[C#]
private void WriteCompleted (int transactionHandle, bool noErrors,
ItemResultCallback[] itemResults)
{
try
{
foreach (ItemResultCallback result in itemResults)
{
if (!result.ResultID.Succeeded)
{
Console.WriteLine("Write failed for item: {0}",
result.ClientHandle);
}
}
}
catch (Exception ex)
{
Console.WriteLine("WriteCompleted exception. Reason: {0}", ex);
}
}
Browse Method
Method
Browse (
ByVal itemName As String,
www. ptc.com
ClientAce 52
Properties
The Browse Method is used to search for tags in the address space of an OPC server. The address space is
usually displayed in a tree structure because it is close to the outline of the items and branches of the
internal hierarchical structure of the server itself.
*If an OPC server returns a continuation point, the Browse must be called again with the same parameters
but using the returned Continuation Point to obtain missing child elements of this node.
www. ptc.com
53 ClientAce
Notes:
1. For more information on Return Value: ReturnCode, refer to ReturnCode Enumeration. In the event
that the function cannot satisfy the request due to invalid arguments or unexpected errors, an
exception will be thrown.
2. Before the Browse method is called, its parent DaServerMgt object must be connected to an OPC
server using the Connect method. Otherwise, a null reference exception will be thrown.
Example Code
These examples show how to browse the entire namespace of the connected server using recursive
functions calls. The results are placed in a tree view control named "tvItems".
[Visual Basic]
'Our main class
Public Class Main
'Create server management object
Dim daServerMgt As New Kepware.ClientAce.OpcDaClient.DaServerMgt
Dim tvItems As New System.Windows.Forms.TreeView
Sub MainThread()
' Create root node
tvItems.Nodes.Add("KepServerEx")
Dim rootNode As TreeNode = tvItems.Nodes(0)
'We assume a connection has already taken place with our
'Server Management object and our connection is still valid
' Browse from root
Browse("", rootNode)
End Sub
Private Sub Browse(ByVal branchName As String, ByVal node As TreeNode)
Dim itemName As String
Dim itemPath As String
Dim continuationPoint As String = ""
Dim maxElementsReturned As Integer
Dim browseFilter As Kepware.ClientAce.OpcDaClient.BrowseFilter
Dim propertyIDs() As Integer
Dim returnAllProperties As Boolean
Dim returnPropertyValues As Boolean
Dim browseElements() As Kepware.ClientAce.OpcDaClient.BrowseElement
Dim moreElements As Boolean = True
' Set input parameters
itemName = branchName
itemPath = ""
maxElementsReturned = 0
browseFilter = Kepware.ClientAce.OpcDaClient.BrowseFilter.ALL
propertyIDs = Nothing ' prevent Visual Studio warning
returnAllProperties = True
returnPropertyValues = False
browseElements = Nothing ' prevent Visual Studio warning
www. ptc.com
ClientAce 54
[C#]
//Our Main Class
public class Main
{
//Create our Server Management Object
DaServerMgt daServerMgt = new Kepware.ClientAce.OpcDaClient.DaServerMgt();
www. ptc.com
55 ClientAce
www. ptc.com
ClientAce 56
}
catch (Exception ex)
{
Console.WriteLine("Browse exception. Reason: {0}", ex);
}
}
Connect Method
Method
Connect(
ByVal url As String,
ByVal clientHandle As Integer,
ByRef connectInfo As Kepware.ClientAce.OpcDaClient.ConnectInfo,
ByRef connectFailed As Boolean
)
Properties
The Connect Method establishes a connection with an OPC server.
Tip: The syntax of the URL that uniquely identifies a server must follow
this format (except for OPC XML-DA):
[OpcSpecification]://[Hostname]/[ServerIdentifier]
Note: For OPC DA servers, the API will attempt to connect using the
ClassID first. If the ClassID is not given (or is found to be invalid), the API
will attempt to connect using the ProgID.
OPC DA Example
opcda://localhost/Kepware.KEPServerEX.V5
opcda://127.0.0.1/Kepware.KEPServerEX.V5/{B3AF0BF6-4C0C-4804-A122-
6F3B160F4397}
OPC XML-DA Example
http://127.0.0.1/Kepware/xmldaservice.asp
www. ptc.com
57 ClientAce
OPC UA Example
opc.tcp://127.0.0.1:49320
The client application can specify a handle to uniquely identify a server
ClientHandle Input
connection. The API will return this handle in ServerStateChanged Events.
Additional connection options are specified using the connectInfo
ConnectInfo Input/Output
parameter. For more information, refer to ConnectInfo Class.
This indicates whether the initial connection to the underlying server
ConnectFailed Output
failed. It only applies if the retryConnect flag was set in the connect call.
Example Code
[Visual Basic]
Imports Kepware.ClientAce.OpcDaClient
Module Module1
Sub Main()
' Declare variables
'Create server management object
Dim daServerMgt As New Kepware.ClientAce.OpcDaClient.DaServerMgt
Dim url As String = _
"opcda://localhost/Kepware.KEPServerEX.V5/{B3AF0BF6-4C0C-4804-A122-6F3B160F4397}"
Dim clientHandle As Integer = 1
Dim connectInfo As New Kepware.ClientAce.OpcDaClient.ConnectInfo
connectInfo.LocalId = "en"
connectInfo.KeepAliveTime = 5000
connectInfo.RetryAfterConnectionError = True
connectInfo.RetryInitialConnection = True
connectInfo.ClientName = "Demo ClientAce VB.Net Console Application"
Dim connectFailed As Boolean
Try
' Call Connect API method
daServerMgt.Connect( _
url, _
clientHandle, _
connectInfo, _
connectFailed)
www. ptc.com
ClientAce 58
Catch ex As Exception
Console.WriteLine("Connect exception. Reason: " & ex.Message)
End Try
If daServerMgt.IsConnected Then
daServerMgt.Disconnect()
End If
End Sub
End Module
[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kepware.ClientAce.OpcDaClient;
namespace Simple_CS_Console_Application_VS_2010_13
{
class Program
{
www. ptc.com
59 ClientAce
int clientHandle = 1;
if (connectFailed)
{
Console.WriteLine("Connect failed.");
}
else
{
Console.WriteLine("Connected to Server Succeeded.");
}
}
catch(Exception ex)
{
Console.WriteLine("Connect exception. Reason: {0}", ex);
}
if (DAserver.IsConnected)
{
DAserver.Disconnect();
}
}
}
}
Notes:
www. ptc.com
ClientAce 60
1. The IsConnected property indicates that a client application has successfully called the Connect
method. This does not necessarily indicate whether ClientAce is connected to the server. For
example, this property would remain True after a connection has failed and ClientAce is in the
process of reconnecting. To test the ClientAce to server connection state, use the ServerState
Property. The server connection state may also be monitored by implementing the
ServerStateChanged Event handler.
2. It is highly recommended that client applications wait at least 1 second after disconnecting from a
server before attempting to connect to that server again.
Disconnect Method
Method
Disconnect()
Properties
The Disconnect Method releases the connection to the OPC Server. All subscriptions and resources will be
freed.
Example Code
[Visual Basic]
If daServerMgt.IsConnected = True Then
daServerMgt.Disconnect()
End If
[C#]
if (daServerMgt.IsConnected)
daServerMgt.Disconnect();
Properties
The GetProperties Method is used to obtain the properties of OPC items.
www. ptc.com
61 ClientAce
For more information on Return Value: ReturnCode, refer to ReturnCode Enumeration. In the event that the
function cannot satisfy the request due to invalid arguments or unexpected errors, an exception will be thrown.
Example Code
These examples show how to get the access rights and data type properties of a single item "Channel_
1.Device_1.Tag_1".
[Visual Basic]
' Declare variables
Dim itemIdentifiers(0) As Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0).ItemName = "Channel_1.Device_1.Tag_1"
Dim propertyIDs(1) As Integer
propertyIDs(0) = Kepware.ClientAce.OpcDaClient.PropertyID.ACCESSRIGHTS
propertyIDs(1) = Kepware.ClientAce.OpcDaClient.PropertyID.DATATYPE
Dim returnAllProperties As Boolean = False
Dim returnPropertyValues As Boolean = True
Dim itemProperties() As Kepware.ClientAce.OpcDaClient.ItemProperties
itemProperties = Nothing
Try
' Call GetProperties API method
daServerMgt.GetProperties( _
itemIdentifiers, _
propertyIDs, _
returnAllProperties, _
returnPropertyValues, _
itemProperties)
' Handle results
Dim itemProperty As Kepware.ClientAce.OpcDaClient.ItemProperty
For Each itemProperty In itemProperties(0).RequestedItemProperties
Dim propertyDescription As String = itemProperty.Description()
Dim propertyValue As String = itemProperty.Value.ToString()
Console.WriteLine( _
"Property: " & propertyDescription & _
" Value: " & propertyValue)
Next
Catch ex As Exception
Console.WriteLine("GetProperties exception. Reason: " & ex.Message)
www. ptc.com
ClientAce 62
End Try
[C#]
// Declare variables
ItemIdentifier[] itemIdentifiers = new ItemIdentifier[1];
itemIdentifiers[0] = new ItemIdentifier();
itemIdentifiers[0].ItemName = "Channel_1.Device_1.Tag_1";
int[] propertyIDs = new int[2];
propertyIDs[0] = (int)PropertyID.ACCESSRIGHTS;
propertyIDs[1] = (int)PropertyID.DATATYPE;
bool returnAllProperties = false;
bool returnPropertyValues = true;
ItemProperties[] itemProperties = null;
try
{
// Call GetProperties API method
daServerMgt.GetProperties(ref itemIdentifiers, ref propertyIDs, returnAllProperties,
returnPropertyValues, out itemProperties);
// Handle results
foreach (ItemProperty itemProperty in itemProperties[0].RequestedItemProperties)
{
string propertyDescription = itemProperty.Description;
string propertyValue = itemProperty.Value.ToString();
Console.WriteLine("Property: {0} Value: {1}",
propertyDescription,
propertyValue);
}
}
catch (Exception ex)
{
Console.WriteLine("GetProperties exception. Reason: {0}", ex);
}
Read Method
Method
Read (
ByVal maxAge As Integer,
ByRef itemIdentifiers() As Kepware.ClientAce.OpcDaClient.ItemIdentifier,
ByRef itemValues () As Kepware.ClientAce.OpcDaClient.ItemValue
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The Read Method is used to read one or more values from the OPC server. It is strongly recommended that
a Subscription be used if the items are read cyclically (and the changed data is received in the DataChanged
Event).
www. ptc.com
63 ClientAce
Note: The Read Method allows more than one item to be read at a time. Because single multi-item writes
can be executed more efficiently than a series of single-item writes, using multi-item writes is recommended
whenever it is possible.
itemIdentifiers Input/Output The API will also set the ServerHandle property. It is
recommended that ItemIdentifier objects be stored if repeated
reads and writes of the same items are intended. The API will
make use of the ServerHandle values to optimize OPC calls to
the server.
The array itemValues contains Value, Quality, and Timestamp
itemValues Output
for each item.
Notes:
1. The return code indicates the overall success of the call. If this code indicates an item-specific error
(such as ITEMERROR, QUALITYNOTGOOD, or ITEMANDQUALITYERROR), each of the ReturnID objects
should be examined to determine which items could not be read and why. In the event that the
function cannot satisfy the request (due to invalid arguments or unexpected errors), an exception will
be thrown. For more information on Return Value:ReturnCode, refer to ReturnCode Enumeration.
Example Code
This example reads two items: "Channel_1.Device_1.Tag_1" and "Channel_1.Device_1.Tag_2".
[Visual BAsic]
www. ptc.com
ClientAce 64
Imports Kepware.ClientAce.OpcDaClient
Module Module1
Sub Main()
' Declare variables
'Create server management object
Dim daServerMgt As New Kepware.ClientAce.OpcDaClient.DaServerMgt
'Create a URL for the server connection this could be an OPC DA or UA connection
Dim url As String = _
"opcda://localhost/Kepware.KEPServerEX.V5/{B3AF0BF6-4C0C-4804-A122-6F3B160F4397}"
'Create a unique id for the client connection
Dim clientHandle As Integer = 1
'Create and configure the connection infomration object and data
Dim connectInfo As New Kepware.ClientAce.OpcDaClient.ConnectInfo
connectInfo.LocalId = "en"
connectInfo.KeepAliveTime = 5000
connectInfo.RetryAfterConnectionError = True
connectInfo.RetryInitialConnection = True
connectInfo.ClientName = "Demo ClientAce VB.Net Console Application"
Dim connectFailed As Boolean
www. ptc.com
65 ClientAce
Catch ex As Exception
Console.WriteLine("Connect exception. Reason: " & ex.Message)
End Try
Do
Console.WriteLine(vbCrLf & "Ready:")
cki = Console.ReadKey()
Catch ex As Exception
'Handle the read exaception
Console.WriteLine("Sync read failed with exception " & ex.Message)
End Try
End If
Loop While cki.Key < > ConsoleKey.Q
If daServerMgt.IsConnected Then
www. ptc.com
ClientAce 66
daServerMgt.Disconnect()
End If
End Sub
End Module
[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kepware.ClientAce.OpcDaClient;
namespace Simple_CS_Console_Application_VS_2010_13
{
class Program
{
int clientHandle = 1;
www. ptc.com
67 ClientAce
connectInfo.KeepAliveTime = 5000;
connectInfo.RetryAfterConnectionError = true;
connectInfo.RetryInitialConnection = true;
connectInfo.ClientName = "Demo ClientAce C-Sharp Console Application";
if (connectFailed)
{
Console.WriteLine("Connect failed.");
}
else
{
Console.WriteLine("Connected to Server Succeeded.");
}
}
catch (Exception ex)
{
Console.WriteLine("Connect exception. Reason: {0}", ex);
}
www. ptc.com
ClientAce 68
{
Console.WriteLine("\r\nHit 'R' to Read a value from the server. \r\nHit 'Q' to Disconnect and
Exit.");
}
do
{
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.R)
{
try
{ // Call Read API method
}
} while (cki.Key != ConsoleKey.Q);
if (DAserver.IsConnected)
{
DAserver.Disconnect();
}
}
}
}
ReadAsync Method
Method
ReadAsync (
www. ptc.com
69 ClientAce
Properties
The ReadAsync Method is used to asynchronously read items of an OPC Server. The read values will be
returned in the ReadCompleted Event. It is strongly recommended that a Subscription be used if the items
are read cyclically (and the changed data be received in the DataChanged Event).
Tip: The ReadAsynch Method allows more than one item to be read at a time. Because single multi-item
writes can be executed more efficiently than a series of single-item writes, using multi-item writes is
recommended whenever it is possible.
itemIdentifiers Input/Output The API will also set the ServerHandle property. It is
recommended that ItemIdentifier objects be stored if repeated
reads and writes of the same objects are intended. The API will
make use of the ServerHandle values to optimize OPC calls to
the server.
The API will return the specified handle along with the
requested values in a ReadCompleted event. Thus, a
transactionHandle Input
ReadCompleted event may be correlated with a particular call
to ReadAsync.
Notes:
1. The return code indicates the overall success of the call. If this code indicates an item-specific error
(such as ITEMERROR, QUALITYNOTGOOD, or ITEMANDQUALITYERROR), each of the ReturnID objects
should be examined to determine which items could not be read and why. In the event that the
function cannot satisfy the request (due to invalid arguments or unexpected errors), an exception will
be thrown. For more information on Return Value:ReturnCode, refer to ReturnCode Enumeration.
www. ptc.com
ClientAce 70
Example Code
These examples read two items: "Channel_1.Device_1.Tag_1" and "Channel_1.Device_1.Tag_2".
[Visual Basic]
' Declare variables
Dim transactionHandle As Integer = 0
Dim maxAge As Integer = 0
Dim itemIdentifiers(1) As Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0).ItemName = "Channel_1.Device_1.Tag_1"
itemIdentifiers(0).ClientHandle = 1 ' Assign unique handle
itemIdentifiers(1) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(1).ItemName = "Channel_1.Device_1.Tag_2"
itemIdentifiers(1).ClientHandle = 2 ' Assign unique handle
Dim returnCode As Kepware.ClientAce.OpcDaClient.ReturnCode
Try
' Call ReadAsync API method
returnCode = daServerMgt.ReadAsync( _
transactionHandle, _
maxAge, _
itemIdentifiers)
' Check result
If returnCode <> _
Kepware.ClientAce.OpcDaClient.ReturnCode.SUCCEEDED Then
Console.WriteLine("ReadAsync failed for one or more items")
' Examine ResultID objects for detailed information.
End If
Catch ex As Exception
Console.WriteLine("ReadAsync exception. Reason: " & ex.Message)
End Try
[C#]
// Declare variables
int transactionHandle = 0;
int maxAge = 0;
ItemIdentifier[] itemIdentifiers = new ItemIdentifier[2];
itemIdentifiers[0] = new ItemIdentifier();
itemIdentifiers[0].ItemName = "Channel_1.Device_1.Tag_1";
itemIdentifiers[0].ClientHandle = 1; // Assign unique handle
itemIdentifiers[1] = new ItemIdentifier();
itemIdentifiers[1].ItemName = "Channel_1.Device_1.Tag_2";
itemIdentifiers[1].ClientHandle = 2; // Assign unique handle
ReturnCode returnCode;
www. ptc.com
71 ClientAce
try
{
// Call ReadAsync API method
returnCode = daServerMgt.ReadAsync(transactionHandle, maxAge, ref itemIdentifiers);
// Check result
if (returnCode != ReturnCode.SUCCEEDED)
{
Console.WriteLine("ReadAsync failed for one or more items");
// Examine ResultID objects for detailed information.
}
}
catch (Exception ex)
{
Console.WriteLine("ReadAsync exception. Reason: {0}", ex);
}
Subscribe Method
Method
Subscribe(
ByVal clientSubscription As Integer,
ByVal active As Boolean,
ByVal updateRate As Integer,
ByRef revisedUpdateRate As Integer,
ByVal deadband As Single,
ByRef itemIdentifiers() As Kepware.ClientAce.OpcDaClient.ItemIdentifier,
ByRef serverSubscription As Integer
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The Subscribe Method is used to register items for monitoring. The server will continuously scan the
subscribed items at the specified update rate and notify the ClientAce API when any item's values or quality
changes. The ClientAce API will relay this information to the client application through a DataChanged Event.
This relieves the client of having to make continuous calls to Read or ReadAsync to poll a set of items, and
can greatly improve the performance of the client application and server.
Note: The server will send an initial update for all items added to an active subscription.
www. ptc.com
ClientAce 72
Notes:
1. The return code indicates the overall success of the call. If this code indicates an item-specific error
(such as ITEMERROR), each of the ReturnID objects should be examined to determine which items
could not be added to the subscription and why. The return code will also indicate if the requested
update rate is not supported by the server. In the event that the function cannot satisfy the request
(due to invalid arguments or unexpected errors), an exception will be thrown. For more information
on Return Value:Return Code, refer to ReturnCode Enumeration.
2. For the server to return item values with a particular data type, that particular type must be
requested with the ItemIdentifier.DataType property. The ResultID will indicate if the server is able to
provide the value as the requested type. If the requested type cannot be provided, the values will be
sent in their canonical (default) data type.
Example Code
These examples show how to create a new subscription for the two items "Channel_1.Device_1.Tag_1" and
"Channel_1.Device_1.Tag_2".
[Visual Basic]
' Declare variables
Dim clientSubscription As Integer = 1
Dim active As Boolean = True
Dim updateRate As Integer = 500
Dim revisedUpdateRate As Integer
www. ptc.com
73 ClientAce
[C#]
// Declare variables
int clientSubscription = 1;
bool active = true;
int updateRate = 500;
int revisedUpdateRate;
float deadband = 0;
ItemIdentifier[] itemIdentifiers = new ItemIdentifier[2];
itemIdentifiers[0] = new ItemIdentifier();
itemIdentifiers[0].ItemName = "Channel_1.Device_1.Tag_1";
itemIdentifiers[0].ClientHandle = 1; // Assign unique handle
itemIdentifiers[1] = new ItemIdentifier();
itemIdentifiers[1].ItemName = "Channel_1.Device_1.Tag_2";
itemIdentifiers[1].ClientHandle = 2; // Assign unique handle
int serverSubscription;
ReturnCode returnCode;
try
{
// Call Subscribe API method
returnCode = daServerMgt.Subscribe(clientSubscription,
active,
updateRate,
out revisedUpdateRate,
www. ptc.com
ClientAce 74
deadband,
ref itemIdentifiers,
out serverSubscription);
// Check results
foreach (ItemIdentifier item in itemIdentifiers)
{
if (!item.ResultID.Succeeded)
{
Console.WriteLine("Subscribe failed for item {0}",
item.ItemName);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Subscribe exception. Reason: {0}", ex);
}
SubscriptionModify Method
Method
SubscriptionModify(
ByVal serverSubscription As Integer,
ByVal active As Boolean,
ByVal updateRate As Integer,
ByRef revisedUpdateRate As Integer,
ByVal deadband As Single
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
SubscriptionModify (
ByVal serverSubscription As Integer,
ByVal active As Boolean
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
SubscriptionModify (
ByVal serverSubscription As Integer,
ByVal updateRate As Integer,
ByRef revisedUpdateRate As Integer
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
SubscriptionModify (
ByVal serverSubscription As Integer,
ByVal deadband As Single
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The SubscriptionModify Method is used to modify the properties of an existing subscription created with the
Subscribe Method. There are three overloads available to change the active UpdateRate and Deadband
subscription properties separately.
www. ptc.com
75 ClientAce
Note: The return code indicates the overall success of the call. If the code indicates an item-specific error
(such as ITEMERROR), each of the ReturnID objects should be examined to determine which items could not
be added to the subscription and why. The return code will also indicate if the requested update rate is not
supported by the server. In the event that the function cannot satisfy the request due to invalid arguments or
unexpected errors, an exception will be thrown. For more information on Return Value:Return Code, refer to
ReturnCode Enumeration.
Example Code
These examples modify the properties of an existing subscription that was created with the Subscribe
Method.
[Visual Basic]
' Declare variables
Dim serverSubscription As Integer ' Assign handle return from Subscribe
Dim active As Boolean = True
Dim updateRate As Integer = 1000
Dim revisedUpdateRate As Integer
Dim deadband As Single = 0
Try
' Call SubscriptionModify API method
daServerMgt.SubscriptionModify( _
serverSubscription, _
active, _
updateRate, _
revisedUpdateRate, _
deadband)
Catch ex As Exception
Console.WriteLine("SubscriptionModify exception. Reason: " & _
www. ptc.com
ClientAce 76
ex.Message)
End Try
[C#]
// Declare variables
int serverSubscription = 0; // Assign handle return from Subscribe
bool active = true;
int updateRate = 1000;
int revisedUpdateRate;
float deadband = 0;
try
{
// Call SubscriptionModify API method
daServerMgt.SubscriptionModify(serverSubscription,
active,
updateRate,
out revisedUpdateRate,
deadband);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred when attempting to modify the subscription: " +
ex.Message);
}
SubscriptionAddItems Method
Method
SubscriptionAddItems(
ByVal serverSubscription As Integer,
ByRef itemIdentifiers() As Kepware.ClientAce.OpcDaClient.ItemIdentifier
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The SubscriptionAddItems Method is used to add items to an existing subscription created with the
Subscribe method.
Note: The server will send an initial update for all items added to an active subscription.
Notes:
www. ptc.com
77 ClientAce
1. The return code indicates the overall success of the call. If this code indicates an item-specific error
(such as ITEMERROR), each of the ReturnID objects should be examined to determine which items
could not be added to the subscription and why. In the event that the function cannot satisfy the
request due to invalid arguments or unexpected errors, an exception will be thrown. For more
information on Return Value:Return Code, refer to ReturnCode Enumeration.
2. For the server to return item values with a particular data type, that particular type must be
requested with the ItemIdentifier.DataType property. The ResultID will indicate if the server is able to
provide the value as the requested type. If the requested type cannot be provided, the values will be
sent in their canonical (default) data type.
Example Code
These examples add the items "Channel_1.Device_1.Tag_3" and "Channel_1.Device_1.Tag_4" to an existing
subscription, created with the Subscribe method.
[Visual Basic]
' Declare variables
' Assign handle return from Subscribe
Dim serverSubscription As Integer
Dim itemIdentifiers(1) As Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0).ItemName = "Channel_1.Device_1.Tag_3"
itemIdentifiers(0).ClientHandle = 3 ' Assign unique handle
itemIdentifiers(1) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(1).ItemName = "Channel_1.Device_1.Tag_4"
itemIdentifiers(1).ClientHandle = 4 ' Assign unique handle
Try
' Call SubscriptionAddItems API method
daServerMgt.SubscriptionAddItems( _
serverSubscription, _
itemIdentifiers)
' Check item results
Dim item As Kepware.ClientAce.OpcDaClient.ItemIdentifier
For Each item In itemIdentifiers
If item.ResultID.Succeeded = False Then
Console.WriteLine("SubscriptionAddItems failed for item: " & _
item.ItemName)
End If
Next
Catch ex As Exception
Console.WriteLine("SubscriptionAddItems exception. Reason: " & _
ex.Message)
End Try
[C#]
// Declare variables
// Assign handle return from Subscribe
int serverSubscription = 0;
www. ptc.com
ClientAce 78
SubscriptionCancel Method
Method
SubscriptionCancel (
ByVal serverSubscription As Integer
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The SubscriptionCancel Method is used to cancel an existing subscription created with the Subscribe
Method.
www. ptc.com
79 ClientAce
Note: In the event that the function cannot satisfy the request due to invalid arguments or unexpected
errors, an exception will be thrown. For more information on Return Value: Return Code, refer to ReturnCode
Enumeration.
Example Code
[Visual Basic]
' Declare variables
Dim serverSubscription As Integer ' Assign handle return from Subscribe
Try
daServerMgt.SubscriptionCancel(serverSubscription)
Catch ex As Exception
Console.WriteLine("SubscriptionCancel exception. Reason: " & _
ex.Message)
End Try
[C#]
// Declare variables
int serverSubscription = 0; // Assign handle return from Subscribe
try
{
// Call SubscriptionCancel API method
daServerMgt.SubscriptionCancel(serverSubscription);
}
catch (Exception ex)
{
Console.WriteLine("SubscriptionCancel exception. Reason: {0}", ex);
}
SubscriptionRemoveItems Method
Method
SubscriptionRemoveItems (
ByVal serverSubscription As Integer,
ByRef itemIdentifiers() As Kepware.ClientAce.OpcDaClient.ItemIdentifier
) As/returns Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The SubscriptionRemoveItems Method removes items from an existing subscription that was created with
the Subscribe Method.
www. ptc.com
ClientAce 80
Note: The return code indicates the overall success of the call. If the code indicates an item-specific error
(such as ITEMERROR), each of the ReturnID objects should be examined to determine which items could not
be removed from the subscription and why. In the event that the function cannot satisfy the request due to
invalid arguments or unexpected errors, an exception will be thrown. For more information on Return
Value:Return Code, refer to ReturnCode Enumeration.
Example Code
These examples remove the items "Channel_1.Device_1.Tag_1" and "Channel_1.Device_1.Tag_2" from an
existing subscription that was created with the Subscribe method.
[Visual Basic]
' Declare variables
Dim serverSubscription As Integer ' Assign handle return from Subscribe
Dim itemIdentifiers(1) As Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0).ItemName = "Channel_1.Device_1.Tag_3"
itemIdentifiers(0).ClientHandle = 3 ' Assign unique handle
itemIdentifiers(1) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(1).ItemName = "Channel_1.Device_1.Tag_4"
itemIdentifiers(1).ClientHandle = 4 ' Assign unique handle
Try
' Call SubscriptionRemoveItems API method
daServerMgt.SubscriptionRemoveItems( _
serverSubscription, _
itemIdentifiers)
[C#]
// Declare variables
int serverSubscription = 0; // Assign handle return from Subscribe
ItemIdentifier[] itemIdentifiers = new ItemIdentifier[2];
itemIdentifiers[0] = new ItemIdentifier();
itemIdentifiers[0].ItemName = "Channel_1.Device_1.Tag_3";
itemIdentifiers[0].ClientHandle = 3; // Assign unique handle
itemIdentifiers[1] = new ItemIdentifier();
www. ptc.com
81 ClientAce
itemIdentifiers[1].ItemName = "Channel_1.Device_1.Tag_4";
itemIdentifiers[1].ClientHandle = 4; // Assign unique handle
ReturnCode returnCode;
try
{ // Call SubscriptionRemoveItems API method
returnCode = daServerMgt.SubscriptionRemoveItems(serverSubscription,
ref itemIdentifiers);
// Check item results
if (returnCode != ReturnCode.SUCCEEDED)
{
foreach (ItemIdentifier item in itemIdentifiers)
{
if (!item.ResultID.Succeeded)
{
Console.WriteLine("SubscriptionRemoveItems failed for item:
{0}", item.ItemName);
}
}
}
}
catch (Exception ex)
{ Console.WriteLine("SubscriptionRemoveItems exception. Reason: {0}", ex); }
Write Method
Method
Write(
ByRef itemIdentifiers() As Kepware.ClientAce.OpcDaClient.ItemIdentifier,
ByVal itemValues() As Kepware.ClientAce.OpcDaClient.ItemValue
) As Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The Write Method is used to write one or more values to the OPC server.
Note: Because single multi-item writes can be executed more efficiently than a series of single-item
writes, using multi-item writes is recommended whenever it is possible.
www. ptc.com
ClientAce 82
Note: The return code indicates the overall success of the call. If this code indicates an item-specific error
(such as ITEMERROR), each of the ReturnID objects should be examined to determine which items could not
be read and why. In the event that the function cannot satisfy the request (due to invalid arguments or
unexpected errors) an exception will be thrown. For more information on Return Value: Return Code, refer to
ReturnCode Enumeration.
Example Code
These examples write the value "111" to tag "Channel_1.Device_1.Tag_1", and "222" to tag "Channel_
1.Device_1.Tag_2".
[Visual Basic]
Imports Kepware.ClientAce.OpcDaClient
Module Module1
Sub Main()
' Declare variables
'Create server management object
Dim daServerMgt As New Kepware.ClientAce.OpcDaClient.DaServerMgt
'Create a URL for the server connection this could be an OPC DA or UA connection
Dim url As String = _
"opcda://localhost/Kepware.KEPServerEX.V5/{B3AF0BF6-4C0C-4804-A122-6F3B160F4397}"
'Create a unique id for the client connection
Dim clientHandle As Integer = 1
'Create and configure the connection infomration object and data
Dim connectInfo As New Kepware.ClientAce.OpcDaClient.ConnectInfo
connectInfo.LocalId = "en"
connectInfo.KeepAliveTime = 5000
connectInfo.RetryAfterConnectionError = True
connectInfo.RetryInitialConnection = True
connectInfo.ClientName = "Demo ClientAce VB.Net Console Application"
Dim connectFailed As Boolean
www. ptc.com
83 ClientAce
Try
' Call Connect API method
daServerMgt.Connect( _
url, _
clientHandle, _
connectInfo, _
connectFailed)
Catch ex As Exception
Console.WriteLine("Connect exception. Reason: " & ex.Message)
End Try
Do
Console.WriteLine(vbCrLf & "Ready:")
cki = Console.ReadKey()
www. ptc.com
ClientAce 84
Catch ex As Exception
'Handle the read exception
Console.WriteLine("Sync read failed with exception " & ex.Message)
End Try
End If
If (OPCItems(0).ResultID.Succeeded) Then
Console.WriteLine(vbCrLf & "Write succeeded. Value Written is: {0}", OPCWriteValue
(0).Value.ToString)
Else
Console.WriteLine(vbCrLf & "Write Failed with result: {0}", OPCItems(0).ResultID.Description)
End If
Catch ex As Exception
'Handle the write exception
Console.WriteLine("Sync write failed with exception " & ex.Message)
End Try
End If
Loop While cki.Key <> ConsoleKey.Q
If daServerMgt.IsConnected Then
daServerMgt.Disconnect()
End If
End Sub
www. ptc.com
85 ClientAce
End Module
[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kepware.ClientAce.OpcDaClient;
namespace Simple_CS_Console_Application_VS_2010_13
{
class Program
{
int clientHandle = 1;
www. ptc.com
ClientAce 86
WriteAsync Method
Method
WriteAsync(
ByVal transactionHandle As Integer,
ByRef itemIdentifiers() As kepware.ClientAce.OpcDaClient.ItemIdentifier,
ByVal itemValues() As kepware.ClientAce.OpcDaClient.ItemValue
) As Kepware.ClientAce.OpcDaClient.ReturnCode
Properties
The WriteAsync Method is used to asynchronously write items to an OPC Server. The write values will be
returned in the WriteCompleted Event.
Note: More than one item may be written at a time with the WriteAsync method. Because single multi-
item writes can be executed more efficiently than a series of single-item writes, using multi-item writes is
recommended whenever it is possible.
itemIdentifiers Input/Output
The API will also set the ServerHandle property. It is recommended
that ItemIdentifier objects be stored if repeated reads and writes of
the same objects are intended. The API will make use of the
ServerHandle values to optimize OPC calls to the server.
The array itemValues contains the Values to be written to the OPC
itemValues Input
server.
Note: The return code indicates the overall success of the call. If this code indicates an item-specific error
(such as ITEMERROR or ITEMANDQUALITYERROR), each of the ReturnID objects should be examined to
determine which items could not be read and why. In the event that the function cannot satisfy the request
www. ptc.com
87 ClientAce
(due to invalid arguments or unexpected errors), an exception will be thrown. For more information on
Return Value:Return Code, refer to ReturnCode Enumeration.
Example Code
These examples write the value "111" to tag "Channel_1.Device_1.Tag_1", and "222" to tag "Channel_
1.Device_1.Tag_2".
[Visual Basic]
' Declare variables
Dim transactionHandle As Integer = 0
Dim itemIdentifiers(1) As Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(0).ItemName = "Channel_1.Device_1.Tag_1"
itemIdentifiers(0).ClientHandle = 1 ' Assign unique handle
itemIdentifiers(1) = New Kepware.ClientAce.OpcDaClient.ItemIdentifier
itemIdentifiers(1).ItemName = "Channel_1.Device_1.Tag_2"
itemIdentifiers(0).ClientHandle = 2 ' Assign unique handle
Dim itemValues(1) As Kepware.ClientAce.OpcDaClient.ItemValue
itemValues(0) = New Kepware.ClientAce.OpcDaClient.ItemValue
itemValues(0).Value = "111"
itemValues(1) = New Kepware.ClientAce.OpcDaClient.ItemValue
itemValues(1).Value = "222"
Dim returnCode As Kepware.ClientAce.OpcDaClient.ReturnCode
Try
' Call WriteAsync API method
returnCode = daServerMgt.WriteAsync( transactionHandle, itemIdentifiers, _
itemValues)
' Check result
If returnCode <> _
Kepware.ClientAce.OpcDaClient.ReturnCode.SUCCEEDED Then
Console.WriteLine("Write request failed for one or more items")
‘ Examine ResultID objects for detailed information.
End If
Catch ex As Exception
Console.WriteLine("WriteAsync exception. Reason: " & ex.Message)
End Try
[C#]
// Declare variables
int transactionHandle = 0;
ItemIdentifier[] itemIdentifiers = new ItemIdentifier[2];
itemIdentifiers[0] = new ItemIdentifier();
itemIdentifiers[0].ItemName = "Channel_1.Device_1.Tag_1";
itemIdentifiers[0].ClientHandle = 1; // Assign unique handle
www. ptc.com
ClientAce 88
IsConnected Property
Property
IsConnected As Boolean
Properties
The IsConnected Property is used to check if the client application has successfully called the Connect
Method. It does not necessarily indicate whether ClientAce is connected to the server. For example, such a
property would remain true even after a connection has failed and ClientAce is in the process of
reconnecting. To test the ClientAce to server connection state, use the ServerState Property. To monitor
the server connection state, implement the ServerStateChanged Event handler.
Value Description
True The client is connected to ClientAce.
False The client is not connected to ClientAce.
ServerState Property
Property
ServerStateAs Kepware.ClientAce.OpcDaClient.ServerState
Properties
The ServerState Property is used to determine the status of the server connection.
Value Description
www. ptc.com
89 ClientAce
This describes the current connection state between the ClientAce API and the OPC
ServerState*
Server.
ClientAceDA_Junction
The ClientAce DA Junction is a customized .NET control that allows VB.NET or C# programmers to easily link
data from OPC DA and OPC UA servers to WinForm controls through a simple drag and drop interface. The
ClientAce .NET API is recommended when building advanced custom OPC client applications that require
more control over OPC functionality. Features of the ClientAce DA Junction include the following:
ClientAceDA_Junction Properties
Although these properties can only be set at the time of design, they are accessible as Read Only properties
at Runtime.
Data
Property Description
Type
The default update rate set in the DA_Junction Object. This is the
DefaultUpdateRate Integer update rate used on all items unless overridden in the individual
item settings.
ShowTimestampInTooltip Boolean This shows the timestamp of the OPC value in the tooltip.
System The back color of the connected control when the quality of the OPC
BackColorQualityBad
Color value is bad.
System The back color of the connected control when the ResultID of the
BackColorError
Color OPC item did not succeed.
DisconnectAllServers Method
This method disconnects all servers in the DA Junction Object.
[DisconnectAllServers()
ReconnectAllServers Method
This method reconnects all servers in the DA Junction Object.
ReconnectAllServers()
Example Code
[Visual Basic]
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs _
) Handles btnDisconnect.Click
Try
www. ptc.com
ClientAce 90
[C#]
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
//Disconnects all servers that are currently connected in the DA_Junction
ClientAceDA_Junction1.DisconnectAllServers();
}
catch (Exception ex)
{
MessageBox.Show ("Received Exception: " + ex.Message);
}
}
private void btnReconnect_Click(object sender, EventArgs e)
{
try
{
//Reconnects all servers that are currently connected in the DA_Junction
ClientAceDA_Junction1.ReconnectAllServers();
}
catch (Exception ex)
{
MessageBox.Show("Received Exception: " + ex.Message);
}
}
www. ptc.com
91 ClientAce
Project Setup
For more information on DA Junction project setup, select a link from the list below.
OPC Items
Controls
Connections Pane
Connection Settings
OPC Items
The OPC Items pane displays the items from an OPC server project and shows where the OPC Servers are
connected. The DA Junction can connect to OPC DA and OPC UA servers. Users can add servers to this
control in three different ways: through the Server Browser, through OPC DA, and through OPC UA.
Server Browser
The Server Browser tab allows users to browse for Enumerated OPC DA Servers or OPC UA servers that
have been registered to a Local UA Discovery server.
www. ptc.com
ClientAce 92
OPC DA
The OPC DA tab allows users to specify a Hostname and ProgramID for servers that may not be enumerated
on a PC.
OPC UA
If there are no Discovery Servers available, the Endpoint URL and Application Name can be specified
instead. Users can also specify the Security and Authentication settings as configured in the UA Server.
www. ptc.com
93 ClientAce
Tip: Once connections are made, they will be listed beneath the OPC Items pane. By expanding the server
connections, users can view the server folders that contain OPC Items. Selected items will be placed in
Connections.
For more information, refer to Connections Pane.
Controls
The Controls pane determines which control properties will be displayed. The example below demonstrates
the 6 controls on Form1.
www. ptc.com
ClientAce 94
Note: The example below displays the selections for Show all properties.
Note: The example below displays the selections for Apply property filter located in the Filter dialog.
The Type Filter, which includes a checklist of available data types, is found in the first tab.
Note: The example below displays the selections for Access Filter tab located in the Filter dialog. The
Show Read Only Properties field is unchecked by default because data is usually written from the OPC
server to the property of the user interface control. To write data from the property, check Show Read Only
Properties in the OPC server.
www. ptc.com
95 ClientAce
Note: The example below displays the selections for Property Level tab in the Filter dialog. The default
level is 2. The higher the number is, the greater the level of property detail that will be shown. If the end
node of a given item is at level 2, then only 2 levels will be shown for that item if the property level filter is set
to 2 or higher. Likewise, if the level filter is set to 3, then only 3 levels of property detail will be shown even if
a given item's end node is at level 4 or higher.
Connections Pane
The Connections pane is used to modify the tag state, server name, tag item, and data direction. It can also
be used to modify or set Visual Studio controls and properties (and set triggers).
Direction
Direction specifies whether the Visual Studio control is Read Only, Write Only, or Read/Write. The default
property is shown in bold.
www. ptc.com
ClientAce 96
Connection Settings
To access an item's Connection Settings, locate the Settings column and then click Browse.
Note: The Connection Settings window has two tabs: General and Trigger. The General tab is used to
specify the update rate, and determine whether to disable DataChange while the control has focus.
The Trigger tab is used to select the control, browse events, and select an event that will trigger a write to
the OPC tag connected to the control. For more information, refer to Triggers.
Important: All referenced controls must be on the local drive. Assemblies that are located on a network
drive should not be referenced, as this will cause the Visual Studio error "Unable to cast object of type
<type> to <type>." This is a limitation of the Microsoft .NET development environment.
www. ptc.com
97 ClientAce
2. Next, drag and drop the ClientAceDA_Junction control from the Toolbox to the new form. The control
label "ClientAceDA_Junction1" will be displayed.
3. Next, drag and drop three VB/C# Label controls and three TextBox controls onto the form. These
controls are located beneath the Windows Forms tab in the Toolbox.
www. ptc.com
ClientAce 98
4. To change the controls' names and text properties to be more descriptive, open Properties and then
click View.
5. Next, select Properties Window and click once on the Label1 control to select it.
www. ptc.com
99 ClientAce
8. Repeat this procedure for all five controls. The changes made to the controls are displayed in the
table below.
www. ptc.com
ClientAce 100
*Leave the Text property for the TextBox controls blank, because they will be updated automatically
by the OPC tag items.
Tip: In ClientAce V4.0, users can also open the configuration by double-clicking on the DA Junction
Object.
3. Click the Ellipses button to launch the ClientAceDA Junction Configuration window.
4. Use the OPC Items pane to add local and remote servers (and to browse for OPC tag items). To view
the VB/C# controls being displayed, open the Control pane.
For more information, refer to DA Junction Configuration Window.
www. ptc.com
101 ClientAce
2. Expand the nodes Local Machine, Remote Machine, or Custom Remote Machines to select the
server of interest. In this example, "KEPware.OPCSampleServer" is used.
3. Next, browse the OPC server to locate the tags to which the Visual Studio controls can connect. Then,
drag and drop each OPC tag item onto the Visual Studio control.
www. ptc.com
ClientAce 102
Note: For example, drag the "K0" Tag to the txtRead and txtWrite controls. Then, drag the K1 Tag to
the txtReadWrite textbox control. The tag items should then be listed in the Connections grid.
Direction Property
www. ptc.com
103 ClientAce
Direction determines whether the Visual Studio control is Read Only, Write Only, or Read/Write. For more
information, refer to Connections Pane.
For this example, leave the txtRead control at the default Read Only setting. Then, change the txtReadWrite
control Read/Write, and the txtWrite control to Write Only. For more information, follow the instructions
below.
1. For the txtReadWrite control, click the Direction column. Then, select Item <=> Control from the
drop-down menu.
2. For the txtWrite control, click the Direction column. Then, select Item <= Control from the drop-
down menu.
Note: When the direction is changed to Write Only (<=) or Read/Write (<=>), the item will display a red "X"
as shown in the image below. The red "X" signifies an error: the control has been set to Write Only or
Read/Write but the control does not yet have its write conditions specified. The Triggers property specifies
the conditions for the write procedures. For more information, refer to "Triggers" below.
Triggers
1. To access an item's Trigger property, select the Settings column. Then, click Ellipses.
Note: The Trigger tab is used to select the control, to browse events, and to select an event that
www. ptc.com
ClientAce 104
will trigger a write to the OPC tag connected to the control. For example, the txtReadWrite and
txtWrite controls need to have their write conditions specified as follows:
l The txtReadWrite control's KeyDown event triggers writes on the txtReadWrite Visual Studio
control.
l The txtWrite control's KeyDown event triggers writes on the txtWrite Visual Studio control.
1. To start, select and expand the txtReadWrite control to display its properties.
2. In the Trigger tab, locate the Event drop-down list and then select KeyDown. Alternatively, drag the
KeyDown property and drop it in the Event column.
4. Next, return to the Configuration Screen and repeat the process for the txtWrite control.
5. To start, select and expand the txtWrite control to display its properties.
6. In the Trigger tab, locate the Event drop-down list and then select KeyDown. Alternatively, drag the
KeyDown property and drop it in the Event column.
www. ptc.com
105 ClientAce
Note: When applicable, the Condition field will provide a drop-down menu of conditions. For
example, if a control is added with KeyDown in the Event field, the Condition drop-down menu will
display a list of valid keys from which users can choose.
8. To save the changes, click OK at the bottom of the Configuration screen. Then, build and run the
application.
Note: The application will use the associated VB or C# controls to read from and write to the OPC
tags.
www. ptc.com
ClientAce 106
1. To start, click on the Ellipses button for ClientAceConfiguration. This will launch the Configuration
window.
www. ptc.com
107 ClientAce
2. Next, click in the Settings column. Locate the item whose default rate will be changed, and then click
the associated Ellipses button.
www. ptc.com
ClientAce 108
1. To start, locate ClientAceConfiguration. Then, click the Ellipses button to launch the Configuration
window.
2. In the Settings column, locate the item whose properties will be changed. Then, click the associated
Ellipses button.
www. ptc.com
109 ClientAce
Note: The selected control is now set for the Data Update Pause when it has focus.
www. ptc.com
ClientAce 110
Additional Controls
For more information on ClientAce Browser Controls, select a link from the list below.
Data
Property Use Description
Type
Indicates if multiple Servers are shown in the
AllowMultipleServers Input Boolean
ItemBrowser.
BrowserWidth Input Integer Indicates the width of the Tree View.
OPCUrl
Servers Input Indicates the Servers currently being used.
Object
Indicates if the Add Server menu items should be shown
ShowAddServerMenuItem Input Boolean
in the server browser pane when right-clicked.
Indicates if the Internal Server Browser should be shown
ShowInternalServerBrowser Input Boolean
at Runtime.
ShowItemList Input Boolean Indicates if the Item List should be shown at Runtime.
Indicates if the Item Name and Path should be shown in
ShowItemNameAndPath Input Boolean
the Item List at Runtime.
Indicates if the Items should be shown in the Browser
ShowItemsInTree Input Boolean
Tree List at Runtime.
Indicates if the Item Properties should be shown in
ShowPropertiesInBrackets Input Boolean brackets beside the Item in the Browser Tree List at
Runtime.
Indicates if the Item Properties should be shown in the
ShowPropertiesInTree Input Boolean
Browser Tree List at Runtime.
ShowPropertyList Input Boolean Indicates if the Property List should be shown at Runtime.
Indicates if the pages should switch automatically from
SwitchTabPages Input Boolean the Item List to the Properties List when an item is
selected in the Tree View List at Runtime.
AddServer Method
This method has two versions. The method below is for a string, and adds an OPC server to the Tree View of
the ItemBrowser.
www. ptc.com
111 ClientAce
The method below uses the URL object for OPC UA connections. This allows a UA server to be added with
certificate and authentication information.
Connect Method
This method has two versions. The method below initiates a connect to the specified server in the
ItemBrowser.
ConnectAll Method
This method initiates a connection to all the servers currently added in the ItemBrowser.
ConnectAll()
Disconnect Method
This method has two versions. The method below initiates a disconnect to the specified server in the
ItemBrowser.
DisconnectAll Method
This method disconnects all servers currently connected in the ItemBrowser.
DisconnectAll()
DisconnectSelectedServer Method
This method disconnects the server currently being used. The Servernode or Childnode must be selected.
DisconnectSelectedServer()
GetSelectedItems Method
This method returns the selected items as an array of Browse Controls OPC DA items. If no item is selected,
the length of the array will be 0.
GetSelectedItems() as Kepware.ClientAce.BrowseControls.OpcDaItem
ResetItemBrowser Method
This method disconnects all connected servers and clears the Tree View and lists.
www. ptc.com
ClientAce 112
ResetItemBrowser()
ItemDoubleClicked Event
This event shows that an OPC item in the browser was double-clicked.
ItemDoubleClicked(
ByVal Sender as Object,
ByVal item as Kepware.ClientAce.BrowseControls.OpcDaItem )
) Handles ClientAceItemBrowser1.ItemDoubleClicked
ItemSelected Event
This event shows that one or more OPC items are selected in the ItemBrowser.
ServerAdded Event
This event shows than an OPC Server was added to the control.
ServerRemoved Event
This event shows than an OPC Server was removed from the control.
Note: The syntax of the URL that uniquely identifies a server must follow this
format (except for OPC XML-DA):
[OpcSpecification]://[Hostname]/[ServerIdentifier]
URL Input
OpcSpecification: Selects the OPC Specification to be used.
www. ptc.com
113 ClientAce
Note: For OPC DA servers, the API will attempt to connect using the ClassID first.
If the ClassID is not given (or is found to be invalid), the API will attempt to connect
using the ProgID.
OPC DA Example
opcda://localhost/Kepware.KEPServerEX.V5
opcda://127.0.0.1/Kepware.KEPServerEX.V5/{B3AF0BF6-4C0C-4804-A122-
6F3B160F4397}
OPC XML-DA Example
http://127.0.0.1/Kepware/xmldaservice.asp
OPC UA Example
opc.tcp://127.0.0.1:49320
Example Code
[Visual Basic]
Private Sub Form3_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles MyBase.Load
Try
‘Display the current configuration of the
CheckBox1.Checked = ClientAceItemBrowser1.ShowAddServerMenuItem
CheckBox2.Checked = ClientAceItemBrowser1.ShowInternalServerBrowser
CheckBox3.Checked = ClientAceItemBrowser1.ShowItemList
CheckBox4.Checked = ClientAceItemBrowser1.ShowItemNameAndPath
CheckBox5.Checked = ClientAceItemBrowser1.ShowItemsInTree
CheckBox6.Checked = ClientAceItemBrowser1.ShowPropertiesInBrackets
CheckBox7.Checked = ClientAceItemBrowser1.ShowPropertiesInTree
CheckBox8.Checked = ClientAceItemBrowser1.ShowPropertyList
CheckBox9.Checked = ClientAceItemBrowser1.SwitchTabpages
Catch ex As Exception
MessageBox.Show("Received Exception: " & ex.Message)
End Try
End Sub
www. ptc.com
ClientAce 114
Try
‘If more than one item is selected then add them to the projects subscribed items
If itemCount > 1 Then
mItems = ClientAceItemBrowser1.GetSelectedItems()
mAdditems(item)
End If
Catch ex As Exception
MessageBox.Show("Received Exception: " & ex.Message)
End Try
End Sub
www. ptc.com
115 ClientAce
2. Verify that all of the ClientAce controls have been added to the Visual Studio Environment. For
information on adding controls to the toolbox, refer to Missing Controls.
www. ptc.com
ClientAce 116
3. To add a control, drag it from the toolbox and drop it onto a form.
Adding a Server
1. At Runtime, the ItemBrowser Control will appear as shown in the image below. The blank left pane
indicates that no servers have been added. To add a server, right-click in the left pane and then
select Add Server.
www. ptc.com
117 ClientAce
2. Next, add an OPC server using the Server Browser, OPC DA, or OPC UA tabs. This example will
demonstrate how to add a server using the OPC DA and OPC UA tabs. For information on adding a
server using the Server Browser tab, refer to Adding a ServerBrowser Control.
Note: When designing an application, it is best to synchronize the ItemBrowser Control with the
ServerBrowser control. Do not connect to a particular server using the ServerBrowser before adding
tags of a different server using the ItemBrowser Control.
For more information, refer to ServerBrowser Control.
www. ptc.com
ClientAce 118
l Application Name: This parameter specifies a name that will be used to identify the server.
l Security Policy: This parameter specifies the Encryption policy that is supported by the
endpoint. Options include None, Basic 128 RSA 15, and Basic 256.
l Message Security Mode: This parameter specifies the message security mode that is
supported by the endpoint. Options include None, Sign, and Sign and Encrypt.
5. When finished, click OK. The chosen server will be placed in the left pane of the ItemBrowser window.
6. To expand the added server, locate the server name or IP Address and then click the + symbol.
www. ptc.com
119 ClientAce
8. Next, click on the tag group to display the tags in the Itemlist tab. In this example, the Device1 group
selected from Channel1 in the server is displayed. The Device1 group's tags are displayed.
Note: The tags that are can be browsed in the ItemBrowser Control can be selected and monitored
by the programming code. To view a tag's properties, click the Properties tab.
OpcDaItem Class
This class describes the management object for an OPC Item selected in the ItemBrowser Control.
www. ptc.com
ClientAce 120
www. ptc.com
121 ClientAce
AddServer Method
This method adds an OPC URL to the recently-used Servers node.
GetSelectedServer Method
The GetSelectedServer Method can be used to return the currently selected server's OPCUrl object or
individual parts. It is used in conjunction with the ServerBrowser object's SelectionChanged and
ServerDoubleclicked Events. For more information, refer to OPCUrl Class.
GetSelectedServer() As Kepware.ClientAce.BrowseControls.OpcUrl
ReBrowseAll Method
This method collapses all tree nodes and discards their children.
ReBrowseAll()
SelectionChanged Event
This event indicates that the selection of the OPC server in the Browse Tree has changed.
ServerDoubleClicked Event
This event indicates that an OPC server in the tree was double-clicked.
ValidateServer Method
This method validates the currently-selected server.
www. ptc.com
ClientAce 122
ValidateServer()
Example Code
[Visual Basic]
Private Sub CLIENTACESERVERBROWSER1_SelectionChanged(ByVal serverIsSelected As Boolean)
_
Handles CLIENTACESERVERBROWSER1.SelectionChanged
Dim mURL as String
Dim mProgID as String
Dim mOPCType as String
Dim mCLSID as String
Dim mHostName as String
Try
mURL = CLIENTACESERVERBROWSER1.GetSelectedServer.Url
mProgID = CLIENTACESERVERBROWSER1.GetSelectedServer.ProgID
mOPCType = CLIENTACESERVERBROWSER1.GetSelectedServer.Type.ToString
mCLSID = CLIENTACESERVERBROWSER1.GetSelectedServer.ClsID
mHostName = CLIENTACESERVERBROWSER1.GetSelectedServer.HostName
mIsValid = CLIENTACESERVERBROWSER1.GetSelectedServer.IsValid
Catch ex As Exception
MessageBox.Show("Exception: " & ex.Message)
End Try
End Sub
Try
mURL = CLIENTACESERVERBROWSER1.GetSelectedServer.Url
mProgID = CLIENTACESERVERBROWSER1.GetSelectedServer.ProgID
mOPCType = CLIENTACESERVERBROWSER1.GetSelectedServer.Type.ToString
mCLSID = CLIENTACESERVERBROWSER1.GetSelectedServer.ClsID
mHostName = CLIENTACESERVERBROWSER1.GetSelectedServer.HostName
mIsValid = CLIENTACESERVERBROWSER1.GetSelectedServer.IsValid
Catch ex As Exception
MessageBox.Show("Exception: " & ex.Message)
End Try
End Sub
www. ptc.com
123 ClientAce
2. Verify that all of the ClientAce controls have been added to the Visual Studio Environment. For
information on adding controls to the toolbox, refer to Missing Controls.
3. To add a control, drag it from the toolbox and drop it onto a form.
www. ptc.com
ClientAce 124
At Runtime, the ServerBrowser Control will appear as shown in the image below.
Local Machine
To expand the Local Machine and display the servers, click on the + symbol. To select a server, simply click
on it. For more information on using the ClientAce API to connect to the server, refer to ClientAce .NET
API Assembly.
Remote Machine
To expand the Remote Machine and display the nodes/machines on the network, click on the + symbol. To
display all Enumerated OPC DA servers and all OPC UA servers that are registered with a Local UA
Discovery Server, click on the + symbol. The Remote Machine's DCOM settings must be configured properly
for users to access its servers. To select a server, simply click on it.
For more information on using the ClientAce API to connect to the server, refer to ClientAce .NET API
Assembly.
1. To start, locate Custom Remote Machines and then click the + symbol.
www. ptc.com
125 ClientAce
3. Next, type the IP Address or the machine name of the remote PC that will be browsed.
4. Press Enter.
Tip: This will create a link that points to the remote machine. To display the servers on the remote
machine, click on the + symbol next to the remote machine IP Address or name.
Note: In this example, the remote machine 10.10.111.181 has been defined as a custom link.
Important: Once a Custom Remote Machine has been created, the link will be saved by the application.
The next time that the application is opened, the Custom Remote Machine will be available and accessible;
however, it is only associated with the application that it was created for originally. For example, when a new
application is created, the Custom Remote Machines created for other applications/projects will not be
available for browsing. A new Custom Remote Machine link must be created for that new application/project.
www. ptc.com
ClientAce 126
OPCUrl Class
This class describes the management object for the URL of an OPC Server selected in the ServerBrowser
Control and ItemBrowser Control.
KEPServerEX Controls
ChannelSetting Control
OPC DA
Although these properties can only be set at the time of design, they are accessible as Read Only properties
at Runtime.
Data
Property Description
Type
The Channel Name of the channel in the server to which the control is
ChannelName String
connected.
The location of the server to which the control is connected. This is called the
NodeName String "localhost" in a local connection, and the IP Address of the Host Name for a
remote connection.
ProgID String The Program ID of the server to which the Channel Settings Control is connected.
www. ptc.com
127 ClientAce
ServerState Control
OPC DA
Although the properties can only be set at the time of design, they are accessible as Read Only properties at
Runtime.
Data
Property Description
Type
The location of the server to which the control is connected. This is called the
NodeName String "localhost" for a local connection, and the IP Address of the Host Name for a
remote connection.
ProgID String The Program ID of the server to which the Channel Settings Control is connected.
Note: If multiple KEPServerEX OPC servers are installed on the local machine, the ChannelSetting Control
will retrieve the channel properties of the server that was installed most recently.
2. Verify that all of the ClientAce controls have been added to the Visual Studio Environment. In Visual
Studio, the Toolbox should include the controls shown below. For more information on adding
controls to the toolbox, refer to Missing Controls.
www. ptc.com
ClientAce 128
3. To add a control, drag it from the toolbox and drop it onto a form.
2. In Channel Name, enter "Channel1" (because that node name is present in the sample KEPServerEX
OPC project).
www. ptc.com
129 ClientAce
Note: If the channel uses a network adapter, it will be listed in the Network Adapter parameter.
Both the Network Adapter and W/R Duty Cycle field can be modified as needed.
Note: When enabled, diagnostics information will be displayed in a separate Diagnostics tab.
Note: The Device1 and Device2 tabs display the properties of the two devices configured under
the channel. The window will display a tab for each device that is configured. The Device Properties
cannot be modified in this window even though they are displayed.
www. ptc.com
ClientAce 130
www. ptc.com
131 ClientAce
Note: If multiple KEPServerEX OPC servers are installed on the local machine, the ServerState Control will
retrieve the project properties of the server that was installed most recently.
2. Verify that all of the ClientAce controls have been added to the Visual Studio Environment. In Visual
Studio, the toolbox should include the controls shown below. For information on adding controls to
the Toolbox, refer to Missing Controls.
3. To add a control, drag it from the toolbox and drop it onto a form.
www. ptc.com
ClientAce 132
Note: Initially, the tag count displayed in the Total Tag Count and Active Tag Count fields is 6. This
accounts for the six state properties that are displayed: Client Count, Total Tag Count, Active Tag Count,
Date, Time, and Project Name.
www. ptc.com
133 ClientAce
OPC Visual
Description
Type Studio Type
Single bit. The following value range depends on implementation:
Boolean Boolean
True = 1 and -1
False = 0
UShort or
Word Unsigned 16 bit value (2 bytes). The value range is 0 to 65535.
UInt16
Short Int16 Signed 16 bit value (2 bytes). The value range is -32768 to 32767.
UInteger or
DWord Unsigned 32 bit value (4 bytes). The value range is 0 to 4294967295.
Uint32
Integer or Signed 32 bit value (4 bytes). The value range is -2,147,483,648 to
Long
Int32 2,147,483,647.
32 bit floating point value (4 bytes). The value range depends on
implementation:
Float Single
For negative values: -3.4028235E+38 to -1.401298E-45 .*
For positive values: 1.401298E-45 to 3.4028235E+38.*
64 bit floating point value (8 bytes). The value range depends on
implementation:
Long or Int64
8 bytes. The value range is 0 through 18,446,744,073,709,551,615 (1.8...E+19).
Char or Wide
0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28) with no
Char
decimal point.*
0 through +/-7.9228162514264337593543950335 with 28 places to the right of
Decimal
the decimal.
www. ptc.com
ClientAce 134
www. ptc.com
135 ClientAce
Applying ClientAce
For more information on applying ClientAce, select a link from the list below.
Licensing ClientAce
Upgrading ClientAce
Signing a Client Application
Deploying a Client Application
Licensing ClientAce
Unless ClientAce is licensed (and all Runtime applications built with the ClientAce .NET controls have been
signed), the applications will run in Demo Mode for one hour. After the demo period expires, another
demonstration period can be started by restarting the application. After ClientAce is licensed and the
Runtime applications built with ClientAce .NET controls are signed, the applications will run in unlimited
Runtime operation. For information on licensing ClientAce, refer to the instructions below.
For all licensing questions, contact Kepware Technologies at [email protected] or +1-207-775-1660 ext. 211.
4. In Registration Information, specify the Name and Company fields. As the information is entered,
the License Information field will be populated with the licensing information needed by Kepware
Technologies.
www. ptc.com
ClientAce 136
5. Once finished, click OK. This will invoke an email message window from the email client application.
To send the message to Kepware Technologies, click Send.
6. Kepware Technologies will then send an email reply containing the licensing code. Copy the code into
the Kepware ClientAce License dialog.
www. ptc.com
137 ClientAce
Note: ClientAce is now licensed. The custom client applications that have been built may now be
signed. For more information, refer to Signing Your Client Application.
Upgrading ClientAce
When upgrading a ClientAce project to a newer version, users should do the following:
1. Clean the project's Bin folders by removing all the files that have been created using the old .dll files.
This is necessary because the project must be created using the new .dll files, and some of the old
files may not be removed when the Solution Explorer is cleaned.
2. In the project's references, remove the current ClientAce .dll files that are referenced. Then, replace
them with the new .dll files.
3. Recompile and test the new project to ensure that it works using the new .dll files.
ClientAce must be licensed from Kepware Technologies before applications can be signed. For more
information, refer to Licensing ClientAce.
Signing the Custom Client Application Using the Visual Studio Sign Add-in
1. To start, open the project that needs to be signed.
2. Next, click the Sign icon in the toolbar. This tags the project's executable file to be signed whenever
the project is built.
www. ptc.com
ClientAce 138
Notes:
1. The license file (*.lic) is saved in the same folder as the executable file.
2. Signing the ClientAce applications will add the following two lines to the application's Post Build
events:
3. The install adds the ClientAce Add-in path to the IDE Add-in Security Option in Tools | Options |
Environment | Add-in Security | Add-in File Paths.
www. ptc.com
139 ClientAce
3. In Signing GUI, click the Ellipses button to browse for the application's executable file.
4. When the executable file is chosen, the signed license code will be displayed in the License File field.
The license file (*.lic) will be saved in the same folder as the executable file.
Note: The license file (*.lic) will be saved to the same folder that is chosen for the build output path in
Project Compile Preferences.
l In Visual Studio 2003 and Visual Studio 2005, the default output path is in bin\Debug\ in the project
folder.
l In Visual Studio 2008, the default output path is in bin\Release.
As a result of this change, Visual Studio 2008 users run in Demo Mode (and receive the Demo Mode popup)
when testing a project in Debug Mode that has been signed. To change this behavior, change the output
path to \bin\Debug.
For information on creating a Visual Studio set-up project so that a ClientAce application is deployed in
Licensed Mode, refer to the instructions below.
1. To start, sign the ClientAce EXE project (see Signing a Client Application).
3. Add the set-up project to the Visual Studio solution that contains the EXE project. In the Solution
Explorer, right-click on the solution and click Add | New Project.... Alternatively, if the solution or any
project is selected in the Solution Explorer, click File | Add... | New Project in the Visual Studio
menu.
4. In Add New Project, select Other Project Types | Setup and Deployment | Setup Project.
www. ptc.com
ClientAce 140
6. Once the set-up project appears in the Solution Explorer, right-click on the setup project and select
Add | Project Output....
7. In Add Project Output Group, locate the project field and select the ClientAce EXE project.
8. In the list box in the middle of the dialog, verify at least Primary Output is selected.
9. Click OK.
11. In Add Files, browse to the "bin\Release\" folder of the ClientAce EXE project (or other folder
according to the build configuration to be deployed.
13. In the Project Explorer, right-click on the solution and choose Project Dependencies....
14. Locate the Dependencies tab and select the setup project.
15. In the list in the middle of the dialog, check the ClientAce EXE project checkbox.
18. In the list at the upper-left corner, select the configuration to be built. This usually matches the folder
from step 11.
19. Locate the setup project in the table in the middle of the dialog, and check the Build checkbox.
21. When users build and deploy the setup project, the *.LIC file is included with the *.EXE. This runs the
application in Licensed Mode.
Note: The instructions above have been tested with a Windows Application project in Visual Studio 2010
and 2013. The steps should be similar for other types of projects.
For information on a specific version of Visual Studio and the .NET Assemblies, select a link from the list
below:
l Visual Studio 2003 and Visual Studio 2005 (.NET 2.0.0.x Assemblies)
l Visual Studio 2008 (.NET 3.5.0.x Assemblies)
l Visual Studio 2010, 2012, and 2013 (.NET 4.0.2.x Assemblies)
Visual Studio 2003 and Visual Studio 2005 (.NET 2.0.0.x Assemblies)
Depending on the ClientAce features being used by the application, one or more of the following files may
be required for the application to run properly:
www. ptc.com
141 ClientAce
Name Version
Kepware.ClientAce.Base.dll 2.0.0.x
Kepware.ClientAce.BrowseControls.dll 2.0.0.x
Kepware.ClientAce.Da_Junction.dll 2.0.0.x
Kepware.ClientAce.KEPServerExControls.dll 2.0.0.x
Kepware.ClientAce.OpcClient.dll 2.0.0.x
YourCustomClientAceApplication.exe
YourCustomClientAceApplication.lic
These files will be located in the output build directory created by Visual Studio for the project. When
deploying the client application created using ClientAce and the .NET 2.0.0.x Assemblies, these files must be
installed in the same location as the custom client executable files.
1. Click Start on the Windows desktop, and then select the Control Panel.
3. Next, scroll through the list of applications. If Microsoft .NET Framework 2.0 is listed, the version
required by ClientAce is already installed and does not need to be installed again.
4. To obtain versions of the .NET Framework, click Start on the Windows desktop and then select
Windows Update.
Note: The actual ClientAce install does not need to be installed on the destination computer for the
custom ClientAce application to work.
Name Version
Kepware.ClientAce.BrowseControls.dll 3.5.0.x
Kepware.ClientAce.Da_Junction.dll 3.5.0.x
Kepware.ClientAce.KEPServerExControls.dll 3.5.0.x
Kepware.ClientAce.OpcClient.dll 3.5.0.x
YourCustomClientAceApplication.exe
YourCustomClientAceApplication.lic
www. ptc.com
ClientAce 142
These files will be located in the project's output build directory that was created by Visual Studio. When
deploying the client application created using ClientAce and the .NET 3.5.0.x Assemblies, these files must be
installed in the same location as the custom client executable files.
1. Click Start on the Windows desktop, and then select the Control Panel.
3. Next, scroll through the list of applications. If Microsoft .NET Framework 3.5 SP1 is listed, the version
required by ClientAce is already installed and does not need to be installed again.
4. To obtain versions of the .NET Framework, click Start on the Windows desktop and then select
Windows Update.
Note: The actual ClientAce install does not need to be installed on the destination computer for the
custom ClientAce application to work.
Name Version
Kepware.ClientAce.BrowseControls.dll 4.0.2.x
Kepware.ClientAce.Da_Junction.dll 4.0.2.x
Kepware.ClientAce.KEPServerExControls.dll 4.0.2.x
Kepware.ClientAce.OpcClient.dll 4.0.2.x
YourCustomClientAceApplication.exe
YourCustomClientAceApplication.lic
These files will be located in the project's output build directory that was created by Visual Studio. When
deploying the client application created using ClientAce and the .NET 4.0.2.x Assemblies, these files must be
installed in the same location as the custom client executable files.
1. Click Start on the Windows desktop, and then select the Control Panel.
www. ptc.com
143 ClientAce
3. Next, scroll through the list of applications. If Microsoft .NET Framework 4.0 is listed, the version
required by ClientAce is already installed and does not need to be installed again.
4. To obtain versions of the .NET Framework, click Start on the Windows desktop and then select
Windows Update.
Note: The actual ClientAce install does not need to be installed on the destination computer for the
custom ClientAce application to work.
www. ptc.com
ClientAce 144
Troubleshooting
For more information on a common troubleshooting problem, select a link from the list below.
CoInitializeSecurity
The ClientAce application must set its security credentials such that an OPC server has the privilege to send
OnDataChange/OnServerShutDown notifications to the client. To set the security credentials, a ClientAce
application must set the security level using CoInitializeSecurity during the application's initialization.
Example Code
The Visual Basic and C# examples below show how to call CoInitializeSecurity in the ClientAce application.
[Visual Basic]
' .Net library for Interoperability
ImportsSystem.Runtime.InteropServices
' declaring the enum for the CoInitializeSecurity call
PublicEnum RpcImpLevel
E_Default = 0
E_Anonymous = 1
E_Identify = 2
E_Impersonate = 3
E_Delegate = 4
EndEnum
PublicEnum EoAuthnCap
www. ptc.com
145 ClientAce
E_None = &H0
E_MutualAuth = &H1
E_StaticCloaking = &H20
E_DynamicCloaking = &H40
E_AnyAuthority = &H80
E_MakeFullSIC = &H100
E_Default = &H800
E_SecureRefs = &H2
E_AccessControl = &H4
E_AppID = &H8
E_Dynamic = &H10
E_RequireFullSIC = &H200
E_AutoImpersonate = &H400
E_NoCustomMarshal = &H2000
E_DisableAAA = &H1000
End Enum
Inherits System.Windows.Forms.Form
www. ptc.com
ClientAce 146
Integer
InitializeComponent()
C#]
usingSystem.Runtime.InteropServices;
publicenum RpcImpLevel
{ Default = 0,
Anonymous = 1,
Identify = 2,
Impersonate = 3,
Delegate = 4
}
publicenum EoAuthnCap
{ None = 0x00,
MutualAuth = 0x01,
www. ptc.com
147 ClientAce
StaticCloaking= 0x20,
DynamicCloaking= 0x40,
AnyAuthority= 0x80,
MakeFullSIC= 0x100,
Default= 0x800,
SecureRefs= 0x02,
AccessControl= 0x04,
AppID= 0x08,
Dynamic= 0x10,
RequireFullSIC= 0x200,
AutoImpersonate= 0x400,
NoCustomMarshal= 0x2000,
DisableAAA= 0x1000
}
publicenum RpcAuthnLevel
{ Default = 0,
None = 1,
Connect = 2,
Call = 3,
Pkt = 4,
PktIntegrity = 5,
PktPrivacy = 6
}
namespace CSharpTestClient
{
www. ptc.com
ClientAce 148
public Form1()
InitializeComponent();
///
///
[STAThread]
Application.Run(new Form1());
[C#]
// .net library required for interoperability
usingSystem.Runtime.InteropServices;
// ******Enums required for CoInitializeSecurity call through C#.......//
publicenum RpcImpLevel
{ Default = 0, Anonymous = 1,
Identify = 2, Impersonate = 3,
Delegate = 4 }
publicenum EoAuthnCap
{ None = 0x00,
MutualAuth = 0x01,
www. ptc.com
149 ClientAce
StaticCloaking= 0x20,
DynamicCloaking= 0x40,
AnyAuthority= 0x80,
MakeFullSIC= 0x100,
Default= 0x800,
SecureRefs= 0x02,
AccessControl= 0x04,
AppID= 0x08,
Dynamic= 0x10,
RequireFullSIC= 0x200,
AutoImpersonate= 0x400,
NoCustomMarshal= 0x2000,
DisableAAA= 0x1000 }
publicenum RpcAuthnLevel
{ Default = 0, None = 1,
Connect = 2, Call = 3,
Pkt = 4, PktIntegrity = 5,
PktPrivacy = 6 }
/*****************end of enum declarations for CoInitializeSecurity call******/
(Continued)
namespace CSharpTestClient
{
publicclass Form1 : System.Windows.Forms.Form
{ // Import the CoInitializeSecurity call from
[DllImport("ole32.dll", CharSet = CharSet.Auto)]
public static extern int CoInitializeSecurity( IntPtr pVoid, int
cAuthSvc,IntPtrasAuthSvc, IntPtr pReserved1, RpcAuthnLevel level, RpcImpLevel impers,IntPtr
pAuthList, EoAuthnCap dwCapabilities, IntPtr
pReserved3 );
privateKepware.ClientAce.DA_Junction.ClientAceDA_Junction ClientAceDA_Junction1;
private System.Windows.Forms.TextBox textBox1;
public Form1()
{
InitializeComponent();
}
/// <summary>
///The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// call the CoInitializeSecurity right before Launching the Application
CoInitializeSecurity( IntPtr.Zero, -1, IntPtr.Zero,
IntPtr.Zero,RpcAuthnLevel.None ,
RpcImpLevel.Impersonate,IntPtr.Zero, EoAuthnCap.None, IntPtr.Zero );
Application.Run(new Form1());
}
}
www. ptc.com
ClientAce 150
Installing Visual Studio 2010 when Visual Studio 2008 and ClientAce are Currently
Installed
For information on installing Visual Studio 2010 when Visual Studio 2008 and ClientAce are already installed,
refer to the instructions below.
3. Once finished, click Start Visual Studio. Then, close Visual Studio.
4. Next, run the ClientAce setup and select Modify. Then, continue through the installation.
Note: This procedure is recommended because the Sign Toolbar and ClientAce Toolbox will not
successfully migrate from Visual Studio 2008. As a result, both the Sign Toolbar and the ClientAce
Toolbox added to Visual Studio 2010 will be invalid.
Repairing the Invalid Sign Toolbar and ClientAce Toolbox Added by Migrate
Settings
Users whose install of Visual Studio 2010 migrated settings from Visual Studio 2008 can use the following
procedure to repair the invalid Sign Toolbar and ClientAce Toolbox.
Manually Removing the Sign Toolbar and ClientAce Toolbox Added by Migrate
Settings
Users who do not want to use ClientAce with Visual Studio 2010 (or whose migration of the Visual Studio
2008 settings added an invalid Sign Toolbar and ClientAce Toolbox) can use the following procedure to
manually remove the Sign Toolbar and ClientAce Toolbox.
2. Locate the Toolbox window. Then, right-click and select Show All.
www. ptc.com
151 ClientAce
At this point, the specified user must run Microsoft Visual Studio and finish setting up the default Visual
Studio environment. Once completed, the ClientAce setup may continue.
The ClientAce setup cannot add toolbars or toolbox items until the Visual Studio environment has been
configured for the current user.
Missing Controls
The following controls are typically added to the system's Visual Studio Environment automatically during
the ClientAce installation process. If the Toolbox does not have any of the ClientAce controls, it is possible
that the controls were unchecked during the ClientAce installation process.
l DA_Junction
l ServerBrowser
l ItemBrowser
l ChannelSetting
l ServerState
1. To start, open a new C# or Visual Basic project using the Visual Studio .Net application.
www. ptc.com
ClientAce 152
2. Then, right-click anywhere on the Toolbox window and select Add Tab.
3. In the empty box, enter "ClientAce". This will create a ClientAce tab.
4. Next, right-click anywhere on the ClientAce tab and select Add/Remove Items.
www. ptc.com
153 ClientAce
5. In the Customize Toolbox window, click the Browse button. Then, navigate to the directory where
the "ClientAce.dll" files are stored.
www. ptc.com
ClientAce 154
6. Click to select the .dll file that contains the controls yet to be added. Then, click Open (or double-click
the .dll file).
www. ptc.com
155 ClientAce
7. Select a .dll file to display the Customize Toolbox window. In this example, the ClientAce.DA_Junction
library is checked for inclusion.
8. To add other controls, click Browse and then select another .dll file. Repeat until all the control files
(that is, all the .dll files) have been added to the Customize Toolbox for inclusion.
www. ptc.com
ClientAce 156
The Toolbox will display all controls that have been added.
Note: To display the applicable references in the Solution Explorer, select View | Solution Explorer.
Controls that have been added to the Visual Studio Environment can also be added to the Visual Studio
project by dragging them from the Toolbox | ClientAce tab onto the form. For more information, refer to
Additional Controls.
Referencing Controls
All referenced controls must be on the local drive. Assemblies that are located on a network drive should not
be referenced, as this will cause the Visual Studio error "Unable to cast object of type <type> to <type>." This
is a limitation of the Microsoft .NET development environment.
Note: This is only an issue with Visual Studio 2005 (not Visual Studio 2003).
1. To start, open Visual Studio. Then, click on the small arrow on the right edge of the blank toolbar
option and select Add or Remove Buttons.
www. ptc.com
157 ClientAce
3. In the Toolbars tab, locate Kepware Sign Bar. Check it, and then click Delete.
l For Visual Studio 2010, 2012, and 2013; specify .NET Framework 4.0.
2. Then, click Advanced Compile Options... | Advanced Compiler Settings and specify x86.
www. ptc.com
ClientAce 158
Appendix
For more information, select a link from the list below.
l V is for Vendor.
l Q is for Quality.
l S is for substatus.
l L is for Limit.
Quality
Bit
QQ Definition Notes
Value
0 00SSSSLL Bad The value is not useful for the reasons indicated by the substatus.
The quality of the value is uncertain for the reasons indicated by the
1 01SSSSLL Uncertain
substatus.
2 10SSSSLL N/A This is not used by OPC.
3 11SSSSLL Good The quality of the value is Good.
Note: Servers that do not support quality information must return 3 (Good). It is also acceptable for a server
to return Bad or Good (0x00 or 0xC0) and to always return 0 for substatus and limit.
www. ptc.com
159 ClientAce
Last Usable Value is different from a bad value with substatus 5 (Last
Last Usable
1 010001LL Known Value), which specifically indicates a detectable communications
Value
error on a "fetched" value. Last Usable Value indicates the failure of
some external source to send a value within an acceptable period of
time. The age of the value can be determined from the TIMESTAMP
value in OPCITEMSTATE.
2-3 N/A N/A This is not used by OPC.
Either the value has "pegged" at one of the sensor limits (in which case
Sensor Not the limit field should be set to 1 or 2) or the sensor is otherwise known to
4 010100LL
Accurate be out of calibration as indicated by some form of internal diagnostics (in
which case the limit field should be 0).
The value returned is outside of the limits defined for that parameter. In
Engineering
this case, the limit field indicates which limit has been exceeded;
5 010101LL Units
however, that does not necessarily mean that the value cannot move
Exceeded
farther out of range.
The value is derived from multiple sources and has less than the
6 010110LL Sub-normal
required number of good sources.
7-15 N/A N/A This is not used by OPC.
Limit
LL Bit Value Definition Notes
www. ptc.com
ClientAce 160
Note: The limit value is valid regardless of the quality and substatus values. In some cases (such as Sensor
Failure), the limit value can provide useful diagnostic information. Servers that do not support limit
information should return 0.
1. In the Solution Explorer, right-click on the project and then select Properties. Then, open the
Application tab.
The Application Manifest will be generated and opened in the Project View.
1. In the Solution Explorer, right-click on the project and then select Add.
3. In Add New Item, select Application Manifest file. Then, click Add.
The Application Manifest will be generated and opened in the Project View.
www. ptc.com
161 ClientAce
www. ptc.com
ClientAce 162
Index
Browse Method 51
BrowseFilter Enumeration 39
Class BrowseElement 29
ClientAce .NET API Assembly 8
ClientAceDA_Junction 89
ClsidFromProgID Method 22
CoInitializeSecurity 144
ConnectInfo Class 29
Converting Visual Studio 2008 to Visual Studio 2010 150
www. ptc.com
163 ClientAce
EndPointIdentifier Class 8
EnumComServer Method 23
fromDER Method 11
fromWindowsStore Method 15
fromWindowsStoreWithPrivateKey Method 18
IsConnected Property 88
Item Update Rate 106
ItemBrowser Control Properties 110
ItemIdentifier Class 32
ItemProperty Class 33
ItemResultCallback Class 33
ItemValue Class 33
ItemValueCallback Class 34
www. ptc.com
ClientAce 164
PkiCertificate Class 9
Project Setup 91
Property ID Enumeration 39
QualityID Class 35
Read Method 62
ReadAsync Method 68
ReadCompleted Event 45
Referencing Controls 156
www. ptc.com
165 ClientAce
Removing Blank Toolbar Options after Uninstalling ClientAce (VS 2005) 156
ResultID Class 36
ReturnCode Enumeration 41
Runtime Requirements 7
toDER Method 10
toWindowsStore Method 12
toWindowsStoreWithPrivateKey Method 14
Troubleshooting 144
www. ptc.com
ClientAce 166
Visual Studio 2003 and Visual Studio 2005 (.NET 2.0.0.x Assemblies) 140
Visual Studio 2008 (.NET 3.5.0.x Assemblies) 141
Visual Studio 2008, 2010, and 2012 157
Visual Studio 2010, 2012, and 2013 (.NET 4.0.2.x Assemblies) 142
WinStoreLocation Enumeration 21
Write Method 81
WriteAsync Method 86
WriteCompleted Event 49
www. ptc.com