You are on page 1of 94

Visual OPC .

NET
Develop OPC UA Clients and Servers
with C# / VB.NET

Windows | Linux | Mac OS X | iOS


Document Control
Version Date Comment

1.0 24.3.2012 Initial version


1.1 30.4.2012 Added Model Compiler chapter

Purpose and audience of document


Microsoft’s .NET Framework is an application development environment that supports multiple languages
and provides a large set of standard programming APIs. This document defines an Application
Programming Interface (API) for OPC UA Client and Server development based on the .NET
programming model.
The OPC UA specification can be downloaded from the web site of the OPC Foundation. But only part 1
(Overview and Concepts) is available to the public. All other parts can only be downloaded from OPC
Foundation members and may be used only as long as the user is an active OPC Foundation member.
Because of this fact the Visual OPC .NET API hides most of the OPC UA specifications to provide the
possibility to delevlop OPC UA Clients and OPC UA Servers in the .NET environment without the need to
be an OPC Foundation member. The API does support OPC Unified Architecture.
This document is intended as reference material for developers of OPC UA compliant Client and Server
applications. It is assumed that the reader is familiar with the Microsoft’s .NET Framework and the needs
of the Process Control industry.

Summary
This document gives a short overview of the functionality of the Visual OPC .NET product family. The goal of this
document is to give an introduction and can be used as base for your own implementations

Desktop | Mobile | Embedded


T ABLE OF C ONTENTS

1 Overview .................................................................................................................................. 8
1.1 OPC Technology ......................................................................................................... 8
1.1.1 Classic OPC Specifications ........................................................................... 8
1.1.2 OPC XML-DA Specification ......................................................................... 8
1.1.3 OPC .NET 3.0 (WCF)................................................................................... 8
1.1.4 OPC Unified Architecture Specification ...................................................... 9
2 Visual OPC .NET Product Line ............................................................................................... 10
2.1 Visual OPC Client .NET ............................................................................................. 10
2.2 Visual OPC Server .NET .............................................................................................11
2.3 Visual OPC Wrapper .NET ........................................................................................ 12
2.4 Visual OPC Proxy .NET ............................................................................................. 13
3 Introduction............................................................................................................................. 14
4 OPC UA Basics ........................................................................................................................ 16
4.1 Specifications ............................................................................................................. 16
4.2 Terms, definitions, and abbreviations ...................................................................... 17
4.2.1 OPC UA terms ............................................................................................. 17
4.2.1.1 AddressSpace ............................................................................... 17
4.2.1.2 Alarm ............................................................................................ 17
4.2.1.3 Attribute ....................................................................................... 17
4.2.1.4 Certificate ..................................................................................... 17
4.2.1.5 Client ............................................................................................ 17
4.2.1.6 Condition ...................................................................................... 17
4.2.1.7 Communication Stack .................................................................. 17
4.2.1.8 Complex Data .............................................................................. 17
4.2.1.9 Discovery ...................................................................................... 18
4.2.1.10 Event ............................................................................................ 18
4.2.1.11 EventNotifier................................................................................ 18
4.2.1.12 Information Model....................................................................... 18
4.2.1.13 Message ....................................................................................... 18
4.2.1.14 Method ......................................................................................... 18
4.2.1.15 MonitoredItem ............................................................................. 18
4.2.1.16 Node ............................................................................................. 18
4.2.1.17 NodeClass .................................................................................... 18

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 3 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.2.1.18 Notification .................................................................................. 18
4.2.1.19 NotificationMessage .................................................................... 19
4.2.1.20 Object ........................................................................................... 19
4.2.1.21 Object Instance ............................................................................ 19
4.2.1.22 ObjectType ................................................................................... 19
4.2.1.23 Profile ........................................................................................... 19
4.2.1.24 Program ....................................................................................... 19
4.2.1.25 Reference ..................................................................................... 19
4.2.1.26 ReferenceType ............................................................................. 19
4.2.1.27 RootNode ..................................................................................... 19
4.2.1.28 Server ........................................................................................... 19
4.2.1.29 Service ......................................................................................... 20
4.2.1.30 Service Set ................................................................................... 20
4.2.1.31 Session ........................................................................................ 20
4.2.1.32 Subscription ................................................................................ 20
4.2.1.33 Variable ....................................................................................... 20
4.2.1.34 View ............................................................................................ 20
4.2.2 Abbreviations and symbols......................................................................... 21
4.3 Address Space ...........................................................................................................22
4.3.1 Object Model ...............................................................................................22
4.3.2 Node Model .................................................................................................23
4.3.2.1 Node Classes ................................................................................23
4.3.2.2 Attributes .................................................................................... 24
4.3.2.3 References................................................................................... 24
4.3.3 Variables ..................................................................................................... 25
4.3.3.1 Properties .................................................................................... 25
4.3.3.2 Data Variables............................................................................. 25
5 Concepts ................................................................................................................................. 26
5.1 Stack API and Client API .......................................................................................... 26
5.2 Discovery Server ....................................................................................................... 26
5.3 Server API ..................................................................................................................27
5.4 OPC UA Core Stack Features................................................................................... 28
5.4.1 WCF Implementation ................................................................................. 28
5.4.2 Interfaces and WCF Service Contracts ...................................................... 29
5.4.3 WCF Bindings and Beahviours .................................................................. 30

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 4 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4.4 EndpointDescriptions and EndpointConfigurations .................................. 31
5.4.5 ConfiguredEndpoints ..................................................................................32
5.4.6 Application Configuration ........................................................................... 33
5.4.7 Extension Objects and Encodable Objects ............................................... 36
5.4.8 Installed Application ................................................................................... 37
5.4.9 Built-in Types and Data Types .................................................................. 38
5.4.9.1 Variants ....................................................................................... 40
5.4.10 Certificate Management and Validation ................................................... 40
5.4.10.1 UserIdentity and UserIdentityTokens ........................................ 41
5.4.11 ServiceResults, ServiceResultExceptions and DiagnosticInfos ................ 42
5.5 Model Compiler ........................................................................................................ 43
5.5.1 Command Line Parameters ....................................................................... 43
5.5.2 XSD Specification ....................................................................................... 43
5.5.2.1 Namespaces ................................................................................ 43
5.5.2.2 ObjectTypes ................................................................................ 44
5.5.2.3 Object .......................................................................................... 44
5.5.2.4 VariableType ............................................................................... 45
5.5.2.5 Variable ....................................................................................... 45
5.5.2.6 ReferenceType ............................................................................ 45
5.5.2.7 DataType ..................................................................................... 45
5.5.2.8 Properties .................................................................................... 45
5.5.3 Usage .......................................................................................................... 46
6 Client API ................................................................................................................................ 49
6.1 Classes ...................................................................................................................... 49
6.1.1 ApplicationInstance .................................................................................... 49
6.1.1.1 Properties .................................................................................... 50
6.1.1.2 Methods ...................................................................................... 50
6.1.2 Discover Servers ......................................................................................... 52
6.1.2.1 Properties .................................................................................... 52
6.1.2.2 Methods ...................................................................................... 52
6.1.3 Session ........................................................................................................ 54
6.1.3.1 Overview ..................................................................................... 54
6.1.3.2 Events .......................................................................................... 56
6.1.4 Subscription ................................................................................................. 61
6.1.4.2 Events .......................................................................................... 62

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 5 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.5 MonitoredItem ........................................................................................... 65
6.1.5.1 Events .......................................................................................... 66
7 Server API ............................................................................................................................... 67
7.1 Getting Started ......................................................................................................... 67
7.1.1 Server Development Process ..................................................................... 67
7.1.1.1 Create the Application Project ................................................... 67
7.1.1.2 Customize and Compile .............................................................. 67
7.1.1.3 Deployment ................................................................................. 68
7.1.2 Upgrading from OPC UA Server SDK .NET ............................................. 68
7.1.3 Changes in Version 1.1 ............................................................................... 70
7.2 Interfaces ................................................................................................................... 71
7.2.1 IOpcServerPlugin Interface ......................................................................... 71
7.2.1.1 Methods ....................................................................................... 71
7.2.2 IOpcServer Interface ...................................................................................75
7.2.2.1 Properties .....................................................................................75
7.2.2.2 Methods ...................................................................................... 76
7.2.3 Using your own server executable ............................................................ 89
8 Common API .......................................................................................................................... 90
8.1 Classes ...................................................................................................................... 90
8.1.1 LicenseHandler ........................................................................................... 90
8.1.1.1 Properties .................................................................................... 90
8.1.1.2 Methods ....................................................................................... 91

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 6 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


Disclaimer
© TerxaSoft GmbH. All rights reserved. No part of this document may be altered, reproduced or
distributed in any form without the expressed written permission of TerxaSoft GmbH.
This document was created strictly for information purposes. No guarantee, contractual specification or
condition shall be derived from this document unless agreed to in writing. TerxaSoft GmbH reserves the
right to make changes in the products and services described in this document at any time without notice
and this document does not represent a commitment on the part of TerxaSoft GmbH in the future.
While TerxaSoft GmbH uses reasonable efforts to ensure that the information and materials contained in
this document are current and accurate, TerxaSoft GmbH makes no representations or warranties as to
the accuracy, reliability or completeness of the information, text, graphics, or other items contained in the
document. TerxaSoft GmbH expressly disclaims liability for any errors or omissions in the materials
contained in the document and would welcome feedback as to any possible errors or inaccuracies
contained herein.
TerxaSoft GmbH shall not be liable for any special, indirect, incidental, or consequential damages,
including without limitation, lost revenues or lost profits, which may result from the use of these
materials. All offers are non-binding and without obligation unless agreed to in writing.

Trademark Notice
Microsoft, MSN, Windows and the Windows logo are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries. All other trademarks are the property
of their respective owners.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 7 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


1 Overview
If your application requires access to the OPC technology you have to decide which of the OPC
Specifications you want to support. The decision depends on many factors like the used OPC specifications
supported by third party products or the system architcture you want to use. TerxaSoft GmbH is
specialized in software consulting and development services for technical and industrial applications based
on OPC and the founder of TerxaSoft GmbH was involved in the design and development of many
software products with OPC connectivity with more then 14 years extensive knowledge about OPC.
The OPC Unified Architecture (UA) is THE next generation OPC standard that provides a cohesive, secure
and reliable cross platform framework for access to real time and historical data and events.
It's time to adapt this specification for use in your applications with keeping in mind that you may need to
support other OPC specifications as well. The Classic OPC specifications are widely used and it is
important that your application can support these specifications. We reccommend designing your
application to use the OPC Unified Architecture in the first place, with the option to have access to the
Classic OPC Specifications. A short overview of the mainly used Classic OPC Specifications should give you
an understanding of the requirements your application design have to fullfill.

1.1 OPC Technology

1.1.1 Classic OPC Specifications


The Classic OPC specifications are DCOM based specifications like OPC Data Access (DA), OPC
Alarms&Events (AE) and OPC Historical Access (HDA). Each of these specification is a separate
specification and several more exists.

1.1.2 OPC XML-DA Specification


The OPC XML-DA specification is a web services based specification and is a step between Classic OPC
and OPC Unified Architecture. The functionality is restricted to OPC DA.

1.1.3 OPC .NET 3.0 (WCF)


OPC .NET 3.0 (WCF) is not a specification like the others mentioned here, it bridges the gap between
Microsoft.NET and the world of Classic OPC. OPC .NET 3.0 is an OPC standard C# Application
Programming Interface (API) designed to simplify client access to OPC Classic servers. It also includes a
formal WCF Interface; however, there is no compliance or certification program for this interface. The
Classic OPC interfaces are still the primary means to ensure multi-vendor interoperability.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 8 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


1.1.4 OPC Unified Architecture Specification
OPC Unified Architecture (UA) is a platform-independent standard through which various kinds of
systems and devices can communicate by sending Messages between Clients and Servers over various
types of networks. It supports robust, secure communication that assures the identity of Clients and
Servers and resists attacks. OPC UA defines standard sets of Services that Servers may provide, and
individual Servers specify to Clients what Service sets they support. Information is conveyed using
standard and vendor- defined data types, and Servers define object models that Clients can dynamically
discover. Servers can provide access to both current and historical data, as well as Alarms and Events to
notify Clients of important changes. OPC UA can be mapped onto a variety of communication protocols
and data can be encoded in various ways to trade off portability and efficiency.
The OPC Foundation provides deliverables for its member companies. These include a .NET based OPC
UA Stack, an ANSI C based OPC UA Stack and a Java based OPC UA Stack. The .NET based OPC UA
Stack is the base of all TerxaSoft GmbH's .NET based products.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 9 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


2 Visual OPC .NET Product Line
The Visual OPC .NET product line consists of toolkits for OPC UA Client and OPC UA Server Development
as well as tools to give applications based on these toolkits access to the Classic OPC specifications.

2.1 Visual OPC Client .NET


The Visual OPC Client .NET offers a fast and easy access to the
OPC UA Client technology. Develop OPC compliant UA Clients
with C#/VB.NET for the .NET 4 frameworks.
With the Visual OPC Wrapper .NET OPC UA Clients has
access to Classic OPC DA, AE and HDA servers.
OPC Clients can be developed fast and easily without the need
to spend a lot of time learning how to implement OPC Unified
Architecture.
The Visual OPC Client API defines classes which can be used to
implement an OPC client capable to access OPC UA servers
supporting different profiles with the same API. These classes
manage client side state information; provide higher level
abstractions for OPC tasks such as managing sessions and
subscriptions or saving and restoring connection information
for later use.

Supported OPC Unified Architecture Profiles:


AddressSpace Lookup Client Facet
Attribute Read Client Facet
Attribute Write Client Facet
Base Client Behaviour Facet
Core Client Facet
DataAccess Client Facet
DataChange Subscriber Client Facet
Discovery Client Facet
Event Subscriber Client Facet
Historical Access
Alarms&Conditions

Supported OPC Specifications (through the Visual OPC Wrapper .NET):

OPC Data Access,


OPC Alarms&Events,
OPC Historical Data Access

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 10 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


2.2 Visual OPC Server .NET
The Visual OPC Server .NET offers a fast and easy access to
the OPC Unified Architecture (UA) technology. Develop OPC
UA 1.01 compliant Servers with C#/VB.NET or any other
compiler capable of generating a .NET assembly.
With the Visual OPC Proxy .NET OPC UA Servers can be
accessed from Classic OPC DA, AE and HDA clients.
The developer can concentrate on his application and servers
can be developed fast and easily without the need to spend a
lot of time learning how to implement the OPC Unified
Architecture specification. The server API is easy to use and
many OPC specific functions are handled by the framework.
The "Framework" includes all OPC UA 1.01 handling and
ensures the OPC compliance. It is implemented as a generic
C# based executable.
The "Server API" defines easy to use interface functions
required for developing OPC UA compliant servers. The OPC
server is supplied as an EXE file with the application adaptation part in a .NET assembly DLL. This
imposes some limitations on the adaptation possibilities but makes the adaptation much easier and
quicker. By using this API UA servers can be easily implemented by adapting just a few functions. There
are only a few functions that have to be implemented. The functions handle the configuration of the
server and the read/write functionality of items.
The provided sample servers and sample clients, together with the detailed documentation and online
help provides all essential information and tools you need to successfully develop your server application.
The Visual OPC Server .NET supports 32bit and 64bit operation.
Supported OPC UA Profiles (Base Edition):
Standard UA Server
DataAccess Server Facet

Supported OPC UA Profiles (Professional Edition):


Standard UA Server
DataAccess Server Facet
Basic Event Subscription Server Facet (under development)
Complex Type Server Facet (under development)
Method Server Facet (under development)
Node Manager Server Facet (under development)
Auditing Server Facet (under development)
Client Redundancy Server Facet (under development)
Historical Access (under development)
Programs (under development)
Alarms&Conditions (under development)

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 11 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


2.3 Visual OPC Wrapper .NET
You have a Classic OPC Server which is no longer supported or
updated by the server vendor but need to integrate it into OPC UA?
You want to eliminate the need to configure DCOM for network
operation? The Visual OPC Wrapper .NET is the right choice for
this.
The Visual OPC Wrapper .NET allows any OPC UA Clients to access
Classic OPC DA, AE and HDA servers. The Visual OPC Wrapper can
be configured with an integrated configuration tool. With this tool
you can specify the Classic OPC Server to be used as well as starting
node (folder) within the UA address space to be used for mapping
the Classic OPC Server address space.
The OPC Foundation provides UA COM Interop Components under
the OPC FOUNDATION REDISTRIBUTABLES license. This means
that OPC Foundation members can redistribute the software as part
of their products but the OPC Foundation expects to support the
redistributed OPC Foundation Software. TerxaSoft decided to
repackage the Wrapper part of the OPC Foundations UA COM Interop Components to be able to support
it more easily.
In general TerxaSoft has tested the wrapper with Classic OPC Servers developed by TerxaSoft. In addition
we have intensively tested the wrapper with Classic OPC Servers from different vendors. In any case
please get in contact with us if you encounter problems using this wrapper.
Features:
OPC DA, AE and HDA address space and functionality is mapped to separate nodes within the UA
address space
Automatically reconnect a Classic OPC Server in case connection is lost
Can be configured to use multiple Classic OPC Servers, each server’s address space mapped to its
own folder
Based on the latest OPC Foundations OPC UA SDK .NET
Intensively tested with Classic OPC Servers based on TerxaSoft products
Intensively tested with Classic OPC Servers from different vendors

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 12 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


2.4 Visual OPC Proxy .NET
You have a Classic OPC Client which is no longer
supported or updated by the client vendor but need to
integrate it into OPC UA? You want to eliminate the need
to configure DCOM for network operation? The Visual
OPC Proxy .NET is the right choice for this.
The Visual OPC Proxy .NET allows any OPC DA, AE or
HDA Client to access OPC UA servers. The Visual OPC
Proxy .NET can be configured with an integrated
configuration tool. With this tool you can specify the OPC
UA Server to be used as well as the Classic OPC Server it
should be mapped to.
The OPC Foundation provides UA COM Interop
Components under the OPC FOUNDATION
REDISTRIBUTABLES license. This means that OPC
Foundation members can redistribute the software as
part of their products but the OPC Foundation expects to
support the redistributed OPC Foundation Software.
TerxaSoft decided to repackage the Proxy part of the OPC Foundations UA COM Interop Components to
be able to support it more easily.
In general TerxaSoft has tested the proxy with Classic OPC Clients developed by TerxaSoft. In addition we
have intensively tested the wrapper with Classic OPC Clients from different vendors. In any case please get
in contact with us if you encounter problems using this proxy.
Features:
OPC DA, AE and HDA address space and functionality is mapped to separate Classic OPC servers.
Based on the latest OPC Foundations OPC UA SDK .NET
Includes a .NET 4 based version of the Local Discovery Server
Includes a .NET 4 based version of the UA Configuration Tool
Intensively tested with Classic OPC Clients based on TerxaSoft products
Intensively tested with Classic OPC Clients from different vendors

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 13 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


3 Introduction
OPC Unified Architecture (UA) is a platform-
independent standard through which various
kinds of systems and devices can communicate
by sending Messages between Clients and
Servers over various types of networks. It
supports robust, secure communication that
assures the identity of Clients and Servers and
resists attacks. OPC UA defines standard sets of
Services that Servers may provide, and individual
Servers specify to Clients what Service sets they
support. Information is conveyed using standard
and vendor-defined data types, and Servers
define object models that Clients can dynamically discover. Servers can provide access to both current and
historical data, as well as Alarms and Events to notify Clients of important changes. OPC UA can be
mapped onto a variety of communication protocols and data can be encoded in various ways to trade off
portability and efficiency.
OPC UA provides a consistent, integrated AddressSpace and service model. This allows a single OPC UA
Server to integrate data, Alarms and Events, and history into its AddressSpace, and to provide access to
them using an integrated set of Services. These Services also include an integrated security model.
OPC UA also allows Servers to provide Clients with type definitions for the Objects accessed from the
AddressSpace. This allows standard information models to be used to describe the contents of the
AddressSpace. OPC UA allows data to be exposed in many different formats, including binary structures
and XML documents. The format of the data may be defined by OPC, other standard organizations or
vendors. Through the AddressSpace, Clients can query the Server for the metadata that describes the
format for the data. In many cases, Clients with no pre-programmed knowledge of the data formats will
be able to determine the formats at runtime and properly utilize the data.
OPC UA adds support for many relationships between Nodes instead of being limited to just a single
hierarchy. In this way, an OPC UA Server may present data in a variety of hierarchies tailored to the way a
set of Clients would typically like to view the data. This flexibility, combined with support for type
definitions, makes OPC UA applicable to a wide array of problem domains. As illustrated below, OPC UA
is not targeted at just the telemetry server interface, but also as a way to provide greater interoperability
between higher level functions.
OPC UA is designed to provide robustness of published data. A major feature of all OPC servers is the
ability to publish data and Event Notifications. OPC UA provides mechanisms for Clients to quickly detect
and recover from communication failures associated with these transfers without having to wait for long
timeouts provided by the underlying protocols.
OPC UA is designed to support a wide range of Servers, from plant floor PLCs to enterprise Servers. These
Servers are characterized by a broad scope of size, performance, execution platforms and functional
capabilities. Therefore, OPC UA defines a comprehensive set of capabilities, and Servers may implement a
subset of these capabilities. To promote interoperability, OPC UA defines standard subsets, referred to as
Profiles, to which Servers may claim conformance. Clients can then discover the Profiles of a Server, and
tailor their interactions with that Server based on the Profiles. Profiles are defined in [UA Part 7].

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 14 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


The OPC UA specifications are layered to isolate the core design from the underlying computing
technology and network transport. This allows OPC UA to be mapped to future technologies as necessary,
without negating the basic design. Mappings and data encodings are described in [UA Part 6]. Two data
encodings are defined in this part:
• XML/text
• UA Binary
In addition, two transport mappings are defined in this part:
• TCP
• SOAP Web services over HTTP
Clients and Servers that support multiple transports and encodings will allow the end users to make
decisions about tradeoffs between performance and XML Web service compatibility at the time of
deployment, rather than having these tradeoffs determined by the OPC vendor at the time of product
definition.
OPC UA is designed as the migration path for OPC clients and servers that are based on Microsoft COM
technology. Care has been taken in the design of OPC-UA so that existing data exposed by OPC COM
servers (DA, HDA and A&E) can easily be mapped and exposed via OPC UA. Vendors may choose to
migrate their products natively to OPC UA or use external wrappers to convert from OPC COM to OPC UA
and vice-versa. Each of the previous OPC specifications defined its own address space model and its own
set of Services. OPC UA unifies the previous models into a single integrated address space with a single
set of Services.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 15 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4 OPC UA Basics
This chapter describes the base concepts of the OPC UA specification. It is not intended to replace
studying the OPC UA specification; its purpose is to introduce the base concepts of the OPC UA
specification.

4.1 Specifications
The OPC UA specification is organized as a multi-part specification, splitted into 3 sections:

1. Core Specification Parts


The first seven parts specify the core capabilities of OPC UA. These core capabilities define the
structure of the OPC AddressSpace and the Services that operate on it.
2. Access Type Specification Parts
Parts 8 through 11 apply these core capabilities to specific types of access previously addressed by
separate OPC COM specifications, such as Data Access (DA), Alarms and Events (A&E) and
Historical Data Access (HDA).
3. Utility Specification Parts
Part 12: describes Discovery mechanisms for OPC UA and Part 13 describe ways of aggregating
data.

Unfortunatley most of the OPC UA specification documents can only be downloaded by OPC Foundation
members from the OPC Foundation web site. Only part 1 (Overview and Concepts) is available to the
public. All other parts are available only to OPC Foundation members and may be used only as long as the
user is an active OPC Foundation member.
The OPC Foundation offers an OPC UA SDK but also this one is only available for OPC Foundation
members. Because of this TerxaSoft GmbH decided to develop the Visual OPC Client .NET with the
following main goals:

Ease of Use
By hiding the complexity of the OPC UA specification it should be possible for a developer with
just OPC UA Basic Knowledge to implement an OPC UA client.
Compliance
By using the OPC UA SDK provided by the OPC Foundation as base of the Visual OPC Client .NET
compliance to the OPC UA specification can be guaranteed.

The following sections give the reader an introduction in OPC UA. Most of these parts are summaries of
the OPC UA specifications and are reduced to those parts which are required for the reader to understand
the basics of OPC UA. Mappings between definitions in the OPC UA specifications and those used in the
Visual OPC Client .NET are given as soon as they are used the first time.
In case you are interested in an Overview of OPC UA please consider downloading part 1 (Overview and
Concepts) through the OPC Foundation web site. The direct link is
http://www.opcfoundation.org/DownloadFile.aspx?CM=3&RI=414&CN=KEY&CI=283&CU=7.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 16 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.2 Terms, definitions, and abbreviations
For the purposes of this specification, the following definitions apply. Please note that the following
sections are an excerpt of part 1 (Overview and Concepts) of the OPC UA specification.

4.2.1 OPC UA terms

4.2.1.1 AddressSpace
AddressSpace is the collection of information that an OPC UA Server makes visible to its Clients. See Part
3: for a description of the contents and structure of the Server AddressSpace.

4.2.1.2 Alarm
A type of Event associated with a state condition that typically requires acknowledgement. See Part 9: for
a description of Alarms.

4.2.1.3 Attribute
An Attribute is a primitive characteristic of a Node. All Attributes are defined by OPC UA, and may not be
defined by Clients or Servers. Attributes are the only elements in the AddressSpace permitted to have data
values.

4.2.1.4 Certificate
A certificate is a digitally signed data structure that describes capabilities of a Client or Server.

4.2.1.5 Client
A software application that sends Messages to OPC UA Servers conforming to the Services specified in
this set of specifications.

4.2.1.6 Condition
A Condition is a generic term that is an extension to an Event. A Condition represents the conditions of a
system or one of its components and always exists in some state.

4.2.1.7 Communication Stack


A layered set of software modules between the application and the hardware that provides various
functions to encode, encrypt and format a Message for sending, and to decode, decrypt and unpack a
Message that was received.

4.2.1.8 Complex Data


Data that is composed of elements or more than one primitive data type, such as a structure.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 17 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.2.1.9 Discovery
Discovery represents the process by which OPC UA Client obtain information about OPC UA Servers,
including endpoint and security information.

4.2.1.10 Event
A generic term used to describe an occurrence of some significance within a system or system component.

4.2.1.11 EventNotifier
A special Attribute of a Node that signifies that a Client may subscribe to that particular Node to receive
Notifications of Event occurrences.

4.2.1.12 Information Model


An organizational framework that defines, characterizes and relates information resources of a given
system or set of systems. The core address space model supports the representation of Information
Models in the AddressSpace. See Part 5: for a description of the base OPC UA Information Model.

4.2.1.13 Message
The data unit conveyed between Client and Server that represents a specific Service request or response.

4.2.1.14 Method
A Method is a callable software function that is a component of an Object.

4.2.1.15 MonitoredItem
A Client-defined entity in the Server used to monitor Attributes or EventNotifiers for new values or Event
occurrences and generate Notifications for them.

4.2.1.16 Node
A Node is the fundamental component of an AddressSpace.

4.2.1.17 NodeClass
A NodeClass is the class of a Node in an AddressSpace. NodeClasses define the metadata for the
components of the OPC UA Object Model. They also define constructs, such as Views, that are used to
organize the AddressSpace.

4.2.1.18 Notification
The generic term for data that announces the detection of an Event or of a changed Attribute value.
Notifications are sent in NotificationMessages.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 18 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.2.1.19 NotificationMessage
A Message published from a Subscription that contains one or more Notifications.

4.2.1.20 Object
An Object is a Node that represents a physical or abstract element of a system. Objects are modelled using
the OPC UA Object Model. Systems, subsystems and devices are examples of Objects. An Object may be
defined as an instance of an ObjectType.

4.2.1.21 Object Instance


An Object Instance is a synonym for Object. Not all Objects are defined by ObjectTypes.

4.2.1.22 ObjectType
An ObjectType is a Node that represents the type definition for an Object.

4.2.1.23 Profile
A specific set of capabilities, defined in Part 7:, to which a Server may claim conformance. Each Server
may claim conformance to more than one Profile.

4.2.1.24 Program
An executable Object that, when invoked, immediately returns a response to indicate that execution has
started, and then returns intermediate and final results through Subscriptions identified by the Client
during invocation.

4.2.1.25 Reference
A Reference is an explicit relationship (a named pointer) from one Node to another. The Node that
contains the Reference is the source Node, and the referenced Node is the target Node. All References are
defined by ReferenceTypes.

4.2.1.26 ReferenceType
A ReferenceType is a Node that represents the type definition of a Reference. The ReferenceType specifies
the semantics of a Reference. The name of a ReferenceType identifies how source Nodes are related to
target Nodes and generally reflects an operation between the two, such as “A Contains B”.

4.2.1.27 RootNode
The beginning or top Node of a hierarchy. The RootNode of the OPC UA AddressSpace is defined in Part
5.

4.2.1.28 Server
A software application that implements and exposes the Services specified in this set of specifications.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 19 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.2.1.29 Service
A Service is a Client-callable operation in an OPC UA Server. Services are defined in Part 4:. A Service is
similar to a method call in a programming language or an operation in a Web services WSDL contract.

4.2.1.30 Service Set


A Service Set is a group of related Services.

4.2.1.31 Session
A Session is a logical long-running connection between a Client and a Server. A Session maintains state
information between Service calls from the Client to the Server.

4.2.1.32 Subscription
A Client-defined endpoint in the Server, used to return Notifications to the Client. Generic term that
describes a set of Nodes selected by the Client (1) that the Server periodically monitors for the existence
of some condition, and (2) for which the Server sends Notifications to the Client when the condition is
detected.

4.2.1.33 Variable
A Variable is a Node that contains a value.

4.2.1.34 View
A View is a specific subset of the AddressSpace that is of interest to the Client.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 20 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.2.2 Abbreviations and symbols
A&E Alarms and Events
API Application Programming Interface
COM Component Object Model
DA Data Access
DCS Distributed Control System
DX Data Exchange
HDA Historical Data Access
HMI Human-Machine Interface
LDAP Lightweight Directory Access Protocol
MES Manufacturing Execution System
OPC OPC Foundation (a non-profit industry association)
PLC Programmable Logic Controller
SCADA Supervisory Control and Data Acquisition
SOAP Simple Object Access Protocol
UA Unified Architecture
UDDI Universal Description, Discovery and Integration
UML Unified Modelling Language
WSDL Web Services Definition Language
XML Extensible Mark-up Language

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 21 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.3 Address Space
The primary objective of the AddressSpace is to provide a standard way for servers to represent Objects to
clients.
Classic OPC servers in general represented this information as hierarchical trees. OPC DA servers for
example expose a hierarchy of branches and items, where branches are used to organize other branches
and items, and only items may have a value. OPC AE servers on the other hand organize their information
as areas and sources.

4.3.1 Object Model


OPC UA considers metadata as a part of the AddressSpace and is not limited to hierarchical trees. The
OPC UA Object Model has been designed to meet this objective. It defines Objects in terms of Variables
and Methods. It also allows relationships to other Objects to be expressed.

Object
Data Change
Notification
Variables
……..
…….. References to
Read/Write …….. other objects

Invoke
Methods
……..()
Event
Notification
……..()
……..()

The elements of this model are represented in the AddressSpace as Nodes. Each Node is assigned to a
NodeClass and each NodeClass represents a different element of the Object Model.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 22 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.3.2 Node Model
The set of Objects and related information that the OPC UA server makes available to clients is referred to
as its AddressSpace.
The AddressSpace consists of Nodes and References. Nodes represent various entities exposed by the
server, such as Variables, Objects and Data Types. Objects and their components are represented in the
AddressSpace as a set of Nodes described by Attributes and interconnected by References.

Node
Attributes Attributes describe a Node
……..
……..
……..
References define
relationships to other nodes
References
……..
……..
……..
Node

4.3.2.1 Node Classes


NodeClasses are defined in terms of the Attributes and References that shall be instantiated (given values)
when a Node is defined in the AddressSpace. Depending on the meaning of a particular Node a Node is
belonging to one of the following Classes:
• Variable
• Object
• Method
• View
• DataType
• VariableType
• ObjectType
• ReferenceType
These NodeClasses are referred to collectively as the metadata for the AddressSpace. Each Node in the
AddressSpace is an instance of one of these NodeClasses. No other NodeClasses shall be used to define
Nodes, and as a result, clients and servers are not allowed to define NodeClasses or extend the definitions
of these NodeClasses.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 23 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.3.2.2 Attributes
Attributes are data elements that describe Nodes. Clients can access Attribute values using Read, Write,
Query, and Subscription/MonitoredItem Services.
Attributes are elementary components of NodeClasses. Attribute definitions are included as part of the
NodeClass definitions and, therefore, are not included in the AddressSpace.
Each Attribute definition consists of an attribute id, a name, a description, a data type and a
mandatory/optional indicator. The set of Attributes defined for each NodeClass shall not be extended by
clients or servers.
When a Node is instantiated in the AddressSpace, the values of the NodeClass Attributes are provided.
The mandatory/optional indicator for the Attribute indicates whether the Attribute has to be instantiated.

4.3.2.3 References
References are used to relate Nodes to each other. They can be accessed using the browsing and querying
Services.
Like Attributes, they are defined as fundamental components of Nodes. Unlike Attributes, References are
defined as instances of ReferenceType Nodes. ReferenceType Nodes are visible in the AddressSpace and
are defined using the ReferenceType NodeClass.
The Node that contains the Reference is referred to as the SourceNode and the Node that is referenced is
referred to as the TargetNode. The combination of the SourceNode, the ReferenceType and the
TargetNode are used in OPC UA Services to uniquely identify References.
Thus, each Node can reference another Node with the same ReferenceType only once. Any subtypes of
concrete ReferenceTypes are considered to be equal to the base concrete ReferenceTypes when
identifying References). The following figure illustrates this model of a Reference.

SourceNode
ReferenceName TargetNode

The TargetNode of a Reference may be in the same AddressSpace or in the AddressSpace of another OPC
UA server. TargetNodes located in other servers are identified in OPC UA Services using a combination of
the remote server name and the identifier assigned to the Node by the remote server.
OPC UA does not require that the TargetNode exists, thus References may point to a Node that does not
exist.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 24 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4.3.3 Variables
Variables are used to represent values. Two types of Variables are defined, Properties and DataVariables.
They differ in the kind of data they represent and whether they can contain other Variables.

4.3.3.1 Properties
Properties are server-defined characteristics of Objects, DataVariables and other Nodes. Properties differ
from Attributes in that they characterise what the Node represents, such as a device or a purchase order.
Attributes define additional metadata that is instantiated for all Nodes from a NodeClass. Attributes are
common to all Nodes of a NodeClass and only defined by this specification whereas Properties can be
server-defined.
For example, an Attribute defines the DataType of Variables whereas a Property can be used to specify the
engineering unit of some Variables.
To prevent recursion, Properties are not allowed to have Properties defined for them. To easily identify
Properties, the BrowseName of a Property shall be unique in the context of the Node containing the
Properties.
A Node and its Properties shall always reside in the same server.

4.3.3.2 Data Variables


DataVariables represent the content of an Object. For example, a file Object may be defined that contains
a stream of bytes. The stream of bytes may be defined as a DataVariable that is an array of bytes.
Properties may be used to expose the creation time and owner of the file Object.
For example, if a DataVariable is defined by a data structure that contains two fields, “startTime” and
“endTime”, it might have a Property specific to that data structure, such as “earliestStartTime”.
As another example, function blocks in control systems might be represented as Objects. The parameters
of the function block, such as its setpoints, may be represented as DataVariables. The function block
Object might also have Properties that describe its execution time and its type.
DataVariables may have additional DataVariables, but only if they are complex. In this case, their
DataVariables shall always be elements of their complex definitions.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 25 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5 Concepts
The Visual OPC Client .NET is a collection of libraries, applications and samples that allow developers to
build OPC Unified Architecture client applications. It is based on the OPC Foundation sample code and is a
pure .NET 4 implementation. The picture on the right illustrates the interfaces between the Visual OPC
Client .NET, the OPC UA Core Stack and the applications.
This chapter is intended as a starting point and shows several usage example of the Visual OPC Client
.NET.

5.1 Stack API and Client API


The OPC UA Core Stack API encapsulates the details of
the wire protocol behind a set of classes and interfaces.
These interfaces implement all of the UA services
defined in the OPC Unified Architecture Specification
Part 4 as method calls. Applications which are built with
the Stack API do not have any direct dependencies on
the wire protocol and support all protocols which are
supported by the Stack.
Each wire protocol used in UA is a combination of a
messaging encoding, a security protocol and a transport
protocol. These combinations are called Stack Profiles
and they are defined in the OPC Unified Architecture
Specification Part 7. The Stack makes use of features
provided by the development environment whenever
possible (e.g. the .NET based Stack uses the WS-Secure Conversation implementation which is a part of
the .NET Framework).
The Stack provides an implementation of the wire protocol(s) plus a variety of helper classes but does not
contain any application level code.
For this reason the Visual OPC Client .NET also provides an API which implement features which are
common to all UA cliant applications. It is built on top of the Stack API and exposes a second API (called
the Client API). The Client API is designed for ease of use.
The OPC UA Core Stack delivered with the Visual OPC Client .NET is based on the OPC Foundations
original version with minor modifications required because of .NET 4 usage.

5.2 Discovery Server


A UA Local Discovery Server (LDS) is a specialized
application which allows clients to discover the UA
Servers that exist on a single machine. All UA Servers
running on a machine should register with the UA Local
Discovery Server using the Stack API. The UA Local
Discovery Server is a standalone executable. The
original OPC UA Discovery server is delivered with the
Visual OPC Client .NET as well as a .NET 4 based
version.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 26 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.3 Server API
The interfaces defined fall into two categories
separating functionality that is intended to be called
by the UA Server generic executable and functionality
that is intended to be called from the Server
Cuistomization DLL.
UA Server SDK
The first interface called IOpcServerPlugin Interface
(OPC UA Server Core functionality)
must be implemented by the Server Customization
DLL and consists of methods which are called by the
UA Server generic executable. These methods are
IOpcServer Interface
used to inform the Server Customization DLL about
different states of the server and allow the
customization part to act accordingly. For example if IOpcServerPlugin Interface
the OnCreateAddressSpace() is called the
customization DLL is allowed to create the address Server Customization
space. C#/VB.NET, ...
The second interface called IOpcServer Interface is
implemented by the UA Server generic executable
and consists of methods which can be called by the Server Customization DLL. For example with the
CreateDataItemVariable() method the customization part can create a new DataItem variable.
Both interfaces are explained in detail in the following chapters. There are several more interfaces defined
which are also explained in detail in the following chapters.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 27 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4 OPC UA Core Stack Features
The Visual OPC Client .NET is build on top of the OPC UA Core Stack. Some features of this stack are
explained in this chapter.

5.4.1 WCF Implementation


The Visual OPC Client .NET is built using the
Windows Communication Foundation (WCF)
which is part of the .NET Framework Version
3.0 and later.
An application which initiates a message
exchange is called the WCF Client and the
application which waits for incoming messages
is called a WCF Service (Note that the use of
the term ‘Service’ in WCF is different from the
use of the term in UA. An UA Service is
equivalent to a WCF Operation).
A WCF Service may expose one or more WCF
Endpoints which represent an addressable
location on the network. Each WCF Endpoint is
described by an address, a binding and a
contract. The address specifies where to send
messages. The binding describes how to send
messages. And the contract describes what the messages contain. WCF Clients need to know this
information before they can access a WCF Service.
A WCF contract has 4 parts: a ServiceContract, an OperationContract, a MessageContract and a
DataContract. The ServiceContract defines the operations supported by a WCF Endpoint. It is
implemented as an interface decorated with the ServiceContract attribute. The OperationContract defines
a single message exchange that a Client may initiate. An OperationContract may define a single message
or a request-response message pair (UA applications only use request-response message pairs). It is
implemented as method decorated with OperationContract attribute. A MessageContract defines the body
of a SOAP message exchanged during an operation. It is implemented as a class decorated with
MessageContract attribute. The DataContract describes a parameter in the message and is also
implemented as a class.
A WCF Channel is logical network connection that can be used to exchange multiple messages. A WCF
Client must create a WCF Channel when it connects to an Endpoint. When a channel is created the
security tokens are negotiated and a unique identifier is assigned. This identifier is used by the application
to associate a UA session with a particular WCF channel. A single UA session can only be accessed via one
WCF channel at any given time. If the WCF channel is closed for any reason (e.g. a network interruption)
the client must create a new WCF channel and associate it with UA Session by calling the ActivateSession
service.
More information on the WCF programming model can be found in the MSDN documentation provided
by Microsoft.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 28 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4.2 Interfaces and WCF Service Contracts
Servers and Discovery Servers implement the Services defined in OPC Unified Architecture Specification
part 4 (Services). Each Service is implemented as a method call on an object supporting a C# interface.
The structures and enumerations defined as Service parameters are implemented with C# classes and
enumerations.
The Services defined in OPC Unified Architecture Specification part 4 are grouped into three interfaces:
ISessionEndpoint, IDiscoveryEndpoint and IRegistrationEndpoint. Each of these interfaces are declared as
WCF ServiceContracts. Each of the methods in the interfaces defines the WCF OperationContract for a UA
Service. The parameters defined for the Services are declared as WCF DataContracts.
All of the interfaces inherit from IEndpointBase which defines the InvokeService OperationContract. All
UA Services can be invoked directly with the method of the same name or via the generic InvokeService
OperationContract. The parameters passed when using InvokeService method are byte arrays containing
the messages encoded with UA Binary encoding. If services are invoked directly by a client the messages
are serialized by the current WCF channel. The Stack also provides standard bindings (see WCF Bindings
and Behaviors) which can configure the WCF channel to serialize messages using UA Binary and call the
InvokeService method in the background. These bindings allow developers to build client applications that
only use the standard methods while using configuration settings to switch between the UA Binary and
UA XML encoding.
The interfaces and the types used by the interfaces are generated automatically using a Code Generator.
This ensures that the ServiceContracts exactly implement the official UA WSDL. A WSDL (Web Services
Definition Language) (pronounced Wiz-Dill) is a language (W3C standard, based on XML) that is used to
describe XML Web Services. These interfaces are summarized in the table below.
Interface Description
ISessionEndpoint Defines all methods used to access the data and events exposed by a Server.
These methods can only be used after the client has created a Session with the
Server. The methods used to create Sessions are also part of this interface.
IDiscoveryEndpoint Defines the methods used to discover Servers and their endpoints. This
interface is implemented by Servers and Discovery Servers.
IRegistrationEndpoint Defines the methods use to register a Server with a Discovery Server. This
interface is only implemented by Discovery Servers.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 29 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4.3 WCF Bindings and Beahviours
WCF Channels and Endpoints require a WCF Binding that specifies the protocol to use plus any
configuration or security parameters. Client and server applications cannot communicate with each other
if the WCF Bindings do not match.
WCF Channels and Endpoints may also have WCF Behaviors which allow the application to insert custom
processing steps into the WCF stack. WCF Behaviors are used by the OPC UA Core Stack to add support
for the UA Binary encoding and for automatic serialization of extensible parameters and structured data
values (see Extension Objects and Encodeable Objects).
WCF Bindings provide a large number of configurable parameters which can create interoperability
problems especially when communicating with non-WCF applications. For this reason the OPC UA Core
Stack defines a number of custom WCF Bindings for different wire protocols. The table below describes
the available WCF Bindings.
Binding URL Scheme Description
UaSoapXmlBinding http Uses SOAP/HTTP + WS-SecureConversation + UA
XML or UA Binary encodings. Implements the
WsHttpXmlOrBinary Transport Profile.
UaTcpBinding opc.tcp Uses UA TCP + UA-SecureConversation + UA Binary
encoding. Implements the UaTcpBinary Transport
Profile.

UaSoapXmlOverTcpBinding net.tcp Uses SOAP/.NET TCP + WS-SecureConversation + UA


XML or UA Binary encodings. Not a supported
binding. Provided to demonstrate that developers can
use protocols other than ones required by the
specifications.
NativeStackBinding opc.tcp Uses UA TCP + UA-SecureConversation + UA Binary
encoding. Implements the UaTcpBinary Transport
Profile. This is the same as the UaTcpBinding except it
uses the ANSI C implementation of the UA TCP
protocol. It is used primarily for testing.

The Binding may be passed directly to the Channel objects (See WCF Channels and Clients) when they are
created, however, the OPC UA Core Stack also provides a BindingFactory mechanism that allows the
Channel to create the correct Binding from the current configuration information. Developers should
initialize the BindingFactory from the application configuration and then pass the BindingFactory to the
Channel object. The Channel object will then create the Binding that matches the scheme in the URL for
the endpoint.
Administrators can then specify the mapping between different URL schemes and .NET classes in the
application configuration file (See Application Configuration).
This mechanism allows new WCF Bindings and protocols to be added to applications after they have been
deployed, however, it does not offer the ability to construct an arbitrary WCF Binding in a configuration
file. This capability was intentionally left out because minor differences in WCF Bindings can create
interoperability problems when applications developed by multiple vendors are deployed in a production

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 30 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


environment. That said, administrators may add behaviors to configuration files as they would with any
other WCF application.

Developers can create new Bindings creating subtypes of the BaseBinding class. The subtypes must define
a constructor with the parameters described in the table below.
Name Type Description
namespaceUris NamespaceTable A reference to the Server’s namespace table.
factory EncodeableFactory A reference to a factory capability of
encoding/decoding extensible parameters and
structured data values
configuration EndpointConfiguration The configuration for Endpoint.

5.4.4 EndpointDescriptions and EndpointConfigurations


An EndpointDescription describes an endpoint provided by an UA Server. The object specifies (among
other things) the name and URI for the server (which allows endpoints from the same server to be
grouped together), the required security policy and security mode, the supported transport profile and the
Server’s application instance certificate. The EndpointDescription object is used by the Server to initialize
its Endpoints (they are passed to the ServiceHost (s) when the Server starts). It is also used by the Client
to initialize the Channel objects. Clients can use the Discovery Services to fetch the EndpointDescriptions
for a Server before connecting. The EndpointDescription class is described completely in the OPC Unified
Architecture Specification Part 4.
An EndpointConfiguration specifies additional parameters which are used by the WCF stack but do not
affect the negotiation of the WCF channel. The table below describes the properties of the
EndpointConfiguration object.
Name Type Description
OperationTimeout Int32 The number of milliseconds to wait for a
response from the Server. This value is only
used by Clients.
UseBinaryEncoding Boolean Encodes messages using the UA Binary
encoding when supported by the Endpoint. The
TransportProfileUri in the EndpointDescription
indicates whether it is supported.
MaxStringLength Int32 The maximum length in characters of a single
string contained in a message.
MaxByteStringLength Int32 The maximum length in bytes of a single byte
string contained in a message. This parameter
is only completely supported when the UA
Binary Encoding is used. If UA XML encoding is
used it should be the same as the
MaxArrayLength.
MaxArrayLength Int32 The maximum length of a single array
contained in a message. This value must be
large enough to accommodate an entire

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 31 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


message when UA Binary is used with the
SOAP/HTTP transport.
MaxMessageSize Int32 The maximum length in bytes for a single
message.

MaxBufferSize Int32 The maximum buffer size to use when sending


or receiving. Note that the WCF stack will
allocate memory blocks of this size so setting
this parameter to large values will consume
memory and reduce performance. The default
value is 65,535.
SecurityTokenLifetime Int32 The number of milliseconds before a security
token must be renewed.

ChannelLifetime Int32 The number of milliseconds before a server


releases the resources for a broken secure
channel. This parameter is only used with the
UA TCP transport.

The EndpointConfiguration is used by custom Bindings to initialize the WCF Channel objects.
Servers create their EndpointDescription and EndpointConfigurations from the configuration provided by
the Administrator. Clients can retrieve the EndpointDescriptions for different Servers using the Discovery
Services, however, they may also be provided by the Administrator and/or User. The Client’s
EndpointConfiguration are always specified by the Administrator and/or User.

5.4.5 ConfiguredEndpoints
Client applications frequently need to persist information that will allow them to reconnect to a Server.
This information includes the EndpointDescription and EndpointConfiguration, however, it could include
other information such as the username/password. The ConfiguredEndpoint and
ConfiguredEndpointCollection classes allow Clients to persist this kind information. They also provide
convenience functions that assist with updating the information using the Discovery Services.
The ConfiguredEndpoint defines an Extensions property which allows application developers to save their
own configuration information with the endpoint.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 32 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4.6 Application Configuration
The stack provides an extensible mechanism for storing the application configuration in an XML file. The
class is extensible so developers can add their own configuration information to it. The table below
describes primary elements of the ApplicationConfiguration class.
Name Type Description
ApplicationName String A human readable name for the application.
ApplicationUri String A globally unique name for the application.
This should be a URL with which the machine
domain name or IP address as the hostname
followed by the vendor/product name
followed by an instance identifier. For
example:
http://machine1/OPC/UASampleServer/4853
DB1C-776D-4ADA-9188-00CAA737B780
ProductUri String A human readable name for the product.
ApplicationType ApplicationType The type of application. Possible values:
Server, Client, ClientAndServer and
DiscoveryServer
SecurityConfiguration SecurityConfiguration The security configuration for the application.
Specifies the application instance certificate,
list of trusted peers and trusted certificate
authorities.
TransportConfigurations TransportConfiguration Specifies the Bindings to use for each
Collection transport protocol used by the application.

TransportQuotas TransportQuotas Specifies the default limits to use when


initializing WCF channels and endpoints.
ServerConfiguration ServerConfiguration Specifies the configuration for Servers
ClientConfiguration ClientConfiguration Specifies the configuration for Clients
TraceConfiguration TraceConfiguration Specifies the location of the Trace file.
Unexpected exceptions that are silently
handled are written to the trace file.
Developers can add their own trace output
with the Utils.Trace(…) functions.
Extensions XmlElementCollection Allows developers to add additional
information to the file.
MessageContext ServiceMessageContext The context to use when
serializing/deserializing messages.
CertificateValidator CertificateValidator This is the custom certificate validator used by
the application.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 33 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


The ApplicationConfiguration can be persisted anywhere but the class provides functions that load/save
the configuration as an XML file on disk. The location of the XML file can be specified in the app.config
file for the application if the ConfigurationLocation is specified as a configuration section.
The declaration for the configuration section looks like this XML fragment:

XML

<configSections>
<section name="DataAccessConsole" type="Opc.Ua.ApplicationConfigurationSection,Opc.Ua.Core"/>
</configSections>

The name may be any text that is unique within the app.config file. The ConfigurationLocation would look
like this XML fragment:

XML

<DataAccessConsole>
<ConfigurationLocation xmlns="http://opcfoundation.org/UA/SDK/Configuration.xsd">
<FilePath>DataAccessConsole.Config.xml</FilePath>
</ConfigurationLocation>
</DataAccessConsole>

The FilePath can be an absolute path or a relative path. If it is a relative path the current directory is
searched followed by the directory where the executable resides. The stack also supports prefixes which
can be replaced with environment variables. The latter functionality requires a token enclosed by ‘%’
symbols at the start of the message. The stack will first check for a symbol that matches one of the values
from the Environment.SpecialFolder enumeration. If not found it will use the environment variable of the
same name.
Note that the same feature exists for all fields that represent file directory paths in the
ApplicationConfiguration object.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 34 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


The Application Configuration may look like:

XML

<?xml version="1.0" encoding="utf-8"?>


<ApplicationConfiguration
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ua="http://opcfoundation.org/UA/2008/02/Types.xsd"
xmlns="http://opcfoundation.org/UA/SDK/Configuration.xsd"
>
<ApplicationName>DataAccess Console Client</ApplicationName>
<ApplicationUri>urn:localhost:DataAccessConsoleClient</ApplicationUri>
<ProductUri>http://terxasoft.ch/DataAccessConsoleClient</ProductUri>
<ApplicationType>Client_1</ApplicationType>
<SecurityConfiguration>
<ApplicationCertificate>
<StoreType>Directory</StoreType>
<StorePath>%CommonApplicationData%\TerxaSoft\CertificateStores\MachineDefault</StorePath>
<SubjectName>Visual OPC Wrapper .NET</SubjectName>
</ApplicationCertificate>
<TrustedIssuerCertificates>
<StoreType>Directory</StoreType>
<StorePath>%CommonApplicationData%\TerxaSoft\CertificateStores\CertificateAuthorities</StorePath>
</TrustedIssuerCertificates>
<TrustedPeerCertificates>
<StoreType>Directory</StoreType>
<StorePath>%CommonApplicationData%\TerxaSoft\CertificateStores\TrustList</StorePath>
</TrustedPeerCertificates>
</SecurityConfiguration>
<TransportConfigurations></TransportConfigurations>
<TransportQuotas>
<OperationTimeout>600000</OperationTimeout>
<MaxStringLength>1048576</MaxStringLength>
<MaxByteStringLength>1048576</MaxByteStringLength>
<MaxArrayLength>65535</MaxArrayLength>
<MaxMessageSize>4194304</MaxMessageSize>
<MaxBufferSize>65535</MaxBufferSize>
<ChannelLifetime>300000</ChannelLifetime>
<SecurityTokenLifetime>3600000</SecurityTokenLifetime>
</TransportQuotas>
<ClientConfiguration>
<DefaultSessionTimeout>60000</DefaultSessionTimeout>
<WellKnownDiscoveryUrls>
<ua:String>opc.tcp://{0}:4840</ua:String>
<ua:String>http://{0}:52601/UADiscovery</ua:String>
<ua:String>http://{0}/UADiscovery/Default.svc</ua:String>
</WellKnownDiscoveryUrls>
<DiscoveryServers></DiscoveryServers>
<EndpointCacheFilePath>Opc.Ua.SampleClient.Endpoints.xml</EndpointCacheFilePath>
<MinSubscriptionLifetime>10000</MinSubscriptionLifetime>
</ClientConfiguration>
<Extensions></Extensions>
<TraceConfiguration>
<OutputFilePath>%LocalApplicationData%\TerxaSoft\Logs\DataAccessConsoleClient.log.txt</OutputFilePath>
<DeleteOnLoad>true</DeleteOnLoad>
<!-- Show Only Errors -->
<!-- <TraceMasks>1</TraceMasks> -->
<!-- Show Only Security and Errors -->
<!-- <TraceMasks>513</TraceMasks> -->
<!-- Show Only Security, Errors and Trace -->
<TraceMasks>515</TraceMasks>
<!-- Show Only Security, COM Calls, Errors and Trace -->
<!-- <TraceMasks>771</TraceMasks> -->
<!-- Show Only Security, Service Calls, Errors and Trace -->
<!-- <TraceMasks>523</TraceMasks> -->
<!-- Show Only Security, ServiceResultExceptions, Errors and Trace -->
<!-- <TraceMasks>519</TraceMasks> -->
</TraceConfiguration>

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 35 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


</ApplicationConfiguration>

5.4.7 Extension Objects and Encodable Objects


UA ExtensionObjects are containers for structured values that can be defined by the application vendor.
These objects have a TypeId which is the NodeId of the DataType Encoding Node and a Body which is a
ByteString or an XmlElement depending on the encoding used.
Encodeable Objects are any objects that implement the IEncodeableObject interface which allows the
Stack to automatically serialize and deserialize types which have been registered with the stack. The
EncodeableFactory is a table of Encodeable Objects indexed by the NodeIds for the supported DataType
Encodings.
The IEncoder and IDecoder interfaces provide an abstraction layer which Encodeable Objects can use to
serialize themselves to and from a stream. The stack provides encoder/decoders for all the encodings
defined in OPC Unified Architecture Specification Part 6 (UA Binary and UA XML at this time). Developers
can implement Encodeable Objects that use other encodings which are embedded in a UA Binary or UA
XML stream.
Classes that implement IEncodeableObject must provide absolute NodeIds for the binary and XML version
of the object. The absolute NodeIds include the NamespaceUri that qualifies the well known NodeId. This
NamespaceUri is assigned by the organization that defines the type being implemented.
The Stack takes care of converting the NamespaceUri to a NamespaceIndex for use on the wire but this
requires that the WCF Channel have access to the table of Namespaces for the Server. This is why the
Bindings included in the stack table a NamespaceTable as a parameter. The Bindings included in the stack
use custom WCF Behaviors which set the WCF OperationContext and the
ServiceMessageContext.ThreadContext property to ensure the Namespace table is available during
message serialization. Developers that create custom Bindings will need to add these behaviors to their
Bindings (ServiceMessageContextMessageInspector for UA XML and BinaryEncodingMessageInspector
for UA Binary)
The ServiceMessageContext also provides access to the EncodeableFactory object.
Note that developers always have the option of manually serializing an Encodeable Object in a
ExtensionObject and they will have to do this if they need to use an encoding that does not match the
current wire protocol. For example, a Client using the UA binary encoding may request that structures be
returned using the XML encoding. The Server will have to manually encode the objects in this case.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 36 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4.8 Installed Application
The stack provides an installation configuration mechanism for installing/uninstalling an application. For
this an InstallConfig.xml file containing the InstalledApplication class definition should be added to your
project as embedded resource. The table below describes some of the primary elements of the
InstalledApplication class.
Name Type Description
ConfigureFirewall Boolean Specifies whether the firewall should be
configured. True if the firewall should be
configured; false otherwise.
DeleteCertificatesOnUninstall Boolean Specifies whether the certificates should be
deleted if the application gets uninstalled.
True if the certificates should be deleted; false
otherwise.
InstallAsService Boolean Specifies whether the application should be
installed as service. True if the application
should be installed as service; false otherwise.
ServiceStartMode StartMode Specifies how the service start mode should
be configured.
ServiceUserName String Specifies the username of the user used for
running the application as service.
ServicePassword String Specifies the password of the user used for
running the application as service.
ServiceDescription String Specifies the description for the service.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 37 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


The InstallConfig.xml file may look like:

XML

<?xml version="1.0" encoding="utf-8" ?>


<s0:InstalledApplication
xmlns:s0="http://opcfoundation.org/UA/SDK/Installation.xsd"
xmlns:s1="http://opcfoundation.org/UA/SDK/Configuration.xsd"
xmlns="http://opcfoundation.org/UA/2011/03/SecuredApplication.xsd"
xmlns:ua="http://opcfoundation.org/UA/2008/02/Types.xsd">
<ApplicationName>DataAccess Console Application</ApplicationName>
<ApplicationUri></ApplicationUri>
<ApplicationType>Client_1</ApplicationType>
<ConfigurationFile>%CommonApplicationData%\TerxaSoft\Config\DataAccessConsole.Config.xml</ConfigurationFile>
<ApplicationCertificate>
<StoreType>Directory</StoreType>
<StorePath>%CommonApplicationData%\TerxaSoft\CertificateStores\MachineDefault</StorePath>
</ApplicationCertificate>
<TrustedCertificateStore>
<StoreType>Directory</StoreType>
<StorePath>%CommonApplicationData%\TerxaSoft\CertificateStores\UA Applications</StorePath>
</TrustedCertificateStore>
<IssuerCertificateStore>
<StoreType>Directory</StoreType>
<StorePath>%CommonApplicationData%\TerxaSoft\CertificateStores\UA Certificate Authorities</StorePath>
</IssuerCertificateStore>
<s0:DeleteCertificatesOnUninstall>true</s0:DeleteCertificatesOnUninstall>
<s0:ConfigureFirewall>true</s0:ConfigureFirewall>
<s0:SetConfigurationFilePermisions>true</s0:SetConfigurationFilePermisions>
<s0:SetExecutableFilePermisions>true</s0:SetExecutableFilePermisions>
<s0:InstallAsService>false</s0:InstallAsService>
<s0:TraceConfiguration>
<s1:OutputFilePath>%CommonApplicationData%\TerxaSoft\Logs\DataAccessConsole.InstallLog.txt</s1:OutputFilePath>
<s1:DeleteOnLoad>true</s1:DeleteOnLoad>
<s1:TraceMasks>2047</s1:TraceMasks>
</s0:TraceConfiguration>
</s0:InstalledApplication>

5.4.9 Built-in Types and Data Types


OPC UA defines a number of built in types. The Stack defines classes or structures for each of these types
and provides support for standard interfaces like IComparable, ICloneable and IFormattable. The table
below describes the built-in types.
Name Type Description
Boolean Boolean A two-state logical value (true or false).
SByte SByte An integer value between -128 and 127.
Byte Byte An integer value between 0 and 256.
Int16 Int16 An integer value between -32768 and 32767.
UInt16 UInt16 An integer value between 0 and 65535.
Int32 Int32 An integer value between – 2147483648 and
2147483647.
UInt32 UInt32 An integer value between 0 and 4294967295.
Int64 Int64 An integer value between –
9223372036854775808 and

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 38 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


9223372036854775807
UInt64 UInt64 An integer value between 0 and
18446744073709551615.
Float Float An IEEE single precision (32 bit) floating point
value.
Double Double An IEEE double precision (64 bit) floating point
value.
String String A sequence of Unicode characters.
DateTime DateTime An instance in time.
Guid Structure (Uuid) A 16 byte value that can be used as a globally
unique identifier.
ByteString Byte[] A sequence of octets.
XmlElement XmlElement An XML element.
NodeId Class An identifier for a node in the address space of
an OPC UA server.
ExpandedNodeId Class A NodeId that allows the namespace URI to be
specified instead of an index.
StatusCode Structure A numeric identifier for a error or condition that
is associated with a value or an operation.
QualifiedName Class A name qualified by a namespace.
LocalizedText Class Human readable text with an optional locale
identifier.
ExtensionObject Class A structure that contains an application specific
data type that may not be recognized by the
receiver.
DataValue Class A data value with an associated status code and
timestamps.
Variant Structure A union of all of the types specified above.
DiagnosticInfo Class A structure that contains detailed error and
diagnostic information associated with a
StatusCode.

The NodeId, ExpandedNodeId, QualifiedName and LocalizedText classes cannot be modified after
construction. This means they can be safely passed around as references without risk of side effects. These
types also define a static property called Null which should be used instead of the default constructor.
The stack provides an enumeration called BuiltInType that can be used to set up switch statements. The
numeric value for each BuiltInType is the same as the NodeId for the corresponding DataType Node.
The stack also provides a helper class called TypeInfo which provides methods to detect the Built-in Type
for an object and to convert between types.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 39 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4.9.1 Variants
UA Variants are the containers for any attribute values that are exchanged between UA applications. The
Variant structure is simply a wrapper for an object but it takes care of converting objects to types that can
be serialized on the wire. For example, any class that implements IList will be converted to an array and
any class that implements IEncodeable will be converted to an ExtensionObject. The Variant also takes
care of converting multidimensional arrays to Matrix objects.
The Variant structure also implements the UA XML encoding rules defined in OPC Unified Architecture
Specification Part 6.

5.4.10 Certificate Management and Validation


The stack provides a number of certificate management functions including a custom CertificateValidator
that implements the validation rules required by the specification. The CertificateValidator is created
automatically when the ApplicationConfiguration is loaded. Any WCF channels or endpoints that are
created with that ApplicationConfiguration will use it.
The CertificateValidator uses the trust lists in the ApplicationConfiguration to determine whether a
certificate is trusted. A certificate that fails validation is always placed in the Rejected Certificates store.
Applications can receive notifications when an invalid certificate is encountered by using the event defined
on the CertificateValidator class.
The Stack also provides the Certificate Identifier class which can be used to specify the location of
certificate . The Find() method will look up the certificate based on the criteria specified (SubjectName,
Thumbprint or DER Encoded Blob).
Each application has a SecurityConfiguration which must be managed carefully by the Administrator since
making a mistake could prevent applications from communicating or create security risks. The elements of
the SecurityConfiguration are described in the table below:
Name Description
ApplicationCertificate Specifies where the private key for the Application Instance Certificate is
located. Private keys should be in the Personal (My) store for the
LocalMachine or the CurrentUser. Private keys installed in the
LocalMachine store are only accessible to users that have been explicitly
granted permissions.
TrustedIssuerCertificates Specifies the Certificate Authorities that issue certificates which the
application can trust. The structure includes the location of a Certificate
Store and a list of individual Certificates.
TrustedPeerCertificates Specifies the certificates for other applications which the application can
trust. The structure includes the location of a Certificate Store and a list of
individual Certificates.
InvalidCertificateDirectory Specifies where rejected Certificates can be placed for later review by the
Admistrator (a.k.a. Rejected Certificates Store)

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 40 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


The Administrator needs to create an application instance certificate when applications are installed, when
the ApplicationUri or when the hostname changes. The Administrator can use the Configuration Tool
included in the SDK or use the tools provided by their Public Key Infrastructure (PKI). If the certificate is
changed the Application Configuration needs to be updated.
Once the certificate is installed the Administrator needs to ensure that all users who are allowed to access
the application have permission to access the Certificate’s private key. This can be also be done with the
UA Configuration Tool or it can be done programmatically via the ICertificateStore interface.
Sometimes a Certificate will fail validation for non-critical reasons and the Administrator wishes to allow
the Certificate anyways (e.g. the certificate has expired). In these situations the Administrator must add
the individual Certificate to either the TrustedIssuerCertificates or TrustedPeerCertificates element and
specify the validation flags for the certificate. The supported validation flags are described in the table
below:
Name Description
SuppressCertificateExpired Allows certificates that are expired or not yet valid.
SuppressHostNameInvalid Allows certificates where the hostname does not match the URL.
Each server Certificate has the hostnames embedded in the
certificate. These hostnames must match the URL being used to
connect to the Server.
SuppressUseNotAllowed Allows certificates where the certificate use was not set
correctly.The set of uses required for UA application instance
Certificates are specified in the OPC Unified Architecture
Specification Part 6.
SuppressRevocationStatusUnknown Allows certificates even if it not possible to check whether they
have been revoked by the issuing authority.

5.4.10.1 UserIdentity and UserIdentityTokens


The stack provides the UserIdentity class which converts UA user identity tokens to and from the
SecurityTokens used by WCF. The Stack currently supports UserNameSecurityToken, X509SecurityToken,
SamlSecurityToken and any other subtype of SecurityToken which is supported by the WCF
WSSecurityTokenSerializer class.
The UA specification requires that UserIdentityTokens be encrypted or signed before they are sent to the
Server. UserIdentityToken class provides a number of methods that implement these features.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 41 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.4.11 ServiceResults, ServiceResultExceptions and DiagnosticInfos
The UA specification introduces the concept of a StatusCode with an associated DiagnosticInfo where the
DiagnosticInfo contains references to strings contained in a common table. This model is useful for
optimizing calls across a network; however, it is cumbersome for programmers. For that reason the Stack
provides the ServiceResult class which combines a StatusCode with a DiagnosticInfo. The
ServiceResultException is an exception that contains the same information.
Support for these classes is built into the Stacks. For example, if an error occurs processing a UA request a
application can throw a ServiceResultException. The Stack will trap the exception and return the correct
fault required by the protocol being used (i.e. if SOAP/HTTP is being used the Stack will convert it to a
SOAP Fault that complies with the UA WSDL). Similarly, the ClientBase classes check for Faults returned
by the Server and converts them to ServiceResultException after looking up all of the strings in the
ResponseHeader.
ServiceResult class can be used by applications while they are processing individual operations. Once all
operations are complete the application can convert the ServiceResult into the StatusCode and
DiagnosticInfo components. The ServiceResult class also has helper functions that construct the object
from a StatusCode, DiagnosticInfo and a StringTable.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 42 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.5 Model Compiler
The Model Compiler (VisualOpc40.ModelCompiler.exe) can be used to create the necessary C# classes of
Information Model’s specified in XML and CSV based files. At the moment the XML files must be edited by
a text editor but a Model Designer is planned for the near future.

Model Compiler Command Line

VisualOpc40.ModelCompiler.exe -d ".\ModelDesign.xml" -cg ".\ModelDesign.csv" -om ".\"

5.5.1 Command Line Parameters


The Model Compiler uses the following command line parameters:
Parameter Description
-? Prints a help text.
-d The path to the XML file which contains the UA information model.
-c The path to the CSV file which contains the unique identifiers for the types
defined in the UA information model.
-cg Generates the unique identifier CSV file if it doesn't exists. If the file already
exists the existing one will be used.
-o The output directory for a single file output.
-om The output directory for a multiple file output.
-id The start identifier
-console The output goes to the standard error output (console) instead of error
window.

5.5.2 XSD Specification


The UA ModelDesign Schema (UA Model Design.xsd) specifies most of the usable UA classes and
contains the following elements:

5.5.2.1 Namespaces
This element defines the mappings between the URIs used to identify namespaces and the symbols used
in code. It is possible that a user defined design file includes other user defined design files. This allows
the user to split larger models into several files. The location of included design files is specified with the
FilePath attribute (absolute or relative path without the .xml suffix).

Namespace sample

<opc:Namespaces>
<opc:Namespace Name="OpcUa" Prefix="Opc.Ua"
XmlNamespace="http://opcfoundation.org/UA/2008/02/Types.xsd">http://opcfoundation.org/UA/</opc:Namespace>
<opc:Namespace Name="Boiler" Prefix="Boiler">http://terxasoft.ch/Boiler</opc:Namespace>
</opc:Namespaces>

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 43 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.5.2.2 ObjectTypes
An ObjectType is a Node that represents the type definition for an Object.

ObjectType sample

<opc:ObjectType SymbolicName="GenericSensorType" BaseType="ua:BaseObjectType">


<opc:Description>A generic sensor that read a process value.</opc:Description>
<opc:Children>
<opc:Variable SymbolicName="Output" DataType="ua:Double" ValueRank="Scalar"
TypeDefinition="ua:AnalogItemType"/>
</opc:Children>
</opc:ObjectType>

5.5.2.3 Object
An Object is a Node that represents a physical or abstract element of a system. Objects are modelled using
the OPC UA Object Model. Systems, subsystems and devices are examples of Objects. An Object may be
defined as an instance of an ObjectType.
Normally instances are created by program logic instead of being part of the model. This is provided as an
example of how to do it when there is a need for persistent instances. Note that the DisplayNames are
overridden for the base level nodes.

Object sample

<opc:Object SymbolicName="Boiler1" TypeDefinition="BoilerType" SupportsEvents="true">


<opc:BrowseName>Boiler #1</opc:BrowseName>
<opc:Children>
<opc:Object SymbolicName="InputPipe" TypeDefinition="BoilerInputPipeType"
SupportsEvents="true">
<opc:DisplayName>Pipe1001</opc:DisplayName>
</opc:Object>
<opc:Object SymbolicName="Drum" TypeDefinition="BoilerDrumType" SupportsEvents="true">
<opc:DisplayName>Drum1001</opc:DisplayName>
</opc:Object>
<opc:Object SymbolicName="OutputPipe" TypeDefinition="BoilerOutputPipeType"
SupportsEvents="true">
<opc:DisplayName>Pipe1002</opc:DisplayName>
</opc:Object>
<opc:Object SymbolicName="FlowController" TypeDefinition="FlowControllerType">
<opc:DisplayName>FC1001</opc:DisplayName>
</opc:Object>
<opc:Object SymbolicName="LevelController" TypeDefinition="LevelControllerType">
<opc:DisplayName>LC1001</opc:DisplayName>
</opc:Object>
<opc:Object SymbolicName="CustomController" TypeDefinition="CustomControllerType">
<opc:DisplayName>CC1001</opc:DisplayName>
</opc:Object>
</opc:Children>
<!-- Link the instance back to the ObjectsFolder -->
<opc:References>
<opc:Reference IsInverse="true">
<opc:ReferenceType>ua:Organizes</opc:ReferenceType>
<opc:TargetId>ua:ObjectsFolder</opc:TargetId>
</opc:Reference>
</opc:References>
</opc:Object>

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 44 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.5.2.4 VariableType

VariableType sample

<VariableType SymbolicName="tns:MultiStateValueDiscreteType" BaseType="tns:DiscreteItemType"


DataType="tns:Number">
<Children>
<Property SymbolicName="tns:EnumValues" DataType="tns:EnumValueType" ValueRank="Array" />
<Property SymbolicName="tns:ValueAsText" DataType="tns:String" />
</Children>
</VariableType>

5.5.2.5 Variable

Variable sample

<opc:Variable SymbolicName="Output" DataType="ua:Double" ValueRank="Scalar"


TypeDefinition="ua:AnalogItemType"/>

5.5.2.6 ReferenceType

ReferenceType sample

<opc:ReferenceType SymbolicName="SignalTo" BaseType="ua:NonHierarchicalReferences">


<opc:Description>A reference that indicates an electrical signal between two
variables.</opc:Description>
<opc:InverseName>SignalFrom</opc:InverseName>
</opc:ReferenceType>

5.5.2.7 DataType

DataType sample

<opc:DataType SymbolicName="VehicleType" BaseType="ua:Structure">


<opc:Fields>
<opc:Field Name="Make" DataType="ua:String"></opc:Field>
<opc:Field Name="Model" DataType="ua:String"></opc:Field>
</opc:Fields>
</opc:DataType>

5.5.2.8 Properties

Properties sample

<opc:Property SymbolicName="SetPoint"/>

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 45 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5.5.3 Usage
The BoilerServer sample can be used as sample implementation of a UaServerPlugin using an information
model based on classes generated with the Model Compiler. Please follow the instructions below to be
able to use the Model Compiler in your own servers.
1. Create a model design
The model of the BoilerServer sample is defined in the file ModelDesign.xml. You can use that as
reference for your own model design files.
2. Use the Model Compiler
For ease of use create a batch file, e.g, BuildDesign.bat, which executes the model compiler. Fo the
BoilerServer sample the batch file looks like:

BuildDesign.bat sample

@echo off
setlocal

SET PATH=%PATH%;..\..\..\..\Scripts;..\..\..\..\Binaries;..\..\..\Binaries

echo Building ModelDesign


VisualOpc40.ModelCompiler.exe -d ".\ModelDesign.xml" -cg ".\ModelDesign.csv" -om ".\"
echo Success!

Execute the batch file and for the BoilerServer sample the following files should be created:
Boiler.Classes.cs
Boiler.Constants.cs
Boiler.DataTypes.cs
Boiler.PredefinedNodes.uanodes
ModelDesign.csv (only if it not already exists)
In addition also some more files are created but not used at the moment.
3. Add the files to your server project
1. Add the C# files Boiler.Classes.cs, Boiler.Constants.cs and Boiler.DataTypes.cs to your project.
2. Add the UANODES file Boiler.PredefinedNodes.uanodes as Embedded resource to your
project.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 46 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


4. Add the used namespaces
You need to add the model design specific namespaces by modifying the OnGetNamespaceUris() method.

OnGetNamespaceUris() method

/// <summary>
/// Defines namespaces used by the application.
/// </summary>
/// <returns>Array of namespaces that are used by the application.</returns>
public string[] OnGetNamespaceUris()
{
// set one namespace for the type model.
var namespaceUrls = new string[2];
namespaceUrls[0] = Boiler.Namespaces.Boiler;
namespaceUrls[1] = Boiler.Namespaces.Boiler + "/Instance";
return namespaceUrls;
}

5. Load the predefined nodes


You need to load the UANODES file by adding this to the OnCreateAddressSpace() method.

OnCreateAddressSpace() method

/// <summary>
/// <para>
/// This method is called from the generic server at the startup; when the first client connects
/// or the service is started. All items supported by the server need to be defined by calling
/// the methods provided by the <see cref="IOpcServer">IOpcServer</see> interface for each item.
/// </para>
/// </summary>
/// <param name="opcServer">The generic server object. Used to call methods the generic server
/// provides.</param>
/// <param name="externalReferences">The externalReferences allows the generic server to link to the
/// general nodes.</param>
/// <returns>The root folder.</returns>
public object OnCreateAddressSpace(IOpcServer opcServer, IDictionary<NodeId, IList<IReference>>
externalReferences)
{
opcServer_ = opcServer;

opcServer_.LoadPredefinedNodes("UaServerPlugin.Boiler.PredefinedNodes.uanodes", externalReferences);

#region Create objects based on the classes generated by the model compiler
// See next step
#endregion

simulationTimer_ = new System.Threading.Timer(DoSimulation, null, 1000, 1000);

// the root node was created by calling the LoadPredefinedNodes() method and therefore we
// return null here.
return null;

The LoadPredefinedNodes() method uses the resource name of the embedded resource which
consists of UaServerPlugin plus the UANODES file name (without extension).

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 47 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6. Use the classes
You can use the classes created by the model compiler in your code, e.g. to dynamically create objects
based on these classes.

Create objects based on the classes generated by the model compiler

#region Create objects based on the classes generated by the model compiler

// find the untyped Boiler1 node that was created when the model was loaded.
var passiveNode = (BaseObjectState)opcServer_.FindPredefinedNode(new NodeId(Boiler.Objects.Boiler1,
opcServer_.NamespaceIndexes[0]), typeof(BaseObjectState));

// convert the untyped node to a typed node that can be manipulated within the server.
boiler1_ = new BoilerState(null);
boiler1_.Create(opcServer_.SystemContext, passiveNode);

// replaces the untyped predefined nodes with their strongly typed versions.
opcServer_.AddPredefinedNode(boiler1_);

// create a boiler node.


boiler2_ = new BoilerState(null);

// initialize it from the type model and assign unique node ids.
boiler2_.Create(
opcServer_.SystemContext,
null,
new QualifiedName("Boiler #2", opcServer_.NamespaceIndexes[1]),
null,
true);

// link root to objects folder.


IList<IReference> references;

if (!externalReferences.TryGetValue(Opc.Ua.ObjectIds.ObjectsFolder, out references))


{
externalReferences[Opc.Ua.ObjectIds.ObjectsFolder] = references = new List<IReference>();
}

references.Add(new NodeStateReference(Opc.Ua.ReferenceTypeIds.Organizes, false, boiler2_.NodeId));

// store it and all of its children in the pre-defined nodes dictionary for easy look up.
opcServer_.AddPredefinedNode(boiler2_);

#endregion

Check also the DoSimulation() method to see how the created objects are used to modify
values during runtime.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 48 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6 Client API
The Client is designed to ease the client development by handling the standard tasks which all clients need
to do. The tasks include:

sending the session keepalive requests


managing the publish pipeline
keeping track of the current status for subscription and monitored items
managing a client side node cache
processing and caching incoming data change and event notifications
saving and restoring the session state including the subscriptions and monitored items

Some features of this Client API are explained in this chapter.

6.1 Classes

6.1.1 ApplicationInstance
The ApplicationInstance class is a class that install,
configures and runs a UA client application. It is the
first object which must be created.

Create an ApplicationInstance object CS

var application = new ApplicationInstance();

The next step is to load the configuration with:

Loading ApplicationConfiguration CS

// Load the Application Configuration and use the


specified config section "DataAccessConsole"
application.LoadConfiguration("DataAccessConsole");

Now then check the application instance certificate:

Check Application Instance Certificate CS

// Check the Application Certificate.


application.CheckCertificate();

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 49 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.1.1 Properties
The ApplicationInstance class has the following properties:
Name Description
CertificateUpdateCallback Gets or sets the certificate update event callback.
Note:
Only one callback is allowed at a time but it is more efficient to call
than an event.
Configuration Gets the used application configuration.
ConfigurationSection Gets the name of the config section containing the path to the
application configuration file.
FirewallUpdateCallback Gets or sets the firewall update event callback.
Note:
Only one callback is allowed at a time but it is more efficient to call
than an event.
Name Gets or sets the name of the application.

6.1.1.2 Methods
The ApplicationInstance class has the following methods:
CheckCertificate This method checks for a valid application instance certificate. This
method throws a ServiceResultException if an error occurs.
Note:
In case a problem with the certificate occurs the
CertificateUpdateEventHandler will be called if used.
LoadConfiguration This method checks for a valid application instance certificate.
This method throws a ServiceResultException if an error occurs. This
method has the following parameters:
Name Description
configSectionName The name of the config section
containing the path to the application
configuration file.
[Return Value] True if the arguments were processed;
False otherwise.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 50 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


ProcessCommandLine This method checks for known command line arguments and process
them. The following command line parameters are handled by this
method:
/silent No output is done during startup of the
application
/configfile Allows the definition of a specific application
configuration file
/install Installs and configures the application
according the configuration file, e.g.
certificates are created and firewall
configured.
/uninstall Uninstalls the application by removing the
changes made during installation.
This method throws a ServiceResultException if an error occurs.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 51 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.2 Discover Servers
The Discover class allows clients to discover the UA Servers that
exist on a single machine.
All UA Servers running on a machine should register with the UA
Local Discovery Server using the Stack API.
If a UA Server running on a machine is registered with the UA
Local Discovery Server a client is able to discover it using the
following code:

Discover local Servers CS

// Discover all local UA servers


var servers = Discover.GetServers(application.ApplicationConfiguration);

Remote servers can be discovered by specifiying an Uri object like shown below:

Discover remote Servers CS

// Discover all remote UA servers


Uri discoveryUri = new Uri("opc.tcp://terxasoft.ch:4840/");
var servers = Discover.GetServers(application.ApplicationConfiguration, discoveryUri);

6.1.2.1 Properties
The Discover class has the following properties:

Name Description
DiscoveryTimeout The timeout in milliseconds to use when discovering servers.

6.1.2.2 Methods
The Discover class has the following methods:
GetConfiguredEndpoint Returns the configured endpoint for a given endpoint description.
Name Description
endpointDescription The endpoint description as
EndpointDescription.
[Return Value] The configured endpoint as
ConfiguredEndpoint.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 52 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


GetEndpointDescriptions Returns a list of endpoint descriptions for the specified server.
This method throws a ServiceResultException if an error occurs.
This method has the following parameters:
Name Description
discoveryUrl The URL of the server as returned by
the GetServers method,
e.g."http://localhost:55541/UA/Samp
leServer"
[Return Value] The available endpoint descriptions
as List<EndpointDescription>.
GetServers Returns a list of servers.
This method throws a ServiceResultException if an error occurs.
This method has the following parameters:
Name Description
applicationConfiguration The configuration for the client
application.
[Return Value] Returns a list of found OPC server
urls as List<string>.
GetServers Returns a list of servers.
This method throws a ServiceResultException if an error occurs.
This method has the following parameters:
Name Description
applicationConfiguration The configuration for the client
application.
discoveryServerUrl The URL of the Discovery Server
to be used as string.
[Return Value] Returns a list of found OPC server
urls as List<string>.
GetServers Returns a list of servers.
This method throws a ServiceResultException if an error occurs.
This method has the following parameters:
Name Description
applicationConfiguration The configuration for the client
application.
uri The URL of the Discovery Server
to be used as Uri.
[Return Value] Returns a list of found OPC server
urls as List<string>.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 53 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.3 Session
There are only a few classes required by an UA client to handle operations
with an UA server. In general an UA client
creates one or more Sessions by using the Session class
creates one or more Subscriptions within a Session by using the
Subscription class
adding one or more MonitoredItems within a Subscription by
using the MonitoredItem class

6.1.3.1 Overview

6.1.3.1.1 Creating a Session


The Session class inherits from the SessionClient which means all of the
UA services are in general accessible as methods on the Session object.
The Session object provides a number of helper methods including a
Create method which Creates and Opens Session. The process required
when establishing a session with a Server is as follows:
1. The Client application must choose the EndpointDescription to use.
This can be done manually or by getting a list of available
EndpointDescriptions by using the
Discover.GetEndpointDescriptions() method.
2. The Client takes the EndpointDescription and uses it to Create the
Session object by using the Create() method. If Create() succeeds the
client application will be able to call other methods.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 54 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


Creating a Session CS

var endpointDescriptions = Discover.GetEndpointDescriptions(http://localhost:55400/VisualOpcWrapper);


var endpoint = new ConfiguredEndpoint(null, endpointDescriptions[2]);

var mySession = Session.Create( application.ApplicationConfiguration,


endpoint,
false,
application.ApplicationConfiguration.ApplicationName,
60000,
new UserIdentity(),
null);

6.1.3.1.2 Keepalive
After creating the session the Session object starts periodically reading the current state from the Server at
a rate specified by the KeepAliveInterval (default is 5s). Each time a response is received the state and
latest timestamp is reported as a KeepAlive event. If the response does not arrive after 2
KeepAliveIntervals have elapsed a KeepAlive event with an error is raised. The KeepAliveStopped property
will be set to true. If communication resumes the normal KeepAlive events will be reported and the
KeepAliveStopped property will go back to false.
The client application uses the KeepAlive event and KeepAliveStopped property to detect communication
problems with the server. In some cases these communication problems will be temporary but while they
are going on the client application may choose not to invoke any services because they would likely
timeout. If the channel does not come back on its own the client application will execute whatever error
recovery logic it has.
Client applications need to ensure that the SessionTimeout is not set too low. If a call times out the WCF
channel is closed automatically and the client application will need to create a new one. Creating a new
channel will take time. The KeepAliveStopped property allows applications to detect failures even if they
are using a long SessionTimeout.

6.1.3.1.3 Cache
The Session object provides a cache that can be used to store Nodes that are accessed frequently. The
cache is particularly useful for storing the types defined by the server because the client will often need to
check if one type is a subtype of another. The cache can be accessed via the NodeCache property of the
Session object. The type hierarchies stored in the cache can be searched using the TypeTree property of
the NodeCache or Session object (the both return a reference to the same object).
The NodeCache is populated with the FetchNode() method which will read all of the attributes for the
Node and the fetch all of its references. The Find() method on the NodeCache looks for a previously
cached version of the Node and calls the FetchNode() method if it does not exist.
Client applications that wish to use the NodeCache must pre-fetch all the ReferenceType hierarchy
supported by the Server by calling FetchTypeTree() method on the Session object.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 55 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.3.1.4 Events
The Session object is responsible for sending and processing the Publish requests. Client applications can
receive events whenever a new NotificationMessage is received by subscribing to the SessionNotification
event.
• The SessionPublishError event is raised whenever a Publish response reports an error.
• The SubscriptionsChanged event indicates when a Subscription is added or removed.
• The SessionClosing event indicates that the Session is about to be closed.

6.1.3.1.5 Multi-Threading
The Session is designed for multi-threaded operation because client application frequently needs to make
multiple simultaneous calls to the Server. However, this is only guaranteed for calls using the Session
class. Client applications should avoid calling services directly which update the Session state, e.g.
CreateSession or ActivateSession.

6.1.3.2 Events

6.1.3.2.1 RenewUserIdentityEvent
The RenewUserIdentityEvent occurs before a reconnect
operation completes and is called to refresh the identity
(reprompt for password, refresh token). Within the event
handler the property Identity of the session object can be
updated before return.
The RenewUserIdentityEventArgs has the following properties:
Name Description
Identity The user identity which should be refreshed.
The following example shows the usage of the RenewUserIdentityEvent:

Add OnRenewUserIdentityEvent Handler

mySession.RenewUserIdentityEvent += new EventHandler<RenewUserIdentityEventArgs>(OnRenewUserIdentity);

OnRenewUserIdentity Event Handler

/// <summary>Called when a Kerberos token needs to be renewed before reconnect</summary>


/// <param name="sender">Source of the event as Session object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnRenewUserIdentity(object sender, RenewUserIdentityEventArgs eventArgs)
{
if (eventArgs.Identity == null || eventArgs.Identity.TokenType != UserTokenType.IssuedToken)
{
return;
}
var session = (Session)sender;
if (session != null)
{
session.Identity = GetKerberosToken();
}

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 56 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


}

6.1.3.2.2 SessionClosingEvent
The SessionClosingEvent occurs to indicate that the session is closing. The following example shows the
usage of the SessionClosingEvent:

Add SessionClosingEvent Handler

mySession.SessionClosingEvent += new EventHandler(OnSessionClosing);

OnSessionClosing Event Handler

/// <summary>Called when a session gets closed</summary>


/// <param name="sender">Source of the event as Session object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnSessionClosing(object sender, EventArgs eventArgs)
{
return;
}

6.1.3.2.3 SessionKeepAliveEvent
The SessionKeepAliveEvent is raised when a keepalive arrives
from the server or an error is detected.
The SessionKeepAliveEventArgs has the following properties:

Name Description
CancelKeepAlive Gets or sets a flag indicating whether the session should send another
keepalive.
CurrentState The current server state.
CurrentTime The current server time.
Status The status associated with the keepalive operation.

The following example shows the usage of the SessionKeepAliveEvent:

Add SessionKeepAliveEvent Handler

mySession.SessionKeepAliveEvent += new EventHandler<SessionKeepAliveEventArgs>(OnSessionKeepAlive);

OnSessionKeepAlive Event Handler

/// <summary>Called when a session keepalive is raised</summary>


/// <param name="sender">Source of the event as Session object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnSessionKeepAlive(object sender, SeesionKeepAliveEventArgs eventArgs)

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 57 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


{
return;
}

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 58 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.3.2.4 SessionNotificationEvent
Raised when a notification message arrives in a publish
response.
The SessionNotificationEventArgs has the following properties:

Name Description
NotificationMessage The Notification Message as NotificationMessage object.
StringTable The string table as IList<string> returned with the notification
message.
Subscription The subscription as Subscription object that the notification applies to.

The following example shows the usage of the SessionNotificationEvent:

Add SessionNotificationEvent Handler

mySession.SessionNotificationEvent += new
EventHandler<SessionNotificationEventArgs>(OnSessionNotification);

OnSessionNotification Event Handler

/// <summary>Called when a session notification is raised</summary>


/// <param name="sender">Source of the event as Session object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnSessionNotification(object sender, SeesionNotificationEventArgs eventArgs)
{
return;
}

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 59 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.3.2.5 SessionPublishErrorEvent
Raised when an exception occurs while processing a publish
response.
The SessionPublishErrorEventArgs has the following properties:

Name Description
SequenceNumber The sequence number for the message that could not be republished.
Status The status as ServiceResult object associated with the keepalive
operation.
SubscriptionId The subscription with the message that could not be republished.

The following example shows the usage of the SessionPublishErrorEvent:

Add SessionPublishErrorEvent Handler

mySession.SessionPublishErrorEvent += new
EventHandler<SessionPublishErrorEventArgs>(OnSessionPublishError);

OnSessionPublishError Event Handler

/// <summary>Called when a session publish error is raised</summary>


/// <param name="sender">Source of the event as Session object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnSessionPublishError(object sender, SeesionPublishEventArgs eventArgs)
{
return;
}

6.1.3.2.6 SubscriptionsChangedEvent
Raised when a subscription is added or removed.

The following example shows the usage of the SubscriptionsChangedEvent:

Add SubscriptionsChangedEvent Handler

mySession.SubscriptionsChangedEvent += new EventHandler(OnSubscriptionsChanged);

OnSubscriptionsChanged Event Handler

/// <summary>Called when a subscription is added or removed</summary>


/// <param name="sender">Source of the event as Session object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnSessionPublishError(object sender, EventArgs eventArgs)
{
return;
}

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 60 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.4 Subscription
The Subscription class stores the client-side state for a Subscription with a
Server. It maintains two sets of properties: the values requested when the
Subscription is/was created and the current values based on the revised
values returned by the Server.
The Subscription object is designed for batch operations. This means the
subscription parameters and the MonitoredItem can be updated several
times but the changes to the Subscription on the Server do not happen
until the ApplyChanges() method is called. After the changes are
complete the SubscriptionStatusChanged event is reported with a bit
mask indicating what was updated.

6.1.4.1.1 Creating a Subscription


The Subscription class provides a number of helper methods including a
Constructor with default values for several. The process required when
using a subscription is as follows:
1. The Subscription object must be created. This can be done by
using the default constructor and using one or more of the
properties available.
2. Items (MonitoredItem) must be added to the subscription.
3. The subscription must be added to the session.
4. The subscription must be created for the session.
5. The subscription changes must be applied, because of the above
mentioned batch functionality.
The following example shows these steps:

Using a Subscription CS

// Create a new subscription


var mySubscription = new Subscription
{
DisplayName = "My Subscription",
PublishingEnabled = true,
PublishingInterval = 500,
};
// Create a MonitoredItem
var monitoredItem = new MonitoredItem
{
StartNodeId = new NodeId("ns=2;s=0:ItemName"),
AttributeId = Attributes.Value,
DisplayName = "Int64",
MonitoringMode = MonitoringMode.Reporting,
SamplingInterval = 1000,
};

// Add the item to the subscription


mySubscription.AddItem(monitoredItem);
// Add the subscription to the session
mySession.AddSubscription(mySubscription);
// Create the subscription.
// Must be done after adding the subscription to a session
mySubscription.Create();
// Apply all changes on the subscription

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 61 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


mySubscription.ApplyChanges();

When a Subscription is created it must start sending Publish requests. It starts off the process by telling
the Session object to send one request. Additional Publish requests can be send by calling the
BeginPublish() method. Applications can use additional Publish requests to compensate for high network
latencies because once the pipeline is filled the Server will be able to return a steady stream of
notifications.
Once the Subscription has primed the pump the Session object keeps it going by sending a new Publish
whenever it receives a successful response. If an error occurs the Session raises a SessionPublishError
event and does not send another Publish.
If everything is working properly the Session saves the message in cache at least once per keepalive
interval. If a NotificationMessage does not arrive it means there are network problems, bugs in the Server
or high priority Subscriptions are taking precedence. The keepalive timer is designed to detect these
problems and to automatically send additional Publish requests. When the keepalive timer expires it
checks the time elapsed since the last notification message. If publishing appears to have stopped the
PublishingStopped property will be true and the Subscription will raise a PublishStatusChanged event and
send another Publish request. Client applications must assume that any cache data values are out of date
when they receive the PublishStatusChanged event (e.g. the StatusCode should be set to
UncertainLastKnownValue). However, client applications do not need to do anything else since the
interruption may be temporary. It is up to the client application to decide when to give up on a Session
and to try again with a new Session.
The Subscription object checks for missing sequence numbers when it receives a NotificationMessage. If
there is a gap it starts a timer that will call Republish() in 1s if the gap still exists. This delay is necessary
because the multi-threaded stack on the client side may process responses out of order even if they are
received in order.
The Subscription maintains a cache of messages received. The size of this cache is controlled by the
MaxMessageCount property. When a new message is received the Subscription adds it to the cache and
removes any extras. It then extracts the notifications and pushes them to the MonitoredItem identified by
the ClientHandle in the notification.
The Subscription is designed for multi-threaded operation because the Publish requests may arrive on any
thread. However, data which is accessed while processing an incoming message is protected with a
separate synchronization lock from data that is used while updating the Subscription parameters. This
means notifications can continue to arrive while network operations to update the Subscription state on
the server are in progress. However, no more than one operation to update the Subscription state can
proceed at one time. Closing the Session will interrupt any outstanding operations. Any synchronization
locks held by the subscription are released before any events are raised.

6.1.4.2 Events

6.1.4.2.1 PublishStatusChangedEvent
Raised to indicate the publishing state for the subscription has stopped or resumed (see
PublishingStopped property).
The following example shows the usage of the PublishStatusChangedEvent:

Add PublishStatusChangedEvent Handler

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 62 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


mySession.PublishStatusChangedEvent += new EventHandler(OnPublishStatusChanged);

OnPublishStatusChanged Event Handler

/// <summary>Called when the publishing state for a subscription has stopped or resumed</summary>
/// <param name="sender">Source of the event as Subscription object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnPublishStatusChanged(object sender, EventArgs eventArgs)
{
return;
}

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 63 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.4.2.2 SubscriptionStatusChangedEvent
Raised to indicate that the state of the subscription has
changed.
The SubscriptionStatusChangedEventArgs has the
following properties:

Name Description
Status The changes as SubscriptionChangeMask object that have affected the
subscription.

The following example shows the usage of the SubscriptionStatusChangedEvent:

Add SubscriptionStatusChangedEvent Handler

mySession. SubscriptionStatusChangedEvent += new


EventHandler<SubscriptionStatusChangedEventArgs>(OnSubscriptionStatusChanged);

OnPublishStatusChanged Event Handler

/// <summary>Called when the state for a subscription has changed</summary>


/// <param name="sender">Source of the event as Subscription object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void On SubscriptionStatusChanged(object sender, SubscriptionStatusChangedEventArgs eventArgs)
{
return;
}

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 64 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


6.1.5 MonitoredItem
The MonitoredItem class stores the client-side state for a
MonitoredItem belonging to a Subscription on a Server. It
maintains two sets of properties:
1. The values requested when the MonitoredItem
is/was created
2. The current values based on the revised values
returned by the Server.
The requested properties are saved when then
MonitoredItem is serialized. Please keep in mind that the
server may change (revise) some values requested by the
client. The revised properties are returned in the Status
property, which is of type MonitoredItemStatus.
The NodeId for the MonitoredItem can be specified as an
absolute NodeId or as a starting NodeId followed by
RelativePath string which conforms to the syntax defined in
the OPC Unified Architecture Specification Part 4. The
RelativePath class included in the Stack can parse these
strings and produce the structures required by the UA
services.
Changes to any of the properties which affect the state of
the MonitoredItem on the Server are not applied
immediately. Instead the ParametersModified flag is set and
the changes will only be applied when the ApplyChanges
method on the Subscription is called. Note that changes to
parameters which can only be specified when the
MonitoredItem was created are ignored if the
MonitoredItem has already been created. Client applications
that wish to change these parameters must delete the
monitored item and then re-create it.
The current values for monitoring parameters are stored in
the Status property. Client application must use the Status.
Error property to check an error occurs while creating or
modifying the item. MonitoredItems that specify a
RelativePath string may have encountered an error parsing
or translating the RelativePath. When such an error occurs
the Error property is set and the MonitoredItem is not
created.
The MonitoredItem maintains a local queue for data changes
or events received from the Server. This means the client
application does not need to explicitly process
NotificationMessages and can simply read the latest value
from the MonitoredItem whenever it is required. The length
of the local queue is controlled by the CacheQueueSize
property.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 65 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


The MonitoredItem provides a MonitoredItemNotification event which can be used by the client
application to receive events whenever a new notification is received from the Server. It is always called
after it is added to the cache.
The MonitoredItem is designed for multi-threaded operation because the Publish requests may arrive on
any thread. However, data which is accessed while updating the cache is protected with a separate
synchronization lock from data that is used while updating the MonitoredItem parameters. This means
notifications can continue to arrive while other threads update the MonitoredItem parameters.
Client applications must be careful when update MonitoredItem parameters while another thread has
called ApplyChanges on the Subscription because it could lead to situation where the state of the
MonitoredItem on the Server does not match the state of the MonitoredItem on the client.

6.1.5.1 Events

6.1.5.1.1 MonitoredItemNotificationEvent
Raised when a new notification arrives.
The MonitoredItemNotificationEventArgs has the
following properties:

Name Description
NotificationValue The new notification as IEncodable.

The following example shows the usage of the MonitoredItemNotificationEvent:

Add MonitoredItemNotificationEvent Handler

mySession.MonitoredItemNotificationEvent += new
EventHandler<MonitoredItemNotificationEventArgs>(OnMonitoredItemNotificationEvent);

OnMonitoredItemNotificationEvent Event Handler

/// <summary>Called when a new notification arrived</summary>


/// <param name="sender">Source of the event as MonitoredItem object.</param>
/// <param name="eventArgs">Event information to send to registered event handlers.</param>
private void OnPublishStatusChanged(object sender, MonitoredItemNotificationEventArgs eventArgs)
{
var notification = e.NotificationValue as MonitoredItemNotification;
if (notification == null)
{
return;
}
var monitoredItem = sender as MonitoredItem;
var message = String.Format("Event called for Variable \"{0}\" with Value = {1}.",
monitoredItem.DisplayName, notification.Value);
Console.WriteLine(message);
}

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 66 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


7 Server API

7.1 Getting Started


This chapter is intended as a starting point and shows several usage example of the Visual OPC Server
.NET.

7.1.1 Server Development Process


Following is a step-by-step description of the server development process.

7.1.1.1 Create the Application Project


1) Copy the sample application directory and rename the copy.
2) Open the solution in Visual Studio and open the file VisualOpc40.Server.Config.xml.
Change the following entries to define the server name URL:
<ApplicationName>TerxaSoft UA Sample Server</ApplicationName>
<ApplicationUri>urn:localhost:UA:SampleServer</ApplicationUri>
<ProductUri>uri:terxasoft.com:UA:SampleServer</ProductUri>
<BaseAddresses xmlns:d3p1="http://opcfoundation.org/UA/2008/02/Types.xsd">
<d3p1:String>http://localhost:55540/UA/SampleServer</d3p1:String>
<d3p1:String>opc.tcp://localhost:55541/UA/SampleServer</d3p1:String>
</BaseAddresses>
3) Select Project - Properties - Debug - Start Action and change the Start External program
application path to VisualOpc40.Server.exe in the project debug output directory.
4) Compile the project.

7.1.1.2 Customize and Compile


1) Edit the source files:
- AssemblyInfo.cs
- UaServerPlugin.cs
and add files with additional classes as required for the project specific device handling.
Build the application project and correct all compile errors.
2) Build the project.
Copy the generic server VisualOpc40.Server.exe into the project output directory.
3) Start the project in debug mode and test the device handling.
Use one of the supplied test clients or your own client to connect to the already started OPC
server.
4) Start an OPC client, connect to the server and check the item address space and the item values.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 67 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


7.1.1.3 Deployment
1) Compile the Solution with Release configuration selected.
2) Copy the files from the Release Output directory to target computer:
- VisualOpc40.Server.exe
- Opc.Ua.Core.dll
- VisualOpc40.v1.dll
- UaServerPlugin.dll
- VisualOpc40.Server.exe.config
- VisualOpc40.Server.config.xml
- binaries\redist\OPC UA SDK 1.01 Redistributables Setup directory content
3) Execute Setup.exe from the binaries\redist\OPC UA SDK 1.01 Redistributables Setup to install the
common OPC UA tools.

7.1.2 Upgrading from OPC UA Server SDK .NET


Upgrading from the OPC UA Server SDK .NET requires some changes in the API because of enhanced
functionality. In the following these changes are explained by showing it for the C# UA sample server.
1) Remove the TerxaSoft40.v2.dll assembly from the references.
2) Add the Opc.Ua.Core.dll assembly to the references.
3) Add the VisualOpc40.v1.dll assembly to the references.
4) Compiling the project will result in several compiler errors mainly because of changes in the
naming of several interfaces and classes. See the table below for the name changes and adapt the
code according it.
OPC UA Server SDK .NET Visual OPC Server .NET
using TerxaSoft; using Opc.Ua;
using VisualOpc.Server;

IOpcBaseDataVariableState BaseDataVariableState
IOpcFolderState FolderState
OpcBuiltInType BuiltInType
OpcValueRanks ValueRanks
OpcAccessLevels AccessLevels
OpcStatusCodes StatusCodes
OpcServerState ServerState
OpcServerProperties ServerProperties
OpcRange Range
OpcReferenceTypes ReferenceTypes
Identifier NodeId
IOpcEndpoint EndpointDescription
Url.ToString() (of Endpoint) EndpointUrl
IOpcSession Session
IOpcSubscription Subscription
SessionName (of Session) SessionDiagnostics.SessionName
ClientLastContactTime (of Session) SessionDiagnostics.ClientLastContactTime
ListViewItem(subscription.Id) ListViewItem(subscription.Id.ToString())

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 68 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


5) Change the following methods:
From: private void CreateDynamicVariable(FolderState parent, object
nodeId, string name, BuiltInType dataType, ValueRanks valueRank,
AccessLevels accessLevel)
To: private void CreateDynamicVariable(FolderState parent, object
nodeId, string name, BuiltInType dataType, int valueRank, byte
accessLevel)

From: public StatusCodes OnStartup(string[] args)

To: public StatusCode OnStartup(string[] args)

From: public StatusCodes OnRunning()

To: public StatusCode OnRunning()

From: public StatusCodes OnShutdown(ServerState ServerState, string


reason, Exception exception)

To: public StatusCode OnShutdown(ServerState opcServerState, string


reason, Exception exception)

From: public StatusCodes OnWriteValue(BaseDataVariableState


originalVariableState, ref object value, ref StatusCodes
statusCode, ref DateTime timestamp)

To: public StatusCode OnWriteValue(BaseDataVariableState


originalVariableState, ref object value, ref StatusCode
statusCode, ref DateTime timestamp)

From: public StatusCodes OnCallMethod(object sender, MethodCallEventArgs


e)

To: public StatusCode OnCallMethod(object sender, MethodCallEventArgs


e)

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 69 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


7.1.3 Changes in Version 1.1
Updating from the Visual OPC Server .NET 1.0.x requires some changes in the API because of enhanced
functionality. In the following these changes are explained by showing it for the C# UA sample server.
1) Change the following methods:
From: public object OnCreateAddressSpace(IOpcServer opcServer,
object externalReferences)
To: public object OnCreateAddressSpace(IOpcServer opcServer,
IDictionary<NodeId, IList<IReference>> externalReferences)

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 70 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


7.2 Interfaces

7.2.1 IOpcServerPlugin Interface


This interface defines functionality that must be implemented by all
Server Customization DLLs.
The IOpcServerPlugin interface is the base for the following sub-
classes:
Name Description

OpcServerPlugin A base class for the Server


Customization.

7.2.1.1 Methods
The IOpcServerPlugin interface has the following methods:
Name Description

OnStartup This method is the first method called from the generic server at the
startup.
This method has the following parameters:
Name Description

args String array with the command line


parameters as they were specified when
the server was being started.
[Return Value] A StatusCode code with the result of the
operation. Returning an error code stops
the further server execution.
The following command line parameters are handled by the generic
server:
/silent No output is done during startup of the server
/configfile Allows the definition of a specific application
configuration file
/install Installs and configures the application
according the configuration file, e.g.
certificates are created and firewall
configured.
/uninstall Uninstalls the application by removing the
changes made during installation.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 71 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


OnCreateAddressSpace This method is called from the generic server at the startup; when the
first client connects or the service is started. All items supported by the
server need to be defined by calling the methods provided by the
IOpcServer interface for each item.
This method has the following parameters:
Name Description

opcServer The generic IOpcServer server object.


Used to call methods the generic server
provides.
externalReferences The externalReferences allows the generic
server to link to the general nodes.
[Return Value] The root folder object
OnRunning This method is called from the generic server when the server was
successfully started and is running.
This method has the following parameters:
Name Description

[Return Value] A StatusCode code with the result of the


operation. Returning an error code stops
the further server execution.
OnShutdown This method is called from the generic server when a Shutdown is
executed.
To ensure proper process shutdown, any communication channels
should be closed and all threads terminated before this method
returns.
This method has the following parameters:
Name Description

[Return Value] A StatusCode code with the result of the


operation.
OnGetServerProperties This method is called from the generic server when the OPC Server
Properties of the current server instance are requested by a client.
This method has the following parameters:
Name Description

[Return Value] An OpcServerProperties object.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 72 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


OnWriteValue This method is called when a client executes a 'write' server call. The
BaseDataVariableState includes all information required to identify the
item as well as original (unmodified) value, timestamp and quality.
Depending on the returned result code the cache is updated or not in
the generic server after returning from this method.
This method has the following parameters:
Name Description

originalVariableState The BaseDataVariableState of the


variable including the original state of
the variable. Can be used to check
what changes happens.
value The value which should be written.
The returned value is used for
updating the cache depending on the
returned result code.
statusCode A StatusCode code which should be
used as new status code for the value.
timeStamp The timestamp the value was written.
The returned value is used for
updating the cache depending on the
returned result code.
[Return Value] A StatusCode code with the result of
the operation.

The following rules apply for updating the cache base on the returned
StatusCode:
1. If the returned value is Bad (something like Bad...) the cache is
not updated with timestamp and value.
2. If the returned value is GoodCompletesAsynchronously the
cache is not updated with timestamp and value. After the
customization DLL has finished its operation it can use
WriteVariable to update the cache.
3. In all other cases the cache is updated with timestamp and
value.
4. In all cases the status code is updated with the status code set
in the 'statusCode' parameter.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 73 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


OnGetLicenseInformation This method is called from the generic server to get the license
information.
This method has the following parameters:
Name Description

licenseOwner Owner of the license.


serialNumber Serial Number
Returning empty strings activates the evaluation version of the Visual
OPC Server .NET. The evaluation allows the usage of the full product
for 30 days.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 74 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


7.2.2 IOpcServer Interface
This interface defines functionality that can be called by all
Server Customization DLLs.

7.2.2.1 Properties
The IOpcServer interface has the following properties:
Name Description

CurrentState Returns the current state of the


server.
LiensedAt The date the license was issued.
Licensee The license owner of the license.
Product The product the license was
issued for.
RestartRequired Indicates whether the server
must be restarted. This is mainly
the case if the server is used in
evaluation mode and the 90
minutes evaluation time expired.
ServiceExpired Indicates wether the service
subscription or evaluation period
is expired.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 75 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


7.2.2.2 Methods
The IOpcServer interface has the following methods:
Name Description

AddInputArguments Adds the input arguments to a method.


This method has the following parameters:
Name Description

parent The method object returned by a call to


CreateMethod the input arguments will be
added to.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
inputArguments The array of input arguments.
[Return Value] A StatusCode code with the result of
the operation. Returning an error
code indicates that the server can't be
stopped.
AddOutputArguments Adds the output arguments to a method.
This method has the following parameters:
Name Description

parent The method object returned by a call to


CreateMethod the output arguments will
be added to.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 76 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


Important: Keep in mind that the actual
ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
outputArguments The array of output arguments.
[Return Value] A StatusCode code with the result of
the operation. Returning an error
code indicates that the server can't be
stopped.
CreateAnalogItemVariable Creates a new AnalogItem variable.
This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new variable will be added
to.
nodeId The unique identifier for the variable in the
server's address space. The NodeId can be
either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that no
two nodes within an address-space share
the same ID's.
name The name of the new variable, e.g. SByte
dataType The data type of the new variable, e.g.
BuiltInType.SByte. See BuiltInType for all
possible types.
valueRank The value rank of the new variable, e.g.
ValueRanks.Scalar. See ValueRanks for all
possible value ranks.
accessLevel The access level of the new variable, e.g.
AccessLevels.CurrentRead. See AccessLevels
for all possible access levels.
initialValue The initial value. If null a default value is
used as initial value.
valuePrecision Specifies the maximum precision that the
server can maintain for the item based on
restrictions in the target environment. The
precision can be used for the following

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 77 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


DataTypes:

• For Float and Double values it


specifies the number of digits after
the decimal place.
• For DateTime values it indicates the
minimum time difference in
nanoseconds. E.g., a precision of
20000000 defines a precision of 20
milliseconds.
instrumentRange The instrument range defines the value
Range that can be returned by the
instrument.
euRange The engineering unit range defines the
value Range likely to be obtained in
normal operation. It is intended for
such use as automatically scaling a bar
graph display.
Senso or instrument failure or
deactivation can result in a returned
item value which is actually outside
this range.
unitName The engineering unit name specifies the
units for the item value, e.g. hertz,
seconds, litres
[Return Value] The created AnalogItemState

CreateDataItemVariable Creates a new DataItem variable.


This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new variable will be
added to.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 78 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


name The name of the new variable, e.g. SByte
dataType The data type of the new variable, e.g.
BuiltInType.SByte. See BuiltInType for all
possible types.
valueRank The value rank of the new variable, e.g.
ValueRanks.Scalar. See ValueRanks for all
possible value ranks.
accessLevel The access level of the new variable, e.g.
AccessLevels.CurrentRead. See
AccessLevels for all possible access levels.
initialValue The initial value. If null a default value is
used as initial value.
valuePrecision Specifies the maximum precision that the
server can maintain for the item based on
restrictions in the target environment. The
precision can be used for the following
DataTypes:

• For Float and Double values it


specifies the number of digits after
the decimal place.
• For DateTime values it indicates the
minimum time difference in
nanoseconds. E.g., a precision of
20000000 defines a precision of 20
milliseconds.
[Return Value] The created DataItemState

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 79 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


CreateDataType Creates a new data type.
This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new variable will be
added to.
externalReferences The externalReferences is an out
parameter that allows the generic
server to link to nodes.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new data type, e.g.
DataType1
[Return Value] The created data type object

CreateFolder Creates a new folder.


This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new folder will be added
to.
path The full path of the new folder, e.g.
/Static/Simple Types
name The name of the new folder, e.g. Simple
Types
[Return Value] The created folder object which can
be used in further calls to
CreateFolder.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 80 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


CreateMethod Creates a new method. Nodes of the type Method represent a
method, that is, something that is called by a client and
returns a result.
This method has the following parameters:
Name Description

parent The parent folder object the new method


will be created in.

nodeId The unique identifier for the variable in


the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new method, e.g.
Method1
callingMethod The method which will be called if the
method is executed.
[Return Value] The created method object.

CreateMultiState Creates a new multi state variable.


DiscreteItemVariable This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new variable will be
added to.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 81 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


no two nodes within an address-space
share the same ID's.
name The name of the new variable, e.g.
MultiState1
accessLevel The access level of the new variable, e.g.
AccessLevels.CurrentRead. See
AccessLevels for all possible access levels.
initialValue The initial value. If null a default value is
used as initial value.
values The possible values the multistate variable
can have.
[Return Value] The created MultiStateDiscreteState

CreateObject Creates a new object.


This method has the following parameters:
Name Description

parent The parent folder object the new method


will be created in.

nodeId The unique identifier for the variable in


the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new object, e.g. Object1
[Return Value] The created object.

CreateObjectType Creates a new object type.


This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new object type will be
added to.
externalReferences The externalReferences is an out
parameter that allows the generic
server to link to nodes.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 82 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new data type, e.g.
ObjectType1
[Return Value] The created BaseObjectTypeState
object
CreateReferenceType Creates a new reference type.
This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new reference type will
be added to.
externalReferences The externalReferences is an out
parameter that allows the generic
server to link to nodes.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new reference type,
e.g. ReferenceType1
[Return Value] The created ReferenceTypeState
object

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 83 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


CreateTwoState Creates a new two state variable.
DiscreteItemVariable This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new variable will be
added to.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new variable, e.g.
MultiState1
accessLevel The access level of the new variable, e.g.
AccessLevels.CurrentRead. See
AccessLevels for all possible access levels.
initialValue The initial value. If null a default value is
used as initial value.
trueState Defines the string to be associated with
this variable when it is TRUE. This is
typically used for a contact when it is in
the closed (non-zero) state.
falseState Defines the string to be associated with
this variable when it is FALSE. This is
typically used for a contact when it is in
the open (zero) state.
[Return Value] The created TwoStateDiscreteState

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 84 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


CreateVariable Creates a new variable.
This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new variable will be
added to.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new variable, e.g. SByte
dataType The data type of the new variable, e.g.
BuiltInType.SByte. See BuiltInType for all
possible types.
valueRank The value rank of the new variable, e.g.
ValueRanks.Scalar. See ValueRanks for all
possible value ranks.
accessLevel The access level of the new variable, e.g.
AccessLevels.CurrentRead. See
AccessLevels for all possible access levels.
initialValue The initial value. If null a default value is
used as initial value.
[Return Value] The created BaseDataVariableState

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 85 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


CreateVariableType Creates a new variable type.
This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new variable type will
be added to.
externalReferences The externalReferences is an out
parameter that allows the generic
server to link to nodes.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new reference type,
e.g. VariableType1
dataType The data type of the new variable type,
e.g. BuiltInType.SByte. See BuiltInType
for all possible types.
valueRank The value rank of the new variable type,
e.g. ValueRanks.Scalar. See ValueRanks
for all possible value ranks.
[Return Value] The created
BaseDataVariableTypeState object

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 86 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


CreateView Creates a new view.
This method has the following parameters:
Name Description

parent The folder object returned by a call to


CreateFolder the new view type will be
added to.
externalReferences The externalReferences is an out
parameter that allows the generic
server to link to nodes.
nodeId The unique identifier for the variable in
the server's address space. The NodeId
can be either:

• uint
• Guid
• string
• byte[]

Important: Keep in mind that the actual


ID's of nodes should be unique such that
no two nodes within an address-space
share the same ID's.
name The name of the new view, e.g. View1
[Return Value] The created ViewState object

GetEndpoints Returns information about the endpoints supported by the server.


This method has the following parameters:
Name Description

[Return Value] Returns a list of Endpoint


information's.
GetNewSimulatedValue Generates a simulated value for each of the supported data types.
This method has the following parameters:
Name Description

deviceItem The BaseVariableState a new value


should generate for.
[Return Value] The new value for the specified
BaseVariableState

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 87 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


GetSessions Returns all of the sessions known to the session manager.
This method has the following parameters:
Name Description

[Return Value] A list of the sessions.

GetSubscriptions Returns all of the subscriptions known to the server.


This method has the following parameters:
Name Description

[Return Value] A list of the subscriptions.

Shutdown Requests a shutdown of the server.


This method has the following parameters:
Name Description

[Return Value] A StatusCode code with the result of


the operation. Returning an error
code indicates that the server can't
be stopped.
WriteVariable Writes to a variable.
This method has the following parameters:
Name Description

deviceItem The BaseVariableState including the


identifier.
newValue Object with new item value.
statusCode New status code of the item value.
timestamp New timestamp of the new item value.
[Return Value] A StatusCode code with the result of
the operation.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 88 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


7.2.3 Using your own server executable
In some cases it may be necessary to replace the generic OPC UA Server executable
(VisualOpc40.Server.exe) with your own executable, e.g. in case you develop a visualization and want to
integrate OPC UA Server functionality. This is very easy to be done with the Visual OPC Server .NET. You
can find a sample solution at \src\server\Ua\UaServer. To be able to start the OPC UA Server functionality
follows the following steps:
1. Add references to VisualOpc40.v1.dll and Opc.Ua.Core.dll to your project.
2. Add the app.config and InstallConfig.xml to your project.
3. Add a “using VisualOpc.Server;” statement.
4. Add a “private static UaServer _uaServer = new UaServer();” variable.
5. Start the server with “_uaServer.Start(args);”

Please see also the provided solutions of the original “VisualOpc40.Server.exe” and ensure that you use
the one for the .NET Framework version you develop for.
In case you have any questions please feel free to contact us.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 89 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


8 Common API
The Common API includes some helper classes and definitions not specially related to client and server
applications.

8.1 Classes

8.1.1 LicenseHandler
The LicenseHandler class is a class used to license the
Visual OPC Client .NET has product. It should be used
before any other class is used.
After purchaseing the Visual OPC Client .NET you will
receive an email with the information required to be used as
parameters for the Validate method of the LicenseHandler
class. The call looks then like:

License as product CS

// License the Visual OPC Client .NET


LicenseHandler.Validate( "Owner","License Key" );

8.1.1.1 Properties
The LicenseHandler class has the following properties:

Name Description
DaysLeft Returns the number of days left for the evaluation of the product.
In case of a licensed product this property gives the number of days left for
updateing.
• Products relesased within this time can be used as licensed version.
• Products released after this time can only be used as evaluation.
IsLicensed Returns wether the product is licensed or used as evaluation version.
LicensedAt Returns the information the license was issued or the first date the
evaluation was started.
LicensedAt Returns the Licensee information.
ProductInformation Returns the product information.
ServiceExpired Indicates wether the service subscription or evaluation period is expired.
Version Returns the Version of the product.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 90 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


8.1.1.2 Methods
The LicenseHandler class has the following methods:

Name Description
Validate Validate the license.
This method has the following parameters:

Name Description
licenseOwner The owner of the license.
licenseKey The license key.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 91 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


License Model …
TerxaSoft’s license model is extremely simple and flexible enabling you to quickly start your work.
TerxaSoft license highlights:
• No royalties, run-times fees, or server deployment charges.
• Simple, per-developer licensing model – each product is licensed to a single user.
We recognize that you may use more than one machine for development, and our license permits our
products to be installed on multiple PCs. Office computer, home computer, laptop – one price covers all
locations.
A license is needed for each developer who will be working with our products, and volume discounts are
available. If you would like to see a custom quotation that includes volume pricing, please contact us at
info@terxasoft.com.

Maintenance Package …
A Maintenance Package includes one year of upgrades to all new releases and fixes of the product, and
email based support. All product licenses include a Maintenance Package for the first year. Support
Incidents can be used and transferred as long as a valid Maintenance Package is available. You are
recommended to re-order a Maintenance Package before expiry date. If you re-order Maintenance

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 92 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


Package after the expiry date, the expiry date of the original Maintenance Package will be considered as
the start date of the re-ordered Maintenance Package.

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 93 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com


Why TerxaSoft?…
Professionalism
TerxaSoft is, measured by the number of employees, truly not a big company. However when it
comes to flexibility, service quality, and adherence to schedules and reliability, we are surely a
great company which can compete against the so called leaders in the industry. And this is THE
crucial point for our customers.

Continuous progress
Lifelong learning and continuing education is, especially in the information technology, essential
for future success. Concerning our customers, we will constantly accepting new challenges and
exceeding their requirements again and again. We will continue to do everything to fulfill the
needs of our customers and to meet our own standards.

High Quality of Work


We reach this by a small, competent and dynamic team of coworkers, which apart from the
satisfaction of the customer; take care of a high quality of work. We concern the steps necessary
for it together with consideration of the customers’ requirements.

TerxaSoft GmbH
Windleweg 3
CH-5235 Rüfenach
Tel.: +41 56 535 16 33

info@terxasoft.ch
www.terxasoft.ch

Visual OPC Client&Server .NET Developer Guide - Version 1.0 - 29/04/12 Page 94 of 94

© Copyright 2012, TerxaSoft GmbH – www.terxasoft.com

You might also like