You are on page 1of 1044

Opcenter Execution Foundation 4.

Development and Configuration Guide

04/2021
PL20201124062203470
Guidelines
This manual contains notes of varying importance that should be read with care; i.e.:
Important:
Highlights key information on handling the product, the product itself or to a particular part of the documentation.
Note: Provides supplementary information regarding handling the product, the product itself or a specific part of
the documentation.
Trademarks
All names identified by ® are registered trademarks of Siemens AG.
The remaining trademarks in this publication may be trademarks whose use by third parties for their own purposes
could violate the rights of the owner.
Disclaimer of Liability
We have reviewed the contents of this publication to ensure consistency with the hardware and software
described. Since variance cannot be precluded entirely, we cannot guarantee full consistency. However, the
information in this publication is reviewed regularly and any necessary corrections are included in subsequent
editions.
Security information
Siemens provides products and solutions with industrial security functions that support the secure operation of
plants, systems, machines and networks. In order to protect plants, systems, machines and networks against
cyber threats, it is necessary to implement – and continuously maintain – a holistic, state-of-the-art industrial
security concept. Siemens’ products and solutions only form one element of such a concept.
Customer is responsible to prevent unauthorized access to its plants, systems, machines and networks. Systems,
machines and components should only be connected to the enterprise network or the internet if and to the extent
necessary and with appropriate security measures (e.g. use of firewalls and network segmentation) in place.
Additionally, Siemens’ guidance on appropriate security measures should be taken into account. For more
information about industrial security, please visit https://www.siemens.com/industrialsecurity.
Siemens’ products and solutions undergo continuous development to make them more secure. Siemens strongly
recommends to apply product updates as soon as available and to always use the latest product versions. Use of
product versions that are no longer supported, and failure to apply latest updates may increase customer’s
exposure to cyber threats.
To stay informed about product updates, subscribe to the Siemens Industrial Security RSS Feed under https://
www.siemens.com/industrialsecurity.

Siemens AG PL20201124062203470 Copyright © Siemens AG 2021


Digital Industries 20210407_134714 Technical data subject to change
Postfach 48 48
90026 NÜRNBERG
GERMANY
Table of Contents
1 Concepts You Need to Know About .................................................................12
1.1 Development and Configuration Environments .................................................................. 12
1.2 Functional Blocks................................................................................................................... 14
1.3 Apps ........................................................................................................................................ 14
1.4 Extension Apps....................................................................................................................... 15
1.5 Data Model Domains.............................................................................................................. 16
1.6 What are Entities .................................................................................................................... 18
1.7 User Authentication ............................................................................................................... 20
2 How to Develop a Manufacturing Solution in Project Studio .........................21
2.1 How to Develop a Functional Block for a Manufacturing Functionality ............................. 21
2.1.1 How to Create a Functional Block....................................................................................................................... 21
2.1.1.1 Creating a Functional Block from Scratch .......................................................................................................... 22
2.1.1.2 Creating a Functional Block with an External Data Source ............................................................................... 24
2.1.1.3 Creating a New Version of Functional Block or App ........................................................................................... 35
2.1.1.4 How to Extend Referenced Functional Blocks ................................................................................................... 37
2.1.2 How to Model a Functional Block........................................................................................................................ 47
2.1.2.1 Working in the Model Project .............................................................................................................................. 48
2.1.2.2 Reserved Keywords.............................................................................................................................................. 52
2.1.2.3 Modifying a Deployed Functional Block ............................................................................................................. 55
2.1.2.4 Modeling Entities ................................................................................................................................................. 56
2.1.2.5 Modeling Commands........................................................................................................................................... 88
2.1.2.6 Modeling Events ................................................................................................................................................... 95
2.1.2.7 Modeling Types .................................................................................................................................................... 97
2.1.2.8 Deprecating Artifacts ......................................................................................................................................... 103
2.1.2.9 Restoring a Previously Deleted AssemblyInfo.cs File....................................................................................... 103
2.1.2.10 Building your Model ........................................................................................................................................... 103
2.1.3 How to Implement Business Logic.................................................................................................................... 105
2.1.3.1 How to Implement Command Handlers........................................................................................................... 107
2.1.3.2 How to Implement Pre-Checks for Business Logic Execution ......................................................................... 124
2.1.3.3 How to Extend Business Logic with Post-Actions ............................................................................................ 129
2.1.3.4 How to Manage Remote Artifacts...................................................................................................................... 131
2.1.3.5 How to Implement Event Handlers................................................................................................................... 143
2.1.3.6 How to Manage Entity Instances ....................................................................................................................... 150

Opcenter Execution Foundation 4.1 - Development and Configuration Guide iii


2.1.3.7 Tracing Process Executions ............................................................................................................................... 205
2.1.3.8 Using Opcenter Execution Foundation C# Analyzer......................................................................................... 212
2.1.3.9 How to Handle Timers ....................................................................................................................................... 216
2.1.3.10 How To Exchange Messages with External Systems ........................................................................................ 230
2.1.3.11 How to Read and Write on Automation Node Parameter Values .................................................................... 231
2.1.3.12 How to Integrate Electronic Signature in Custom Applications ...................................................................... 233
2.1.3.13 How to Use Semi-Automatic Acquisition in Work Instructions ....................................................................... 252
2.1.3.14 How To Manage Application Logs ..................................................................................................................... 253
2.1.3.15 How to Leverage Opcenter Execution Foundation Functional Blocks............................................................ 263
2.1.4 How to Create a Functional Block Package ...................................................................................................... 332
2.1.4.1 Adding Third-Party Files to the Functional Block Installer Project ................................................................. 333
2.1.4.2 Compiling the Database Initialization File........................................................................................................ 333
2.1.4.3 Compiling Application Log Message Files......................................................................................................... 338
2.1.4.4 Generating the Reference Documentation of a Functional Block................................................................... 340
2.1.4.5 Defining the Build Order of a Functional Block ................................................................................................ 342
2.1.4.6 Automatically Updating Referenced Functional Blocks .................................................................................. 343
2.1.4.7 Generating a Functional Block Package ........................................................................................................... 344
2.2 How to Develop an App for a Manufacturing Use Case ...................................................... 346
2.2.1 How to Create an App ........................................................................................................................................ 346
2.2.1.1 Creating a New App............................................................................................................................................ 347
2.2.1.2 Creating a New Version of an App ..................................................................................................................... 350
2.2.1.3 Referencing Functional Blocks from an App .................................................................................................... 351
2.2.1.4 Importing Views from Opcenter EX FN Databases ........................................................................................... 356
2.2.2 How to Model the Public Object Model............................................................................................................. 361
2.2.2.1 Working in the Public Object Model project ..................................................................................................... 363
2.2.2.2 Modeling Entities in the POM ............................................................................................................................ 366
2.2.2.3 Modeling Parameter Types in the POM............................................................................................................. 370
2.2.2.4 Modeling Enumeration Types in the POM ........................................................................................................ 371
2.2.2.5 Modeling Commands in the POM ...................................................................................................................... 372
2.2.2.6 Modeling Reading Functions ............................................................................................................................. 378
2.2.2.7 Modeling Signals in the POM ............................................................................................................................. 381
2.2.2.8 Modeling Roles ................................................................................................................................................... 393
2.2.2.9 Handling Referenced Events in an App............................................................................................................. 395
2.2.2.10 Building the Public Object Model Project ......................................................................................................... 397
2.2.3 How to Implement Business Logic in an App ................................................................................................... 398
2.2.3.1 Importing Composite Command Handlers into an App .................................................................................. 399
2.2.3.2 Importing Event Handlers into an App ............................................................................................................. 401

iv Opcenter Execution Foundation4.1 - Development and Configuration Guide


2.2.3.3 Implementing Composite Command Handlers in an App ............................................................................... 402
2.2.3.4 Implementing Event Handlers in an App .......................................................................................................... 404
2.2.3.5 Importing and Implementing Reading Function Handlers.............................................................................. 406
2.2.3.6 How to Debug Business Logic ........................................................................................................................... 409
2.2.4 How to Develop UIs............................................................................................................................................ 419
2.2.4.1 Concepts You Need to Know About UI Development....................................................................................... 421
2.2.4.2 Code-Based Development of Standard UI Components and UI Modules....................................................... 480
2.2.4.3 Model-Driven Development of UI Modules and UI Screens ............................................................................. 526
2.2.4.4 How To Debug UI Modules and Screens ........................................................................................................... 666
2.2.5 How to Create and Release an App Package .................................................................................................... 669
2.2.5.1 Adding Third-Party Files to the App Installer Project....................................................................................... 670
2.2.5.2 Compiling the Database Initialization File in the App...................................................................................... 670
2.2.5.3 Managing the Application Log File of an App ................................................................................................... 675
2.2.5.4 Generating the Reference Documentation of an App ...................................................................................... 677
2.2.5.5 Defining the Build Order of an App ................................................................................................................... 679
2.2.5.6 Automatically Updating Referenced Functional Blocks in an App.................................................................. 679
2.2.5.7 Generating an App Package .............................................................................................................................. 680
2.3 How to Develop an Extension App ...................................................................................... 682
2.3.1 How to Create an Extension App....................................................................................................................... 682
2.3.1.1 Creating an Extension App ................................................................................................................................ 683
2.3.1.2 Creating a New Version of an Extension App .................................................................................................... 688
2.3.1.3 Referencing Other Functional Blocks from an Extension App......................................................................... 688
2.3.1.4 Loading Base App changes from an Extension App ......................................................................................... 691
2.3.2 How to Extend the POM of an Extension App ................................................................................................... 692
2.3.3 How to Create new Artifacts and Business Logic in an Extension App............................................................ 693
2.3.4 How to Extend User Interfaces in an Extension App ........................................................................................ 694
2.3.5 How to Generate an Extension App Package.................................................................................................... 695
2.4 How to Manage Projects under Source Control ................................................................. 695
2.4.1 Creating an Automatic Build Process for Project Studio Files......................................................................... 696
2.4.2 Importing and Merging a Project Studio Model ............................................................................................... 697
2.4.2.1 UL File Examples ................................................................................................................................................ 700
2.4.3 Configuring the .gitignore File........................................................................................................................... 712

3 How to Manage a Manufacturing Solution in Solution Studio .....................713


3.1 How to Access Solution Studio............................................................................................ 714
3.2 How to Authenticate in Solution Studio ............................................................................. 715
3.3 How to Configure Solution Studio Settings........................................................................ 715

Opcenter Execution Foundation 4.1 - Development and Configuration Guide v


3.4 How to Create a New Solution ............................................................................................ 716
3.4.1 Creating a Solution from Scratch ...................................................................................................................... 717
3.4.2 How to Create a Solution from a Backup.......................................................................................................... 717
3.4.2.1 Restoring SQL Server Databases ....................................................................................................................... 719
3.5 How to Manage the Solution ............................................................................................... 721
3.5.1 Checking Solution Status .................................................................................................................................. 722
3.5.2 Creating a Backup of a Solution ........................................................................................................................ 723
3.6 How to Add Apps .................................................................................................................. 724
3.6.1 Adding a New App to a Solution........................................................................................................................ 725
3.6.2 Removing an App from a Solution .................................................................................................................... 727
3.7 How to Manage Apps and Extension Apps.......................................................................... 727
3.7.1 Adding Extension Apps to a Solution ................................................................................................................ 727
3.7.2 Viewing App and Extension App Details............................................................................................................ 728
3.7.3 Reloading Apps and Extension Apps in a Solution ........................................................................................... 729
3.7.4 Updating Apps and Extension Apps in a Solution ............................................................................................ 730
3.8 How to Configure Apps ........................................................................................................ 733
3.8.1 Configuring Command Settings ........................................................................................................................ 733
3.8.2 Configuring Protected Command Settings....................................................................................................... 737
3.8.3 Configuring Event Subscriptions....................................................................................................................... 739
3.9 How to Configure Accounts ................................................................................................. 742
3.9.1 Viewing Users and Groups ................................................................................................................................. 745
3.9.2 Configuring Roles ............................................................................................................................................... 745
3.9.2.1 Creating Roles .................................................................................................................................................... 746
3.9.2.2 Assigning Rights to Roles ................................................................................................................................... 746
3.9.2.3 Assigning Users and Groups to Roles................................................................................................................ 747
3.9.2.4 Applying Changes to Hosts................................................................................................................................ 747
3.10 How to Configure User Interfaces ....................................................................................... 748
3.10.1 Managing SWAC Components ........................................................................................................................... 749
3.10.1.1 Importing SWAC Components........................................................................................................................... 749
3.10.1.2 Migrating the SWAC Component Manifest........................................................................................................ 750
3.10.1.3 Reloading the SWAC Component Manifest....................................................................................................... 751
3.10.1.4 Updating SWAC Components............................................................................................................................ 751
3.10.2 Designing Mashup UI Modules .......................................................................................................................... 751
3.10.2.1 Creating a Mashup UI Module............................................................................................................................ 752
3.10.2.2 Designing UI Screens ......................................................................................................................................... 754
3.10.2.3 Testing and Generating a Mashup UI Module................................................................................................... 764

vi Opcenter Execution Foundation4.1 - Development and Configuration Guide


3.10.3 Configuring UI Applications............................................................................................................................... 765
3.10.3.1 Creating a UI Application ................................................................................................................................... 767
3.10.3.2 Modifying UI Application Properties ................................................................................................................. 768
3.10.3.3 Selecting UI Modules ......................................................................................................................................... 769
3.10.3.4 Configuring the UI Application Menu ................................................................................................................ 770
3.10.3.5 Testing a UI Application..................................................................................................................................... 771
3.10.3.6 Resetting UI Applications .................................................................................................................................. 772
3.11 How to Configure Maintenance........................................................................................... 772
3.11.1 What is Maintenance.......................................................................................................................................... 773
3.11.2 How to Execute Maintenance on the Live (Runtime) Database....................................................................... 776
3.11.2.1 Configuring Maintenance Registry .................................................................................................................... 777
3.11.2.2 Defining a Maintenance Configuration ............................................................................................................. 780
3.11.2.3 Enabling a Maintenance Configuration at Runtime ......................................................................................... 784
3.11.3 How To Execute Maintenance on the Archiving Database............................................................................... 785
3.11.4 How to Manually Align the Live Database and the Archiving Database .......................................................... 785
3.12 How to Configure Deployment Settings ............................................................................. 787
3.12.1 Configuring Data Sources .................................................................................................................................. 788
3.12.2 Configuring Worker Roles .................................................................................................................................. 791
3.12.2.1 Parallel vs. Sequential Command and Event Handler Execution.................................................................... 792
3.12.2.2 Viewing and Editing an Existing Worker Role ................................................................................................... 794
3.12.2.3 Creating a New Worker Role .............................................................................................................................. 795
3.13 How to Deploy a Manufacturing Solution........................................................................... 796
3.13.1 Creating the Deployment Package ................................................................................................................... 797
3.13.2 Viewing Deployment Package Details............................................................................................................... 798
3.13.3 Deploying the Solution Package to Hosts......................................................................................................... 799
3.13.4 Accessing the UI Application ............................................................................................................................. 801
3.13.5 Debugging Runtime UI Applications ................................................................................................................. 802
3.13.6 Monitoring Hosts with Host Monitoring............................................................................................................ 803
3.13.7 Troubleshooting Deployment Operations........................................................................................................ 804
3.14 How to Manage Documentation ......................................................................................... 808
3.14.1 Loading Product and Custom Documentation into the Documentation Center............................................ 809
3.14.2 Managing Documentation Releases.................................................................................................................. 810
3.14.3 Searching for Information in Documentation .................................................................................................. 811
3.15 How to Use Opcenter Execution Foundation in Multilanguage ........................................ 812
3.15.1 How to Display Solution Studio and UI Applications in a Default Language .................................................. 812
3.15.1.1 Downloading Resources from Support Center................................................................................................. 813

Opcenter Execution Foundation 4.1 - Development and Configuration Guide vii


3.15.1.2 How to Localize the UI Application ................................................................................................................... 813
3.15.1.3 Localizing Solution Studio in a Default Language............................................................................................ 816
3.15.1.4 Setting the Runtime Language.......................................................................................................................... 817
3.15.1.5 Configuring Languages for Login Page ............................................................................................................. 818
3.15.2 How to Display Solution Studio and UI Applications in a Custom Language ................................................. 819
3.15.2.1 Generating Custom Localization Packages ...................................................................................................... 819
3.15.2.2 How to Localize the UI Application into a Custom Language.......................................................................... 821
3.15.2.3 Localizing Solution Studio into a Custom Language ....................................................................................... 824
3.15.2.4 Setting the Runtime Language for Custom Languages ................................................................................... 826
3.15.2.5 Configuring Custom Languages for Login Page ............................................................................................... 827

4 Best Practices for Software Development .....................................................828


4.1 Best Practices for Developing Business Logic .................................................................... 828
4.1.1 Best Practices for Business Continuity ............................................................................................................. 828
4.1.2 Best Practices for Submit Operations............................................................................................................... 829
4.1.3 Best Practices for Automation Writing Operations .......................................................................................... 830
4.2 Best Practices for Implementing Queries ........................................................................... 833
4.3 Best Practices for Implementing Reading Functions ......................................................... 836
4.4 Best Practices for Developing UIs ....................................................................................... 836
4.5 Best Practices for Maintaining Project Studio Solution ..................................................... 842
4.5.1 Best Practices for Managing Solution References............................................................................................ 842
4.5.2 Best Practices for Compiling Project Studio Solutions .................................................................................... 844

5 How to Integrate Opcenter Execution Foundation with Third-Party Business


Logic.................................................................................................................846
5.1 Creating a Manufacturing Integration Solution ................................................................. 846
5.2 Invoking Third-Party Business Logic................................................................................... 847
5.3 Executing Queries on a Third-Party Data Model................................................................. 849
5.4 Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean
interface................................................................................................................................ 850
5.5 Subscribing to Signals from C# Client Applications ........................................................... 858
5.6 Managing Client Authorization............................................................................................ 865
5.6.1 Requesting an Access Token from Opcenter EX FN Authorization Server ...................................................... 866
5.6.2 Obtaining the Access Token starting from an X.509 certificate....................................................................... 871
5.6.2.1 Generating a valid certificate and its private key ............................................................................................. 871
5.6.2.2 Creating a JWT Access Token and using a certificate to sign it ....................................................................... 873
5.6.2.3 Importing the Certificate into the Opcenter EX FN Solution ........................................................................... 876

viii Opcenter Execution Foundation4.1 - Development and Configuration Guide


5.7 Interacting with Opcenter Execution Foundation by Using cURL ..................................... 878
5.7.1 Code Snippets for cURL projects....................................................................................................................... 880

6 How to Monitor Opcenter EX FN Runtime Processes ....................................889


6.1 Monitoring Worker Runtime Instances ............................................................................... 889
6.2 Monitoring Worker and Host Status from Web Clients ...................................................... 891
6.2.1 Retrieving Information from Scenario Subsystems ......................................................................................... 919
6.3 Logging and Analyzing Application Traces with Trace Viewer .......................................... 936
6.3.1 Analyzing Application Traces with Trace Viewer Stand-Alone ........................................................................ 937
6.3.2 Starting Trace Viewer Session ........................................................................................................................... 938
6.3.3 Choosing Trace Providers.................................................................................................................................. 940
6.3.4 Setting the Logging Mode.................................................................................................................................. 951
6.3.5 Splitting ETL Files............................................................................................................................................... 953
6.3.6 Choosing Columns ............................................................................................................................................. 954
6.3.7 Sorting Events .................................................................................................................................................... 957
6.3.8 Grouping Correlated Messages ......................................................................................................................... 958
6.3.9 Applying Filters and Highlights ......................................................................................................................... 965
6.3.10 Setting the Display Configuration ..................................................................................................................... 965
6.3.11 Setting the Display Options in the Main Panel ................................................................................................. 966
6.3.12 Exporting Traces to a Persistent Storage.......................................................................................................... 967
6.3.12.1 Exporting Traces To Windows Performance Monitor....................................................................................... 968
6.3.12.2 Modifying Trace Viewer Persistent Logging Parameters ................................................................................. 969
6.3.13 Generating Custom Trace Providers ................................................................................................................. 970
6.4 Persisting System, Security and Application Messages on Microsoft Event Viewer ......... 971
6.4.1 Opcenter EX FN System, Security and Application Traces............................................................................... 973
6.4.2 Configuring the SIMATIC IT UAF Log Router Service via Script...................................................................... 1006
6.4.3 Subscribing to Security and System Events in a Cluster Scenario ................................................................ 1010
6.5 Viewing Opcenter EX FN Application Dumps.................................................................... 1013
7 How To Perform Database Maintenance Operations..................................1015
7.1 Managing Indexes in Opcenter Execution Foundation .................................................... 1015
7.2 Performing Maintenance on Timer Tables ....................................................................... 1020
7.3 Using Maintenance Stored Procedures ............................................................................ 1023
7.3.1 Purge of __MTLog table ................................................................................................................................... 1023
7.3.2 Purge of __SynchronizationLog table............................................................................................................. 1025

8 How to Migrate a Manufacturing Solution...................................................1026


8.1 Updating the Projects in Project Studio ........................................................................... 1026

Opcenter Execution Foundation 4.1 - Development and Configuration Guide ix


8.1.1 Updating SIMATIC IT UAF 2.0 Projects in Project Studio................................................................................ 1028
8.1.2 Updating SIMATIC IT UAF 2.1 or 2.1 Update 1 Projects in Project Studio ..................................................... 1029
8.1.3 Updating SIMATIC IT UAF 2.2 Projects in Project Studio................................................................................ 1031
8.1.4 Updating SIMATIC IT UAF 2.3 Projects in Project Studio................................................................................ 1032
8.1.5 Updating SIMATIC IT UAF 2.4 Projects in Project Studio................................................................................ 1032
8.1.6 Updating SIMATIC IT UAF 2.5 Projects in Project Studio................................................................................ 1033
8.1.7 Updating Opcenter EX FN 3.0 Projects in Project Studio ............................................................................... 1034
8.1.8 Updating Opcenter EX FN 3.1 Projects in Project Studio ............................................................................... 1035
8.1.9 Updating Opcenter EX FN 3.2 Projects in Project Studio ............................................................................... 1037
8.1.10 Updating Opcenter EX FN 3.3 Projects in Project Studio ............................................................................... 1038
8.1.11 Updating Opcenter EX FN 4.0 Projects in Project Studio ............................................................................... 1039
8.2 Updating the Solution in Solution Studio......................................................................... 1040
8.2.1 Running scripts for Upgraded Apps ................................................................................................................ 1040
8.3 Building and Deploying the Updated Solution in Solution Studio.................................. 1041
8.4 Completing the App Migration .......................................................................................... 1042

x Opcenter Execution Foundation4.1 - Development and Configuration Guide


ID OpcenterEXFN_DevelopmentConfigurationGuide

Title Development and Configuration Guide

Product Title Opcenter Execution Foundation

Version Title 4.1

Product Version OpcenterEXFN_4.1.0.0

Category Development, Configuration

Summary Provides technical information to work efficiently with Opcenter


Execution Foundation.

Audience Developer, System Integrator, Support Engineer, Project Engineer

Revision PL20201124062203470

State Published

Author Siemens AG

Language en-US

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 11


Concepts You Need to Know About

Development and Configuration Environments

1 Concepts You Need to Know About


The following concepts are considered prerequisites to understanding how to work efficiently with Opcenter
Execution Foundation® (Opcenter EX FN):
• Development and Configuration Environments
• Functional Blocks
• Apps
• Extension Apps
• Data Model Domains

1.1 Development and Configuration Environments


Opcenter Execution Foundation manages the entire lifecycle of a Manufacturing Solution, from development to
deployment.
A Manufacturing Solution aggregates all artifacts and configurations that make up a Manufacturing Operations
Management solution for a specific customer.
Part of the artifacts and the business logic of a Manufacturing Solution are developed in Project Studio as
Functional Blocks, which are then packaged into Apps (aggregations of Functional Blocks and UIs). Other artifacts
are created and configured using Solution Studio.

Manufacturing Solution Lifecycle


The overall Manufacturing Solution management lifecycle is shown in the following picture and described below:

12 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Concepts You Need to Know About

Development and Configuration Environments

Setup and Configuration


This initial phase involves the installation of Opcenter Execution Foundation and the configuration of security and
system settings, such as Windows users, the production database, the system repositories and the Documentation
Center.

Functional Block development in Project Studio


Functional Blocks are developed in Project Studio
Project Studio is a development environment, integrated in Microsoft Visual Studio, which is composed of an
articulated system of graphic tools, templates and add-ons, which have been designed to give direct access to the
back-end and data model. It has a default starting page (corresponding to the [Installed Extension]
Engineering.VSPackage.StartPage option in the startup customization environment of Visual Studio), which can
be changed.
Its main target is to reduce code development by offering an interactive rapid development environment where you
can model entities, commands and events. The custom business logic required for commands and events is
implemented by the user through specific handlers automatically generated in Project Studio, whilst no code
development is required for entities.

App Development in Project Studio


Apps aggregate several Functional Blocks and provide a Public Object Model, which is a public reading model
containing all the artifacts that will be exposed to the web clients as access points of the Opcenter Execution
Foundation back-end functionalities.
Like Functional Blocks, Apps are developed in Project Studio.
During the App development stage you can also develop a set of UI Components and UI Modules as UI building
blocks of the final solution.
All the artifacts generated during this stage are packaged for the final solution configuration in Solution Studio.

Solution Definition
New solutions are created in Solution Studio, starting from Apps created in Project Studio.
Solution Studio is a full web configuration client from which any authorized user can manage its solution. A solution
can reference multiple Apps.
Solution Studio offers administrative functionalities (for example to create, update or delete a solution) and UI
Development tools, such as the Mashup Editor, which enables you to quickly design and configure screens, and the
UI Application editor, which enables you to aggregate these screens into a UI Application.
Solution Studio also offers backup and restore functionalities as it saves all configuration and deployment
information in a system repository (for example, the distribution logic of worker roles, event subscriptions, host
configurations, security roles).

Solution Engineering and Configuration


In the engineering and configuration phase, solution metadata is uploaded from existing Apps and solution
governance is configured (user roles, worker roles, external domains governance configuration).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 13


Concepts You Need to Know About

Functional Blocks

The customer solution is configured through the App Public Object Model and UI building blocks by defining the
relevant manufacturing rules (e.g. which commands are called for a particular event) and additional UI Applications
for different target user roles.

Solution Deployment
The Manufacturing Solution, which you developed and configured with Project Studio and Solution Studio, can be
deployed in a runtime environment through Solution Studio deployment functionalities.
The Manufacturing Solution can be deployed in a distributed environment. This essentially means that you can
deploy it over several web server hosts, whilst still granting load balancing and failover capabilities. Each host can
be individually joined to the network and the current solution can be deployed on it. When all hosts are correctly
updated to the latest solution version, Opcenter Execution Foundation will be ready to perform create/
update operations on the production database and start runtime services on all runtime hosts. Each host can also
communicate its status to the network in order to activate failover logic.

1.2 Functional Blocks


In Opcenter Execution Foundation manufacturing solutions are made up of building blocks, called Functional
Blocks. A Functional Block can be considered as a specific micro-solution that provides a data model and business
logic for a single manufacturing functionality, relative to a specific business area (e.g. Labeling and Printing, Pallet
Management), which are used to develop basic manufacturing functionalities (for example, pallet handling).
They contain one data model, which belongs to a data model domain.
Initially a Functional Block is an empty structure. From this structure you can:
• create all the elements required to build a solution from scratch, such as entities, types, events and commands,
and the files required to deploy the Functional Block.
• pre-populate the Functional Block with artifacts from referenced existing functional blocks or imported views
from external data sources, such as Microsoft SQL Server or Oracle Database.
Each Functional Block has a version number, made up of a Major, Minor and Patch number.

What does a Functional Block contain?


Functional Blocks correspond to Visual Studio solutions, and they are made up of a series of Visual Studio projects,
each with a specific purpose.
There are Visual Studio projects for:
• the data model
• the business logic of commands and events
• the generation and deployment of the Functional Block itself.

What can you do with a Functional Block?


Functional Blocks cannot be deployed on the target machine. They can be referenced from Apps, which can then be
used to create and configure a solution in Solution Studio.

1.3 Apps
Apps are used in Project Studio to create and generate specific manufacturing use cases, based on multiple
manufacturing functionalities (i.e. Functional Blocks).

14 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Concepts You Need to Know About

Extension Apps

Like Functional Blocks, Apps correspond to Visual Studio solutions, and they are made up of a series of Visual
Studio projects, each with a specific purpose.
There are projects to:

• create the Public Object Model


• develop the business logic of commands and events
• create the user interface
• generate and deploy the App.
Each App has a version number made up of a Major, Minor and Patch number.

What is the Public Object Model?


Each App contains a Public Object Model (POM). Through the POM you expose artifacts to be accessed by clients. In
particular, the POM contains:
• Events, entities, complex types (parameter types, value types and enumeration types) and protected
commands of referenced Functional Blocks.
• Entities imported from views created on top of SQL Server or Oracle databases.
• Composite commands (i.e. commands that can call logic developed in referenced Functional Blocks), Signals
(i.e. messages related to specific business events and entity-related operations), predefined User Roles (i.e.
groups of operations that can be executed only by certain users) and predefined Event Subscriptions directly
modeled inside the Public Object Model.
• Reading Functions

What can you do with an App?


The App represents the entry point for the configuration of the Manufacturing Solution in the web based Solution
Studio environment.
Each App, once developed, is compiled and released as a package that will then be used to create and configure a
solution in Solution Studio.
A solution can contain multiple Apps.

1.4 Extension Apps


Starting from a base App, you can create a new App as an extension of the base App.
The main benefit of the Extension App is that you can make changes to its published Public Object Model without
changing the original App.
Extension Apps cannot be further extended with other Extension Apps.

Extension of the Public Object Model


The Public Object Model of the Extension App contains the public artifacts from the base App or from any
referenced Functional Blocks.
As for all referenced artifacts, the referenced Public Object Model cannot be modified and consequently you cannot
remove or rename public Entities, Commands, Reading Functions and Types coming from the Base App.
In an Extension App, the Public Object Model can be extended by:
• importing additional entities from the Base App and any referenced Functional Blocks
• referencing additional Functional Blocks and importing their entities
• creating new composite commands and reading functions
• creating new pre-defined roles and event subscriptions

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 15


Concepts You Need to Know About

Data Model Domains

• releasing new UI screens.

1.5 Data Model Domains


Data modeling is an abstract representation of the data structures to be used in the tables of a company’s database
in order to easily organize the data you have to store and the data you want to retrieve and show. Data modeling
represents a powerful expression of the company's business requirements.
A data model organizes data elements (entities) and their relationships, it standardizes how these elements relate
to one another and it provides you a way to access them without directly writing on the database or reading from it.
Opcenter Execution Foundation information is organized in three distinct data models:
• A writing model
• A reading model
• Event Store

What is the writing model?


The writing model works with .NET classes and manages the data structures that will contain the data you need to
store. This data model relies on Microsoft Entity Framework, which is used as a middle layer for transforming .NET
classes into database tables and relationships. Entity Framework enables developers to work with data in the form
of domain-specific objects and properties, such as customers and customer addresses, without having to deal with
the underlying database tables and columns where this data is stored. With the Entity Framework, developers can
work at a higher level of abstraction when they deal with data, and can create and maintain data-oriented
applications with less code than in traditional applications.
The architecture of Opcenter Execution Foundation has moved another step forward, and instead of asking you to
develop objects and properties through .NET classes, it provides you with a graphic tool for managing data model
entities and relationships.
The writing model can be accessed through Opcenter Execution Foundation API interfaces for writing and reading
purposes.

What is the reading model?


The reading data model organizes and exposes data only for reading purposes. This data model exposes its
database structures through OData services.
It is kept separate from the writing model because the architecture of Opcenter Execution Foundation applies
similar concepts to those described in the Microsoft CQRS pattern.
The benefit of this separation is appreciated immediately when the reply speed of the data warehouse is more
important than the organization of the data itself. In these contexts you can model your reading database
according to how you want to retrieve and view data on your client, without configuring complex queries, with
additional joins and so on. A reading model could be, for example, a denormalized model, where relationships
between tables (such as one-to-many or many-to-many) are transformed into one unique simplified relationship
within the same table.
Consequently, you could have several reading models for one single writing model. Each application that needs
specific reading logic can implement its own model. An example is the Business Intelligence layer, which needs to
aggregate large amounts of data, perform complex calculations and quickly display the results.
The reading model can be constantly synchronized with the writing model by applying synchronization logic based
on event subscriptions.
It can be queried only for reading purposes through OData queries, as well as through product API interfaces.

16 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Concepts You Need to Know About

Data Model Domains

What is the Event Store data model?


The Event Store data model is used to store all the events that are related to write operations executed on the write
database. Opcenter Execution Foundation constantly monitors these operations: when a change is performed on
the write database, the system raises an event, the CommittedEvent event, and writes it to the Event Store
database.
External components could subscribe to the CommittedEvent in order to keep write and read databases aligned.
This alignment mechanism is event-based. When the CommittedEvent is posted to the Event Store, these modules
could monitor the changes that occurred in the write database and persist the corresponding changes on the read
database.
The CommittedEvent is available as a referenced event inside the model project of each Functional Block type. By
implementing a custom event handler and then subscribing this handler to the CommittedEvent, you can associate
any logic with the latest changes made to the write data model (for example, in order to handle
the synchronization of a custom read data model). You can also create a subscription to the CommittedEvent and
implement custom logic in an external application that uses the IUnifiedSdkLean public interface.
Each Functional Block belongs to a specific data model domain. Domains make it easier to manage large data
models by dividing data into specific contexts and clearly defining the relationships among them.
Domains are autonomous components, with their own domain models and their own business logic.
Opcenter Execution Foundation provides three data model domains and the possibility to create user data models
for external data sources. These data model domains constitute the data model, which can spread business logic
over different databases. The data domain models are:
• Reference Data (RF), which should typically define the set of possible values to be used by other data fields, and
are widely re-used and widely referenced. Reference data normally changes slowly, reflecting changes in
business operation modes, rather than changes that occur in the normal course of business (for example units
of measure and status transitions).
• Master Data (MS), which should contain the main basic business entities, for example Material Definitions and
Bills of Materials. This data represents business objects that are typically agreed on and shared across the
enterprise, and used across multiple systems, applications and processes.
• Operational Data (OP), which should contain business events or manufacturing transactions (such as
production orders, material transfers, non-conformances, manufacturing operation jobs etc) that occur within
manufacturing operations, or business objects that are created and managed during manufacturing operation
lifecycles (for example lots, sublots).
• User, which can contain a reading data model imported from an external data source. User domains must have
a name and a two digit acronym which is different from the acronyms assigned to the standard domains listed
above.

Predefined data model


Opcenter Execution Foundation provides a predefined data model which is delivered by a set of Apps.
This data model is built within the three standard Opcenter Execution Foundation domains (Reference Data, Master
Data and Operational Data) and is delivered by means of Functional Blocks. These Functional Blocks contain a set
of predefined entities and commands that can be used as they are or can be further extended through custom
Functional Blocks.
The list of entities and commands is documented in the reference guides related to the Functional Blocks and Apps.

Communication between data model domains


Domains should be able to run alone at runtime. However each domain is part of the same overall system so they
need to exchange data with one another.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 17


Concepts You Need to Know About

What are Entities

Communication is principally of two main types:


• information: information belonging to a specific domain can be linked to information from other
domains via value types. A domain can contain data from another domain, which has been denormalized via
value types. This information can then be synchronized in your business logic by subscribing to a
CommittedEvent.
• business logic:
• events, where domains can respond to events that are raised by other domains, and domains can
publish events that other domains may subscribe to.
• composite commands - in a large system scenario, where a large number of domains are involved,
communication based on event subscriptions can be complicated. Composite commands provide a way
to aggregate and route business logic calls that belong to different domains. Through these
commands users can use APIs to call business logic and raise events from different domains. Composite
command handlers can be created in an App, using commands created in a Functional Block.

Database distribution
One of the advantages to having multi domains is to allow a database architecture where each domain is hosted on
a different server, or several domains are hosted on several database servers.
Currently, Opcenter Execution Foundation supports only an architecture where all domains are hosted on a single
server.
However, adopting multi-domain from the start makes it possible to adopt different complex and distributed
architectures in the future.

1.6 What are Entities


Entities are abstract items that refer to the most common things that represent the objects and the operations
involved in your manufacturing production.
For example, an entity could be the material definition entity type, whose corresponding structure in the database
will be used to store real material definitions, such as milk, fans, chassis and so on.
Entities are characterized by properties, which will be used in the database to store the characteristics of the entity
(such as the color, the type and so on) and its behavior (such as its visibility and accessibility).
You can create a new entity from scratch by providing a set of basic information (the name of new entity, the
description etc) as well as the set of properties.

18 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Concepts You Need to Know About

What are Entities

The standard fields required are a name and description for the new entity, a list of tags/keywords, which make it
possible to search for the entity, and whether or not the entity can be physically extended (sealed).
Entities can be extended in two different ways:
• Physical extension: new columns are added to the entity table in the database.
• Logical extension: a new column is added to the facet table that accompanies each entity in the database.

Physical extension
The physical extension can be viewed as a semantic extension: a certain entity, such as a lot, could be considered
complete and exhaustive for a vertical solution if it also contains, for example, the Barcode property (or the Color
property or any other property). In this case, the added property is shared and can be used by all the other entities
that inherit from the modified entity.
Entities can be physically extended through inheritance, by creating a new sub-entity, as long as the entity has not
been sealed.
For example, you may have the WorkOrder entity containing a set of properties, such as ID, name, description:
• To customize this entity for a discrete manufacturing solution, you could extend it by creating a new sub-entity
called ProductionOrder, which contains the following properties: ErpOrder and ErpPlant. This new
entity extends WorkOrder and inherits ID, name, description, from WorkOrder.
• To customize the ProductionOrder entity for a specific project, you could extend it through a new sub-entity
called WorkBookingOrder, which contains the following properties: SerialNumber and ParentBatch. This
entity inherits all the properties from WorkOrder entity (ID, name, description) and
from ProductionOrder entity (ErpOrder and ErpPlant).

Logical extension (facets)


The logical extension (facet) can be viewed as a functional extension. A facet is always associated to a particular
functionality (such as the warehouse management functionality, or the traceability functionality).
A logically extended entity has a facet table, which contains its extension properties.
For example, you may have the WorkOrder entity containing a set of properties, such
as ID, name, description, estimated start time, estimated end time, actual start time, actual end time. You may
decide to add the customer's required properties (SerialNumber, ParentBatch, ErpOrder and ErpPlant) directly
to this entity.

Attached document management


It is always possible to attach documents (of different sizes and types) to business entities, such as master data, like
material definitions or recipes or work instructions; operational data, like orders, operations, non-conformances,
etc.
Files are typically provided through a specific UI, and can be of any type (PDF, CAD images, etc.).

Revision management
Entities that belong to the Master Data domain support revision management.
The instances of these entities are enriched with specific properties and SDK methods, which enable revision
management. For example, a specific revision can be locked, to ensure that it is not modified, or uniquely identified
as the current revision.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 19


Concepts You Need to Know About

User Authentication

1.7 User Authentication


Authentication in Opcenter Execution Foundation is managed by means User Management Component
functionalities.
By default, to log on to Solution Studio or to the UI Application, you must enter user and password in an interactive
dialog box.
By means of User Management Component, you can enable different login modes such as for example the
Integrated Windows Authentication (also called Autologin in UMC), PKI and so on.
To properly configure these authentication modes, you must refer to the UMC Web UI User Manual.
If you configure the Integrated Windows Authentication, pay attention that you might need to configure specific
Windows accounts with the proper UMC administrative rights in order to be able to perform administrative
operations in UMC without using the built-in admin UMC account.

20 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2 How to Develop a Manufacturing Solution in Project Studio


To develop a manufacturing solution with Opcenter Execution Foundation you must:
1. Develop basic manufacturing functionalities by creating Functional Blocks.
2. Develop a manufacturing use case by creating an App.

2.1 How to Develop a Functional Block for a Manufacturing


Functionality
Manufacturing functionalities (Functional Blocks) are basic functionalities which can then be used in more than one
App.
An App can contain many different Functional Blocks from various standard or custom domains.
They are developed in Project Studio through the creation of Functional Blocks.

Workflow
The manufacturing functionality workflow involves four main steps, which are described below and illustrated in
the following workflow diagram:
1. Create a Functional Block.
2. Model Data.
3. Implement Business Logic.
4. Create a Package.

2.1.1 How to Create a Functional Block


The creation of a Functional Block is the first part in the development of a manufacturing solution.
Once created the Functional Block, you can start defining the Data Model either from scratch, or by extending
artifacts from referenced Functional Blocks or by importing artifacts from external database views.
Files that make up your Functional Block solution can be versioned and merged using source control integration.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 21


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Workflow
The creation phase involves the following steps:
1. Create either a:
• Functional Block from scratch: this option creates a new Functional Block that belongs to a specific data
model domain.
• Functional Block with an external data source: this option will import artifacts from an external data
source (such as Microsoft SQL Server or Oracle Database).
2. If needed, create references to existing Functional Blocks: this option references an existing Functional Block to
integrate and extend its artifacts into your model.

2.1.1.1 Creating a Functional Block from Scratch


1. From the start page of Visual Studio, select the File > New > Project command.
2. In the left pane, click Installed and then expand the Simatic IT node.
3. Select FunctionalBlock.Library.
4. Enter a name for the Functional Block, which will then be used in the solution. The name can contain 20
characters maximum, it cannot contain dots and cannot be modified once inserted.

 The name of the Functional Block must not be identical to the name of any referenced Functional
Blocks or artifact types (e.g. "event", "command" etc) and must not contain reserved keywords.

5. Enter the location where the Functional Block will be created. The location name cannot contain the following
special characters: < (less than), > (greater than), : (colon), " (double quote), / (forward slash), \ (backslash), |
(vertical bar or pipe), ? (question mark), * (asterisk), & (ampersand), # (hashtag), % (percentage), , (comma).
6. Click OK: the creation process is simplified by an integrated wizard which guides you through the necessary
steps.

22 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

7. Enter a prefix for the Functional Block (see constraints below). The prefix is then added to the Functional Block
name in order to easily identify it during the development and configuration process.

 Prefix naming constraints


• The prefix cannot start with a number.
• The prefix cannot contain:
• special characters (< (less than), > (greater than), : (colon), " (double quote), / (forward
slash), \ (backslash), | (vertical bar or pipe), ? (question mark), * (asterisk), ! (exclamation
mark)
• underscore (_) or hyphen (-)
• accented characters (for example à, ò, é, ù and so on)
• C# keywords
• dots (.) as the first or last character
• commas
• spaces
• non-latin characters (for example, 新浪网 or ‫)ﻣﺆﺳﺴﺔ‬.

8. Select which data model domain your Functional Block will belong to.
9. Modify the major version (the first two-digit number) of the Functional Block if the default value (01.00.00) does
not correspond to your requirements.
10. Insert a description providing other users with additional and exhaustive information on the functionality
provided by the Functional Block.
Note: During the modeling phase, it will be possible to modify the description of the Functional Block at any
time, right-clicking the Installer project and selecting the Properties command.
11. Select the projects you need (a complete Functional Block will require all of them):
• Model Project: from which you can model entities, commands, events and types.
• Command Handler Project: from which you can implement the business logic for commands.
• Event Handler Project: from which you can implement the business logic for events.
• Installer Project: where the files required to create the functional block package are contained.

 Once you have created your Functional Block, you can subsequently remove or add projects from Visual
Studio.
Bear in mind that you cannot add Reading Function or User Interface projects or an App solutions to a
Functional Block, as well as any other projects which are not supported by the Functional Block wizard.

Result
If you have selected all available projects the structure displayed in the Solution Explorer pane is the following:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 23


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.1.2 Creating a Functional Block with an External Data Source


This page describes how to create a Functional Block in order to import views from external data sources and
create logic (only in reading mode) on imported entities.
The creation procedure does not differ from the one for standard Functional Blocks, except for the selection of the
User domain.

Prerequisites
• The external database is configured with the required permissions:
• SQL Server configuration, as described at section Configuring a Third-Party MSSQL Database of the
Opcenter Execution Foundation Installation Guide
• Oracle configuration, as described at section Configuring a Third-Party Oracle Database of the Opcenter
Execution Foundation Installation Guide
• Views have been created respecting the prerequisites for external data source views.

Procedure
1. From the start page of Project Studio, select File > New > Project.
2. In the left pane, click Installed and then expand the Templates\Simatic IT node.
3. Select Functional Block (Library).
4. Enter a name for the Functional Block, which will then be used in the solution. The name can contain 20
characters maximum, it cannot contain dots and cannot be modified once inserted.

 The name of the Functional Block must not be identical to the name of any referenced Functional
Blocks, and must not contain C# reserved keywords , such as event, events or commands.

5. Enter the location where the Functional Block will be created. The location name cannot contain the following
special characters: < (less than), > (greater than), : (colon), " (double quote), / (forward slash), \ (backslash), |
(vertical bar or pipe), ? (question mark), * (asterisk), & (ampersand), # (hashtag), % (percentage), , (comma).
6. Click OK: the creation process is simplified by an integrated wizard which guides you through the necessary
steps. Pay attention that to use an external data source you must select the User domain as described in the
following steps.

24 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

7. Enter a prefix for the Functional Block (see constraints below). The prefix is then added to the Functional Block
name in order to easily identify it during the development and configuration process.

 Prefix naming constraints


• The prefix cannot start with a number.
• The prefix cannot contain:
• special characters (< (less than), > (greater than), : (colon), " (double quote), / (forward
slash), \ (backslash), | (vertical bar or pipe), ? (question mark), * (asterisk), ! (exclamation
mark)
• underscore (_) or hyphens (-)
• accented characters (for example à, ò, é, ù and so on)
• C# keywords
• dots (.) as the first or last character
• commas
• spaces
• non-latin characters (for example, 新浪网 or ‫)ﻣﺆﺳﺴﺔ‬.

8. Select User from the Domain drop-down list.


9. Enter a name for your user domain to identify it.
10. Specify an acronym to identify the user domain, which must be different from those already used for standard
domains (OP, RF, MS) and must not start with a number.
11. Modify the major version (first two-digit number) of the Functional Block if the default value (01.00.00) does not
correspond to your requirements.
12. Insert a description providing other users with additional and exhaustive information on the functionality
provided by the Functional Block.
Note During the modeling phase, it will be possible to modify the description of the Functional Block at any
time, right-clicking the Installer project and selecting the Properties command.
13. Select the projects you need (a complete Functional Block will require all of them):

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 25


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• Model Project: from which you can model entities, commands, events and types.
• Command Handler Project: from which you can implement the business logic for commands.
• Event Handler Project: from which you can implement the business logic for events.
• Installer Project: where the files required to create the functional block package are contained.
14. Open the Model project: the External Data Source tab will be displayed in the Model Explorer pane, from
where you can now import views.

Result
If you have selected all available projects the structure displayed in the Solution Explorer pane is the following:

 Once you have created your Functional Block, you can subsequently remove or add projects from Visual
Studio.

2.1.1.2.1 Prerequisites for External Data Source Views


Views that can be imported into Project Studio must respect certain conditions that are described in this page. This
page does not describe how to create views.

 The person in charge of creating the views must know both the logic and the semantic of the source tables,
in order to correctly use the C# types while implementing the handlers that use the corresponding entities
as a reading model.

26 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

General rules for fields


• Views must not contain fields ending with _id and fields containing dots "." (e.g. use "StatusId" instead of
"Status.StatusId").
• The view must contain (at least) the Id field (case insensitive) and the data returned by the view must guarantee
the uniqueness of the Id field. Its type can be Int, Guid, Bigint or String. The column property must be non-
NULL-able in SQL Server while it can be both non-NULL-able and NULL-able in Oracle. Note Sometimes you may
not realize that MSSQL Server/ Oracle treats your columns as NULL-able. For example, CAST (col1 AS
bigint) produces a NULL-able column. While ISNULL (CAST (col1 AS bigint), 1) produces a non-NULL-able
column. Bear in mind that at runtime you cannot have a NULL value in the Id field.

Third-party types
Views can contain only Opcenter Execution Foundation supported types and the conversion from third-party to
supported types is performed as follows:
Oracle

Oracle type Is Supported Project Studio System .NET Corresponding


Type Type

NUMBER(19) bigint System.Int64

NUMBER(1) bool System.Boolean

CHAR String System.String

Date Cast to TIMESTAMP(6) Datetime System.DateTimeOffse


WITH TIMEZONE t

TIMESTAMP(6) WITH Datetime System.DateTimeOffse


TIMEZONE t

NUMBER(x, y) Decimal System.Decimal

Decimal types with Scale = 0


are not supported.

NUMBER Decimal System.Decimal

Considered as a number
(38,19)

BINARY_FLOAT Cast to NUMBER Decimal System.Decimal

NUMBER(10) Int System.Int32

NCHAR String System.String

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 27


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Oracle type Is Supported Project Studio System .NET Corresponding


Type Type

NVARCHAR2 (CLOB in case String System.String


of length MAX)

NUMBER(5) Smallint System.Int16

NUMBER(3) Tinyint System.Byte

VARCHAR2 String System.String

RAW(16) Guid System.Guid

RAW (BLOB in case of Blob System.Byte


length MAX)
Data is imported according to C# type precision and not to Oracle type precision. For example NUMBER(10) accepts
a value between -2147483648 and 2147483647 instead of 10 digits
MSSQL

Microsoft SQL Server Is Supported Project Studio System .NET Corresponding Type
Type

bigint bigint System.Int64

bit bool System.Boolean

char String System.String

date Cast to Datetime System.DateTimeOffset


datetimeoffset

datetime Cast to Datetime System.DateTimeOffset


datetimeoffset

datetime2 Cast to Datetime System.DateTimeOffset


datetimeoffset

datetimeoffset Datetime System.DateTimeOffset

decimal Decimal System.Decimal

float Cast to decimal Decimal System.Decimal

28 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Microsoft SQL Server Is Supported Project Studio System .NET Corresponding Type
Type

int Int System.Int32

nchar String System.String

nvarchar String System.String

smallint Smallint System.Int16

tinyint Tinyint System.Byte

varchar String System.String

Uniqueidentifier Guid System.Guid

varbinary Blob System.Byte

2.1.1.2.2 Connecting to an External Data Source


This page describes how to connect to an external data source so that its views can then be imported inside a
Functional Block.
There can be only one external database connection at a time. You can import views from different database
connections, as long as they belong to the same provider, but these views must all be present on the single
database which is then used in production. See Importing Views from an External Data Source for further details.

Prerequisite
You have defined a Functional Block associated with a User domain.

Procedure
1. Within the Functional Block of User type, open the Model project.
2. In the Model Explorer, open the External Data Source area.
3. Right-click the required data source provider (either MSSQL or Oracle) and then click Add Oracle/MSSQL
Server.

 If you cannot see the Oracle data source provider, check the Prerequisites for Opcenter Execution
Foundation Configuration Tool in the Opcenter Execution Foundation Installation Guide.

4. Set the following parameters:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 29


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Parameter Description

Server Name The name of the server (and the server instance, if required). Only
for MSSQL, click on the drop-down list box to automatically populate it
with the available servers.

Initial Catalog (Only for MSSQL) The database name.

Schema The schema name (only for Oracle). It cannot contain dots (.).

Authentication The authentication mode of the user. The available options are:
• Windows Authentication: in this case the database
connection is made using the credentials of the interactive
user who is running Visual Studio (and consequently Project
Studio) and who must also have the necessary grants to
access the SQL/Oracle views.
• (Only for MSSQL) Sql Authentication: in this case the
database connection is made using the credentials of the
user who must have the necessary grants to access the SQL
views.
• (Only for Oracle) Oracle Authentication: in this case the
database connection is made using the credentials of the
user who must have the necessary grants to access the
Oracle views.
For more information, see How To Configure Third-Party Databases in
the Opcenter Execution Foundation Installation Guide.

User Name (Only in case of database authentication) The name of the user who
must have the necessary grants to access the SQL/Oracle views.

Password (Only in case of database authentication) The password associated


with the user who must have the necessary grants to access the SQL/
Oracle views.
5. Click Test Connection to make sure the external data source is viable.
6. Click OK.
7. Check there is a green plug icon below the connection node which indicates you are correctly connected to the
external data source: you can now import its views into the Functional Block.

Editing a connection
You can edit your database connection, as long as it uses the same data source provider, by right-clicking the
connection node in the External Data Source view and selecting Edit.
The system connects to the target repository and loads its views.
• If the name of a new database view corresponds to a previously imported entity, and differences are found, the
corresponding view is marked with an asterisk and an exclamation mark. The view can then be updated.
• Any views that were previously imported and that are not present in the new database connection will still be
displayed as artifacts in the central work pane, but a warning message will be displayed.

Refreshing a connection

30 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

If you know changes have been made to the MSSQL/Oracle database views, you can incorporate these changes into
your imported views by refreshing the connection.
This is simply done by right-clicking the connection node in the External Data Source view and selecting Refresh.
Any inconsistencies between the source database views and imported views will be marked by an asterisk and an
exclamation mark. At this point you can update the corresponding database views.

Changing provider
If you want to change provider you must first remove any views you imported from the initial provider.
Imported views can be deleted either by right-clicking any entities that have been dragged and dropped into the
central pane and selecting Delete, or by deleting the corresponding entities from the Object Model view.
You then add the new connector following the standard procedure.

2.1.1.2.3 Importing Views from an External Data Source


This page describes how to import views into a Functional Block associated with an external data source, and the
constraints you must consider before importing views.
If you use a third-party data model as an external data source, the logic you will build on imported entities is limited
to the logic you can develop on a read data model (see Operations allowed on imported entities paragraph below).
Write operations on external data sources can be developed through Composite Commands inside an integrated
manufacturing solution.

Prerequisites
• You have defined a Functional Block with a User domain (which is specific for reading data from external data
sources)
• You have correctly configured your third-party database (see How To Configure Third-Party Databases in the
Opcenter Execution Foundation Installation Guide)
• You have created your views respecting specific prerequisites

Constraints on importing views from different databases


During the deployment phase of your solution, when you set the database connections to the external data sources,
you can specify only one connection for each referenced Functional Block. Consequently, you must consider the
following constraints if you want to import views from different databases inside the same Functional Block:
• During the development of your Functional Block you can import views from different databases, as long as they
belong to the same data source provider (i.e. either MSSQL Server or Oracle). If you have already imported views
from a database and you want to import views from another database (belonging to the same provider), you
can edit the connection and import views from the second database (in the External Data Source area of your
Functional Block). If this is your strategy, be aware that before you set the connection to the external
database for solution deployment, you must verify that your production database contains exactly all the views
that you have imported during the development phase, because at that point you will specify only one
connection string to one single database. If the views you have used do not exist on this target database, you

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 31


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

must manually create them on it.

• Once you have imported a view from a particular data source provider (e.g. MSSQL Server) you cannot at that
point add views from other data source providers (e.g. Oracle). To switch data source provider you must delete
all the entities from the previous provider in the model, and then import new views from the new provider.
• If you want to import views from different external data sources, you should use separate Functional Blocks.

Procedure
1. Within the Functional Block of User type, open the Model project.
2. In the Model Explorer, open the External Data Source area.
3. In the tree list, expand the node with your data source and select the views relative to the entities to be
imported in the reading data model by either:
• dragging and dropping the views into the central area, or
• right-clicking the required views and selecting Import View. Views imported in this way are not
displayed as entities in the central working area.

 Multi-selection is enabled for both operations.

Result
Imported entities are displayed:
• in the Object Model view
• in the External Data Source in bold
• in the central working pane if they were imported via a drag and drop operation.

Operations allowed on imported entities


You can perform the following operations on these imported entities from an external data source:

32 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Operation Type Allowed

Create relationships between imported entities.

 To create relationships between external entities and Opcenter


Execution Foundation entities,
you can also create relationships inside the POMModel of the App.

Create value types to expose imported entities to other domains

Write a description for an imported entity and for each single property of an
imported entity

Remove an imported entity from your model (by deleting it from the Object
Model)

Assign tags to an imported entity

Add the Securable attribute to an imported entity

Create a facet from an imported entity

Physically extend an imported entity (this entity is Sealed)

Create indexes for imported entities

2.1.1.2.4 Updating External Data Source Views


Once you have imported entities from an external data source view you may want to update your views to
incorporate any potential differences between the external data source view and your imported views.
This update operation can be performed after editing or refreshing your connection.
If any of the entities you have imported have changed in any way these inconsistencies will be notified by an
asterisk and an exclamation mark next to the corresponding view in the data source tree view.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 33


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 The following is not modified by the update operation:


• descriptions defined for entities and their properties
• annotations defined for entities (e.g. securable flag).
• tags defined at entity level.

Project Studio guides you in this process so you are constantly aware of the possible implications of your choices.
Views can be updated by adding properties and editing annotations within a new minor version, but a new major
version is required to edit property types and delete properties.

Updating views
Update views by right-clicking the modified view in the External Data Source view and selecting Update: one of
the following three messages will be displayed with a list of the corresponding properties:

Error message Description Update Implications

The selected property has been New properties have been inserted The entity is enriched with
added to the data source view. into the source database view additional properties

The selected property has been Properties have been removed from The corresponding entity
removed from the data source the source database view properties are removed, and if
view. used:
• in relationships, these
relationships are also removed.
• in command argument(s),
these arguments are also
removed.
• in parameter type parameters,
these parameters are also
removed.

34 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Error message Description Update Implications

The selected property has been Any combination of the following • If entity properties have been
changed in the data source view. modifications may have been made added, the entity is enriched
to the source database view: with additional properties.
• If entity properties have been
• some property types have
removed, the corresponding
changed
entity properties are removed,
• properties have been inserted
and if used:
• properties have been removed
• in relationships, these
relationships are also
removed.
• in command
argument(s), these
arguments are also
removed.
• in parameter type
parameters, these
parameters are also
removed.
If entity property types have
changed the corresponding
properties are updated, and if
used:
• in relationships, these
relationships are also
removed.
• in command
argument(s), these
arguments are also
removed.
• in parameter type
parameters, these
parameters are also
removed.

2.1.1.3 Creating a New Version of Functional Block or App


Each Project Studio solution (Functional Block, App or Extension App) applies semantic versioning to indicate the
types of changes contained in a specific version. This helps other developers, whose code depends of the
Foundation solution, to understand modifications and adjust their own code, if necessary.
Each Solution has a specific version made up of three numbers, where each number represents the following:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 35


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

When you create a new Functional Block its version is 01.00.00.


Once you have deployed your Functional Block, or referenced it from another Functional Block, or used it in an App,
you should then create a new version of the Functional Block before modifying it.
The type of version (Patch, Minor or Major) depends on the modifications you intend to make:

Version Types Add Element Remove Element Change Element Change Handlers

Patch

Minor

Major

Elements may be entities, facets, commands, pre-checks, post-actions, events, parameter types, value types,
enumeration types, type aliases and their related arguments.
Elements that are already part of the model cannot be modified or removed in Patch or Minor versions.

Patch
When you create a new patch no changes can be made to the model itself.
The patch is basically intended for bug fixing. Only the business logic at C# level in the handlers can be modified.
All options that allow additions and changes to the data model will be disabled in Project Studio.

Minor Version
When you create a new minor version you can add elements to your model, such as entities or commands.
Generally you cannot modify the existing model, for example you cannot add new properties or attributes to
existing entities. Properties can only be added in the following case: if the existing entity has been defined as
Sealed or if the entity has been imported from an external data source view. Since these entities cannot be
extended, you can freely add properties without compromising the integrity of the model.
However, you can add parameters to existing commands, pre-checks, post-actions, events and so on.
None of the added elements can be set as mandatory, as this would break compatibility with the existing version.
All options that allow changes to and deletion of elements in the data model will be disabled in Project Studio. You
can however modify and delete elements that have been added in the minor version itself.
A new minor version will reset the patch number to 00 (e.g. a new minor version 02 could be for example 01.02.00).

36 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Major Version
A new major version leaves you with complete freedom to delete and modify elements and destroy compatibility.
A new major version will reset the patch and minor version numbers to 00 (e.g. a new major version 02 would be
02.00.00).

 New Major/Minor versions vs new Patch versions require different operations in Solution Studio (i.e.
update vs reload, respectively, as explained at Updating Apps and Extension Apps in a Solution
and Reloading Apps and Extension Apps in a Solution).

Procedure
1. Right-click the Installer project of the Functional Block for which you want to create a new version, in the
Solution Explorer pane and select Properties.
2. Click the Version button and enter the new version, noting that:
• if you enter a new Major version the Minor and Patch versions will be set to 00
• if you enter a new Minor version the Patch version will be set to 00.

 If the original Functional Block had been referenced in Reference Manager from another Functional Block,
you must now update these references.

2.1.1.4 How to Extend Referenced Functional Blocks


In addition to defining a model in Project Studio by modeling the artifacts from scratch or by importing entities
from a third-party data source, it is also possible to reference the models of Functional Blocks for which you do not
have the source files (as for example, the Functional Blocks released by the Opcenter Execution
Foundation Foundation Apps).
Referencing external Functional Blocks could be useful, for example, if you want to use the capabilities provided by
a Functional Block and extend them with some custom-specific implementations, such as if you need to add
properties to existing entities, create relationships among entities, implement event handlers (see the table below
for operation details).
You can easily reference Functional Blocks by using Reference Manager.

 There is no limit to the number of Functional Blocks you can reference. However, as a general rule, you
should add references to Functional Blocks that are stable and preferably read-only to avoid inconsistency
issues.

Possible operations in Reference Manager


The operations you can perform in Reference Manager depend on the current version of the Functional Block you
are working on.
For more information on versions see Creating a New Version of Functional Block or App.
The possible operations are:
• Install a Functional Block to reference a new Functional Block
• Update the version of a previously referenced Functional Block
• Restore the files of a previously installed Functional Block

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 37


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Version Install/Reference Uninstall Update Restore

Patch

Minor

Major

Possible operations on referenced artifacts


You can perform several operations to extend artifacts belonging to referenced Functional Blocks.

2.1.1.4.1 What Is Reference Manager


Reference Manager is a tool in Project Studio that allows you to browse and reference existing Functional Blocks.
The Functional Blocks displayed in Reference Manager must have been previously saved in a specific
folder: %ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
Some basic information is provided on each Functional Block, such as its name, version, prefix, platform version,
description and the Functional Blocks it references in turn (dependencies). You can see from the tool which
Functional Blocks have already been referenced (indicated by a green check) and those that cannot be referenced
due to incompatibility or other issues (indicated by a red cross).
When you add a reference to a Functional Block (i.e. install a Functional Block) Reference Manager performs the
following operations:
• unzips the folder of the referenced Functional Block and saves its files locally.
• adds the model assembly .dll files to the command and event handlers.
• ensures that the referenced Functional Block is included in the Functional Block package.
Information on the referenced Functional Blocks is then saved in the packages.reference file:

packages.reference content
<functionalblocks>
<functionalblock>
<name>RefMan.FBLibRM</name>
<version>01.00.00</version>
<type>Library</type>
</functionalblock>
</functionalblocks>

 You can also perform this operation manually, using the standard Visual Studio Add Reference command,
but with the following drawbacks:
• You will have to manually add the model assembly .dll files of the Functional Block to the command
and event handler project.
• You will have to add details of the referenced Functional Block to the installer project so that it will be
included in the Functional Block package.
• Project Studio will not disable operations according to the type of version you are working on, with the
consequent risk of incompatibilities.

38 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.1.4.2 Installing a Referenced Functional Block


When you install a new Functional Block with Reference Manager you are creating a new reference to a Functional
Block.
This operation can be performed when you are working on a Minor or Major version.

Prerequisites and constraints


• The output zip file of the Functional Block you want to reference, created during the Functional Block
generation, must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
• The Functional Block packages must have been created in at least version 2.0 of SIMATIC IT UAF or migrated to
this version. If you try to install a Functional Block from a prior version an error message will be displayed.

 If two referenced Functional Blocks themselves reference the same Functional Block (i.e. A and B both
reference C) Reference Manager checks to see whether they reference the same version.
If they differ by patch or minor version the highest version is loaded.
For example:
• A references version 01.00.01 of Functional Block C
• B references version 01.00.02 of Functional Block C
Reference Manager will load version 01.00.02 as this should not cause compatibility issues.
If they differ by major version an error is returned and the operation will not be possible.

Procedure
1. In the Solution Explorer pane, double-click the packages.reference file in the Solution Items folder.
2. If enabled, click Restore packages, in order to be sure to correctly update all solution references.
3. Click on the Browse tab and select the Functional Block you want to reference. If it can be installed, its details
will be displayed in the pane on the right, otherwise an error message will be displayed.
4. Click Install. If the Functional Block contains references to other Functional Blocks, these will be displayed
under Dependencies and will automatically be installed if their .zip files are available in the folder, otherwise
you will receive an error message.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 39


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Result
• The packages you have installed will be displayed in the Installed tab and will have a green tick icon next to
them.
• According to the projects contained in the referenced Functional Block, the Solution Explorer tree view will
contain, under the References folder of each project, the .um, .umd and .dlls of the referenced projects. The
folder SimaticITPackages, if it does not already exist, will be created in the folder where your project files are
saved. A subfolder will be created for each referenced Functional Block, its name is comprised of the name and
version of the referenced Functional Block. The files contained in the .zip file are saved in this folder, with the
following structure:
• config folder, with the Dbinit.xml file for initializing the database
• handlers folder, with the command and event handlers
• model folder, with the data model files and assemblies
• ExternalDependencies folder, with third-party files required by the Functional Block you are referencing
• Manifest.xml file
• The .um file of the original Functional Block displays all the referenced artifacts in the Model Explorer.

Removing referenced Functional Blocks from your solution


You can remove references if you are working on a Major version.
If you are working on a Minor version you can remove references that you have created during the current version
itself.
1. Double-click the packages.reference file in the Solution Items folder of the Solution Explorer.
2. Click Restore packages, in order to be sure to correctly update all solution references.
3. Click on the Installed tab.
4. Select the Functional Block you want to remove and click Uninstall.

40 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.1.4.3 Updating a Functional Block Reference


The references you can update depend on the version you are working on:
• Patch version - you can update your reference to a new Patch version. For example, if you referenced version
01.00.00. of Functional Block x, and 01.00.01 is available in Reference manager you can update the reference.
You could not update to version 01.01.00 as this would imply a new minor version.
• Minor version - you can update your reference to a new Patch or Minor version. For example, if you referenced
version 01.00.00. of Functional Block x, and 01.01.00 is available in Reference manager you can update the
reference. You could not update to version 02.00.00 as this would imply a new major version.
• Major version - you can updates all references to any version.
You can also update your reference and keep the same version of the referenced Functional Block. For example, if
you add a dll in the package of your referenced Functional Block and update its reference, the reference section of
the Functional Block's handler project is automatically recalculated , i.e. the reference is added to the new dll.

Prerequisite
The output zip file of the original version we want to upgrade from, together with the zip of the new version we
want to upgrade to must be already present in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

 If a referenced Functional Block is missing in the file system repository (i.e. %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks), and the system prevents you from
building the solution, we suggest that you perform the procedure described in the
document Troubleshooting: How to fix a Project Studio Solution if a referenced Functional Block is missing
available on GTAC site. The article will help you to manually remove the missing references from the
project and be able to install or restore the packages you need.

Procedure
1. In the Solution Explorer pane, double-click the packages.reference file in the Solution Items folder.
2. Click Restore packages, in order to be sure to correctly update all solution references.
3. Click on the Installed tab and select the Functional Block you want to update. If it can be updated, its details
will be displayed in the pane on the right, otherwise an error message will be displayed.
4. Click Update. If the Functional Block contains references to other Functional Blocks, they will be automatically
installed if their .zip files are available in the folder, otherwise you will receive an error message.

 If two referenced Functional Blocks themselves reference the same Functional Block (i.e. A and B both
reference C) Reference Manager checks to see whether they reference the same version.
If they differ by patch or minor version the highest version is loaded.
For example:
• A references version 01.00.01 of Functional Block C
• B references version 01.00.02 of Functional Block C
Reference Manager will load version 01.00.02 as this should not cause compatibility issues.
If they differ by major version an error is returned and the operation will not be possible.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 41


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.1.4.4 Restoring a Functional Block Reference


If you need to replace the files of the same version of a previously referenced Functional Blocks you can restore your
reference.
This may be necessary if:
• you have accidentally deleted some of the files, or
• your solution configuration is under source control, and another user has created a reference to which you must
align your solution, or
• you are creating a new machine.
The Restore operation simply unzips the folder of the referenced Functional Block in the local folder without adding
references (e.g. .um, .dll files) and can be performed whether you are working in a Patch, Minor or Major version.
This procedure can also be performed automatically.

Prerequisites
The new output zip file of the Functional Block you want to restore, created during the Functional Block generation,
must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

 If a referenced Functional Block is missing in the file system repository (i.e. %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks), and the system prevents you from
building the solution, we suggest that you perform the procedure described in the
document Troubleshooting: How to fix a Project Studio Solution if a referenced Functional Block is missing
available on GTAC site. The article will help you to manually remove the missing references from the
project and be able to install or restore the packages you need.

Procedure
1. Double-click the packages.reference file in the Solution Items folder of the Solution Explorer.
2. Click Restore packages. If the zips of the referenced Functional Blocks have been saved in the correct folder the
referenced Functional Blocks will be restored on the user's machine, otherwise an error message will be
displayed.

2.1.1.4.5 Referencing a Functional Block without Reference Manager


If you do not want to use Reference Manager to reference Functional Blocks, for example for backward
compatibility with previous versions, you can manually reference Functional Blocks or model project assemblies.

 Reference Manager provides useful information on any possible incompatibilities which may incur by
referencing a specific version, and if you do not use Reference Manager this valuable information will not
be available.

Procedure
You must perform the following steps to manually reference a Functional Block:
1. Add a reference to the required Functional Block.
2. Add the model assembly .dlls to the handler projects of commands, reading functions and events (i.e. the model
assembly dlls either of the referenced Functional Blocks or of the same Functional Block, according to the
project implementations).

42 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

3. Add a reference to the Functional Block in the references.xml file.

2.1.1.4.5.1 Manually Referencing a Functional Block


This manual procedure should only be used if you do not want to use Reference Manager.

Prerequisites
The output files of the Functional Block you want to reference must have been saved in specific destination folders,
so that they can be referenced. These output files are created during the Functional Block generation.
Extract the following files from the output package of the Functional Block to be referenced and then copy them to
the following folders:

Files Source folder (in the Functional Block Destination folder


package)

*.um <Prefix>.<FunctionalBlockName>\model\m %ProgramData%


anufacturingmodel \Siemens\SimaticIT\Unified\Engineering\Dev
\ModelSource

*.umd <Prefix>.<FunctionalBlockName>\model\m %ProgramData%


anufacturingmodel \Siemens\SimaticIT\Unified\Engineering\Dev
\ModelSource

*.dll <Prefix>.<FunctionalBlockName>\model\b %ProgramData%


in \Siemens\SimaticIT\Unified\Engineering\Dev
\ModelBin

Procedure
1. Inside the Solution Explorer pane, right-click the model project folder and select Add > Reference.
2. Click on the Browse button and browse to the .um file placed in %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Dev\ModelSource.

Updating referenced Functional Blocks


If the functional block you are developing contains a reference to a Functional Block that in the meantime has been
modified, you must copy the files that have been modified of the referenced functional block to avoid
misalignment.
The operation to be performed is as follows:
1. Close MS Visual Studio.
2. Copy the modified *.um files and the relative *.dll files to the proper folders (as described in
the Prerequisites section above).
3. Reopen MS Visual Studio.

2.1.1.4.5.2 Manually Adding Model Assemblies


When compiled, the model project generates a set of assemblies containing the definitions of all the objects you
have modeled, such as entities, commands, events etc.
Inside your command handler or event handler code you may want to perform operations on entities that have
been modeled either inside the same Functional Block or inside another Functional Block.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 43


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

These references are automatically managed in Project Studio. Reference Manager automatically adds model
assemblies for referenced Functional Blocks.
However, you can perform this operation manually. This is essential if you have referenced Functional Blocks
without using Reference Manager.

Procedure
1. Right-click your command (or event) handler project and select Add > Reference.
2. Browse to the output assembly folder of the model project, select the .dll files to be referenced and confirm the
operation:
• for the model assemblies of the Functional Block on which you are working, the folder could be C:
\MyFolder\<Prefix>.<FunctionalBlockName>.<Acronym>Model\bin\Debug
• for the model assemblies of referenced Functional Block, the folder could be: %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Dev\ModelBin (remember that you must have also referenced
the .um data model file from within your model project, and not from the command or event handler
projects).

 References must be added to files and not to solution projects.

Model project assemblies


In particular, you may need to add references from your handler projects to the following model assemblies (see
also Using the Query Methods and the Data Model Assemblies):

Assembly name Description

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the commands, post-


Acronym>Model.Commands.dll actions and pre-checks.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the private commands.


Acronym>Model.Commands.Internal.dll

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definition of the entity interfaces that


Acronym>Model.dll are required to execute writing and transactional
reading operations.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the events (required for


Acronym>Model.Events.dll example, if you are working on referenced events
inside custom event handlers).

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the classes where the committed event


Acronym>Model.PlainModel.dll JSON can be deserialized.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definition of the entity interfaces that


Acronym>Model.ProjectionModel.dll are required to execute read operations on the
reading model using the ProjectionQuery method.

<Prefix>.<DomainName>.<FunctionalBlockName>< It is for internal use only.


Acronym>Model.ReadingModel.dll

44 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Assembly name Description

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the types (value types,


Acronym>Model.Types.dll type aliases, enumeration types) that are required to
execute writing and transactional reading
operations, and of the types (parameter types,
enumeration types) that are required to handle the
events, commands and reading functions.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the classes of the types where the


Acronym>Model.Types.PlainModel.dll committed event JSON can be deserialized.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definition of the type interfaces that


Acronym>Model.Types.ProjectionModel.dll are required to execute read operations on the
reading model using the ProjectionQuery method.

<Prefix>.<DomainName>.<FunctionalBlockName>< It is a deprecated model maintained only for


Acronym>Model.Types.ReadingModel.dll compatibility. It contains the definition of the type
classes that are required to execute read operations
on the reading model using the ProjectionQuery
method.

 If you try to delete the assembly of a data model that has already been deployed you could encounter
problems when you try to deploy the solution. It is possible to temporarily allow these potentially
destructive deletions during the configuration phase.

2.1.1.4.5.3 Manually Adding Referenced Functional Blocks to the Installer


Project
Details of any referenced Functional Blocks are automatically added to the Library or App Functional Block package
when you create the reference using Reference Manager.
However, if you reference Functional Blocks manually, you must then insert this information in
the References.xml file, which is part of the Installer project, so that the generation of the Functional Block
package is performed correctly.

Procedure
1. In the Solution Explorer, expand the Installer project > Config folder and open
the <Prefix>.<FunctionalBlockName>.References.xml file.
2. Enter/modify the values in the following tags inside the <functionalblock> node:

Tag Description

<name> The name tag of the Functional Block corresponds to


the <Prefix>.<FunctionalBlockName> string contained in the package zip file
(except for the version number). For example, if the zip file name is
Siemens.ACM_OPV01.00.00.zip the name to be inserted is Siemens.ACM_OP.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 45


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Tag Description

<version> The version tag of the Functional Block. For example, if the zip file name is
Siemens.ACM_OPV01.00.00.zip the version to be inserted is: 01.00.00.

<type> The type must be set to Library.

References XML file example

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


<reference>
<funtionalblocks>
<functionalblock>
<name>Siemens.SimaticIT.OPFoundation</name>
<version>01.00.00</version>
<type>Library</type>
</functionalblock>
</funtionalblocks>
</reference>

2.1.1.4.6 Possible Operations to Extend Artifacts


What you see in the Model Explorer depends on whether the data model you are referencing belongs to the same
domain as the model project folder where you are adding the reference:
• If the data model belongs to the same domain you will be able to see all its entities, commands, events and
types in the Model Explorer (with a lock icon, meaning that they cannot be modified).
• If it belongs to a different domain you will only see its events, value types, parameter types and enumeration
types.

Operation Type Allowed - same domain Allowed - different domain

View referenced entities

View referenced types (value types,


parameter types and enumeration types)

View referenced private commands

View referenced protected commands

View referenced events

Extend a referenced entity

46 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Operation Type Allowed - same domain Allowed - different domain

Create relationships (possible via Value Types)


between referenced entities
(without back navigation property)

Implement command handlers for


referenced commands

Implement pre-checks for referenced


commands

Implement post-actions for referenced


commands

Implement event handlers for referenced


events

Create custom event handlers


for referenced events

Create indexes for referenced entities

Create clustered indexes for referenced


entities

2.1.2 How to Model a Functional Block


When you have created your standard or custom Functional Block and added any artifacts from referenced
Functional Blocks you can start modeling your model.
During this phase plant requirements are analysed and additional entities, commands and events, necessary to
implement the required manufacturing functionality, are defined in Project Studio.
The Manufacturing Model is defined using a specific Manufacturing Modeling Language, through which APIs are able
to generate the required corresponding assemblies/files.
The custom business logic required for commands and events is implemented through specific Handlers
automatically generated in Project Studio, whilst no code development is required for entities.

Workflow
The main steps of the Modeling phase, performed in the Model Project, are:
1. Modeling entities.
2. Modeling commands.
3. Modeling events.
4. Modeling types.
5. Build the Model project.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 47


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 You can also:


• import existing artifacts from other projects
• restore an erroneously deleted AssemblyInfo.cs file
• deprecate artifacts.

2.1.2.1 Working in the Model Project


The Model Project is made up of various working areas:

• Solution Explorer
• Model Explorer
• Model Designer
• Model Details
• Properties pane

Solution Explorer
If you have selected all available projects while creating the Functional Block the Solution Explorer pane displays
the following structure:

48 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The <Prefix>_<DomainAcronym>_<FunctionalBlockName>.dm file, which will contain the graphical


representation of the data model (in the Diagrams sub-folder), is created within the model project folder.
Model Explorer
To display the contents of your model, double-click
the <Prefix>_<DomainAcronym>_<FunctionalBlockName>.dm file in Solution Explorer: the artifacts the model
consists of, such as the entities, commands, events, value types, parameter types and enumeration types, are listed
in the Object Model pane.

 If you created a Functional Block associated with a user domain, as in the following example, the Model
Explorer pane will have an additional External Data Source tab.

Clicking on the Object Model tab you will see that your Functional Block is already populated with two referenced
events and a specific value type.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 49


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The artifact tree can be viewed in a hierarchical or flat mode, by enabling or disabling the flat view icon in the
menu bar. The flat view allows you to see all entities, facets and extensions at the same level, which means you can
see all entities, even if the root entity has been deleted or belongs to a referenced model.
The flat view also displays the relative indexes.
The filter icon  in the menu bar allows you to select only a specific group of artifacts.

Model Designer
Your model can be displayed graphically in the central Model Designer pane, with its corresponding relations and
extensions, so you can easily see and check the relationships that exist between different elements. Model diagrams
are saved as DM files and can be versioned in source control systems, but cannot be merged. A default DM file is
created with the name of the model itself, which you can modify as required, but it cannot be renamed or deleted.
You can also create additional model diagrams by right-clicking the Diagram folder in your model, selecting Add
New Item > Add New Diagram and and providing a name for the new Model Diagram Class you will create. These
additional files will be saved in the Diagrams folder, together with the default DM file. They can be deleted but not
renamed.
Each DM model can display a different part of the data model, which may be particularly useful if the data model
contains many artifacts, or if you want to display only a particular part of the model. DM files are graphical
representations of the same underlying data model, so if, for example, you delete an artifact from the model it will
be removed from all the DM files where it was present. In this case each DM file will display the dirty asterisk in its
title bar, indicating that the file must be saved as the underlying model has changed.
Right-clicking in any empty area within the Model Designer pane allows you to perform a series of useful
operations involving the model artifacts, such as
• adding new artifacts
• selecting artifacts in order to move them
• collapsing and expanding the view
• exporting the view as an image
• hiding all artifacts
• increasing/decreasing the size of the tiles (zooming in/out).

50 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Model Details pane

The configurations performed for the data model are displayed in the Model Details pane after selecting the
relative artifact either in the Siemens Project Studio Model tree or in the central Model Designer pane. From this
pane, it is also possible to define new properties for entities, define relations between entities, create indexes and
specify parameters for commands and events, by clicking on the corresponding tab, and right-clicking at the top of
the specific window. However, it is easier to perform these operations in the Model Designer pane.

Properties pane
If you click on any of the properties in the Model Designer pane, the Properties pane is displayed, where you can
define the attributes of the selected property.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 51


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.2.2 Reserved Keywords


There are certain words that cannot be used when dealing with artifacts in Project Studio, as they have already
been defined elsewhere.
Some of these words are only reserved for certain artifacts, such as commands, others are C# keywords that should
be avoided for any elements that will then be used in C# identifiers.

 Naming Conventions
In order to avoid duplicated names, the uniqueness check of artifact names is case insensitive.
Regarding the artifact name, the only characters supported are alphanumeric characters and underscore
(_) and the first character cannot be a digit.

Naming Conventions
In addition to the reserved keywords, the uniqueness check of artifact names is case insensitive so Artifact names
must respect the following naming rules In addition to the keywords check Artifact names must respect the
following rules:
• Allowed characters are uppercase and lowercase letters, digits and '_' (underscore).
• The starting character can be uppercase and lowercase letter or '_' (underscore).
• Artifact names must be unique (within the FB/App and the uniqueness check is case insensitive).

Entity and Facet Properties


The following words should not be used as they are reserved for internal use:
• AId
• ChangeTracker
• ConcurrencyToken
• ConcurrencyVersion
• CreatedOn
• EntityType

52 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• Id
• IsCurrent
• IsDeleted
• IsFrozen
• IsLocked
• LastUpdatedOn
• Operation
• OptimisticVersion
• Revision
• SessionId
• SourceRevision
• ToBeCleaned
• Discriminator

Commands and Composite Commands


The word CommandFullName and Response cannot be used in the input parameters of commands and composite
commands.

Events
The word EventFullName cannot be used in the parameters of events.

Reading Functions
The following words cannot be used within reading functions:
• FunctionResponse
• FullName
• AppName
• BaseReadingFunctionFullName

Project Studio reserved words


• string
• tinyint
• smallint
• int
• bigint
• decimal
• bool
• DateTime
• Guid
• Blob
• TimeSpan

C# reserved words
The following words are C# keywords and should never be used in the name of a Functional Block or App or by any
element which could subsequently be part of a C# identifier:

abstract dynamic is select while

add else join set yield

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 53


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

alias entity let short

as enum lock sizeof

ascending event long stackalloc

async explicit namespace static

aux extern new string

await false nul struct

base finally null switch

bool fixed object this

break float operator throw

byte for orderby true

case foreach out try

catch from override typeof

char get params unit

checked global paramtype ulong

class goto partial unchecked

command group private unsafe

con icommand prn ushort

const ievent protected using

continue if public value

decimal implicit readonly valuetype

default in ref var

delegate int remove virtual

descending interface return void

do internal sbyte volatile

double into sealed where

54 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.2.3 Modifying a Deployed Functional Block


Careful planning is required when you create your data model, and you should make sure that ideally no further
modifications need to be made to the data model once it is deployed in Solution Studio, and its data structures are
created in the Opcenter EX FN live database.
If you perform any of the following operations on a data model when the corresponding solution has already been
deployed, errors will be produced when you try to redeploy the solution and update its data structures:

Operation type Allowed

Deleting an entity

Deleting an entity property

Deleting a value type

Deleting a value type property

Deleting an enumeration type

Deleting an assembly containing definitions of entities

Modifying binary field lengths

Reducing string field lenghts

Modifying Scale or Precision for decimal types

Changing the data type of an entity property

Removing navigation properties between entities

These potentially destructive operations can be permitted temporarily in the configuration phase by enabling data
loss, but it is of upmost importance to remove this setting before deploying the solution in production.

 Even if data loss is enabled, potentially destructive operations are possible when the data types are
compatible. For example, if you decide to change an int from 32 to 8 bit in a specific column, the column
must not contain numbers greater than 256, otherwise the update operation will fail in any case.

2.1.2.3.1 Enabling Potentially Destructive Operations


It may be necessary to enable the possibility to perform destructive operations ( data loss ) when:
• Modifying a deployed Functional Block
• Removing an App from a Solution in Solution Studio
• Migrating Apps from previous product versions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 55


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Procedure
1. With local administrative rights, create a file called deploy_configuration.xml in the folder
%SITUnifiedSystemRoot%bin.
2. Edit the file as follows:

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


<configurations>
<DeployProject dataLossAllowed="True" />
</configurations>

3. If you are in a distributed environment, copy the file on all Opcenter EX FN hosts, in the same folder mentioned
at step 1.
4. Update the database while deploying the solution package.

 Make sure you delete the deploy_configuration.xml file before using your solution on the production
line.

2.1.2.4 Modeling Entities


These are the main operations you can perform with entities and types within a Functional Block:
• create a new base entity
• extend an existing entity (logically or physically)
• add properties to an entity
• creating indexes
• create relationships between entities

 You can also hide/show entities, extensions, relationships and compositions by right-clicking on the entity
and selecting Hide/Show Selected Artifacts, Hide/Show Related Artifacts, Hide/Show Relationships/
Compositions.

System Entities
All Functional Blocks contain a reference to an internal SystemData.Foundation Functional Block. This Functional
Block defines a set of entities, which are not visible in the Object Model or Public Object Model of your Functional
Block or App, and that are:
• File (see Attaching Documents to Entities)
• Folder (see Attaching Documents to Entities)
• AuditTrailRecord (see How to Retrieve Audit Trail Information and Apply Custom Logic in the Opcenter Execution
Foundation User Manual)
• SegregationTags (see What is Data Segregation in the Opcenter Execution Foundation User Manual)
Only the AuditTrailRecord entity can be published in the Public Object Model.

Modifying entities
The operations described above and their results are summarized in the Model Details pane which is
displayed when you create and select an entity:

56 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Tab Description

The General tab contains read-only information on the entity itself.


The only operation that can be performed here is adding tags to the entity to facilitate
search operations. To add a tab, click Add and either enter a new tag or select one from the
list.

In the Properties tab you view and modify the properties added to the selected entity.

The Extension tab displays the extended entities that have been created starting from the
selected entity. This information is read-only.

In the Relations tab you can view and modify relationships that have been created
between entities.

In the Compositions tab you can view and modify composition relationships you have
created between entities.

The Facets tab displays the logical extensions that have been created for the selected
entity. This information is read-only.

The Indexes tab allows you to view and modify indexes created for the selected entity.

2.1.2.4.1 Creating Entities


This page describes how to create entities, specify their options and behavior and set whether they are base entities
or not. The page also describes how to remove an entity from the data model.

Accessibility options
Entities have specific options, which may modify their accessibility.
These options are defined when they are created, and may be inherited by any extended entities.
A Major version is required to successively change these options. If you are working on a minor version, you can
however modify the elements added within the minor version itself.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 57


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Accessibility Description Inherited by Inherited by Inherited by parts


option physically logically in composition
derived entities extended facets relationship

Restricted You can restrict access to


entities in order to maintain
control over the commands
that can modify them.
Restricted entities can be
created/updated/copied only
by the command handlers
that have been developed in
the same Functional Block.
If this option is removed,
instances of these entities
can be created/updated/
copied directly by
commands that belong to
Functional Blocks of the
same domain.
The option does not affect
the following operations:
bulk delete, bulk insert, bulk
import, add new revision,
freeze/unfreeze, lock/unlock,
set current and mark for
cleaning.
The restricted characteristic
is inherited by physically
extended entities and facets.

Sealed The entity cannot be


physically extended, i.e. new
extended entities cannot be
created from this base entity.
Only base entities can be
sealed.

58 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Accessibility Description Inherited by Inherited by Inherited by parts


option physically logically in composition
derived entities extended facets relationship

Securable By enabling this option, you


can restrict the runtime
visibility of the entity to
specific users by configuring
roles. Roles are configured
either at App level or at
Solution level.
If you unselect the option or
if you select the option but
you do not associate the
entity to any roles, will make
the entity visible to all
authenticated users.
The option is automatically
inherited by all derived
entities and facets.
Consequently, you cannot
set this option on derived
entities. The option can be
also set on entities imported
from external domains as
well as on entities imported
into the POM Model from the
Opcenter EX FN database
views.

Behaviors
You can assign a behavior to an entity to enrich it with additional specific properties and platform methods to
manage these properties.
Behaviors are defined for a specific domain.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 59


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Behavior Description Domain

Revision The Revision behavior allows you to give a version Master Data
identifier to instances of entities and then specify which
specific version you want to use.
As the Revision is added to the logical key of the entity:
• you must define a logical key for the entity before
building the model.
• once set, and consequently part of the logical key,
this behavior cannot be removed from the entity.

 For more information on the Revision behavior


see Managing Revisions of Entity Instances

Procedure
1. Right-click in any empty area in the central Model Designer pane and select Add > Entity.

2. Leave Base Entity as None as new entities must be created at root level.
3. Enter a name for your entity. If the name provided for the new entity is not valid the border of the edit box will
be red to confirm the operation is not enabled. Certain reserved keywords should not be used in the entity
name.
4. Enter a description for your entity. The Description edit box supports markdown formatting, thus allowing you
to correctly format the information to be included in the reference documentation file.
5. Clear Restricted if you want to allow command handlers from Functional Blocks in the same domain to directly
perform Create/Update/Delete operations on the entity.
6. Select Sealed if you don't want the entity to be physically extended.
7. Clear Securable if you want to unrestrict the entity's visibility to any authorized users.
8. Select Revision if you want to manage revisions for your Master data entity.

60 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Result
The newly-created entity is now displayed in the central working pane with the entity icon , and properties can
be added to the entity.

Deleting entities
Entities can be deleted (right-clicking the name or icon of the entity in the central Model Designer pane and
selecting Delete) if they have not been physically or logically extended.
To delete entities that have been extended, you must either first remove its extended entities or select the Delete
on cascade option, which means that the entity's extensions will also be deleted.

 If you try to delete the entity of a data model that has already been deployed you could encounter
problems when you try to deploy the solution.
It is possible to temporarily allow these potentially destructive deletions during the configuration phase.

2.1.2.4.2 Extending Entities


This page describes how to extend base entities. Physically extending entities
When a base entity is extended its properties are inherited by the new entity, along some of its characteristics,
depending on the type of extension.
Entities can be extended with either:
• a physical extension creating a vertical derived entity, or
• a logical extension, creating a facet.

Physically extending entities


If you vertically extend an existing entity, you actually create a new extended entity. This new entity includes
(inherits) the properties that belong to the base entity. You can extend only one base entity at a time (i.e. multiple
inheritance is not allowed). This means that this type of extended entity cannot inherit properties from multiple
entities.
Entities that have been sealed cannot be physically extended.
As far as the database is concerned, the vertical extension adds a new sparse column to the table of the base entity
for each added property of the extended entity. Consequently, the properties that you create cannot have the same
name. This implies that you can create two extensions only if the names of their properties are different.
From a user experience point of view, all properties (inherited and extended) are accessible at the same level,
because they are properties of the same interface. This means that you have less flexibility (concerning names, for
example) but higher performance (because all the properties belong to a unique table). See a code example for
creating extended entity instances.
Procedure
1. Right-click the name or the icon of the entity itself in the central Model Designer pane and select New Entity:
the entity you are extending will be displayed in the Base Entity edit box.
2. Enter a name for the new entity. Certain reserved keywords should not be used in the entity name.

 The Restricted flag is inherited from the base entity, and cannot be modified for extended entities.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 61


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

3. Enter a description for the extended entity. The Description edit box supports markdown formatting, thus
allowing you to properly format the information to be included in the reference documentation file.
Result

The extended entities you have created are displayed in the Model Designer pane and in the Extension tab of
the Model Details pane (if the parent entity is selected).
Your extended entity can be physically extended with other entities, as long as it is not sealed.
You can now add properties to your extended entity in the same way as they are added to root entities.

Logically extending entities with facets


Unlike the vertical extension, which is based on inheritance, the facet extension is made up of a list of properties
that are added to the facet entity, which is linked to the base entity.
As far as the database is concerned, facet extensions are stored in a separate table, which is different from the table
where the base entity, together with its properties, are stored.
For each entity, the system creates a related facet table where the extension properties (facets) are stored. All the
columns in a facet table are sparse columns. The column names are created by concatenating the name of the facet
with the name of the property. This solution makes it possible to have properties with same name in different facets
for the same entity (while this is not allowed in the vertical extension).
Using a facet-type extension, you can associate multiple facets to the same entity. Each facet is stored in a separate
row. Each entity has a Facets property. This property is a back-navigation property and to use it refer to Adding and
Removing Navigation Properties.
From a user experience point of view, if you use facets to extend an entity you have more flexibility (concerning
names, for example), but lower performance (because you have two tables involved). See a code example for
creating facet instances.

 Limitations
• You cannot extend entities contained in a Functional Block associated with a third-party user domain.
• Only root entities can be logically extended.
• Facets cannot have a logical key.
• If you associate more than one instance of the same facet to the same entity instance, the queries that
you will generate in the Signal Rules will retrieve only one facet instance, without the possibility to
choose which facet instance.
• In a Functional Block relationships cannot be created between entities and facets.
• Same facets cannot be published in different Extension Apps.

Procedure
Facets can be either created from scratch or as a copy of existing ones. When a facet is copied, its properties are
copied, but not its index.
1. Right-click the name or the icon of the entity itself in the central Model Designer pane and select New
Facet. The entity you are extending will be displayed in the Base Entity edit box.
2. Enter a name for the facet. The name for the facet cannot contain spaces or special characters and it cannot
start with a number or end with the word Facet. Certain reserved keywords should not be used in the facet
name.
3. Enter a description for the facet. The Description edit box supports markdown formatting, thus allowing you to
properly format the information to be included in the reference documentation file.

62 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Result

The facets you have created are displayed in the Model Designer pane and in the Facets tab of the Model
Details pane.
Your facet can no longer be extended in any way.
You can now add properties to your facet in the same way as they are added to root entities.

2.1.2.4.3 Adding Properties to Entities and Other Artifacts


When you have created or extended your entities in the data model you can add properties in Project Studio.
1. Select the entity in the central Designer Model pane.
2. Right-click on the name or icon of the entity and select New Property: a new property is added to the entity.
3. In the Model Details pane, click on the property you have just created and modify its name, keeping in mind the
following constraints:

 Property naming constraints


• Properties must not have the same name as the element they belong to. For example, the entity
"Order" cannot have a property called "Order".
• Certain reserved keywords should not be used in property names.

4. Click on the browse button next to the new property to select the property type. There are four possible types of
properties:
• System Types (e.g. string, bool)
• Value Types: made up of one or more of properties, which can be used cross-domain.
• Enumeration Types: a data type consisting of a set of named values called enumerators.
• Type Aliases: made up of a custom type for which custom constraints have been defined.

 Parameter Types
Parameter Types, which are made up of one or more properties, can be used as complex types only
inside commands and events (not inside entities).

The properties displayed are filtered by type in the Model Details pane:

Type Properties of the specific Properties of the root System Properties


entity entity

Local

Local + Inherited

All

Modifying property attributes

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 63


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 If the property of an entity is used by other artifacts (for example, as an input parameter of a command),
you can change the property name but you cannot modify the following attributes:
• the property types and the property annotations
• the entity annotations (i.e. Sealed, Securable, Restricted and Revision)
If you try to modify these attributes, an error is displayed in Project Studio.

When you click on a property in Project Studio, the Properties pane is automatically displayed, where you can
modify the values for your property attributes.
You can also assign a description to the property in this pane. The Description edit box supports markdown
formatting, thus allowing you to properly format the information to be included in the reference documentation
file.
Property attributes are not maintained when the property is then re-used within a different entity, command or
event.
If you try to delete or modify the data type or shorten the length (string/binary) of a property attribute, which
belongs to a data model that has already been deployed, you could encounter problems when you try to deploy the
solution.
It is possible to temporarily allow these potentially destructive deletions during the configuration phase.

Constraints and validation


Validation rules are checks carried out on entities according to the attributes that have been set for the properties.
The following constraints are applied to the properties of entities to ensure the validity of your data model.
For Logical Key constraints see Logical Key Definition.

MaxLength attribute
If the MaxLength attribute is set for an entity, and this limit is exceeded, a validation error rule is triggered.
If, for any artifact type, the MaxLength attribute for String and Blob types is not specified (empty value) the
maximum length possible for the type will be automatically applied (i.e. 2GB (-1 byte)), regardless of whether your
underlying system is x32 or x64.
If specified the value can be between:
• 1 and 2GB (-1 byte) for Oracle databases
• 1 and 4GB (-1 byte) for SQL databases
• 1 and 2000 characters for Oracle or SQL databases if the LogicalKey is set to true.
If the From - To attribute is set, the validation rule depends on the data type:
• for an int or decimal: the value cannot exceed the specified range,
• for a string: the length of the string cannot exceed the specified range.

Decimal type
Decimal type entity properties are represented in .NET using the System.Decimal floating-point data type but are
persisted on the database using a fixed-point type.
When using the Microsoft SQL Server database provider, the maximum allowed precision (mantissa) is 38 and the
scale (exponent) can range from 0 to the precision value. When using the Oracle database provider, the maximum
allowed precision (mantissa) is 31 and the scale (exponent) can range from 0 to the precision value.

64 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Due to a Oracle ODP.NET library bug, a scale value of 0 is not supported, so, if 0 is used, the system automatically
converts it to 1 and increments the precision value by a unit. If the precision specified by the user is already at its
maximum value (31), it will stay 31 and the maximum integer digit available will, therefore, be only 30.
While the .NET System.Decimal datatype allows a lower precision of 29 digits (in respect to the 31/38 offered by the
databases), it is subjected to floating-point arithmetic, which consequently means that it may have 29 digits before
or after the decimal separator. You must choose how to cope with this in a fixed-point decimal arithmetic. It would
be necessary to use a mantissa of 58 and a scale of 29 to cover losslessly all the .NET Decimal range. This is not
available on the database so it is necessary to select whether to give up digits to the left of the decimal separator
(thus having more digits to the right of the decimal separator) or sacrificing digits to the right of the decimal
separator (and being able to store larger numbers).
The default values are:
• precision = 18,
• scale = 3.

From - To
If the From - To attribute is set, the validation rule depends on the data type:
• for an int or decimal: the value cannot exceed the specified range,
• for a string: the length of the string cannot exceed the specified range.

Mandatory
If you set a property to Mandatory, the value of these properties cannot be null.
If you want to add the Mandatory attribute to a new or existing entity property and if the corresponding table is
already populated, the following default values will be inserted to respect validation constraints and ensure reading
capabilities (while if you set a custom default value for this newly added property, this value will be inserted instead
of the system default value):

Data Type System Default Value

String -

Bool false

Integer (int, tinyint, smallint, bigint) 0

Decimal 0

DateTime 1899-12-30 00.00.00

Guid 00000000-0000-0000-0000-00000000000

Blob 0

Timespan 0

EnumerationType 0

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 65


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The operation of updating the database will fail if you set the Mandatory attribute to a new navigation property of
an entity, whose corresponding database table is already populated, because the system default value is not
related to an existing entity.
The Mandatory attribute has the following effect on the validation rules of Value Types:

Mandatory Value Type Behavior

Yes Value Type instantiated with all properties Validation rules turned on
set to null

Yes Value Type instantiated with at least one Validation rules turned on
property filled

No Value Type instantiated with all properties Validation rules turned off
set to null

No Value Type instantiated with at least one Validation rules turned on


property filled

Data type possible attributes


If you want to modify the data type of a property, the Property Browser will display only the attributes available for
the selected type.
For example, if you select Enumeration Type, the only attributes you can modify, and consequently the only
attributes that will be displayed, are Default and Mandatory.

Root entities and physically extended entities

Default MaxLengt Mandatory Scale From - To LogicalKey Precision


h

String

Decimal

Integer (int,
tinyint,
smallint,
bigint)

DateTime

Guid

Bool

ValueType

66 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Default MaxLengt Mandatory Scale From - To LogicalKey Precision


h

Blob

TimeSpan

Enumeration
Type

Facets

Default MaxLength Mandatory Scale From - To Precision

String

Decimal

Integer (int,
tinyint,
smallint, bigint)

DateTime

Guid

Bool

ValueType

Blob

TimeSpan

EnumerationTy
pe

Value Types

Default MaxLength Mandatory Scale From - To Reference Precision

String

Decimal

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 67


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Default MaxLength Mandatory Scale From - To Reference Precision

Integer
(int, tinyint,
smallint,
bigint)

DateTime

Guid

Bool

Blob

TimeSpan

Enumeration
Type

Parameter Types

Parameter Property Optional Allow Empyt String MaxLength From - To


Type

String

Tinyint

Smallint

Int

Bigint

Decimal

Bool

Datetime

Guid

entity.propertyId

68 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Parameter Property Optional Allow Empyt String MaxLength From - To


Type

Parameter Type only true is


allowed

Blob

TimeSpan

EnumerationType

List<simple property>

List<value type>

List<parameter type> only true is


allowed

List<entity prop>

List<enumeration
type>

 The Allow Empty String annotation (which accepts True or False) allows you to pass an empty string as
property value. It can only be used with String types and if Optional is set to False.

2.1.2.4.4 Logical Key Definition


The Logical Key (also called natural key) groups the business properties which uniquely define an entity.
Unlike the Id of the entities, which is a surrogate key and is meaningful only inside the database where it has been
generated, the Logical Key retains its meaning outside the database; in fact it can be used to compare two entities
from different databases.
The Logical Key is used, for instance, during the import/export operations among different databases in order to
check whether an entity is already present in the destination repository or not.
The AId property of the entities is a hash of the logical key.
When you choose the properties whose values will be promoted to Logical Key, you must keep in mind what the
Logical Key is used for and consequently select only the properties that are really required for that purpose.

Modeling notes
All business entity types should have a Logical Key, except for some specific cases.
An example of entity which should not require a Logical Key could be a Log entity which tracks all events related to
a specific plant. In this use case, the system should treat each event as a different row, both inside the same

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 69


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

database and across different databases. If an entity has no logical key defined, the AId is set to the same value as
the Id value.
You can set the Logical Key on the following properties:

Property Type Can be part of a Logical Key

Simple (plain) properties (except for Blob, Enum and


TimeSpan)

Forward navigation properties, except Many-To-Many


cardinality

Value Types without reference properties

System properties (Id, Aid, CreatedOn, etc...)

Properties of type Decimal and TimeSpan

Properties belonging to extended entities

Properties belonging to facets

Backward-navigation properties

Forward-navigation properties in a Many-To-Many


cardinality

Value Types containing reference properties

 Constraints
• If LogicalKey is set to true:
• it is mandatory to provide a value for the property (this is valid also for Value Types: if you
promote to LogicalKey a Value Type of an entity, all the Value Type properties become
mandatory regardless of how they have been set in the Value Type and you cannot create the
entity unless you define all the Value Type values).
• the corresponding property of the entity will be displayed with a key icon
• its value cannot be changed anymore
• If a Value Type contains properties whose Reference attribute is set to true, the LogicalKey attribute
cannot be assigned to the Value Type.
• If you set the logical key on a new entity property whose corresponding database table is already
populated and if the entity has no other logical keys, the operation of updating the database will fail
because the system will try to set a system default value for all the existing rows as it does for
the mandatory fields in update mode (while this is not acceptable for a logical key).
• No errors will be returned if you set the logical key on an existing entity property whose corresponding
database table is already populated (as long as the data stored in the logical key column is unique) or if
you set the logical key on a new property if the entity has already another logical key (in this case, the
first logical key already ensured that data is unique, regardless of the inserted system default value).

70 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Implementation notes
When you are about to create an entity, you must set the properties that belong to its Logical Key before calling the
Submit() method.
If you try to submit an entity, which has the same Logical Key as an entity that has already been inserted, the
system returns an error.
After the entity is created in the database, you can no longer:
• modify the properties of the Logical Key
• add foreign keys to an already existing attribute (this does not apply to the Public Object Model in the App).
If you have already set a value for a Logical Key property, you can no longer change it.

Logical Key limitation in Oracle


The logical key management does not consider whether Oracle has been configured as case sensitive or not.
Consequently, if Oracle has been configured as case sensitive, the same logical key string that is generated once
with upper case characters and once with lower case characters will return a logical key violation error.
For example, let us assume you have defined the Logical Key on NId and Revision entity properties. If you try to
submit an entity instance with NId = Material, Revision = 01.00, and then another entity instance with NId =
MAterIAL, Revision = 01.00, the system will return a logical key violation error.
Nevertheless, Oracle can also be configured in case-insensitive mode by means of a dedicated script. In this mode,
the limitation is overcome.
For the script, see How to Configure a Case-Insensitive Access to the Oracle Database in the Opcenter Execution
Foundation Installation Manual.

Example
If you had a MaterialDefinition entity type with the following properties:
• Name
• Description
• MajorVersion
• MinorVersion
• MaterialClass (navigation property)
you could set a meaningful Logical Key on Name, MajorVersion, MinorVersion.
If you did so, you could store many materials having same name but different versions (regardless of the class and
the description).

2.1.2.4.5 Creating Indexes for Entities


When you have added properties to your entities in the data model you can create indexes for these properties in
Project Studio.
Indexes improve database performance in terms of data retrieval speed as they can be used to quickly find data
without having to search every row in a database table each time it is accessed.
You can create indexes for entities that belong to referenced Functional Blocks, as long as they belong to the same
domain.
If you create an index on an extended entity, you will also see the properties of the root entity, and you can use
these properties in the index.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 71


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Procedure
1. Right-click the name or the icon of the entity, in the central Designer Model workspace.
2. Select Add > New Index.
3. In the Add New Index dialog box select the properties to include in the index and modify their order with the
arrows.

 To create an index on the ID of an entity, select its name in square brackets as the index property.
For example, in the following example the ID of the entity is [MaterialDefinition].

Result
The index and its properties are displayed in the Indexes tab of the Model Properties pane.
From here you can edit/delete the index by right-clicking it and selecting Edit/Delete.
The indexes of referenced entities cannot be modified.

Clustered Indexes
If an index is set as clustered, the data rows within the entity will be ordered according to the index.
Clustered indexes can be created for root level entities (not for extended entities or facets), and there can be only
one clustered index for each root entity.
Clustered indexes cannot be created for the entities of referenced Functional Blocks, even if they belong to the
same domain.

72 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 For more information on Index Management, see also Managing Indexes in Opcenter Execution
Foundation.

2.1.2.4.6 Creating Relationships between Entities


When you have created or extended your entities in the data model you can create relationships between these
entities in Project Studio.
There are different ways to create relationships between entities, depending on where the entities are located:
• in the same Functional Block and in the same domain
• in different domains but within the same solution
• within an external data source in the same domain
It is also possible to create composition relationships between two entities.

2.1.2.4.6.1 Creating Relationships between Entities in the Same Domain


When you have created or extended your entities in the data model you can create relationships between these
entities in Project Studio.
If these entities belong to the same domain, these relationships can be created in the Relationships tab of the
entity.

Possible relationships
Entities Type of relationship Allowed

Entities belonging to different Functional Blocks, Many to One


where the referenced entity is the target entity
(One).

Entities belonging to different Functional Blocks, Many to One


where the referenced entity is the source entity
(Many).

Entities belonging to different Functional Blocks Many to Many

A facet and another entity Many to One

A facet and another entity Many to Many

An extended entity and its base entity, where the Many to One
base entity is target entity (One).

An extended entity and its base entity, where the Many to One
base entity is source entity (Many).

An extended entity and its base entity Many to Many

Navigation properties (forward-navigation and backward-navigation)


When you define a relationship between two entities you can provide a way to browse for related entities.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 73


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

For example, if you create a Many to One relationship between two entities (e.g. Order and Customer), the source
entity provides a list of related entities. This list is provided by the mandatory forward-navigation property.

Additionally, you may want to have a way to browse the source entities from the target entity. This is provided by
the backward-navigation property, which is optional for Many to One relationships and mandatory for Many to
Many relationships.

Many to One relationships


In this type of relationship, one instance of the source entity can be linked to one instance of the target entity, while
one instance of target entity can be linked to many instances of the source entity.

74 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 Example
For example, you may need to create a relationship between Work Order Operations (Many/Source) and
their Work Order (One, Target).
In this case:
• each Work Order Operation will have a mandatory forward navigation property, indicating its
"parent" work order and
• each Work Order may have an optional backward navigation property, indicating its "child" work
order operations.

1. Right-click the source entity, which will act as the Many part of the relationship, in the central Designer Pane
and select Add New Relationship.

2. Select an entity in the Target Entity Name drop-down list.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 75


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

3. Enter a unique name in the Navigation Property field of the source entity, with which the relationship can be
recognized as a property of the entity. This property is used as a forward-navigation property.
4. If required, enter an optional Navigation Property also for the target entity, to make it possible to identify
linked source entities from the target entity. This property is used as a backward-navigation property.
5. Ensure the Cardinality of the source entity is set to Many and the target entity is set to One (default values).
6. Select Mandatory if one instance of the Source entity must be linked to one instance of the Target entity (i.e.
Null is not allowed as a value). In this case it is not possible to set the delete behavior to OnDeleteSetNull.
7. Select Logical Key if the navigation property will be part of the logical key of the source entity.
8. Select the required deletion behavior (logical deletion) from the Delete Action drop-down list:
• OnDeleteCascade: if the target entity (Work Order in the example) is deleted, the source entities related
to the target entity (Work Order Operations in the example) are also deleted.
• OnDeleteSetNull: if the target entity (Work Order in the example) is deleted, the navigation properties
of the source entities related to the target entity (Work Order Operations in the example) are set to null.
This option cannot be used if the relationship has been defined as Mandatory, as in this case the
navigation property, being mandatory, can never be set to null. If you try to set the relationship as
Mandatory with OnDeleteSetNull, the build operation will fail in Project Studio.
• OnDeleteNoAction: means that no delete operations are allowed. In our example, if you try to delete a
Work Order when it has related Work Order Operations, the operation will fail with errors. The related
Work Order Operations must be deleted before attempting to delete the Work Order.
9. Add an optional description for the relationship.
10. Click OK.

Many to Many relationships


In this type of relationship one instance of each entity can be linked to many instances of the other entity.

76 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 Example
For example, you may need to create a relationship between Users (Many/Source) and
their Groups (Many, Target).
In this case:
• each User will have a mandatory forward navigation property, indicating all the groups it is related to
and
• each Group will have a mandatory backward navigation property indicating all the users related to it.

1. Right-click one of the entities, which will act as the source entity, in the central Designer Pane and select Add
New Relationship.

2. Select an entity from the Target Entity Name drop-down list.


3. Enter a unique name in the Navigation Property field of the source entity, with which the relationship can be
recognized as a property of the source entity. This property is used as a forward-navigation property.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 77


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

4. Enter a mandatory Navigation Property for the target entity, to make it possible to identify linked entities from
the target entity. This property is used as a backward-navigation property.
5. Ensure the Cardinality of the both entities is set to Many.
6. Select the required deletion behavior from the Delete Action drop-down list:
• OnDeleteCascade: if the target entity is deleted it will be removed and the source entities related to the
target entity are deleted as well.
• OnDeleteSetNull: in order to delete an entity, the navigation properties that link it to other entities must
first be set to null.
• OnDeleteNoAction: means that no delete operations are allowed. If you try to delete a target entity
when it has related source entities, the operation will fail with errors. The related source entities must be
deleted before attempting to delete the target entity.
7. Add an optional description for the relationship.
8. Click OK.

Result
The two entities associated in the relationship will be connected through an association link in the Model Designer
pane indicating their type of relationship (n-1 or n-n). If you click on the association link, the source entity is
highlighted in blue.

Other types of links, such as entity extensions, facets and signals, are represented by a dotted (non-clickable) line.
You can create, edit and delete the entity properties, relationships and compositions both in the Model Details
pane as in the Model Designer by expanding the related nodes: Properties, Relationships and Compositions.

78 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

A key icon indicates whether a navigation property has been set to Logical Key.

The relationship is displayed in the Relationships tab in the Model Details pane.
The Navigation properties are used to create a column on the entity that will work as a foreign key.

To delete/edit the relationship, right-click the selected relationship in the Model Details pane and select Delete/
Edit. If it cannot be edited (e.g. in a referenced entity) it will be grey.

 For the required business logic, see also Creating Associations Among Entities and Querying on Referenced
Entities.

2.1.2.4.6.2 Creating a Composition Relationship


A composition relationship is a strong relationship, which can be created between entities.
It is used to define relationships where a main base entity is made up of other part entities, for example a BOM
(composite entity) and its BOM Items and specifications (part entities).

Composition relationships have the advantage of being treated as a group when copied. If the composite entity is
copied all its part entities are also copied, along with their forward and backward navigation properties.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 79


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

For more details on copying composition relationships see Copying Entity Instances.

Properties of a composition relationship


• The part entity follows the lifecycle of the composite entity, for example:
• if the composite entity is deleted its part entities are deleted too.
• the primary key of the composite entity is added to the logical key of the part entity.
• Restricted, Securable and Revision accessibility attributes applied to the composite entity are not
however inherited by the part entities.
• The OnDeleteCascade deletion behavior is set automatically for composition relationships.
• Cyclic graphs are not permitted within composite relationships, the relationship must be created as a
hierarchical tree.
• Recursive relationships are permitted. For example, an entry (part entity) can be in a composition relationship
with an order (composite entity), but can also be the composite entity for its sub-entries (part entities). In the
example the entity will contain a navigation property towards the order and towards its sub-entries. As a part
entity can only have only one composite entity at a time at runtime only one of these two navigation properties
can have a value. Consequently null values must be permitted, and the navigation property cannot be tagged as
Mandatory:

Possible composition relationships


Composition Applied on Description

Part Entity Base Entity The part entity can be a root entity.

Part Entity Derived Entity The part entity cannot be an extended


or facet entity.

80 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Composition Applied on Description

Part Entity Multi-Composite Entity The part entity can have only one
composite entity.

Part Entity Recursive The part entity can contain a


composition relationship with one of
its own sub-entites.

Part Entity Recursive with mandatory If a recursive composition is created,


cardinality the mandatory flag cannot be
selected.

Composite Entity Base Entity The composite entity can be a root


entity.

Composite Entity Derived Entity The composite entity can be an


extended or facet entity.

Composite Entity Multi-Part Entity The composite entity can have more
than one part entity.

Procedure

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 81


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

1. Right-click the name or the icon of the part entity, which will act as the source entity for the relationship, in the
central Designer Pane and select Add New Composition.

2. Select the entity which will act as the target composite entity in the relationship from the Composite Entity
Name drop-down edit box.
3. Enter a unique name in the Navigation Property field with which the relationship can be recognized as a
property of the part entity.
4. Select a direction for the cardinality of the relationship, which can be OneToMany or ManyToOne, depending
on which entity in the relationship is the composite (One) and which is the part (Many).
5. Select Mandatory if a value must be provided for navigation property (i.e. Null is not allowed as a value).
Mandatory cannot be selected for recursive or ManyToMany relationships. If selected, the build operation
would fail.
6. Add an optional description for the relationship.
7. Click OK.

Result
The two entities associated in the composition relationship will be connected with a line in the Model
Designer pane:

82 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The relationship is also displayed in the Composition tab in the Model Details pane.
To delete/edit the relationship, right-click the selected relationship and select Delete/Edit. If it cannot be edited
(e.g. in a referenced entity) it will be grey.
The Navigation properties are used to create a column on the entity that will work as a foreign key. You can query
on related entities through the Include extension method.

2.1.2.4.6.3 Creating Relationships between Entities from Different Domains


Once you have created (or extended) your entities in the data model, you can create relationships between these
entities in Project Studio.
If these entities belong to different domains, you can create these relationships only by using Value Types. If these
entities belong to the same domain you can create relationships by using standard associations (navigation
properties).
Value Types are custom properties which can act as containers for a number of properties, and are visible from
other domains.

Simple and Reference Value Types


There are two types of Value Types:
• Simple: Simple Value Types are containers of simple type properties (i.e. string, decimal and so on). They
cannot be used to establish relationships among entities, as they do not 'point' to any other entities. They could
be used to group properties that you may want to reuse inside other entities. For example, suppose you want to
manage quantities, where each quantity contains a decimal value (e.g. 10) and a unit of measure (e.g. kg).
Instead of creating two properties for each entity (decimal QtyValue and string UoM) you could create a simple
Value Type (QuantityType), which contains two properties (QtyValue and UoM). This Value Type would only
need to be defined once, and could then be reused in various entities.
• Reference: Reference Value Types are containers that have at least one property, which is defined as an Entity
type (i.e. a property which 'points' to another entity). These Value Types can be used to link entities cross-
domain. Reference Value Types allow you to denormalize the linked entity and access its properties from the
domain where you are developing your logic. This functionality gives you the possibility to perform an intra-
domain query instead of a cross-domain query (ProjectionQuery) as cross-domain queries are more time-
consuming.
This page focuses on Reference Value Types.

Workflow

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 83


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The procedure for creating and using a Value Type, which is described in this page, consists in several subsequent
macro-steps:

Creating the Reference Value Type


Example: In the Functional Block that contains the domain from which you want to expose your entity (for example
the MasterData domain, or the third-party user domain), you can create a MaterialDefinition entity with its
properties, and a MatDefVT Value Type that maps a subset of MaterialDefinition properties:
1. Create an entity whose properties will be exposed in a different domain.
2. Create a value type.
3. Create a property for the value type that declares its entity-type, by selecting the first entry, which corresponds
to the name of the entity.

4. Add any other required properties and associate them to the properties of the entity you want to expose.
5. In the Properties pane check that the Reference attribute of each property is set to True (the default value
when you link a property to an entity, see the note below).
6. Build the model project and then the Functional Block package as usual.
7. (Optional) Repeat the same procedure to create other Value Types in other domains. For example, in
the ReferenceData domain you can create a UoM entity, and a UOMVT Value Type that maps the Name of
the UoM entity.

84 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 • To create the properties of the referenced entity in the reading model you must reference the whole
entity (as in step 3), if you fail to do so the properties will not be created in the reading model.
• Setting the Reference attribute to True allows you to use the OData EXPAND function and the
INCLUDE function in queries and projection queries to retrieve data on the referenced entity. If the
Reference attribute is set to False, the defined entity properties will be created in the reading model,
but the referenced entity cannot be accessed in queries.
• In the writing model, the properties are created in additional columns, whether the Reference
attribute is set to True or False.

Using the Value Type in the target entity


Example: In the Functional Block that contains the domain from which you want to access the entity properties of
the Reference Value Type (for example in the OperationData domain), you can create a Lot entity with a set of
properties that use the referenced Value Types in their types (for example MatDefVT and UOMVT):

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 85


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

1. Create or open the required Functional Block: this is the project which contains the entity you want to link to the
properties exposed through the Value Type of the referenced domain.
2. Verify that the references to the required Functional Block have been correctly managed: the reference Value
Type is consequently displayed:

3. Create a new entity.


4. Add one or more properties and set the property types by browsing to the referenced Value Types.

Implementing the code to use the related entity properties


Compile the model project of the Functional Block in which you have used the referenced Value Types and proceed
with the required implementation inside your command/event handlers. A C# example of how to
use Reference Value Type properties is provided.

Example
The picture below displays a relationship between the OperationalLot entity belonging to the Operation Data
domain, the MaterialDefinition entity belonging to the Master Data domain and the UoM entity belonging to the
Reference Data domain. This relationship is achieved by creating a Value Type that maps some of the properties of

86 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

the MaterialDefinition entity (MaterialDefinition_VT Value Type) and some properties of the UoM entity (UOM_VT
Value Type), by creating a reference from the Operation Data domain to the Master Data domain and
the Reference Data domain, and then setting the MaterialDefinition_VT and the UOM_VT Value Types as
properties of the OperationalLot entity.

2.1.2.4.6.4 Creating Relationships between Entities in User Domains


You can create relationships between entities within user domains that belong to the same external data source.
Relationships can be created between properties of type Guid, Int, String and an entity.

Procedure
1. Inside the Model Explorer pane of your Functional Block, click the entity you want to join.
2. In the Properties tab of the Model Details pane right-click the property (of type Guid, Int or String) that will be
used for the relationship, and select Create Relationship.
3. In the Parent Entity Name edit box browse to the entity to which you want to create the relationship.
4. Click OK: the relationship is displayed in the central pane and the property used to create the relationship is no
longer displayed in the list of properties.

Relationship Characteristics
The characteristics of the relationship cannot be modified and are:

Characteristic Value

cardinality OneToMany

deletion option OnDeleteNoAction

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 87


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Removing a relationship
To remove a relationship:
1. Click on the Relationships tab in the Model Details pane.
2. Right-click the row corresponding to the relationship you want to delete.
3. Select Remove Relationship.

2.1.2.4.7 Renaming Entities and Types


You can rename the following artifacts as long as they are not referenced (i.e. they do not have a lock icon next to
their name):
• entities (and their physical and logical extensions)
• types (value types, parameter types and enumeration types).
It is not possible to rename events and commands.

Procedure
1. Right-click the entity in the Model Explorer tree and select Rename.
2. Enter a new name for the entity which has not already been used within the Functional Block. Certain reserved
keywords should not be used in entity and type names.

Result
The entities and types are automatically renamed in all work areas in Project Studio.
The properties of entities and types can be renamed by simply retyping their names in the Model Details pane.

 If you rename entities and/or types that have already been used in the logic of command/event handlers
you must manually update the code contained in these files.

2.1.2.5 Modeling Commands


Commands act as messages containing a request to execute a specific logic and all the input required to fulfill that
logic.

88 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The commands in your Functional Block are outlined in the modeling phase in Project Studio.
Any commands included in data models you may have referenced when the Functional Block was created are
displayed in the MES Model Explorer, but you can also create new commands in the same environment.
Referenced commands are displayed with a lock icon and they cannot be modified in Project Studio.
Commands can either be protected or private, which affects the rules that determine how commands can be
invoked.
In the following sections we will go through:
• the difference between private and protected commands (command classification)
• how to create commands
• how to add parameters
• how to develop Pre-Checks for executing a validation logic for commands.
• how to develop Post-Actions to extend commands.

2.1.2.5.1 Private and Protected Commands


This topic describes the command types you can model inside your Functional Block: private or protected.
Another command type, called Composite Command, can be created only inside the App and has different
characteristics.
The type of command you will implement determines some execution constraints that must be considered before
outlining the entire model project.

Private vs protected commands


You can invoke a protected command from the command handler of any Functional Block that contains a reference
to the model project of the command you are invoking. The command handler and invoked command must belong
to the same domain. Protected commands can then be imported into the POM Model of the App. Once imported,
they will be visible on the Service Layer and can be called by clients that use the IUnifiedSdkLean interface.
You can invoke a private command only from the command handler of the Functional Block to which the invoked
command belongs. For this type of command, additional constraints are applied to the code implementing event
handlers and IUnifiedSdkLean interface. Private commands cannot be imported into the POM Model of the App and
are consequently not visible on the Service Layer.

Command invocation rules


The following table shows which command types can be invoked according to the class you are implementing:

Invoker (Invoked) Protected command (Invoked) Private command

Protected command handler (same domain) (same Functional Block)

(different Functional Block)

Event handler (if assigned to a Worker Role)

IUnifiedSdkLean (if published by an App and


assigned to a Worker Role)

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 89


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.2.5.2 Creating Commands


This page describes how to create standard Commands (private or protected). Commands are by default defined as
Securable objects, meaning that you can limit their runtime execution to certain users while configuring user roles
(either at App level or at Solution level).

Procedure
Commands can be either created from scratch or as a copy of existing ones.
1. In the central Designer Model pane right-click and select Add > Command.

2. Enter a name for the new command. This name cannot successively be modified. Certain reserved keywords
should not be used in command names.
3. Enter a description for the command. The Description edit box supports markdown formatting, thus allowing
you to correctly format the information to be included in the reference documentation file.
4. Select either of the following:
• Protected, (selected by default) the command can be invoked from any Functional Block that contains a
reference to the current one and belongs to the same domain.
• Private, the command can be invoked only within the current Functional Block and only inside the same
domain. For this type of commands, additional constraints are applied to the code implementing event
handlers and IUnifiedSdkLean interface.
5. Clear Securable (Protected commands only) if you do not want to assign the command invocation to any roles.
6. Click OK: commands are displayed in the central Designer Model pane with a specific icon in the model tree,
according to their access modifier:
private commands

protected commands

 Referenced commands are visible only if they are protected (not private) and are identified with the
icon

7. Add input and output parameters to the command.


8. If necessary, in the General tab of the Model Details pane add tags to the command to facilitate search
operations (by clicking Add and either entering a new tag or selecting one from the list).

90 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Adding logic to commands


When you have created the structure of a command with its parameters, the related C# classes (handlers) are
automatically generated when you build the Model project.
You can then import and complete these handlers in the implementation phase.

2.1.2.5.3 Adding Parameters to Commands and Events


After you have modeled a command or an event, you can add the parameters that define its structure.
Concerning events, ensure that the data structure contains the same information that you have planned to use in
the event envelope. The envelope, which can be specified when you fire the event, is used for setting filtering
criteria on the event type you want to subscribe to. Events do not have output parameters.

Adding parameters
1. Right-click the name or the icon of the artifact in the central Designer Model pane and select either Add new
Input Parameter or Add new Output Parameter.

2. In the Properties tab of the Model Details pane, enter a user-friendly name. Certain reserved keywords
should not be used in parameter names.
3. Click on the browse button and select the property from the Property Browser dialog box, which can belong to
three distinct categories:
• properties of other entities (from Data Model node),
• System Types: simple types, such as string, bool, int etc..,
• Types: Parameter Types, Type Aliases, Enumeration Types.

Configuring parameter attributes


You can define parameter attributes to set validation criteria or data dimension.
If you set validation attributes on output parameters, these attributes are used for data structure validation at the
end of the handler execution (see Implementing Command and Event Handlers or Importing and Implementing
Reading Function Handlers).
You can also assign a description to the parameters in this pane. The Description edit box supports markdown
formatting, thus allowing you to correctly format the information to be included in the reference documentation
file.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 91


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

1. Select the parameter of your artifact in the Parameters tab of the Model Details pane.
2. In the Properties pane enter the attributes for your selected properties:

Option Allow MaxLen Scal From - IsList Precisio UseDefault


al Empty gth e To n IfNotSet
String

String

Integer
(int, tinyint,
smallint, bigint)

DateTime

Guid

Bool

Decimal

ParameterType

TimeSpan

Blob (only for


commands and
reading
functions)

EnumerationTy
pe

 • If the UseDefaultIfNotSet option is set to true, when the user does not specify the parameter value in
the command invocation, the system automatically sets the parameter value to the type default. If the
property is set to false, when the user does not specify the parameter value in the command
invocation, the system returns an error. The default is the system type default (e.g. for integers: 0, for
boolean: false, and so on).
• The Command output parameters (i.e. the Command Response) for which the Optional attribute has
been set to False, are mandatory at runtime only if the Response does not contain an error code.
• If, for any artifact type, the MaxLength attribute for String and Blob types is not specified (i.e. empty
value) the maximum length possible for the type will be automatically applied (i.e. 2GB (-1 byte)),
regardless of whether your underlying system is x32 or x64. If specified, the value must be between 1,0
and 2GB (-1 byte).
• The AllowEmtpyString annotation (which accepts True or False) allows you to pass an empty string
as parameter value. It can only be used with String types and if Optional is set to False.

92 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.2.5.4 Modeling Pre-Checks


You can define Pre-Checks for all Protected Commands as well as for all Composite Commands.
Pre-Checks can be used to implement conditions that determine the execution, or the non execution, of a
command.
They can be defined for non private commands in the Functional Blocks as well as for composite commands inside
Base or Extension Apps.
At runtime, Pre-Checks will be executed only if the command they refer to has been published in an App/Extension
App.
This additional code is executed at the beginning of the command handler logic, performing required checks before
the command execution.
Depending on the Pre-Check behavior you will configure at Solution level in Solution Studio, at the first Pre-Check
failure:
• the Pre-Check execution stops, according to the stop and fail behavior (default).
• all Pre-Checks are executed anyway, according to the fail and proceed behavior.
The command will be executed after the success of all Pre-Checks.
This functionality allows you to reuse existing commands by simply enabling or disabling the Pre-Checks, without
rewriting business logic.
The Securable attribute is not available because the Pre-Checks are always associated with the same role
permissions that are associated with the referenced Base Command/Composite Command.

 The Base Commands for which you implement the Pre-Check can belong to: the same Functional Block
that contains the Pre-Check, a referenced Functional Block, a Base App or Extension Apps.
If you need to add a Pre-Check to the Public Commands of an App, you must create an Extension App for
that App.

 If you call a Functional Block command containing Pre-Checks and published in more than one Extension
App of the same Base App, at runtime all Pre-Checks will be executed. In case of ambiguity problems, the
system will adopt the following behavior:
• If a Pre-Check is enabled in one Extension App and disabled in another Extension App, at runtime the
Pre-Check will be executed.
• If a Pre-Check is enabled in all Extension Apps with a different execution order, at runtime the Pre-
Check will be executed according to the alphabetical order by default.
• If the Pre-Check behavior is configured setting the StopAndFail in one Extension App and the
FailAndProceed in another Extension App, at runtime the StopAndFail behavior will be applied and
the Pre-Check execution will be stopped at the first Pre-Check failure.

Procedure
1. In the Object Model pane, right-click the Base Command (or Composite Command) and select New Pre-Check.
2. Enter the Pre-Check name and description.
3. Leave the Enabled check-box selected (set by default) if you want the Pre-Check be always executed by default
(regardless of the App that publishes it). If you want to disable it, remove the selection and the Pre-Check will
not be executed.
4. Only in Public and Composite Commands, configure the Pre-Check behavior by setting
the PreCheckBehavior option, as following:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 93


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• Leave the StopAndFail value (default) to stop the Pre-Check execution at the first Pre-Check failure.
• Set the FailAndProceed value to proceed with the Pre-Check execution anyway.
5. Click OK.

 • You cannot enter input or output parameters.


• In edit mode, you can change both in major and in minor version:
• the Enable option.
• the PreCheckBehavior option.
• the description.
• You can delete an existing Pre-Check only in a major version.
• If needed, you can modify the Pre-Checks configuration in Solution Studio:
• by enabling or disabling their execution.
• by modifying the Pre-Check behavior (stop and fail behavior or fail and proceed behavior)
• by changing the order in which the Pre-Checks will be executed.

After building the Object Model as for the other Object Model artifacts, you can proceed as described at section How
to Implement Pre-Checks for Business Logic Execution.

2.1.2.5.5 Modeling Post-Actions


You can extend the business logic of Commands belonging to Functional Blocks (both Referenced and not
Referenced), as well as the business logic of Composite Commands belonging to Base Apps and Extension Apps,
by implementing Post-Actions.
Post-Actions represent additional code that will be executed at the end of the Handler of the Command/Composite
Command.
In this context, the Command/Composite Command that will be extended is referred to as to 'Base Command'.
You can create several Post-Actions for the same Base Command, even within the same Functional Block.
If you have more Post-Actions for the same Base Command, the platform executes all the Post-Actions regardless of
how or when the Base Command was invoked.
This behavior applies to Protected Commands and Composite Commands, whereas in Private Commands and
Public Commands Post-Actions cannot be created.

 If you want to change the configuration of a Command with Post-Actions from Protected to Private, you
must remove all Post-Actions manually before proceeding, otherwise an error will be returned.

The Securable attribute is not available because the Post-Actions are always associated to the same role
permissions that are associated to the referenced Base Command.
The Optional attribute is available to make the Post-Action execution optional. In this case, both in Project Studio
and in Solution Studio you can decide either to enable the Post-Actions and execute them or to disable the Post-
Actions and not execute them. Otherwise, the Post-Action execution is mandatory by default.

Procedure
1. In the Object Model pane, right-click the Base Command (or Composite Command) and select New >
Post-Action.
2. Enter the Post-Action name and description.
3. Click OK.
4. If you want the Post-Action execution be optional, open the Properties pane and set the Optional attribute to
True. Otherwise, if you leave this option set to False (default), the Post-Action execution will be mandatory.

94 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

5. If you want the execution of an optional Post-Action be disabled, open the Properties pane and set the
Enable attribute to False. Otherwise, if you leave this option set to True (default), the Post-Action execution will
be enabled.

 • In edit mode you can change:


• the Optional attribute both in major and in minor and in patch version.
• the Enable attribute both in major and in minor and in patch version.
• the description both in major and in minor version.
• You cannot enter input or output parameters.
• You cannot drag and drop the Post-Action to the central Model Designer.
• If needed, you can modify the Post-Action configuration in Solution Studio both by enabling/disabling
the Post-Action execution and by changing the order in which the Post-Actions will be executed.

2.1.2.6 Modeling Events


Events enable a class or an object to notify other classes or objects when something interesting occurs.
The events in your Functional Block are outlined in the modeling phase in Project Studio.
Any events included in data models you may have referenced when the Functional Block was created are displayed
in the Model Explorer, but you can also create new events in the same environment.

Events are identified by a specific icon and are displayed as orange elements in the Model Designer pane.

Referenced events are displayed with a lock icon and they cannot be modified in Project Studio, although
event handlers can be created for them.
A referenced event is visible regardless of the domain in which the source event was created.

System Events
All Functional Blocks contain a reference to an internal Functional Block, the SystemData.Foundation Functional
Block. This Functional Block exposes a set of events, which are visible in the Model Project of your Functional Block
as referenced events:
• AuditTrailRecordCreated (see How to Retrieve Audit Trail Information and Apply Custom Logic in the Opcenter
Execution Foundation User Manual)
• CommittedEvent
• DebugStartupEvent
• SessionAligned, SessionAlignment, SessionCreated, SessionDeleted, SessionPopulated and
SessionUpdated.
• TimerEvent

Workflow
To model events, you have to:
1. Create events.
2. Add input parameters.
3. Create event handlers.

2.1.2.6.1 Creating Events


This page describes how to model an event and define the event structure through input parameters.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 95


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

While defining the event structure, we suggest that you unify the information contained in the event structure with
the information you will use in the event envelope.

Procedure
Events can be either created from scratch or as a copy of existing ones.
1. In the central ModelDesigner pane right-click and select Add > Event.

2. Enter a name for the new event. This name cannot successively be modified. Certain reserved keywords should
not be used in the event name.
3. Enter a description for the event. The Description edit box supports markdown formatting, thus allowing you to
correctly format the information to be included in the reference documentation file. Events are identified by a
specific icon

and are displayed in the central ModelDesigner pane.


4. Clear Securable if you want to enable all authorized users to perform operations on the event, without needing
to assign it to a user role.
5. Add input parameters to the event.
6. In the General tab of the Model Details pane you can add tags to the event to facilitate search operations (by
clicking Add and either entering a new tag or selecting one from the list).

Adding logic to events


When you have created the structure of an event with its input parameters, the related C# classes (handlers) are
automatically generated when you build the Model project.
After the modeling phase, you can then implement the event handlers.

2.1.2.6.2 Creating Event Handlers


Unlike commands for which you can implement only one Command Handler, events may have different Event
Handlers, even in different domains. Each event can then be associated to (single or multiple) event handlers
through event subscriptions.
This page describes how you can create an event handler and how you can give it a custom name.
This procedure applies both for events created inside the same domain and for events that are referenced from
other domains.

96 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Procedure
To define custom event handlers both for events modeled inside the same domain and for events that are
referenced from other domains:
1. Select the required event in the Event node in the Model Explorer and drag it into the central Designer Model.
2. Right-click the event and select New Event Handler.
3. Enter a name for the new event handler and confirm: the new handler is displayed in the Handlers tab of
the Model Details pane.

2.1.2.7 Modeling Types


These are the main operations you can perform with types within a Functional Block:
• create value types
• create type aliases
• create parameter types
• create enumeration types.

2.1.2.7.1 Creating Value Types


Value types are complex types, made up of one or more properties.
They can be used as simple containers of properties (only) for entities, although their main use is to associate
entities from different domains.

Procedure
Value Types can be either created from scratch or as a copy of existing ones.
1. In the Model Designer pane, right-click in any empty area and select Add > Value Type.

2. Enter a name for the value type. The name must not contain spaces or special characters and cannot start with a
number. Certain reserved keywords should not be used in the value type name.
3. Enter a description for the value type. The Description edit box supports markdown formatting, thus allowing
you to properly format the information to be included in the reference documentation file.
4. Click OK: value types are identified by a specific icon in the Model Explorer pane.

Result
The newly created value type is an empty container to which you must add properties.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 97


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

If you add system type properties, the value type can be used inside entities as a property container. To use the
value type in this way, create an entity and select the value type you have created while browsing the type of the
property.
If you add properties of other entities as property types, the value type will be used inside target entities of other
domains as a reference value type.

Adding Properties to Value Types


Properties and property attributes are added to value types in the same way as they are added to entities and other
artifacts.
Note that value types cannot contain other values types in their properties.
If you select the first property of the entity (e.g. [MaterialDefinition] in the example below), instead of a simple type,
it corresponds to selecting the identifier of the entity:

FileType Value Type


All Functional Blocks contain a reference to an internal Functional Block. This internal Functional Block exposes a
value type, the FileType, which is visible in the Model Project of your Functional Block as a referenced value type.
It can be used to attach files to entities (for example images, documents etc).
As the FileType is a referenced value type, it cannot be modified or deleted.

Deleting Value Types


To delete a Value Type, which has been used in a property, you must select the Delete on Cascade option in the
Delete dialog box. This will delete the Value Type and all the properties that use the Value Type.
If you try to delete the Value Type of a data model that has already been deployed you could encounter problems
when you try to deploy the solution.
It is possible to temporarily allow these potentially destructive deletions during the configuration phase.

98 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.2.7.2 Creating Type Aliases


Type aliases are custom types, based on simple types with added constraints, which can be used cross-domain.
The aim of a type alias is to guarantee that the type is used in the same way in the whole solution.
For example if you create a type alias MyString, based on the simple type String, with a constraint where
MaxLength = 10, and then use MyString in a property of MyEntity, when you modify the constraint of MyString to
MaxLength = 5, the property of MyEntity will also be modified and will inherit the same constraint. Bear in mind
that you cannot modify the type alias attributes from MyEntity.
To see how type aliases are used in business logic see Using Type Aliases.

Procedure
1. In the Model Explorer pane right-click the Types node and select New Type Alias.

2. Insert a name for the type alias. The type alias name cannot contain spaces or special characters and it cannot
start with a number. Certain reserved keywords should not be used in the type alias name.
3. Select the base simple type on which you want to base your type alias (string, tinyint, smallint, int, bigint,
decimal, DateTime, Guid, Bool, Blob or TimeSpan).
4. Enter a description for the type alias. The Description edit box supports markdown formatting, thus allowing
you to correctly format the information to be included in the reference documentation file.

Result
Type aliases are displayed in the Model Explorer pane, identified by the icon .
You can now specify the attributes for the type alias in the Properties pane. These attributes will be inherited by the
entity property, or the command/event/reading function parameter that uses the just defined type alias as
property/parameter type (see the table below).

 To delete a type alias, which has been used in a property or parameter, you must select the Delete on
Cascade option in the delete dialog box.
This will delete the type alias and all the properties and parameters that use the type alias.

Simple types and attributes for Type Aliases

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 99


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Default Mandator MaxLeng Scale LogicalKe From - To Precision


y th y

String not for


command and
event parameters

Decimal not for


command and
event parameters

Integer (int, not for


tinyint, command and
smallint, event parameters
bigint)

DateTime

Guid

Bool not for


command and
event parameters

Blob

TimeSpan

2.1.2.7.3 Creating Parameter Types


Parameter types are made up of one or more properties, which can be used as arguments of commands and events.
They can be used cross-domain.
The parameter types of referenced data models can be used as arguments of commands and events, but cannot be
modified or deleted.
If the parameter type has been used in commands and/or events the Delete on Cascade option must be selected,
otherwise it will not be possible to delete the parameter type.
The model assembly of the .dll that contains the parameter types (*.Types.dll), required to use parameter types in
command or event handlers, is automatically added to your solution. However, if required it can be added
manually.

Procedure
Parameter types can be either created from scratch or as a copy of existing ones.

100 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

1. In the Model Designer pane, right-click in any empty area and select Add > Parameter Type.

2. Enter a name for the parameter type. Certain reserved keywords should not be used in the parameter type
name.
3. Enter a description for the parameter type. The Description edit box supports markdown formatting, thus
allowing you to correctly format the information to be included in the reference documentation file.

Result
The new parameter type is displayed in the Model Designer pane with the icon.

 To delete a parameter type, which has been used in a property or parameter, you must select the Delete
On Cascade option in the delete dialog box.
This will delete the parameter type and all the properties and parameters that use the parameter type.

Adding Properties to Parameter Types


Properties and property attributes are added to parameter types in the same way as they are added to entities. The
properties of parameter types can also be made up of lists of properties, such as strings, or types.
The following property types can be used for a parameter type:

Type Description

System Types Possible simple properties are: string, int, bigint, smallint, tinyint,
decimal, bool, DateTime, Guid, Blob, Span.

Entity Properties You can use the type of an entity property (not the property itself) by
browsing to the entity object and then to one of its properties.

Enumeration Types A data type consisting of a set of named values called enumerators.

Parameter Types You can nest any parameter type taking into account that the related
property must be set to Optional.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 101


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Type Description

Lists Lists of:


• system properties
• entity properties
• enumeration types
• parameter types

2.1.2.7.4 Creating Enumeration Types


Enumeration types are data types consisting of a set of enumerators. Each enumerator is made up of a name and
value pair.
They can be used for any artifacts: entities, facets, parameter types, value types, commands and events, but not
type aliases.

Procedure
Enumeration types can be either created from scratch or as a copy of existing ones.
1. In the Model Designer pane, right-click in any empty area, select Add > Enumeration Type.

2. Enter a name for the enumeration type. The name must not contain spaces or special characters and cannot
start with a number. Certain reserved keywords should not be used in the enumeration type name.
3. Enter a description for the enumeration type. The Description edit box supports markdown formatting, thus
allowing you to correctly format the information to be included in the reference documentation file.
4. Click OK.

Result
The new enumeration type is displayed in the Model Designer pane with the icon.
The newly created enumeration type is an empty container to which you must add the enumerators .

Adding enumerators to enumeration types


When you have created your enumeration type in the data model, you can add enumerators in Project Studio.
1. Select the enumeration type in the central Model Designer pane.
2. Right-click on the name or icon of the enumeration type and select New Enumeration Type.
3. In the Model Details pane, click on the enumerator you have just added and modify its name. Its name must not
contain C# keywords.

102 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

4. Click on the enumerator you have just added and modify its value, which must be an integer.

Deleting enumeration types


To delete an enumeration type, which has been used in a property or parameter, you must select
the Delete on Cascade option in the delete dialog box.
This will delete the enumeration type and all its enumerators.
If you try to delete the enumeration type of a data model that has already been deployed, you could encounter
problems when you try to deploy the solution.
It is possible to temporarily allow these potentially destructive deletions during the configuration phase.

2.1.2.8 Deprecating Artifacts


You can declare as deprecated each artifact, by specifying the platform version, according to the format x.y or xx.yy
(for example, 3.0 or 03.00).
This means that, from the specified version, artifacts are maintained only for compatibility reasons and they are
no longer used.
For this purpose, we provide you a dedicated annotation that you need to mark, as described in the following
procedure.
The deprecated annotation can be modified in major versions of FB/App, whereas in minor versions it can be
modified only in the artifacts created in the current minor version. Otherwise, the annotation will be displayed as
read-only.
Artifacts deprecated in the Functional Block are automatically set as deprecated in the referenced App as well,
where they are displayed as read-only.

Procedure
1. In the Model Explorer, select the artifact you want to set as deprecated.
2. In the Properties pane > Accessibility area, fill the Deprecated field by inserting the Opcenter Execution
Foundation version where the artifact is deprecated.

2.1.2.9 Restoring a Previously Deleted AssemblyInfo.cs File


The AssemblyInfo.cs file, which is contained in the Properties folder of the Model project of the Functional Block/
App, must never be deleted.
However, if you need to, you can manually restore it by following this procedure.

Procedure
1. Within the Model project from where the file has been removed, right-click the Properties folder and select Add
> New Item.
2. From the displayed dialog box, select the Assembly Information File template and click Add. The system will
assign a default name to the file, regardless of the name you assigned.

2.1.2.10 Building your Model


When you have completed the modeling phase you must build your model in Project Studio.
This intermediate build of the project will allow you to generate the model assemblies and implement the business
logic of your commands and events.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 103


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

At this phase you can build only the model, not the entire solution. If you compile the entire solution now, you will
receive a blocking error because command and event handlers have not been imported yet.

Prerequisites
If you are building a model created in a previous version of Opcenter Execution Foundation, make sure you have
correctly migrated the model to the current version.

Performing the Build operation


The build operation can be performed in one of two ways:
• select the model project and choose command Build > Build
<FunctionalBlockName>.<DomainAcronym>Model
• right-click the model project and select Build from the shortcut menu
All the compiled files are saved by default in the bin\Debug folder of the Model project (for example
Projects\MyFBLibrary\MyFBLibrary\MYFBLibrary.RF.Model\bin\Debug). Do not add any references to the .um
/.umd files directly contained in the Model\ folder (for
example Projects\MyFBLibrary\MyFBLibrary\MYFBLibrary.RF.Model\): these files are project development files.

Performing the Rebuild operation


If you have performed one of the following operations, you must use the Rebuild command (instead of the Build
command) to correctly regenerate the model output assemblies (otherwise a compilation error is returned):
• you have deleted either all entities, or all commands, or all events or all types from the model project;
• you have set all protected commands to private (or viceversa).

Setting the output verbosity level


If you need to show more information about the compilation output, for example to analyze build errors, do the
following:
1. In Visual Studio, select Tools > Options command.
2. In the Options dialog box, select Projects and Solutions > Build and Run and set the required verbosity level
(for example, Detailed) and confirm.

Example of output without verbosity:

Example of output with verbosity:

104 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3 How to Implement Business Logic


Once you have finished the modeling phase, you can implement the logic to be executed in the command handlers
and event handlers.
You carry out this implementation phase by writing code in the C# classes available within the Functional Blocks in
Project Studio.

 Any system integrators/customers that use Opcenter Execution Foundation to customize applications and
business logic, must write the code in a secure way, by respecting any secure coding guidelines in place on
the customer’s site.
The Opcenter Execution Foundation platform cannot be held responsible for the security of the modeled
artifacts, such as UI Components, events, commands, reading functions and so on.

Workflow
The main steps of the implementation phase are:
1. Import the handler templates (command handlers, event handlers, pre-check handlers and so on).
2. Add file references to the model assemblies to build logic on entities that belong to the same Functional Block.
The file references for referenced Functional Blocks should be added using Reference Manager.
3. Write the business logic by invoking the required platform public functionalities. The syntax of the logic you
write is dynamically checked by the UAF C# Analyzer.
4. For remote command invocations, see How to Manage Remote Artifacts.
5. For entity creations, see How to Manage Entity Instances.

Possible operations
Refer to the dedicated sections about the integration with specific parts of the product, such as for example
• Integrating with Automation Gateway Server
• Exchanging messages with external systems
• Integrating Electronic Signature
• Handling Timers
• Using Semi-Automatic Acquisition in Work Instructions
• Managing Application Logs

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 105


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Implementation phase representation

 For more information on how to extend the business logic of referenced Functional Blocks, see How to
Implement Pre-Checks for Business Logic Execution and How to Extend Business Logic with Post-Actions.

Hints for supporting business continuity during planned Windows updates


In order to minimize the risks of inconsistencies during the Windows updates (see How to Install Windows Updates in
Business Continuity in the Opcenter Execution Foundation Installation Guide), you should develop your business logic
by keeping in mind the following best practices:
• For any critical events, define the related event handlers as reliable because during the stop for maintenance
procedure, the execution of handlers related to unreliable events might not be completed or re-executed.
Unreliable event handlers, indeed, generate temporary queues that are deleted when the process is stopped.
The same happens when the queues that are generated by event subscriptions via
IUnifiedSdkLean SubscribeEvent method are set in either of the following ways:
• with the queueName property set to null or
• with the ListenerOptions.QueueAutoDeletable property set to true.
For more information on these topics, see Configuring Reliable Event Handlers and Developing Third-
Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface.
• Develop command handlers/event handlers by considering that your logic could be re-executed (we
recommend that you implement applications according to the idem potency principles).
• Whenever invoking the SendCommand IUnifiedSdk API, use C# statements to wait for the command
result.

106 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.1 How to Implement Command Handlers


Concepts you need to know about
• Transaction Management
• Command Retry Management
• Command Timeout Management
• Retrieving the Identity of the Handler in Execution
• Invoking Commands
• Invoking Remote Commands
• Tracing Process Executions
• Best Practices for Software Development

Workflow
The minimum workflow to be followed to implement Command Handlers is as follows:
1. Import Command Handlers.
2. Write the business logic.
3. Debug your code inside Command Handlers.

2.1.3.1.1 Importing Command Handlers


Command handlers contain the business logic required to reach a specific manufacturing target (for example,
creating an order after a material check).
You must enter the code describing this logic in the class corresponding to the modeled command. This class,
which you can import through a wizard, is made up of two partial classes contained in two separate files. These files
are automatically generated and named by the Functional Block compiler. Only
the <CommandName>Handler.cs file must be modified.
In order to write your code, you must import the template classes into your Command Handler project.

 The model assemblies of entities that have been modeled in the same Functional Block are managed
automatically within Project Studio if you use the Import from the Model command. If you import
command handlers manually you will then have to manually import the relative manifest and .dll files.
Similarly, the model assemblies of entities from referenced Functional Blocks are automatically managed
by Reference Manager. However, if you do not use Reference Manager you will have to manually add the
model assemblies of referenced Functional Blocks.

Importing the C# class of the command handler


After you have compiled the Model project at the end of the command modeling phase, import the
required .cs files, with the relative relative manifest and .dll files, in the Solution Explorer as follows:
1. Right-click the CommandHandler project and then select the Import from the Model command.
2. Select the commands to be imported from the list.
3. Expand the following folder structure (automatically created at the end of the import procedure):
CommandHandler project > <FunctionalBlockName>.<DomainAcronym>Model > Commands sub-folder.
Here you will find the imported C# files.
4. Open the required <CommandName>Handler.cs file and write the required code.

Manually adding command handlers to the project

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 107


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

In some cases, for example if a .cs file has been removed by mistake, you may need to manually add command
handler templates to your project instead of using the import functionality:
1. Expand the command handler project.
2. Right-click on the Commands sub-folder and select Add > Existing Item.
3. Browse to the .cs files that you want to use in your project (for example,
MyProject.RFModel\bin\Debug\MyProject.RFModel\Commands).

Examples
The command handler below implements the code for a command, defined as follows:

Command Name Parameter

MyCommand Input: InputParameter1 (string)

Input: InputParameter2 (string)

Output: OutputParameter1 (Guid)

108 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command handler Execute() method (not to be modified)

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
[...]

namespace MyDomain.MySubDomain
{
/// <summary>
/// Class initialize
/// </summary>
public partial class MyCommandHandlerShell : ICommandHandler
{
private IUnifiedSdk Platform;

/// <summary>
/// Execute
/// </summary>
/// <param name="unifiedSdk"></param>
/// <param name="command"></param>
/// <returns></returns>
public Response Execute(IUnifiedSdk unifiedSdk, ICommand command)
{
this.Platform = unifiedSdk;
return MyCommandHandler((MyCommand)command);
}
/// <summary>
/// Retrieve the type of the command
/// </summary>
public System.Type GetCommandType()
{
return typeof(MyCommand);
}
}
}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 109


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command handler implementation

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Handler;
using Siemens.SimaticIT.Unified;
using Siemens.SimaticIT.SDK.Diagnostics.Tracing;
[...]

namespace MyDomain.MySubDomain
{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class MyCommandHandlerShell
{
/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HandlerEntryPoint]
private MyCommand.Response MyCommandHandler(MyCommand command)
{
Guid myGuid = Guid.NewGuid();

// Put your code here before the CallCommand

MyOtherCommand.Response res = Platform.CallCommand<MyOtherCommand,


MyOtherCommand.Response>(new MyOtherCommand { ParamOfMyOtherCommand =
command.InputParameter1 });
var localVariable = res.OutputParamOfMyOtherCommand;

Platform.Tracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",

Siemens.SimaticIT.SDK.Diagnostics.Common.Category.Informational,
"My local variable value is {0}",
localVariable);

// Put your code here after the CallCommand


// Returns command response with output parameters or error information
return new MyCommand.Response(){ OutputParameter1 = myGuid,
OutputParameter2 = localVariable };
}
}
}

110 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.1.2 Implementing Command and Event Handlers


You can implement the logic of commands and events inside command and event handlers. Command and event
handlers are grouped inside projects. There can only be one command handler project and one event handler
project for each functional block.
From the code of the handlers you can invoke and use Opcenter EX FN public functionalities exposed by the
IUnifiedSdk Interface and the IUnifiedSdkEvent Interface, documented in the Opcenter Execution
Foundation Platform Reference Online help.
According to the handler you are developing and whether you are referencing another model project or not, the
available functionalities will be different. This topic aims at giving you an overview of the possible operations.
At the end of the handler implementation, you can debug your code directly from Project Studio either by using the
Opcenter EX FN App Debugging tool or by writing additional code.

Description of command and event handlers


When you define a new event or command and then build the Model project, the system generates the following C#
classes for each event or command:
• <Command/EventName>Handler.cs, which you must modify, is already configured to expose the method that
you have to implement. This method has been automatically configured to receive the input of the related
command/event and to return the expected response.
• <Command/EventName>HandlerExecution.cs, which you must not modify, is automatically configured to
expose:
• the Execute() method that will be invoked by the Worker.
• the Platform variable, on which an instance of an object that implements either
the IUnifiedSdk interface (for command handlers) or the IUnifiedSdkEvent interface (for event
handlers) is injected.
After importing the events and commands in the relative handler project from Project Studio, you can modify the
<Command/EventName>Handler.cs file (for each command or event, respectively).
At runtime the worker invokes the code of the handler by calling the Execute() method of the <Command/
EventName>HandlerExecution.cs class. When this method is invoked, the worker executes the handler logic with
the input from the received command request and then it prepares the reply to be returned.

Input, Output and Command Response


The input parameters define the input data structures that will be passed to the Command.
The Response Class of the Command returns the Command output parameter and two properties: a boolean
property regarding the execution result (Succeeded) and an Error property containing the error code and the error
message.

Using model assemblies in command and event handlers


When compiled, the model project generates a set of assemblies containing the definitions of all the objects you
have modeled, such as entities, commands, events etc (see the list of the generated assemblies if needed).
Inside your command handler or event handler code you may want to perform operations on entities that have
been modeled either inside the same Functional Block or inside another Functional Block.
These references are automatically managed by in Project Studio, both for your current project and for any
referenced Functional Blocks.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 111


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

If you have not used Reference Manager to add references to Functional Blocks you can add model assemblies
manually.

Comparing operations available inside command and event handlers


The following table compares the operations that you can execute from the code of a command and of an event
handler.

Operation Type Command Event


Handler Handler

Read data from write model, if the entity is inside the same domain

Read data from write model, if the entity is inside another domain

Read data from read model, if the entity is inside the same domain

Read data from read model, if the entity is inside another domain

Read data from read model, if the entity is from a user domain

Read data from archived entities

Write data (create, update, delete entity instance), if the domain of the entity (if
and the domain of the command/event are the same and the Functional the entity is not
Blocks are different. restricted)

Write data (create, update, delete entity instance), if the domain of the entity
and the domain of the command/event are different

Write data (create, update, delete entity instance), if the entity belongs to a
user domain

Call published in role commands (synchronously/asynchronously)

Call private commands (synchronously/asynchronously)

Call remote commands (synchronously/asynchronously)

Get remote entities

Invoke reading functions

Read from Automation entities

Write on Automation entities

112 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Operation Type Command Event


Handler Handler

Trigger events

Subscribe to events

Write trace logs

Access to the current user identity (Principal property)

Send messages to Opcenter Connect MOM

Get data segregation session information

 Automation Gateway functionalities, exposed by the Automation Sdk interface, can be accessed only if you
compile the Command Handler/Event Handler/Reading Function Handler by choosing the 64-bit
compilation option.

Command validation
If you set validation attributes on the command parameters, when you invoke a command (either from another
handler, or from a client through the Service Layer or from a client that uses IUnifiedSdkLean interface), the
provided values will be validated accordingly. If you set validation attributes on the command output parameters,
the response that a command handler returns will be validated too. A failure in this validation will result in the
command execution failing.

Handler implementation example


The following code example shows some of the possible operations you can execute inside command handlers
(while inside event handlers you can execute only a subset of these operations, as shown in the comparative table):
• Creating, modifying or deleting an entity instance.
• Invoking the Submit() method to write the change on the database.
• Invoking commands: you may invoke a command asynchronously, perform an action at the end of
an asynchronous command call, or invoke a command synchronously.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 113


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command handler example

using System;
using System.Collections.Generic;
using System.Linq;
using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Handler;
using Siemens.SimaticIT.Unified;
using Siemens.MasterData.prjb.MSModel.DataModel;
using Siemens.MasterData.quality.MSModel.Commands;
using Siemens.MasterData.prjb.MSModel.Events;
using System.Threading.Tasks;
[...]

namespace Siemens.MasterData.prjb.MSModel.Commands
{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class NCHandlingHandlerShell
{
/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HandlerEntryPoint]
private MyCommandHandling.Response MyCommandHandlingHandler(MyCommandHandling
command)
{
ITracer tracer = Platform.Tracer;

// code for entity instance creation done by means of Submit platform API
var iev = Platform.Create<IMyEntity>();
iev.prop1 = command.input1;
iev.prop2 = command.input2;
// manage an enumeration type
iev.prop3 = Platform.Types.Color.Red;
// .....
Platform.Submit(iev);

// call synchronous command


var command2Response = Platform.CallCommand<Command2,
Command2.Response>(new Command2(command.input3, command.input4));
if (command2Response.Succeeded)
{
// call asynchronous commands
var task1 = Platform.SendCommand<Command3, Command3.Response>(new
Command3(command.input5));

114 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var task2 = Platform.SendCommand<Command4, Command4.Response>(new


Command4(command.input6, command.input7, command.input8));
Task.WaitAll(task1, task2);
var response1 = task1.Result;
// check tasks response
return new MyCommandHandling.Response() { Value1 =
response1.Counter };
}
return new MyCommandHandling.Response() { Error = new ExecutionError(-1,
"Impossible to complete.") };
}
}
}

2.1.3.1.3 Transaction Management


Transaction management describes the way sequences of commands are handled. This page handles with the
following related concepts: command chains, transactions, Submit and Commit operations, optimistic
concurrency.

Command chains
Opcenter Execution Foundation does not manage direct calls between .NET classes. To invoke logic that is
described inside other parts of your program, you must call a command or raise an event. A command
handler usually contains a sequence of commands that are executed within a single transaction, which may
operate on different entities within the same domain. Since a command may call another command, which may call
another command, and so on, we talk about a chain of commands, or rather, a tree of commands, because from
one command we can send the request to more than one command.

Transactions
Although all commands are defined in the same way, only the first command of the tree is the one that triggers the
entire execution logic. This command is called the root command and determines the scope of the
entire transaction. This means that the entire command tree shares the same transaction scope.
The first invoked command also conveys contextual information that the system uses to execute, or not execute,
the required logic. An example of context could be the identity of the user that is sending the command request.
Inside the same command tree, the identity information is shared among all the steps of the command execution
and is used by the Opcenter Execution Foundation platform to evaluate whether a request can be fulfilled or
not. Command requests performed without identity information will not be processed.
In the command chain, when the root command is launched, all sub-commands in the command chain use the
same transaction. This also applies to the parallel execution of commands within the same transaction.
A root thread is instantiated when a root command execution is required, and this thread is responsible for setting
the correct database connection and database transaction.
Command requests performed without identity information will not be processed.

 If you are using remote commands, be aware that this invocation mode is out of the transaction. Refer
to How to Manage Remote Calls for more information.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 115


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Submit and Commit operations


Along with the code implemented for each single command, the Submit() method must be invoked to publish the
changes to the context so that changes are then available to the other sub-commands (if the Submit() method is
not invoked, modifications are not visible at all to the sub-commands).
When the command chain finishes, the system closes the sequence and either:
• execute a COMMIT TRANSACTION instruction and persist the changes on the database if the transaction
completed successfully.
• execute a ROLLBACK TRANSACTION instruction, without persisting the changes, and reinstate the initial
status if the transaction raised an error.
If the transaction completed successfully, Information Services write the list of the executed operations in
the CommittedEvent event.

116 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Optimistic concurrency
Every time a new entity is inserted or updated, a unique version is generated as an attribute of the entity. On any
entity update, a check on the entity version is performed to make sure that the entity has not been modified in the
meantime. To handle possible concurrent transactions which attempt to modify the same piece of data, Opcenter
Execution Foundation applies an optimistic concurrency control, which allows multiple transactions to access the
same data, as it is assumed that data conflicts are rare.
Opcenter Execution Foundation applies the Snapshot Isolation level that prevents from detecting entity changes
performed in other transactions. According to the database management system in use, concurrent transactional
updates are differently handled.
On SQL Server databases, if a transaction attempts to commit modifications to data that have been changed since
the transaction began, the transaction will be roll-backed and an error will be raised.
On Oracle databases, this behavior is not available, and if concurrent transactions are going to modify the same
piece of data, no exception is raised and the changes are applied by the commit operations one after the other.

2.1.3.1.4 Command Retry Management


When the execution of a command fails, there are a number of situations in which the system internally tries to
execute the command again.
Opcenter Execution Foundation applies two types of retries: an immediate retry and a delayed retry. In this topic we
will see when these retry types are executed and what logic is applied.
The immediate retry is applied when a transaction error occurs (for example, if there is a concurrency failure or a
deadlock error).
The delayed retry is applied when a timeout error or a system error occurs and these errors cannot be internally
managed.

 If the failure occurs in the handler code and the user does not handle it properly, the system does not
execute any retry operation. The result of the command will be completed with a failure indicating the
problem in the handler.

Immediate retry logic


The immediate retry is applied on commands defined as public and published in role, for both worker roles
configured for parallel execution as well as for sequential execution.
If a command is aborted due to a transaction error, the following behavior is applied:
• in case of parallel execution configuration, copy of the failed command is sent to the Manufacturing Service Bus
and the command is re-executed.
• in case of sequential execution configuration, the failed command is re-executed by the same worker straight
away.
In both cases, the involved worker re-executes the command depending on the timeout value configured for the
command (and not the number of retries, as in the delayed retry logic described below). Further retries will be
executed as long as there is time left.
If you have a composite command, the system does not perform any retry operations on the composite command
itself, but does however apply an immediate retry on its called subcommands. The worker, being it parallel or
sequential, re-executes the failed subcommands straight away, without sending them to the Manufacturing Service
Bus.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 117


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Delayed retry logic


The delayed retry is applied to a root command (e.g. C1), if this command is public and published in role, when a
system or timeout error occurs.
This type of retry is not applied to composite commands and to its subcommands and it is also not applied to the
commands hosted in a Sequential Worker Role.
Considering a failed command C1, the retry manager functionality does the following:
1. It checks if at least one retry operation can still be performed,
2. If there are remaining retries, it sends a new command C2, which is a copy of C1, to the Manufacturing Service
Bus. Command C2 can then be unqueued from the Manufacturing Service Bus with a delay time defined as
follows:
The retry strategy is an exponential back-off proportional to the timeout specified for a specific command and the
power of the retry number that is being processed. This retry time is defined as follows:

RetryTime(n) = Tout • 2n-1


where:
• n is the number of the retry that the system is about to execute (1 corresponds to the first retry, 2 to the second,
and so on. By default, the maximum number of retries is set to 3).
• Tout is the command timeout (by default, 30 seconds).
The retry time (RetryTime(n)) is calculated starting from the moment when the command (C1, in our example) is
sent to the Manufacturing Service Bus. The retry time indicates, for each sent command, the time that must pass
before the worker can unqueue the command from the Bus and start its execution.
Consequently, the retry time is set as follows: the first retry is scheduled after 30 seconds, i.e. immediately after the
end of the C1 command timeout. The second retry is scheduled after 1 minute after the C1 command dispatch and
the third retry is scheduled after 2 minutes after the C1 command dispatch.

The maximum time that the client (such as either an Event handler, or an SdkLean application or the Service Layer)
could potentially wait for is:
MaxTotalTime = RetryTime(N) + Tout
where:
• N is the maximum number of possible retries (by default 3)
• Tout is the timeout of the last retried command (by default 30 seconds)
The result of this formula, if Tout and N are set to their defaults, is 150 seconds. Note that the maximum total time is
not the sum of the retry times. The formula, which uses N set to a maximum possible value, represents the
maximum time delay that can be scheduled for the command, added to the last possible timeout of the command.
After this time has elapsed, if the client is an SdkLean application or an Event Handler, a UnifiedException is raised.
If you are accessing via Service Layer, you will receive a "500" HTTP status code (Internal Server Error) and the body
of the response will contain the "error.code" field set to "1005".

118 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Configuring command retries and timeout


In the Worker Roles page in Solution Studio, you can configure
• (only for parallel worker roles) the value of the maximum possible retries (n),
• as well as the command timeout (Tout).

2.1.3.1.5 Command Timeout Management


The execution of a command handler is characterized by a timeout, which may behave differently according to the
type of operation.
This topic describes the different logic applied.

Configuring the Command timeout


The timeout value can be configured in the Worker Roles page in Solution Studio.
It may be useful to increase either the timeout value or the retry number, but not both values at the same time.
The timeout value should be increased for long-running operations, whereas the retry number should be increased
only for short operations, that might fail due to temporary errors (such as network failures and so on).
In any case, the total time (including timeout and retries) must be inferior to the timeouts configured in the:
• client web application
• Opcenter EX FN database

Handling command timeout


During each phase of the execution of the command handler, the system checks whether the command timeout has
expired or not. If the timeout has expired, all the involved Opcenter Execution Foundation layers react to this
timeout by aborting the operations that were going to be executed and by raising an exception.
However, the timeout can also expire during the execution of an operation.
According to the API called, the following could occur:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 119


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• If the operation is a not a long-running operation, Opcenter Execution Foundation does not abort the operation
and a check is executed before committing changes to verify whether a transaction error or command timeout
has occurred. If affirmative a rollback operation is performed.
• If the operation is a long-running operation that belongs to either
the IUnifiedSdkInformation and IUnifiedSdkDataReading interfaces (e.g. BulkInsert method), Opcenter
Execution Foundation verifies the timeout during the execution and aborts the operation throwing a
UnifiedException. Commit operations, however, cannot be aborted once their execution has started.
The logic of command timeout management is valid for all commands. Retries are supported for some types of
commands.
A different behavior is applied to the transaction management of composite commands.

Retrieving remaining execution time


A public method, the GetRemainingExecutionTime method, is available for retrieving the remaining execution
time before timeout expires. This method could be called for example before calling a long-running operation.

2.1.3.1.6 Retrieving the Identity of the Handler in Execution


Opcenter Execution Foundation IUnifiedSdk interface exposes the Principal property, documented at section
Principal of the Opcenter Execution Foundation Platform Reference Online Help. This property is an instance of
the ClaimsPrincipal standard Microsoft .NET type.
It allows you to retrieve the identity associated with the handler execution request. This means that the retrieved
identity refers to the client that sent the command and contains the claims associated with this identity.
Opcenter Execution Foundation uses the .NET ClaimsPrincipal object to provide you with the same user
experience as that of the standard .NET developer. For example, the authorization strategy is based on the
separation between business logic and security issues.

Example use case


In a scenario where the user is identified by a set of custom properties, you may want to retrieve the identity of the
user who is performing the command request in your command handler, and execute a query on the custom
properties associated with this identity.
Your aim could be to apply custom logic to the retrieved identity properties, for example to enable or block a
specific operation at runtime.

2.1.3.1.7 Invoking Commands


Opcenter Execution Foundation does not manage direct calls between .NET classes. To invoke logic that is
described inside other parts of your program, you must call the command that triggers that part of the logic. The
command is defined during the command modeling phase. The logic is defined inside the command handler or the
event handler.
Since a command may call another command, which may call another command, and so on, we can talk about a
chain of commands, as from one command you can send a request to many commands. All commands within the
same chain belong to the same transaction.
To invoke commands, you must use the methods exposed by the platform public interfaces ( IUnifiedSdk
Interface and IUnifiedSdkEvent Interface, documented in theOpcenter Execution Foundation Platform Reference
Online help).
Not all commands can be invoked from anywhere. The system applies constraints according to the following
conditions:

120 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• the code that contains the call (i.e. whether you are inside a command handler, an event handler or a Lean Sdk
Client)
• the command type (i. e. whether the command is private or protected)
• the domain of the model you are implementing

Synchronous and asynchronous commands


You can invoke commands both synchronously and asynchronously.
Asynchronous calls can be used when you need to put in parallel more command executions. More specifically,
they provide a way to perform operations without blocking the callers' threads. The caller thread/method can
continue its work without waiting for this asynchronous method to complete its job.
The SendCommand method performs asynchronous calls and the CallCommand performs synchronous calls.
These methods are defined as generic methods and are exposed by two different interfaces, according to the
project template you are working in:
• IUnifiedSdk, if you are inside a command handler
• IUnifiedSdkEvent, if you are inside an event handler
For both these generic methods, specify in input the command type to be invoked and the type of the command
response. Then create the command class, which is of the same type as the one you have passed in the command
and specify the list of properties to be used to initialize the command class.
When a first-level command is invoked from a consumer, the request is added to the queue of messages within the
Bus, and then it is redirected to the first available worker that has been configured to listen to that
command. Although command execution logic is based on message exchange, the underlying logic is the standard
request-reply command execution logic. This means that when you define the signature of your command, even if
you do not define any return parameters, the system always prepares a reply message.

Private and protected commands


The command modeling phase prompts you to configure commands as either private or protected, thus setting
constraints on the possible command invocations (both synchronous and asynchronous) among different
Functional Blocks.
You cannot invoke private commands that have been modeled in a referenced Functional Block, even if it belongs
to the same domain of the Functional Block whose business logic you are currently implementing:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 121


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 If you develop a call to a private command contained in a referenced Functional Block, the system returns
an error at runtime and invalidates the whole transaction. This situation may occur because if you try to
call a referenced private command, Visual Studio Intellisense permits you to browse referenced private
methods and the functional block solution compilation does not return any error, leading you to the idea
that such a call type is possible. The error raises only at runtime, when the worker tries to resolve the call.

Constrains do not apply to calls within the same Functional Block:

To successfully implement command calls, verify that the following references to the assemblies containing the
definitions of the commands have been added to your handlers:
• <Prefix>.<DomainName>.<FunctionalBlockName>.Model.Commands.dll: this is the assembly containing the
definitions of the commands.

122 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• <Prefix>.<DomainName>.<FunctionalBlockName>.Model.Commands.Internal.dll: this is the assembly


which contains the definitions of private commands.
These references should be created automatically in Project Studio, but these references can be added manually if
required.

Examples of asynchronous and synchronous calls


You can invoke a command asynchronously as follows:

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
[...]

// call asynchronous commands


var task1 = Platform.SendCommand<Command3, Command3.Response>(new
Command3(command.input5));
var task2 = Platform.SendCommand<Command4, Command4.Response>(new
Command4(command.input6, command.input7, command.input8));

You can use a task to wait for the end of an asynchronous call as follows:

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
[...]

var task1 = Platform.SendCommand<Command3, Command3.Response>(new


Command3(command.input5));
var task2 = Platform.SendCommand<Command4, Command4.Response>(new
Command4(command.input6, command.input7, command.input8));
Task.WaitAll(task1, task2);
var response1 = task1.Result;
var response2 = task2.Result;
// check task response
return new MyCommandHandling.Response() { Value1 = response1.Counter, Value2 =
response2.Label };

You can invoke a command synchronously as follows:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 123


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

//Call command example 1


WriteOnMaterialDefinition.Response matDefEvent =
Platform.CallCommand<WriteOnMaterialDefinition,
WriteOnMaterialDefinition.Response>(new WriteOnMaterialDefinition { CreatedCode =
evt.Code });

//Call command example 2


var cmd = new WriteOnMaterialDefinition(){CreatedCode = evt.Code};
WriteOnMaterialDefinition.Response matDefEvent =
Platform.CallCommand<WriteOnMaterialDefinition,
WriteOnMaterialDefinition.Response>(cmd);

//Call command example 3


var cmd = new WriteOnMaterialDefinition();
cmd.CreatedCode = evt.Code;
WriteOnMaterialDefinition.Response matDefEvent =
Platform.CallCommand<WriteOnMaterialDefinition,
WriteOnMaterialDefinition.Response>(cmd);

 Remember to properly check and manage responses of command invocations. In particular, pay attention
to unsuccessful responses of sub-Commands.

2.1.3.1.8 Invoking Remote Commands


To invoke logic that is implemented in another App, you must call the remote command that triggers that part of
the logic. The command must be defined as explained at How to Manage Remote Calls.
Since a command may call a remote command, which may call another command or remote command, and so on,
we can talk about a chain of commands, since from one command you can send a request to many commands.
All remote commands within the same chain are executed out of the transaction.
To invoke commands, you must use the methods exposed by the platform public interfaces ( IUnifiedSdk
Interface and IUnifiedSdkEvent Interface, documented in theOpcenter Execution Foundation Platform Reference
Online help).
Remote commands can be invoked from anywhere except from a client that uses the IUnifiedSdkLean interface.
Remote commands support both synchronous ad asynchronous call (refer to the related section in Invoking
Commands).

2.1.3.2 How to Implement Pre-Checks for Business Logic Execution


After you have modeled the Pre-Checks, and built the Model project, you can proceed by importing the Pre-Check
Handler and the implement the required logic.
Before you start writing the code, read first section Runtime execution behavior below.

Workflow
1. Import the Pre-Check Handler.
2. Implement the Handler of the Pre-Check.
3. Build the package.

124 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Importing the Pre-Check Handler


After you have compiled the Model project, import the required .cs files, with the relative relative manifest and .dll
files, in the Solution Explorer as follows:
1. Right-click the CommandHandler project and then select the Import from the Model command.
2. Select the Pre-Check to be imported from the list.

3. Expand the following folder structure (automatically created at the end of the import procedure):
CommandHandler project\<FunctionalBlockName>.<DomainAcronym>Model\Commands\Pre-
Checks\<BaseCommandName>. Here you will find the imported C# files: <Pre-CheckName>Handler.cs
and <Pre-CheckName>HandlerExecution.cs.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 125


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Example

using [...]
namespace [...]

{
[Handler(HandlerCategory.BasicMethod)]
public partial class AlreadyExist_PreCheckHandlerShell
{
[HandlerEntryPoint]
private PreCheckResponse
AlreadyExist_PreCheckHandler(ManageEntityAllProperties command)
{
string trace = $"[ManageEntityAllProperties] - [{"AlreadyExist"}]
{"starting ..."}";
platform.Tracer.Write("Siemens-SimaticIT-Trace-Execution-Engine",
Category.Informational, trace);
var entity = platform.ProjectionQuery<IAllProperties>().FirstOrDefault(x
=> x.propertyString == command.parameterString);
if (entity != null)
{
trace = $"[ManageEntityAllProperties] - [{"AlreadyExist"}] Entity
<{entity.propertyString}> already exists";
platform.Tracer.Write("Siemens-SimaticIT-Trace-Test", Category.Error,
trace);
var response = new PreCheckResponse();
response.SetError(1, $"Entity <{entity.propertyString}> already
exists");
return response;
}
trace = $"[ManageEntityAllProperties] - [{"AlreadyExist"}] {"completed"}";
platform.Tracer.Write("Siemens-SimaticIT-Trace-Execution-Engine",
Category.Informational, trace);
return new PreCheckResponse();
}
}
}

Implementing the Pre-Check logic


As for the Commands, the system generates two files for the same C# class: the <Pre-CheckName>Handler.cs file,
which must contain the business logic, and the <Pre-CheckName>HandlerExecution.cs file, which must not be
modified.
In input, the Handler receives the input arguments of the Base Command.
In output, the Response Class of the Pre-Check returns:
• a boolean property regarding the execution result (Succeeded)
• an Error property containing the error code and the error message
• the Pre-Check name.

126 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

From the code of Pre-Check Handlers you can only execute read operations and access the functionalities exposed
by the IUnifiedPreCheckSdk interface from Protected Commands and the IUnifiedSdkPreCheckComposite
Interface from the Composite Commands, documented in the Opcenter Execution Foundation Platform Reference
Online Help.
The following table sums up the operations that you can execute from the code of a Pre-Check Handler.

Operation Type in Pre-Check Handler For For Composite


Protected Command
Comman
d

Read data from the writing model, if the entity is inside the same domain

Read data from the writing model, if the entity is inside another domain

Read data from the reading model, if the entity is inside the same domain

Read data from the reading model, if the entity is inside another domain

Read data from the reading model, if the entity is inside a user domain, i.e.
legacy system data

Read data from Automation entities

Get the properties and the content of the file as a data stream by specifying the
file GUID

Get CommittedEvents

Call Reading Functions

Write trace logs

Access to the current user identity through the Principal property

Get data segregation session information

Write data (create, update, delete entity instance), if the domain of the entity
and the domain of the Pre-Check Handler are the same

Write data (create, update, delete entity instance), if the domain of the entity
and the domain of the Pre-Check Handler are different

Write data (create, update, delete entity instance), if the entity belongs to a user
domain

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 127


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Operation Type in Pre-Check Handler For For Composite


Protected Command
Comman
d

Write data on Automation entities

Call published in role commands (synchronously/asynchronously)

Call commands (synchronously/asynchronously)

Call remote commands

Get remote entities

Trigger events

Subscribe to events

Send messages to Opcenter Connect MOM

Building the Package


Once you have finished all the implementations, you can build your extended Functional Block package (see How to
Create a Functional Block Package) or your extended App package (see How to Generate an Extension App
Package).

Runtime execution behavior


The platform will execute at runtime all the Pre-Checks enabled for a Base or Composite Command only if the
invoked Base Command is Public.
In particular, if the Pre-Check is associated with a Protected Command (base command) defined in a Functional
Block, the Pre-Check will be activated if:
• the App (or one of its extended Apps) refers to the Functional Block where the Pre-Check is defined and
• the base command is published in the App.
Example:
• In the Functional Block FB1 you have defined the protected command Cmd1.
• The command Cmd1 is published in 2 Apps: App1 and App2.
If you need to add a Pre-Check to the Public Commands of an App , you must create an Extension App for that App.

Condition Pre-Check visible to App1 Pre-Check visible to App2

Pre-Check of Cmd1 is defined in FB1

128 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Condition Pre-Check visible to App1 Pre-Check visible to App2

Pre-Check of Cmd1 is defined in FB2 and


App1 has a reference to FB2

Pre-Check of Cmd1 is defined in FB2 and


• App1 is extended with App1Ext
• App1Ext has a reference to FB2
If a Pre-Check fails, also the related Command fails and the error of the Pre-Check is passed to the error returned by
the Command response.
If there are more than one Pre-Checks, and the first Pre-Check fails, if you have set the fail and proceed behavior, all
the successive Pre-Checks are executed anyway. Otherwise, the system applies the stop and fail behavior by
default; in this case, all the successive Pre-Checks are not executed. Both the first Command and all Commands in
the list will be executed after the success of all Pre-Checks.
If a Pre-Check of a root Command fails, the root Command fails (as described above) and the sub-commands are
not executed.
If a Pre-Check of a sub-command in a command chain fails, the following situations occur:
• if the Pre-Check returns an expected failure, the failure must be managed inside the code of the invoking
command handler
• if the Pre-Check returns an unexpected error, the entire transaction is rollbacked and no changes are
committed.

2.1.3.3 How to Extend Business Logic with Post-Actions


After you have modeled the Post-Actions and you have built the Model project, you must import the Post-
Action .cs files, with the relative manifest and .dll files, to implement the required business logic in the Solution
Explorer.

Workflow
1. Import the Post-Action Handler
2. Implement the Handler of the Post-Action
3. Build the Package

Importing the Post-Action Handler


1. Right-click the CommandHandler project and then select the Import from the Model command.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 129


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2. Select the Post-Action to be imported from the list.

3. Expand the following folder structure (automatically created at the end of the import procedure):
CommandHandler project\
<FunctionalBlockName>.<DomainAcronym>Model\Commands\PostActions\<BaseCommandName>. Here
you will find the imported C# files: <Post-ActionName>Handler.cs and <Post-
ActionNAme>HandlerExecution.cs.

130 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Implementing the Post-Action logic


As for the Commands, the system generates two files for the same C# class: the <Post-ActionName>Handler.cs file,
which must contain the business logic, and the <Post-ActionName>HandlerExecution.cs file, which must not be
modified.
As for Command Handlers or Composite Command Handlers, from the code of Post-Action Handlers you can access
all the functionalities exposed by the IUnifiedSdk interface that you can find documented in the Opcenter Execution
Foundation Platform Reference Online help.
In input, the Handler receives both the input arguments of the Base Command and the response returned by the
Base Command Handler.
In output, the behavior is the following:
• when the Base Command Handler returns an Error, all Post-Action handlers will be executed until one of them
returns an Error.
• when any Command Handler in the chain (both Base Command Handler and Post-Action Handlers) returns an
Error, the overall Result will be of Error. The final result will be the Error Response returned as last. All Success
Responses will be disregarded and the overall transaction will be rollbacked.

Building the Package


Once you have finished all the implementations, you can build your extended Functional Block package (see
topic How to Create a Functional Block Package) or your extended App package (see topic How to Generate an
Extension App Package).

2.1.3.4 How to Manage Remote Artifacts


The remote call functionality enables service-oriented architecture aimed to reduce dependencies between the
invoking Apps and the invoked Apps (loose coupling).
This approach is internally achieved by means of an internal discovery service and a dedicated class
(IRemoteCommand).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 131


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Thanks to this implementation pattern, you can share manufacturing services among Apps and reduce the
complexity of the relationship build mechanism. This pattern, indeed, improves the development experience,
reducing the effort of the project implementation.
The Service Apps model will be reached by enriching your Apps and Functional Blocks with remote command
invocations and remote entity queries.

Available operations
• How to Manage Remote Calls
• How to Manage Remote Entity Queries

2.1.3.4.1 How to Manage Remote Calls


To implement the Service Apps model, let's see now how to implement a remote command invocation.
This approach is achieved by means of an internal discovery service and a dedicated class (IRemoteCommand).

Workflow

132 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

To enrich your solution with remote calls, go through the following steps:
1. Create the Remote Artifact project.
2. Create a new class implementing IRemoteCommand.
3. Invoke your Remote Command.

2.1.3.4.1.1 Creating the Remote Artifact Project


Create a new Remote Artifacts project as follows or open the existing project and go to step 6:
1. In Project Studio, inside the solution that will contain the remote invocation/query, add a new Visual C# type
project.
2. Name the project as follows: <Functional Block/App/ExtensionApp Name>.RemoteArtifacts.
3. Inside this project, add a reference to the %SITUnifiedSystemRoot%bin\SimaticIT.Unified.Common dll.
4. Then, create a folder for each Remote App you want to communicate to.
5. Name each new folder by the short name of the remote App to be invoked (e.g. if the app zip name is
Siemens.SimaticIT.MaterialV04.01.00.zip, then the folder name will be Material).
6. Inside each new folder, create as many C# classes as required by the number of the remote Commands you
will invoke, defining each class in a dedicated .cs file. These classes will implement the IRemoteCommand
interface as described in the dedicated topic.
7. If the target commands contain complex type parameters, such as Parameter Types or Enumeration
Types, create as many C# classes / enums, respectively, as the existing types, defining each class in a
dedicated .cs file (examples are provided). For more information on Command parameters, see Adding
Parameters to Commands and Events.

Creating the new IRemoteCommand class


To perform a remote call, you need to implement a new class of IRemoteCommand type inside the invoking App/
Functional Block/Extended App (e.g. App1, in the example below).
The IRemoteCommand interface is designed to implement remote calls to external Apps (e.g. App2 below) without
using binary references inside the project.
Either from a Command Handler available in a Functional Block of App1, or from a Composite Command Handler of
App1, you can remotely invoke any Commands that have been published inside the Public Object Model of a
different App or Extension App (thus if they are either Public Commands or Composite Commands).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 133


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 Remember: A Command can be remotely invoked only if it belongs to the Public Object Model of an App/
Extension App.

To explain how remote calls must be implemented, let's introduce two terms: the Target Command and the
Remote Command.
• With Target Command we will refer to the Command that actually performs the business logic, which must be
present in the Public Model of a certain App.
• With Remote Command we will refer to a new wrapper class, namely implementing the IRemoteCommand
interface, which must be built on the basis of the Target Command data structure and is internally used to find
the Target Command.
To properly implement the new class, you must know in advance the structure of the Target Command. Remember
that no intellisense is provided.
The IRemoteCommand interface requires a set of information (such as app name, called ServiceName, the app
version, namely ServiceVersion, and command parameters) that is used by an internal discovery service to address
the call to the correct command.

 Remember: To correctly build a Remote Command you must know how the Target Command is modeled.

134 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 (*) The service version is a mandatory parameter. If, at runtime, the discovery service does not find the
precise version, it selects the version of the actually deployed app.
For more details, see the error type table below.

Adapt the following example to properly implement an IRemoteCommand class:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 135


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

public class CreateMaterialTrackingUnit : IRemoteCommand


{
public string ServiceName => "Material";
public string ServiceVersion => "04.01.00";
public string CommandFullName => "";
public string CommandShortName => "CreateMaterialTrackingUnit";

public string NId { get; set; }


public string Name { get; set; }
public string Description { get; set; }
public MTUCodeType CodeType { get; set; }
public string Code { get; set; }
public string MaterialLotNId { get; set; }
public string MaterialNId { get; set; }
public string MaterialRevision { get; set; }
public string MaterialUId { get; set; }
public Quantity Quantity { get; set; }
public string TemplateNId { get; set; }
public string StateMachineNId { get; set; }
public bool? UseDefault { get; set; }
public string EquipmentNId { get; set; }
public Guid? MaterialTrackingUnitAggregateId { get; set; }

public class Response : Response<CreateMaterialTrackingUnit>


{
public Guid MaterialTrackingUnitId { get; set; }
}
}

Enumeration Type parameters


Detail of the MTUCodeType property in the Remote Command class. We suggest that you create a dedicated .cs file
to define the MTUCodeType enumeration type.

public enum MTUCodeType


{
None = -1,
BatchId = 0,
SerialNumber = 1
}

Parameter Type parameters


Detail of the Quantity property in the Remote Command class. We suggest that you create a dedicated .cs file to
define the Quantity parameter type.

136 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

public class Quantity


{
public string UoMNId { get; set; }
public decimal? QuantityValue { get; set; }
}

Type Alias parameters


In case of Type Alias parameters, you have to directly use the data type to which the Alias refers, without creating
any dedicated class. For example, if the target Command has a Description parameter defined as a Type Alias of
string type, in the IRemoteCommand you only need to define a Description property of string type.

Entity Property type parameters


In case of entity property type parameters, if the entity property is a simple type (e.g. int, string, bool etc..), you only
need to declare the same property type directly in the IRemoteCommand class. Instead, if the entity property type
is a Value Type or an Enum, you must create a separate class as described for Parameter Types and Enumeration
Types.

Invoking the Remote Command


You can invoke Remote Commands both synchronously and asynchronously, from any of the following handlers:
• Composite Command handlers and Event Handlers of Apps and Extension Apps,
• Command Handlers and Event handlers of Functional Blocks
To invoke the Remote Command, you use standard SendCommand/CallCommand APIs and address the
invocation to the class that you build in the IRemoteCommand interface.
Starting from the previous implementation example, follow this example to properly call the Remote Command
(where CreateMaterialTrackingUnit is the class that implements the IRemoteCommand interface):

var result = platform.CallCommand<CreateMaterialTrackingUnit,


CreateMaterialTrackingUnit.Response>(new CreateMaterialTrackingUnit() { /*Set the
properties here*/ });

When you are invoking a remote command from a SendCommand/CallCommand method, take into account the
following information about how to handle errors:

Error Type Expected Behavior

Invalid App Name Each remote command must be specified along with its name. If you have specified
a wrong app name, an exception of type UnifiedDiscoveryServiceException is
raised.

Invalid App version Each remote command must be specified along with its version. If you have
specified a wrong app version, a warning message is traced with the Event Tracing
for Windows with the Siemens-SimaticIT-Trace-DiscoveryService provider
enabled. In this case, the Remote Command will be invoked anyway.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 137


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Error Type Expected Behavior

Invalid Command The remote command must be constructed by specifying the exact command name
contract and parameters names and types. If this is not done, an error is returned where the
IsSucceeded boolean is false and in the error object you will find an error code 6404
with the related error message.

Missing mandatory The remote command must be constructed by specifying the exact parameters
parameters (name, type and value). If this is not done, an error is returned where the
IsSucceeded boolean is false and in the error object you will find an error code 6400
with the related error message.

Invalid Response The remote command must be constructed by specifying also the exact return type.
If this is not done, an error is returned where the IsSucceeded boolean is false and
in the error object you will find an error code 6500 with the related error message.

 For diagnostics purposes, you can use the ITracer functionalities: remote invocations propagate the
CorrelationID to the called remote commands (for more information, see Grouping Correlated Messages).
A dedicated trace provider is available to log operations executed by the Discovery Service (Siemens-
SimaticIT-Trace-DiscoveryService). See Choosing Trace Providers.

 Remote commands are always out of transaction. This means that, in case of error, no rollback is
automatically performed.
For this reason, we recommend that you use them in a non-transactional context (e.g. in Composite
commands), or in any situation where:
• it is not required an atomic execution of the involved business logic;
• it is possible to deal with the scenario where the same remote call is invoked more than once due to
the retry mechanism of a command handler execution in case of commit failure.
In future implementations, Foundation will provide compensation logics that are now in charge of the
user.
Compensation logic, which is now under the user responsibility, are planned for future implementations.

2.1.3.4.2 How to Manage Remote Entity Queries


To implement the Service Apps model, let's see now how to implement a remote query invocation.
Similarly to the Remote Commands, this approach is achieved by means of an internal discovery service and a
dedicated interface (IRemoteEntity).

Workflow

138 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

To enrich your solution with queries on remote entities, go through the following steps:
1. Create or enrich the Remote Artifact project.
2. Create a new class implementing IRemoteEntity.
3. Query your remote Entity.

Creating the new Remote Artifacts Project


Create a new Remote Artifacts project as follows or open the existing one and go to step 6:
1. In Project Studio, inside the solution that will contain the remote invocation/query, add a new Visual C# type
project.
2. Name the project as follows: <Functional Block/App/ExtensionApp Name>.RemoteArtifacts.
3. Inside this project, add a reference to the %SITUnifiedSystemRoot%bin\SimaticIT.Unified.Common dll.
4. Then, create a folder for each Remote App you want to communicate to.
5. Name each new folder by the short name of the remote App to be invoked (e.g. if the app zip name is
Siemens.SimaticIT.MaterialV04.01.00.zip, then the folder name will be Material).
6. Inside each new folder, create as many C# classes as required by the number of the remote Entities you will
query on, defining each class in a dedicated .cs file. These classes will implement the IRemoteEntity
interface as described in the dedicated topic.
7. If the target entities contain complex type properties whose values you want to be returned, such as Value
Types or Enumeration Types, create as many C# classes / enums, respectively, as the existing types, defining
each class in a dedicated .cs file (examples are provided). For more information on Entity properties,
see Adding Properties to Entities and Other Artifacts.

Implementing IRemoteEntity class


To perform a remote query, you need to implement a new class of IRemoteEntity type inside the invoking App/
Functional Block/Extended App.
The IRemoteEntity interface is designed to implement remote queries to external Apps without using binary
references inside the project.
From the Handlers that can access the GetRemoteEntities API (see details below), you can remotely query Entities
that have been published inside the Public Object Model of a different App or Extension App (thus if they are Public
Entities).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 139


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 Remember: An Entity can be remotely queried only if it belongs to the Public Object Model of an App/
Extension App.

To explain how remote queries must be implemented, let's introduce two terms: the Target Entity and the Remote
Entity.
• With Target Entity we will refer to the Entity that actually models the needed information, which must be
present in the Public Model of a certain App.
• With Remote Entity we will refer to a new wrapper class, namely implementing
the IRemoteEntity interface, which must be built on the basis of the Target Entity data structure and is
internally used to find the Target Entity.
To properly implement the new class, you must know in advance the structure of the Target Entity. Remember that
no intellisense is provided.
The IRemoteEntity interface requires a set of information (such as app name, app version and entity name) that is
used by an internal discovery service to run the query by means of the correct entity. Additionally, you must also
specify the entity properties that you want to be filled in with the related query results.

 Remember: To correctly build a Remote Entity you must know how the Target Entity is modeled, but
unlike remote commands (for which an exact mapping between target and remote command parameters
is required) here you only need to declare the properties whose values you want to retrieve.

 (*) The service version is a mandatory parameter. If, at runtime, the discovery service does not find the
precise version, it selects the version of the actually deployed app.

140 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Adapt the following example to properly implement an IRemoteEntity class and declare only the properties whose
values you want to retrieve (i.e. not necessarily all values that have been defined at target entity level:

public class MaterialTrackingUnit : IRemoteEntity


{
public MaterialTrackingUnit()
{
ServiceName = "Material;
ServiceVersion = "04.01.00";
EntityName = "MaterialTrackingUnit";
}

public string ServiceName { get; internal set; }

public string ServiceVersion { get; internal set; }

public string EntityName { get; internal set; }

// Custom entity properties


public string NId { get; set; }

public string Name { get; set; }

public string Description { get; set; }

public MTUCodeType CodeType { get; set; }

public QuantityType Quantity { get; set; }

public string MaterialNId { get; set; }

public string MaterialRevision { get; set; }

public string MaterialUId { get; set; }

public string EquipmentNId { get; set; }

public string TemplateNId { get; set; }

public string Code { get; set; }

public Guid MaterialLot_Id { get; set; }

public Guid MaterialTrackingUnitAggregate_Id { get; set; }

public StatusType Status { get; set; }


}

Value Type class declaration


Detail of the Quantity property in the Remote Entity class. We suggest that you create a dedicated .cs file to define
the Quantity Value Type.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 141


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

public class QuantityType


{
public string UoMNId { get; set; }
public decimal? QuantityValue { get; set; }
}

Detail of the StatusType property in the Remote Entity class. We suggest that you create a dedicated .cs file to
define the StatusType Value Type.

public class StatusType


{
public string StateMachineNId { get; set; }
public string StatusNId { get; set; }
}

Enumeration Type class declaration


Detail of the MTUCodeType property in the Remote Entity class. We suggest that you create a dedicated .cs file to
define the MTUCodeType enumeration type.

public enum MTUCodeType


{
None = -1,
BatchId = 0,
SerialNumber = 1
}

Type Alias properties


In case of Type Alias parameters, you have to directly use the data type to which the Alias refers, without creating
any dedicated class. For example, if the target Entity has a Description property defined as a Type Alias of string
type, in the IRemoteEntity you only need to define a Description property of string type.

Querying remote entities


To invoke the query on the remote entity, you can adapt the following GetRemoteEntities API example.
The GetRemoteEntities API is available in the Handlers of the following artifacts: Commands, Composite
Commands, Pre-Checks, Post-Actions and Event Handlers (i.e. everywhere except for Reading Functions and
SDKLean).
The GetRemoteEntities API accepts in input the filter parameter (optional) which can be used to refine the query
before its execution. To properly use this parameter, you must specify a Dictionary with the following accepted
OData query options:

142 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• $filter, used to specify a filtering where clause, for example: { "filter", "Name eq 'Matxx'"},
• $orderby, used to order the returned data, such as for example in ascending or descending mode, for example:
{ "orderby", "Name desc"},
• $top, used to return only the specified number of records, for example: { "top", "10"},
• $skip, used in conjunction with the top option to paginate data records, for example: { "skip", "10"}.

// The filter parameters are accepted both with $ and without;


// accepted filter params are "$filter", "$orderby", "$top", "$skip"

Dictionary<string, string> filter = new Dictionary<string, string>


{
{ "orderby", "Name desc"},
{ "top", "10"}
};

var entities = Platform.GetRemoteEntities<MaterialTrackingUnit>(filter);

Unlike the remote command invocations, for which you have a Response class that returns information related to
the command execution and the execution error, the GetRemotEntities method returns either an IQueryable type
of the entity you have specified, or throws an exception (UnifiedRemotingException). This exception does not
invalidate the Handler execution.

2.1.3.5 How to Implement Event Handlers


Workflow
The minimum workflow to be followed to implement event handlers is as follows:
1. Import Event Handlers.
2. Write the business logic.
3. Configure the Event Handler reliability.
4. Debug your code inside Event Handlers.

2.1.3.5.1 Importing Event Handlers


Event handlers contain the business logic that will be executed when the event to which your handler has
been subscribed is raised.
You must insert the code describing this logic in the class corresponding to the modeled event. This class, which
you can import through a wizard, is made up of two partial classes that are contained in two separate files. Only
the <EventName>Handler.cs file must be modified.
Unlike command handlers, for which you must have a one-to-one relationship with the command, you can have
more event handlers for the same event, because you can associate several handlers to the same event inside
different event subscriptions.
In order to write your code, you must import the template classes into your Event Handler project.

 If an event handler is removed from the model, you must manually delete the corresponding C# class,
otherwise it will be included in the App manifest.

Prerequisite

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 143


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The event handler has been created.

Importing the C# class (or multiple C# classes) of the event handler


After you have compiled the Model project at the end of the event modeling phase, import the required .cs files,
with the relative manifest and .dll files, as follows:
1. Right-click the EventHandler project and select Import from the Model.
2. Select the event handler you just created and click OK.
3. Expand the folder structure of the EventHandler project and open the <EventNameHandler>.cs file.

Adding references to develop custom event handlers


If you want to implement code inside a custom event handler (which is an additional handler that can be
created with a custom name during the modeling phase) and this custom event handler has been generated for a
referenced event, you must also manually add a file reference to the assembly file containing the definition of
source event (<Prefix>.<FunctionalBlockName><DomainAcronym>Model.Events.dll).
This assembly can be found in %SITUnifiedSystemData%\Engineering\Dev\ModelBin if you have
already referenced the functional block.

Manually adding event handlers to the project


In some cases, for example if a .cs file has been removed by mistake, it is useful to manually add event handler
templates to your project instead of using the import functionality:
1. Expand the event handler project.
2. Right-click on the Events sub-folder and select Add > Existing Item.
3. Browse to the .cs files that you want to use in your project (for example,
MyProject.RFModel\bin\Debug\MyProject.RFModel\Events).

 The manual procedure must not be used as an alternative to the Import from Model command, as when
event handlers are added manually it will then also be necessary to manually import the relative manifest
and .dll files.

Comparing operations available inside command and event handlers


The following table compares the operations that you can execute from the code of a command and of an event
handler.

Operation Type Command Event


Handler Handler

Read data from write model, if the entity is inside the same domain

Read data from write model, if the entity is inside another domain

Read data from read model, if the entity is inside the same domain

Read data from read model, if the entity is inside another domain

Read data from read model, if the entity is from a user domain

144 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Operation Type Command Event


Handler Handler

Read data from archived entities

Write data (create, update, delete entity instance), if the domain of the entity (if
and the domain of the command/event are the same and the Functional the entity is not
Blocks are different. restricted)

Write data (create, update, delete entity instance), if the domain of the entity
and the domain of the command/event are different

Write data (create, update, delete entity instance), if the entity belongs to a
user domain

Call published in role commands (synchronously/asynchronously)

Call private commands (synchronously/asynchronously)

Call remote commands (synchronously/asynchronously)

Get remote entities

Invoke reading functions

Read from Automation entities

Write on Automation entities

Trigger events

Subscribe to events

Write trace logs

Access to the current user identity (Principal property)

Send messages to Opcenter Connect MOM

Get data segregation session information

Examples
The event handler below implements the code for an event, defined as follows:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 145


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Event Command Name Parameter

MyEvent Input: InfoParameter1 (string)

Input: InfoParameter2 (string)

Event Handler Execute() method (not to be modified)

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified.Lean;
[...]

namespace MyDomain.MySubDomain
{
/// <summary>
/// Class initialize
/// </summary>
public partial class MyEventHandlerShell : IEventHandler
{
private IUnifiedSdkEvent Platform;

/// <summary>
/// Execute
/// </summary>
/// <param name="unifiedSdk"></param>
/// <param name="evt"></param>
/// <param name="envelope"></param>
/// <returns></returns>
public void Execute(IUnifiedSdkEvent unifiedSdk, IEvent evt, EventEnvelope
envelope)
{
this.Platform = unifiedSdk;
MyEventHandler((MyEvent)evt, envelope);
}
/// <summary>
/// Retrieve the type of the event
/// </summary>
public System.Type GetEventType()
{
return typeof(MyEvent);
}
}
}

146 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Event Handler Implementation

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Handler;
using Siemens.SimaticIT.Unified.Lean;
[...]

namespace MyDomain.MySubDomain
{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.Event)]
public partial class MyEventHandlerShell
{
/// <summary>
/// This is the Event handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="evt"></param>
/// <param name="envelope"></param>
/// <returns></returns>
[HandlerEntryPoint]
private void MyEventHandler(MyEvent evt, EventEnvelope envelope)
{
// Put your code before the CallCommand
MyOtherCommand.Response res = Platform.CallCommand<MyOtherCommand,
MyOtherCommand.Response>(new MyOtherCommand { ParamOfMyOtherCommand =
command.InfoParameter1 });
var localVariable = res.OutputParamOfMyOtherCommand;
// Put your code after the CallCommand

Platform.Tracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",

Siemens.SimaticIT.SDK.Diagnostics.Common.Category.Informational,
"My local variable value is {0}",
localVariable);
}
}
}

2.1.3.5.2 Configuring Reliable Event Handlers


The communication infrastructure offers a reliable mechanism for handling Events based on the acknowledgement
that the Platform returns when the execution of an Event Handler is completed.
In the same way as Commands are unqueued from the Manufacturing Service Bus only after the related Command
Handler has returned a successful response, Events can be also definitively removed from the Bus only after an
acknowledgement of complete execution is returned.
The acknowledgment can be notified either at the beginning or at the end of the Event Handler execution.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 147


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

This second option offers a higher communication reliability than the first, because if the host of the worker process
fails, this option ensures a retry execution of the Event Handler.
Since events are used as a decoupling mechanism for the business logic (i.e. there is no response sent to the
sender), the Platform considers completed those Event Handlers that fail for unhandled exceptions. Only
infrastructure failures are covered for reliability. User code that raises exceptions during the processing should be
fixed in order to avoid losing data.
If you use the IUnifiedSdkLean interface to subscribe to an event, you can set the acknowledgement mode of the
executed callback code within the Subscribe method signature by choosing a deferred acknowledgement
(acknowledgment notified after a successful callback execution) instead of an immediate acknowledgement
(delivered at the beginning of the callback execution).
If you use the Solution Studio standard subscription functionality, you can leverage a similar behavior by setting the
IsReliable attribute in Project Studio.
The IsReliable attribute modifies the mechanism of the execution acknowledgment for the Event Handlers and
consequently the moment in which Events are completely handled.
Be aware that the use of the IUnifiedSdkLean interface with multiple user callbacks, which are subscribed to the
same event, does not prevent these callbacks from being re-executed if a failure occurs in between.
On the other hand, if you configure the IsReliable attribute on events that are subscribed to multiple Event
Handlers inside workers, the Platform correctly manages the Event Handlers as follows: the completed Event
Handlers are not re-executed if they have been completed before the failure, while Event Handlers that abort during
the failure are re-executed from the beginning (see note below).

Implementation note about Reliable Handlers


In case of failure, it is worth noticing that an Event Handler, which is configured as reliable, might have already been
partially executed and since it does not open or concur to any transaction, it is not rolled back. Consequently, an
Event Handler could potentially be executed more than once for the same event. Thus we strongly recommend you
write the Handler code respecting the idem-potency principle.
For more information on the failure management of event handlers, see Parallel vs. Sequential Command and
Event Handler Execution.

Setting the IsReliable option


1. Select the Event from the Model Explorer pane.
2. In the Model Design pane, click the Details tab and select the Event Handler.
3. Do either of the following:
• in the Model Details pane, select the IsReliable check box
• in the Properties pane, set the IsReliable option to True (available only in Functional Blocks).

2.1.3.5.3 Raising Events


You can raise events from the code of command handlers, event handlers and third-party applications through the
following interfaces:

148 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• IUnfiedSdk for command handlers


• IUnifiedSdkEvent for event handlers
• IUnifiedSdkLean for third-party applications.
You can raise events in two modes:
• immediately, if you call the FireEvent method
• at the end of a successful transaction, if you call the FireEventOnCommit method (available only from
IUnifiedSdk interface).
As for command invocation generic methods, you can specify the properties to be used to initialize the event class:

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
[...]

var materialDefinitionEvent = new OnMaterialDefinitionCreated() { Code =


command.Code};
Platform.FireEvent(materialDefinitionEvent);

 You should not modify the event and the envelope to be sent after you have called the FireEvent/
FireEventOnCommit methods, because these changes could modify the payload of the triggered event.
This could happen, for example, if you send multiple events using a loop and if you re-use the same event
and envelope class instances to specify different values. See code examples for the IUnifiedSdk Interface of
the Opcenter Execution Foundation Platform Reference Online Help.

Event validation
When you raise an event, you do not receive any response from the subscriber, apart from a successful reply when
the message arrives at the Manufacturing Service Bus.
If you set validation attributes on the event parameters, when you fire an event the provided values will be
validated accordingly (as it happens for commands). A failure in this validation will return an execution
fail (i.e. System.ComponentModel.DataAnnotations.ValidationException).

Event envelope
The FireEvent method and the FireEventOnCommit method contain an optional input parameter, the envelope
parameter, which defines the properties of the event instance.
When you raise the event, you can specify the event instance you are firing through the properties of the envelope
object, which is described by the EventEnvelope Class of the Opcenter Execution Foundation Platform Reference
Online Help.
The envelope object properties can be used to filter on events by setting filters at event subscription level.

Examples

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 149


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
[...]

//example 1 of FireEvent call with envelope


EventEnvelope newEnvelope = new EventEnvelope() { Category = "INFO" };
Platform.FireEvent(evt, newEnvelope);
Console.WriteLine("Event fired and going to execute its handler");

//example 2 of FireEvent call with envelope


VehicleMoved v = new VehicleMoved();
v.VehicleCode = myVehicle.Code;
EventEnvelope vehicleInfo = new EventEnvelope { Category = "Production", Tag =
"Automotive" };
Platform.FireEvent(v, vehicleInfo);

2.1.3.6 How to Manage Entity Instances


The following topics describe how to write the code which is necessary to execute the following (write) operations
on entities:
• Instantiating entity interfaces (creating or updating)
• Deleting entity instances
• Adding and Removing Navigation Properties
• Managing lifecycles of entity instances
• Managing revisions of entity instances
• Instantiating extended entities
• Copying entities
• Creating facet instances
• Using the bulk insert or the bulk import methods
• Attaching documents to entities
• Creating Associations Among Entities
• Creating Associations Among Entities
• Using Type Aliases
• Handling the CommittedEvent
• Managing the Event Store
• Using Reference Value Type Properties

As far as reading operations are concerned, see:


• Using the Query Methods and the Data Model Assemblies
• Querying on Referenced Entities
• Troubleshooting Parallel Query Execution Commands
• Managing Remote Entity Queries

2.1.3.6.1 Creating and Updating Entity Instances via Submit method


From the command handler code you cannot directly create entities (i.e. tables in the database), but you can
create, update or delete entity instances (i.e. the rows of the tables that correspond to the modeled entities).
The way you perform these operations depends on whether editing is restricted or not for the entity in question:

150 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• If editing is restricted you can create, update or delete instances of entities only by using the commands from
the same Functional Block as the entity.
• If editing is not restricted you can create, update or delete instances of entities with commands from different
Functional Blocks, as long as both Functional Blocks belong to the same domain.

 The Restricted flag is set to true by default when the entity is created, but can be modified during the
creation phase.

To instantiate entities you can only use the platform Create method. If you use standard C# instantiation methods,
the command execution will return an error.
To create an entity instance, you must work with the Opcenter Execution Foundation writing model, which is
exposed through the entity interfaces. Consequently, you have to call the Create method by specifying the interface
type (an underlying class instance will be generated, see TypeMapper).

 You can retrieve the interface type through the RetrieveQueryTargetType method, and providing as an
input parameter either the logical name used in Project Studio for the entity (<namespace>.<entity-
name>) or the full interface name (<namesapce>.<interface-name>).

After the Create method, you can manipulate the entity instance and then call the Submit method in order to
persist the entity on the database. This method submits the entity instance to the command handler context and
makes it available to the other commands of the same transaction. The Submit method persists the specified entity
along with all the entities present in the graph to which the specified entity belongs (i.e. if you submit an entity and
its forward and/or backward navigation properties point to other entities, they will be persisted, too). The
submitted entities will be visible outside the transaction after the commit operation, which is implicitly performed
after the end of each root command. Bear in mind that when removing a child from a parent, the graph of the
parent entity will no longer have any references to the child. Since the information about the link between children
and parents is persisted on the database within the children records, it is necessary to submit the child explicitly
(for examples, see Adding and Removing Navigation Properties).
To read from the just created instance, you can use the Query method, which reads only from the writing model,
inside the transaction, inside the same domain. If you try to do the same with the ProjectionQuery method, you
cannot retrieve any data from the just created instance.
The Create method has an override method which allows you to create multiple instances at the same time. It
accepts in input the interface type and the number of instances you want to create, and returns a list of IEntity
types. This list of IEntity types can be passed in input to the bulk insert method for multiple entity creation.
When you update an entity instance through the Submit method, Opcenter Execution Foundation updates the row
version within the database and updates the cache of the command (i.e. the chain of commands that refer to a root
command). The row version is internally used for data integrity check in optimistic concurrency while the cache
allows you to execute quick queries without querying the database. For this reason, the cache is also refreshed with
the data returned by the GetEntity method each time you invoke it (see the Opcenter Execution
Foundation Platform Reference Online Help). The GetEntity public method is provided with two overload methods:
the first method accepts in input the Id of an entity instance and it should be used each time you want to perform a
query by Id, the second method accepts in input the entity logical key. Both methods search first inside the cache
and then, only if no results are found, inside the database.

Creating an entity instance


This example shows how you can create an instance of the UoMCategory entity by means of the
CreateUoMCategory command defined as follows:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 151


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Name Parameter Description

CreateUoMCategory Input: NId (string) Natural key identifier. This property is flagged
as a LogicalKey, so if another UomCategory
with the same NId is already present, the
creation operation will fail.

Input: Name (string) The name assigned to the UoM category

Input: Description (string) Additional information on the UoM category

Output: UoMCategoryId Primary key of the new UoM category


(Guid)

CreateUoMCategory command handler example

using Siemens.SimaticIT.Handler;
using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
[...]

/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HandlerEntryPoint]
private CreateUoMCategory.Response CreateUoMCategoryHandler(CreateUoMCategory
command)
{
IUoMCategory uomCategory =
Platform.Query<IUoMCategory>().SingleOrDefault(x => x.NId == command.NId);
if (uomCategory != null)
{
return new CreateUoMCategory.Response{ Error = new ExecutionError(-1,
"already exists") };
}
uomCategory = Platform.Create<IUoMCategory>();
uomCategory.NId = command.NId;
uomCategory.Name = command.Name;
uomCategory.Description = command.Description;
Platform.Submit(uomCategory);
return new CreateUoMCategory.Response { UoMCategoryId = uomCategory.Id };
}

Updating an entity instance

152 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

This example shows how you can update an instance of the UoMCategory entity by means of
the UpdateUoMCategory command defined as follows:

Command Name Parameter Description

UpdateUoMCategory Input: Id (Guid) Primary key of the UoM category to be


updated.

Input: Name (string) The name assigned to the UoM category

Input: Description (string) Additional information on the UoM category

Output not required

UpdateUoMCategory command handler example

using Siemens.SimaticIT.Handler;
using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
[...]

/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HandlerEntryPoint]
private UpdateUoMCategory.Response UpdateUoMCategoryHandler(UpdateUoMCategory
command)
{
IUoMCategory uomCategory =
Platform.Query<IUoMCategory>().SingleOrDefault(x => x.Id == command.Id);
if (uomCategory == null)
{
return new UpdateUoMCategory.Response { Error = new
ExecutionError(-1, "does not exist") };
}
if (command.Name != null)
{
uomCategory.Name = command.Name;
}
if (command.Description != null)
{
uomCategory.Description = command.Description;
}
Platform.Submit(uomCategory);
return new UpdateUoMCategory.Response();
}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 153


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.6.2 Deleting Entity Instances via Delete and Bulk Delete


You can delete entity instances by using the following Opcenter Execution Foundation public methods: Delete and
BulkDelete.
The method used may depend on the life cycle or revision of the entity.
Entities deleted by both the Delete and BulkDelete method are included in the payload of the CommittedEvent.

Using the Delete method


To use the Delete method you must query the database for entities that correspond to the specified requirements.
The delete method can then be used to delete each single instance, one at a time, and is consequently appropriate
when you must delete only one entity instance.
If you have more than one instance, or if you already have the Id of the instance to be deleted, the BulkDelete
method is highly recommended for performance issues.

Using the BulkDelete method


The BulkDelete method uses the type and Id of the entities to be deleted. Once you have retrieved the Ids of the
entities of to be deleted, you can pass these Ids singularly or in a list as an input parameter for the method. The Ids
can be directly passed in by means of a LINQ query expression.
The BulkDelete is also provided with an overload method, which uses the type and the logical keys of the entities to
be deleted. The list of entity logical keys can be directly passed in by means of a LINQ query expression.
This method is much faster than the previous Delete when more than one instance must be deleted, as only a single
round-trip is required on the database.
The method simply deletes all the entities it finds, and does not return an error if it does not find all or any of the
indicated entities.

 For code examples, see Delete and BulkDelete methods in the Opcenter Execution Foundation Platform
Reference Online Help.

 Deleting extended entities


In case of extended entities, both methods execute the deletion according to the following rules:
• If an entity is extended with facets, all the related facets will also be deleted.
• If an entity is extended physically, the methods will delete all the instances that correspond to the
specified Id and entity type, regardless of the hierarchy level.

2.1.3.6.3 Adding and Removing Navigation Properties


You can add or remove entity instances that are linked with one-to-many and many-to-many relationships,
including segregation tags, as shown in the following pages:
• Managing one-to-many relationships
• Managing many-to-many relationships

2.1.3.6.3.1 Managing One-to-Many Relationships


You can manage one-to-many relationships both from the entity child side as well as from the entity parent side.

154 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

If you query on the child side, the query will be faster because the related item will be always only one (see
section Adding an entity by using back-navigation properties below).

 To remove relationships, you cannot use the Clear method. Use either of the Remove method as shown
below.

Adding an entity by using forward-navigation properties


If you want to link a child entity to a parent entity by using a forward-navigation property, you can use the following
snippet of code:

var myParent = Platform.Query<IParent>().Single(x => x.Name == “MyParent1”);


var myChild = Platform.Create<IChild>();
myChild.Name = “MyChild1”;
myChild.ParentNav = myParent;
Platform.Submit(myChild);

If you know the Id of the parent entity, you can use “myChild.ParentNav_Id = myParent.Id;" instead of
“myChild.ParentNav = myParent;”. This latter way is faster because you do not need to Query the parent.
If the parent entity has a back-navigation property towards its children, the back-navigation property is
automatically aligned when executing “myChild.ParentNav = myParent;” and so, even if you replace
“Platform.Submit(myChild);” with “Platform.Submit(myParent);” you reach the same goal because the parent
entity represents a graph containing its children (that will be submitted together with the parent).

Adding an entity by using back-navigation properties


If the relation between the involved entities has been configured to expose a back-navigation property and you
want to link a child entity to a parent entity by using a back-navigation property, you can use the following snippet
of code:

var myParent = Platform.Query<IParent>().Include("ChildrenBackNav").Single(x =>


x.Name == “MyParent1”);
var myChild = Platform.Create<IChild>();
myChild.Name = “MyChild1”;
myParent.ChildrenBackNav.Add(myChild);
Platform.Submit(myParent);

Here the Submit method submits both the parent and the child because the Submit method submits all the entities
belonging to the graph which is passed as argument to the method; indeed, the parent entity, which is passed to
the Submit method, has a link to the child entity (through the back-navigation property).

Removing an entity by using forward-navigation properties


To remove an entity by using forward-navigation properties, you can use the following snippet of code:

var myChild = Platform.Query<IChild>().Include("ParentNav").Single(x =>


x.Name == “myChild1”);
myChild.ParentNav = null;
Platform.Submit(myChild);

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 155


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Removing an entity by using backward-navigation properties


To remove an entity by using its backward-navigation property, you can write the following snippet of code:

var myParent = Platform.Query <IParent>().Include("ChildrenBackNav").Single(x=>


x.Name == “myParent1”);
var myparent = Platform.Query <IParent>().Single(x => x.Name == “myParent1”);
var myChild = myParent.ChildrenBackNav.Single(x => x.Name == “myChild1”);
myParent.ChildrenBackNav.Remove(myChild);
Platform.Submit(myChild);

Note that if we had written "Platform.Submit(myParent);" instead of "Platform.Submit(myChild);" we would have


not submitted the child because if you call the Submit method on the parent entity, the parent that is passed to the
Submit method does not contain the child anymore (the link has been just removed). Consequently, the Submit
method cannot submit the child because the child is no longer part of the parent graph. To remove the child and its
parent you must in this case submit the child (and not the parent) because the link between the parent and its
children is actually written on the database inside the child.

Associating and removing facets


Facets and entities are linked by a One-To-Many association.
Association between entities and facets follows all the behaviors described in the previous paragraphs concerning
the associations between entities.
If you want to link a facet to a parent entity by using the backward-navigation property, you can use the following
snippet of code:

var myEntity = Platform.Query<IMyEntity>().Include("Facets").Single(x=> x.Name ==


"myEntity");
myEntity.Facets.Add(facet);

Platform.Submit(facet); // or Platform.Submit(myEntity);

If you want to link a facet to a parent entity by using the forward-navigation property, you can use the following
snippet of code:

var myFacet= Platform.Query<IMyEntityFacet>().Single(x=> x.Name == "myFacet");


var myEntity = Platform.Query<IMyEntity>().Single(x=> x.Name == "myEntity");

myFacet.MyEntity = myEntity; // or myFacet.MyEntity_Id = myEntity.Id;

Platform.Submit(facet);

If you remove a facet from an entity and then you submit the facet, the facet remains orphan (i.e. it can be linked to
another entity).
To remove a facet, you can write the following snippet of code:

156 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var myEntity1 = Platform.Query<IMyEntity>().Include("Facets").Single(x=> x.Name ==


"myEntity1");
var facet = myEntity1.Facets.Single(x => x.MyProp == "Test");
myEntity1.Facets.Remove(facet); // or facet.MyEntity = null;

Platform.Submit(facet);

// Here the facet is orphan


// We can do a further association:
var myEntity2 = Platform.Query<IMyEntity>().Include("Facets").Single(x=> x.Name ==
"myEntity2");
myEntity2.Facets.Add(facet); // or facet.MyEntity = myEntity2;

Platform.Submit(facet);

2.1.3.6.3.2 Managing Many-to-Many Relationships


You can add and remove many-to-many relationships by using two different modes: a slower mode, which uses the
Include method, and a faster mode, which uses a dedicated platform API.

 To remove relationships, you cannot use the Clear method. Use either of the removal methods as shown
below.

Adding a many-to-many relationship (slower method)


You can add many-to-many relationships with the Include method as follows:

var myUser1 = Platform.Query<IUser>().Single(x => x.Name == “MyUser1”);


var myUser2 = Platform.Query<IUser>().Single(x => x.Name == “MyUser2”);
var myTeam = Platform.Query<ITeam>().Include("Users").Single(x => x.Name ==
“MyTeam”);
myTeam.Users.Add(myUser1);
myTeam.Users.Add(myUser2);
Platform.Submit(myTeam);

Adding a many-to-many relationship (faster method)


You can manage many-to-many relationships (both forward and backward navigation properties) without querying
the related entities with the Include method, only if the entities to be linked are already present on the database. In
this case, you can use the AddManyToManyRelationship method as described in the following code snippet (see
also the Opcenter Execution Foundation Platform Reference Online Help).
Bear in mind that after using these methods, you must always query the involved entities before you can use their
instances for any other operations.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 157


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var myUser1 = Platform.Query<IUser>().Single(x => x.Name == “MyUser1”);


var myUser2 = Platform.Query<IUser>().Single(x => x.Name == “MyUser2”);
var myTeam = Platform.Query<ITeam>().Single(x => x.Name == “MyTeam”);
Platform.AddManyToManyRelationship(myTeam, x => x.Users, new List<IUser> { myUser1,
myUser2 });

Removing a many-to-many relationship (slower method)


You can remove many-to-many relationships as follows:

var myTeam = Platform.Query<ITeam>().Include("Users").Single(x => x.Name ==


“MyTeam”);
var myUser1 = myTeam.Users.Single(x => x.Name == "MyUser1");
myTeam.Users.Remove(myUser1);
Platform.Submit(myUser1);

Removing a many-to-many relationship (faster method)


You can remove many-to-many relationships (both forward and backward navigation properties) without querying
the related entities with the Include method, only if the entities to be removed are already present on the database.
In this case, you can use the RemoveManyToManyRelationship method as described in the following code snippet.

var myTeam = Platform.Query<ITeam>().Single(x => x.Name == “MyTeam”);


var myUser1 = Platform.Query<IUser>().Single(x => x.Name == “MyUser1”);
Platform.RemoveManyToManyRelationship(myTeam, x => x.Users, new List<IUser>
{ myUser1 });

Adding or removing data segregation tags


You can add data segregation tags by adding a standard many-to-many relationship towards the required entity
instance.

var myTeam = platform.Create<ITeam>();


var segregationTag =
(Siemens.SimaticIT.SystemData.Foundation.DataModel.ISegregationTag)

platform.Query<Siemens.SimaticIT.SystemData.Foundation.DataModel.ProjectionModel.ISeg
regationTag>();
myTeam.SegregationTags.Add(segregationTag);
Platform.Submit(myTeam);

To remove data segregation tags you cannot use the Clear method. You can create a loop after materializing the
data segregation list as follows:

158 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var myTeam = Platform.Query<ITeam>().Include("Users").Single(x => x.Name


== “MyTeam”);
foreach (var user in Users)
{
myTeam.Users.Remove(user);
}
Platform.Submit(myTeam);

2.1.3.6.4 Managing Life Cycle Attributes of Entity Instances


You can manage the life cycle of entity instances through a set of system attributes that allow you to define which
operations can be performed on the entity instance.

Attribute Description

IsFrozen Frozen instances are visible in the database and can be queried and deleted
but cannot be updated.
The IsFrozen attribute of Instances is set to true with the Opcenter EX
FN IUnifiedSdk Interface Freeze method and subsequently set to false if
necessary with the Unfreeze method.
The IsFrozen attribute is independent from the IsLocked and IsCurrent
properties, which are part of the Revision behavior.
The Freeze/Unfreeze methods are also provided with overload methods
which use the type and Id of the entities to be frozen/unfrozen. The Ids can be
directly passed in by means of a LINQ query expression as an input parameter
for the method. These methods are much faster than the Freeze/Unfreeze
methods which work on single instance, because only a single round-trip is
required on the database.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 159


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Attribute Description

IsDeleted Deleted instances are no longer visible and cannot be queried or modified, but
are present in the database.
The Opcenter EX FN IUnifiedSdk Interface Purge method can physically remove
all logically deleted instances, which were deleted prior to the date set in the
beforeDate property of the method.
The Purge method is domain specific, and cannot be used cross-domain.

 Info on Purge
• If a logically deleted entity is physically deleted with the Purge
method, all its related entities are also physically deleted,
regardless of the delete behavior specified in the relationship (e.g.
OnDeleteSetNull, OnDeleteNoAction or OnDeleteCascade).
• The Purge method is transactional on each single entity.
Consequently, a rollback operation will be performed only on the
instances of the entity for which the method failed or timed out.
• Indexes should be recreated after purging operations.
• When the IsDeleted attribute of an entity is greater than 0 (i.e.
true) the entity will not be visible or queryable in the database,
but this attribute will be used by the Purge method to physically
delete the entity from the database.

 Interaction between Purge and Archiving rules


• The Purge method does not check whether the Maintenance
Archiving Rules have been configured or not. The data will be
removed regardless of whether it have already been archived or
not.

ToBeCleaned Instances marked for cleaning are still visible but cannot be modified or
deleted, until they are eventually physically removed by the maintenance.
The user can set the ToBeCleaned flag according to their maintenance policy,
using the MarkForCleaning method of the Opcenter EX FN IUnifiedSdk
Interface.
The MarkForCleaning method is limited to Master Data Domain and
Operational Data Domain.
The BulkMarkForCleaning method uses the type and Id of the entities to be
marked for cleaning. The Ids can be directly passed in by means of a LINQ
query expression as an input parameter for the method. This method is much
faster than the MarkForCleaning method which works on single instance,
because only a single round-trip is required on the database.

Available operations

160 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Attribute Value Can submit Can logically Can purge Can mark Can copy
delete for
cleaning

IsFrozen true

IsFrozen false

IsDeleted 0 (false)

IsDeleted >0 (true)

IsLocked true

IsLocked false

ToBeCleaned true

 The operation is never possible on instances with the attribute set as specified.

The operation may be possible on instances with the attribute set as specified, if no other attributes in
this table prevent it.
The operation is possible but has no effects.

Attribute inheritance
The attributes are inherited according to the following logic:

Element Inherits Attribute Notes

Facet instances As facet instances are intrinsically linked to the


root entity instance, you cannot delete the facet of
an entity when IsFrozen = true or ToBeCleaned =
true, as this would be considered an update of the
root entity instance.

Derived entity instances Derived entity instances are not linked to the root
entity and IsFrozen, IsDeleted and ToBeCleaned
attributes are not inherited from any entity.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 161


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Element Inherits Attribute Notes

Entities in Composition Propagation proceeds through the hierarchy from


parent to child entities, so the IsFrozen, IsDeleted
and ToBeCleaned attributes of the composite
entity are inherited by the part entities, but if you
modify a part entity the composite entity will not
be modified.
If the IsFrozen attribute of the composite entity is
true you cannot add or remove part entities.
If the ToBeCleaned attribute of the composite
entity is true, you cannot add or remove part
entities.

 When a composite entity instance is


frozen/unfrozen, the row version of its
part entity instances is not automatically
updated (as happens for
the Submit method). Consequently, if
you need to submit an updated part
entity instance directly after freezing/
unfreezing its composite entity, you must
first re-query the part entity instance you
want to modify.

Entities in Relationships The IsFrozen attribute is never inherited.


The IsDeleted attribute is inherited when the
OnDeleteCascade option has been chosen for the
relationship. In this case all related entities are
also logically deleted.

The ToBeCleaned attribute is never inherited.


Instances at the One end of a relationship will be
physically deleted only when all instances at the
Many end have been physically deleted.

2.1.3.6.5 Managing Revisions of Entity Instances


One of the behaviors that can be assigned to entities is the Revision behavior.
This behavior allows the user to decide when a specific revision of an entity must be used.
The flag is set when creating the entity but can also be modified in the Properties pane in Project Studio.

Constraints
• The entity must belong to the Master Data domain.
• The entity must be a base entity.
• You must assign a logical key to the entity. This check is carried out when the model is built.

162 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Revision Properties
When an entity is flagged as Revision four properties will be automatically added to the class of the entity when the
model is built.
These properties can only be modified by specific Opcenter EX FN Platform methods, exposed by the IUnifiedSdk
interface (for more information see the Opcenter Execution Foundation Platform Reference Online Help).

 The IsCurrent and IsLocked properties are independent from the IsFrozen attribute, which is part of the
entity life cycle attributes.
The IsLocked and IsCurrent properties can both be set to true for the same entity, consequently not
allowing any changes to be made to the current revision.

Property Data Type Description

Revision String Represents the identifier of the revision. It must be unique


for all instances of entities with the same logical key and
cannot be NULL.

SourceRevision String If you create a new revision by copying an existing revision,


using the Revision.AddNewRevision method, this property
will contain the Revision identifier of the base entity, from
which the instance was copied. The IsFrozen attribute is set
to false (0).
If you use the Copy method, passing a new logical key in the
properties of the method, the SourceRevision field is set to
null and its IsLocked and IsCurrent properties will be set to
false.

IsCurrent Boolean If IsCurrent is set to true, the selected entity instance is to


be considered the current revision. The instance can
however be deleted.
This boolean value can only be modified by the following
methods:
• Revision.SetCurrent
• Revision.UnsetCurrent
Only one (or no) entity instance, with the same logical key
(not considering the Revision identifier, which is part of the
logical key), can have the IsCurrent flag set to true. So if you
invoke the Revision.SetCurrent method to set the flag to
true on a new instance, the flag of the previous current
revision instance will automatically be set to false.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 163


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Property Data Type Description

IsLocked Boolean If IsLocked is set to true, the entity instance cannot be


modified or deleted, and you cannot add, remove or modify
its facets.
This value is propagated in a composition relationship.
However, when a composite entity instance is locked/
unlocked, the row version of its part entity instances is not
automatically updated (as happens for the Submit method).
Consequently, if you need to submit an updated part entity
instance directly after locking/unlocking its composite
entity, you must first requery the part entity instance you
want to modify.
This boolean value can only be modified by the following
methods:
• Revision.Lock
• Revision.Unlock
The BulkLock and BulkUnlock methods use the type and Id
of the entities to be locked/unlocked. The Ids can be directly
passed in by means of a LINQ query expression as an input
parameter for the method. These methods are much faster
than the Lock and Unlock methods which work on single
instance, because only a single round-trip is required on the
database.

Examples of use
The following is an example of the management of a Master Data entity, with the Revision behavior:
• Creating the MaterialDefinition entity
• Locking the MaterialDefinition entity
• Copying the MaterialDefinition entity
• Setting the MaterialDefinition entity to IsCurrent
Creating the MaterialDefinition entity

Id Name Revision SourceRevision IsCurrent IsLocked

F0001 MyMat RevA Null False False

164 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

///example of code meta language, where Id is the unique identifier of the single
instance

CreateMaterialDefinition(Id, Name, Revision)


{
var p = Platform.Create<IMaterialDefinition>();
p.Name = Name;
p.Revision = Revision;
p.Nid = Id;
Platform.Submit(p);
}

Locking the MaterialDefinition entity

Id Name Revision SourceRevision IsCurrent IsLocked

F0001 MyMat RevA Null False True

///example of code meta language, where Id is the unique identifier of the single
instance

LockMaterialDefinitionRevision(Id)
{
var p = Platform.Query<IMaterialDefinition>(x => x.Id == Id);
Platform.Revision.Lock(p)
}

Copying the MaterialDefinition entity

Id Name Revision SourceRevision IsCurrent IsLocked

F0001 MyMat RevA Null True/False True/False

F0001 MyMat RevB RevA False False

///example of code meta language, where Id is the unique identifier of the single
instance

CopyMaterialDefinitionRevision(Id,NewRevision)
{
Platform.Revision.AddNewRevision<IMaterialLot>(Id, NewRevision);
}

This AddNewRevision method copies all the properties as they are, changing only the SourceRevision and
Revision properties.
Setting the MaterialDefinition entity to IsCurrent

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 165


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Id Name Revision SourceRevision IsCurrent IsLocked

F0001 MyMat RevA Null False True/False

F0001 MyMat RevB RevA True False

///example of code meta language, where Id is the unique identifier of the single
instance

SetCurrentMaterialDefinition(Id)
{
var p = Platform.Query<IMaterialDefintion>(x->x.Id equals Id);
Platform.Revision.SetCurrent(p)
}

2.1.3.6.6 Creating Extended Entities and Using the TypeMapper


This topic describes how Opcenter Execution Foundation manages the creation of an entity instance, and more
specifically, the creation of an extended entity instance, once an entity or an extended entity has been modeled.
Moreover, the page explains the functionality of the TypeMapper, which allows you to manage entity types during
the creation of entities.

General rules on creating entity instances


The creation of entity instances depends whether editing restrictions were set or not for the entity when it was
created:
• If the Restricted flag is set to true, the creation of an entity must always be performed by the business-logic of
the commands inside the Functional Block to which the entity belongs. This is particularly evident with derived
entities (i.e. an entity extends another entity and inherits its properties) where the base entity belongs to
another Functional Block. In this scenario, you must create your extended entity instance by calling the
appropriate command of the Functional Block that contains the parent entity and the TypeMapper can be
configured to ensure the instance is created for the extended entity and not the base entity. This procedure is
recursive. Moreover, inside each Functional Block you can only set the properties that are not inherited from
external entities.
• If the Restricted flag is set to false, entity instances can be created directly from commands defined in other
Functional Blocks, as long as they belong to the same domain.

What is the TypeMapper


When you create an instance of an entity (e.g. a Lot) with the Create method of IUnifiedSdk interface, you specify
the corresponding interface type (e.g. ILot, that is the corresponding interface type).
The TypeMapper configuration drives the type created by the Create method.
When you specify the interface type in the Create method, the system creates an instance of a class implementing
the specified interface. But in order to do this, the system must also know which class must be instantiated if the
entity to be created has several extended (derived) entities. Indeed, the underlying instance may represent one of
the n entities which derive from the specified one.

166 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

If you consider the example of a data model containing Lot, ExtendedLot, ExtendedExtendedLot, and you call the
Create<ILot> method, the method can return an instance of Lot, ExtendedLot or ExtendedExtendedLot since they
all implement the ILot interface. The choice of the correct class is based on the TypeMapper and the instructions
defined by the user.

TypeMapper default behavior


The default mapping for the TypeMapper is 1 to 1 between the entity and the type.
This means that, if it is not differently configured, the TypeMapper instructs the Create command to return the
same entity as requested, i.e. when the method is called as Create<ILot> it will return a Lot instance.
When called as Create<IExtendedLot> it will return an ExtendedLot instance.
When called as Create<IExtendedExtendedLot> it will return an ExtendedExtendedLot instance.

TypeMapper customization
You can customize the default behavior of the TypeMapper by using two methods: RegisterMapping and
ResetMappings .
With the RegisterMapping method you can call the Create method on a certain entity and use it to actually create
the instance of another entity.
As an example, we may have EntityB that derives from EntityA.
RegisterMapping<IEntityA, IEntityB> modifies the TypeMapper behavior so that the Create method will return
an EntityB instance even if IEntityA was specified.
If you call the ResetMappings method you will remove all customizations that have been specified inside the
current command. In this way, you will return to the previously defined value, which could be either the default
configuration of the TypeMapper or the TypeMapper configuration that has been set in the caller command.
The configuration of the TypeMapper is always propagated to the sub-commands, if these are called.
The RegisterMapping<T, K> method has a non-generic corresponding method: RegisterMapping(type entityA,
type entityB) which works in the same way.

TypeMapper override behavior


When you have two subsequent mappings inside the same command chain that map a base entity to two
differently derived entities, if the second mapping is performed towards a less extended entity, the latter mapping
specification is ignored.
For example, if you call RegisterMapping<T,K1> and then you call, in the same command
chain, RegisterMapping<T,K2>, where K1 derives from K2, the mapping which should return K2 is ignored.
This behavior is useful when you have a nested chains of commands.

Example of creation of an extended entity


As an example, you may have the following data model developed in different layers (i.e. Functional Blocks):

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 167


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Product, Libraries and Project Functional Blocks define respectively Lot, ExtendedLot, ExtendedExtendedLot.
Libraries and Project extend the base entity by inheriting properties from the upper layer.
The following pseudo-code describes how to implement the entity creation:

CreateLotCommand
{
CreateInstanceOfLot.
SetLotProperties.
SubmitLot.
}

CreateExtendedLot
{
Call CreateLotCommand.
SetNonInheritedExtendedLotProperties.
SubmitExtendedLot.
}

CreateExtendedExtendedLot
{
Call CreateExtendedLotCommand.
SetNonInheritedExtendedExtendedLotProperties.
SubmitExtendedExtendedLot.
}

The command chain contained in this example demonstrates that only the command associated to the base entity
(Lot) actually creates the entity.

Code example
The following example shows how to use the TypeMapper to create an extended entity, using the create commands
of the base entity.
In this example:
• Lot has two properties: Name and Quantity.

168 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• ExtendedLot also has the property Description.


• ExtendedExtendedLot also has the property ExpirationDate.

[HandlerEntryPoint]
private CreateLot.Response CreateLotHandler(CreateLot command)
{
var lot = Platform.Create<ILot>();
lot.Name = command.LotName;
lot.Quantity = command.LotQuantity;

Platform.Submit(lot);

return new CreateLot.Response();


}

[HandlerEntryPoint]
private CreateExtendedLot.Response CreateExtendedLotHandler(CreateExtendedLot
command)
{
Platform.RegisterMapping<ILot, IExtendedLot>();
var lotId = Platform.CallCommand<CreateLot, CreateLot.Response>(new
CreateLot(command.Name, command.Quantity).Id;
var lot = Platform.GetEntity<IExtendedLot>(LotId);
lot.Description = command.Description;

Platform.Submit(lot);

return new CreateExtendedLot.Response();


}

[HandlerEntryPoint]
private CreateExtendedExtendedLot.Response
CreateExtendedExtendedLotHandler(CreateExtendedExtendedLot command)
{
Platform.RegisterMapping<ILot, IExtendedExtendedLot>();
var lotId = Platform.CallCommand<CreateExtendedLot,
CreateExtendedLot.Response>(new CreateExtendedLot(command.Name, command.Quantity,
command.Description).Id;
var lot = Platform.GetEntity<IExtendedExtendedLot>(LotId);
lot.ExpirationDate = command.ExpirationDate;

Platform.Submit(lot);

return new CreateExtendedExtendedLot.Response();


}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 169


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.6.7 Copying Entity Instances


Entity instances that have already been submitted can be copied, using the Copy method.
All the properties of the entity are also copied, including forward navigation properties, but not backward
navigation properties, consequently:
• If a child entity is copied, the reference to its original father entity is maintained (through its forward navigation
property).
• If a parent entity is copied, its children are not copied (as the backward navigation property is not copied, and
consequently the parent entity has no trace of its child entities).
This behavior is different if the entities are part of a composition relationship.

Copying unique properties


If the entity contains properties that have been tagged as Unique, the values of these properties must be modified
when the copy operation is used, otherwise the value would be copied and the unique constraint violated, causing
the operation to fail.
The Copy method offers a way to specify new values for selected properties in order to respect unique constraints,
through the propertyValuesSpecification parameter.

Copy method
The method returns the Id of the new entity:

NewEntityId = Copy(entityType, entityId, PropertyValuesSpecification)

Where:
• entityType is a C# type
• entityId is the Guid of the entity to be copied
• PropertyValuesSpecification type is created as an instance of a new Sdk class, which contains the name and
value of each property to be modified.
There is also a generic version of the Copy method with the following parameters:

NewEntityId = Copy<T>(Guid, PropertyValues)

Copying entity instances in composition relationships


Composition relationships allow you to copy the whole composition as a group.
The Copy operation is performed on the father composite entity, and a copy is created of:
• the composite entity
• its part entities
• forward and backward navigation properties.
The relationship between all the members of the composition relationship are maintained.
When you copy a composite entity you must specify a new logical key for the entity and a new value for any other
properties of the composite entity that have been tagged as Unique.

170 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The new logical key of the composite entity is then added to the logical key of its part entities as a foreign key. Since
the logical key of the composite entity is part of the unique contraint of each part entiy, there is no need to re-define
any unique values of the part entities.
If the copied part entity has navigation properties for relationships that do not belong to the composition, the link
to the orignal entities is maintained, but a new copy of the linked entities is not created.

 You cannot perform a Copy operation starting from the part entity in a composition relationship.

2.1.3.6.8 Creating Facet Instances


This topic describes how to create facet instances, link them to an entity, and remove them.

Example of model artifacts


Our code example starts from a Model Project containing an entity and its related facet extensions:

Artifact Example Property Type

MaterialDefinition (entity) NId String

Description String

TCMaterialReference (related facet extension) NId String

Description String

TCDesignator (related facet extension) NId String

Description String
You have a command (CreateMaterialDefinition) that will be used to create the entity instance and its facets.

Example code for creating facet instances


In the imported command handler class for the CreateMaterialDefinition command, you can specify values for the
facets, and then assign them to the required entity instance. For example, you can assign a facet to MaterialA and
another to MaterialB:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 171


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

/// WRITE OPERATIONS ON FACETS

public partial class CreateMaterialDefinitionHandlerShell


{
/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HandlerEntryPoint]
private CreateMaterialDefinition.Response
CreateMaterialDefinitionHandler(CreateMaterialDefinition command)
{
// Put your code here
// return new CreateMaterialDefinition.Response() { ... };

// Create entity "matDef1"


var matDef1= Platform.Create<IMaterialDefinition>();
matDef1.Description = "MaterialA";
matDef1.NId = "001";

// Create entity "matDef2"


var matDef2= Platform.Create<IMaterialDefinition>();
matDef2.Description = "MaterialB";
matDef2.NId = "002";

// Create facet "designator1"


var designator1 = Platform.Create<ITCDesignator>();
designator1.NId = "0234xxx";
designator1.Description = "Position";

// Create facet "designator2"


vardesignator2 = Platform.Create<ITCDesignator>();
designator2.NId = "08888xxx";
designator2.Description = "Position";

// Create facet "matref"


var matRef= Platform.Create<ITCMaterialReference>();
matRef.Nid = "6986987";
matRef.Description = "Location";

// Add facets to entities using backward-navigation properties


matDef1.Facets.Add(designator1);
matDef1.Facets.Add(matRef);
matDef2.Facets.Add(designator2);

// OR
// Add facets to entities using forward-navigation properties
// designator1.MaterialDefinition = matDef1;
// matRef.MaterialDefinition = matDef1;
// designator2.MaterialDefinition = matDef2;

172 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Platform.Submit(matDef1);
Platform.Submit(matDef2);

return new CreateMaterialDefinition.Response();


}
}

Reading from facets


You can execute read operations on facets as follows:

/// READ OPERATIONS ON FACETS

// Retrieve entity with all its facets


var readMatDef = Platform.Query<IMaterialDefinition>().Include("Facets").First(x =>
x.Description == "MaterialA");

// Retrieve a facet starting from a given entity


var readLibFacet = readMatDef.Facets.OfType<ITCDesignator>().Single();

// Retrieve a facet by its NId property


var readMatDefBis = Platform.Query<IMaterialDefinition>().Include("Facets").First(x
=> x.Facets.OfType<ITCMaterialReference>().Single().NId == "6986987");

// Retrieve a facet by its NId property and the foreign-key property to


MaterialDefinition entity
var myFacet = Platform.Query<ITCMaterialReference>().Single(x => x.NId == "6986987"
&& x.MaterialDefinition_Id == readMatDef.Id);

Removing facets
A facet is automatically deleted if you delete the entity to which the facet belong. If you want to delete a facet
manually, you can call the Delete method of the UnifiedSdk interface (e.g. Platform.Delete(myFacet)).

Querying facets from the Service Layer


You can run queries on facets in the same way as you run queries on related entities. All facets are related to the
parent entity through a standard navigation property. Consequently, when you call the ProjectionQuery method,
you can use the Include("Facets") extended method. From OData, you can use the Expand functionality.

2.1.3.6.9 Inserting Multiple Entity Instances via Bulk Insert and Bulk Import
You can insert multiple entity instances through the following methods, exposed by the IUnifiedSdk public
interface: BulkInsert and BulkImport.

BulkInsert method
The BulkInsert method can be invoked from a command handler (the method is transactional) but it is not
available for Lean applications (IUnifiedSdkLean) or from event handlers (IUnifiedSdkEvent interface) .
Unlike the Submit method, it does not execute update operations: it only inserts new entity instances.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 173


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The accepted input for the BulkInsert method is a list of IEntity types (List<IEntity>) as well as an option regarding
the operation type. The list of entities is returned by the override Create method. The options, which are applicable
only on MS SQL Server, allow you to choose between setting a table lock or a row lock during the bulk insert (see MS
SQL Server documentation for further explanations). A row lock is suitable if the system must keep running and
there are other actors who are writing on the destination tables; whereas a table lock is more appropriate if the
destination tables are used by concurrent bulk-inserts and there are no other actors writing on the destination
tables.
If you want to insert multiple objects that have relationships with other objects, the method first inserts all root-
level objects (i.e. the objects without parent entities) and then the objects that have dependencies with the already
inserted objects. During this operation, the method groups and inserts objects of the same type and then their
children (while the Submit method inserts each object and its related objects within the same workflow).
Consequently, it is particularly advantageous to use the BulkInsert method if you need to insert a considerable
number of instances of the same entity type with relationships with other entities. This operation can also be
performed when the root-level object is in Frozen status.
The method returns an error if you try to update an already existing root entity. If a child entity already exists, the
method skips it without returning any errors.
At the end of the BulkInsert operation, the CommittedEvent is fired with the following characteristics: the Tag
property of the envelope object (instance of EventEnvelope class) is set to Bulk and the return argument payload is
empty. To retrieve the event payload, specific methods are available (see CommittedEvent details).
After using the BulkInsert method, the row version of the entity instance is not automatically updated in the
command cache (in this same way as the Submit method). Consequently, if you need to submit an updated entity
instance directly after a BulkInsert, you must first requery the entity instance you want to modify.
The following code snippet shows a partial example of how to call the BulkInsert method. This example considers
that there is a back-navigation on the Material Class and consequently it is sufficient that you invoke the BulkInsert
on the IMatClass to automatically insert the linked Material Definitions.

BulkInsert method

var myMatClass = Platform.Create<IMatClass>();


myMatClass.Code = <any value>;
myMatClass.Name = <any value>;
for (int i = 0; i < NumberOfItems; i++)
{
var myMatDef = ctx.Create<IMatDef>();
myMatDef.Code = <any value>;
myMatDef.Name = <any value>;
myMatDef.Parent = myMatClass;
}
Platform.BulkInsert(new List<IEntity>() { myMatClass }, new BulkOptions { Lock =
LockType.RowLock });

174 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 Related and derived entities


If the BulkInsert method is used to insert entities that have cross-relationships with one another, the
following situations may occur:
• Case 1: The BulkInsert method cannot be directly used on entities that have a circular reference. For
example, if entity A has a navigation property towards B and entity B has a navigation property
towards A.
• Case 2: The BulkInsert method can be used if you split the logic into separate sub-calls that exclude
circular dependencies. For example, if entity A1 references B1, which references A2, which does not
reference B and if entity A3 references B2 which references B1, you must split the BulkInsert call as
follows and in the following order:
1. Call BulkInsert containing A2.
2. Call BulkInsert containing B1 and B2.
3. Call BulkInsert containing A1 and A3.

BulkImport method
The BulkImport method inserts or updates a list of entities specified in input through a list (IEnumerable) of IEntity
types in the database.
The method is transactional and can be invoked only from the code of Command Handlers.
Unlike the BulkInsert method, which fails if the entity already exists in the database, the BulkImport method
checks whether an entity, with the same logical key, is already present, and if so, it updates all its property values
(excluding internal systems fields). If the target entity to be updated does not contain the logical key, the method
cannot update its records (and thus it only appends values on new rows).
The method fails by default if you try to update an entity instance which is flagged as frozen, locked or marked to
be cleaned (ValidationOption is set to Managed). If you want to update an entity instance flagged as frozen,
locked or marked to be cleaned, the ValidationOption of the BulkImport parameter must be set to Unmanaged.
If the target entity to be updated contains many-to-many relationships that are not included in the source entity,
the method does not delete this piece of information, but simply adds/updates the specified values (i.e. BulkDelete
+ BulkInsert <> BulkImport).
If you set the FacetOption of the BulkImport parameter to Replace, all the facets of the target entity to be updated
will be removed and replaced by the facets of the imported entity. If you choose Append as parameter option value,
all facets of the imported entity will be added to the facets of the existing entity.
If you set the M2MOption of the BulkImport parameter to Replace, all the many-to-many relationships of the
target entity to be updated will be removed and replaced by the many-to-many relationships of the imported
entity. If you choose Append as parameter option value, all many-to-many relationships of the imported entity will
be added to the many-to-many relationships of the existing entity.
If you set M2MOption of the BulkImport parameter to ReplaceSegregationTag, all the segregation tags of the
target entity to be updated will be removed and replaced by the segregation tags of the imported entity.
After using the BulkImport method, the row version of the entity instance is not automatically updated in the
command cache (in this same way as the Submit method). Consequently, if you need to submit an updated entity
instance directly after a BulkImport, you must first requery the entity instance you want to modify. Keep in mind
that primary key and foreign key properties are not aligned on the instances after a bulk import operation is
occurred.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 175


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 • You can invoke a BukImport and then a Submit operation (in the same transaction) only if:
• the Submit and BulkImport involve different entity types,
• the Data Segregation is not active.
If the entities involved by BulkImport and Submit are the same, or if the Data Segregation is active,
the runtime execution returns an error. In this last case, you should either repeat
the BulkImport method to update previously inserted records, or update and submit the record in a
separate transaction.
• If you invoke the BulkImport on an audit trail relevant entity type, the BulkImport will behave as
follows:
• in case of inserted entity, all information is traced (with action set to added)
• in case of updated entity, the oldValue is always set to null (with action set to modified)

2.1.3.6.10 Attaching Documents to Entities


Opcenter Execution Foundation provides you with a centralized file store service, which can store a large amount of
files that you can retrieve through a token (GUID).
Since from client applications you cannot directly upload a file to the file store, you must invoke a Command that
executes the PutContent method and you must pass the base64-encoded contents of the file to this Command.
This page describes how to implement the business logic that can be triggered by client applications that
implement a file upload request.

Public APIs for reading and writing on the file store


Both for commands and composite commands, the platform public IUnifiedSdk interface allows you to execute the
following runtime operations:
• Add a folder to the file store.
• Add a file to the file store by providing a set of basic properties such as name and content type (e.g. extension).
This operation returns a GUID, which uniquely identifies the file inside the file store database, and additional file
information (such as the user who performed the operation, the file size, the operation time stamp).
• Retrieve the properties and the content of the file as a data stream by specifying the file GUID.
• Remove a file from the file store by specifying its GUID.
You can write on the file store only from Command Handlers.
Applications that use the IUnifiedSdkLean interface or clients that directly read from the Opcenter EX FN Service
Layer can only execute read operations on the file store.
The file store is automatically pre-configured during the post-installation phase and created during the deploy
phase (when also the Opcenter EX FN database is created).
The Opcenter EX FN public interface exposes two interfaces, IUnifiedSdkContentReading
and IUnifiedSdkContentWriting, which offer the following functionalities:
• Read a folder or a list of folders from the file store: GetFolder,GetFolderByName and GetFolderList.
• Write a folder on the file store: AddFolder
• Remove a folder from file store: DeleteFolder.
• Read a file from the file store: GetContent, GetContentByName, GetContentList and GetContentPayload.
GetContent, GetContentByName, GetContentList return only the file metadata or a list of file metadata (not
the file payload), while GetContentPayload returns the payload of the file. The payload is a byte array,
contained in an object of Stream type which can be handled either as a MemoryStream (for which all bytes are
loaded in memory) or as a FileStream (for which all bytes are loaded in chunks for performance enhancement
reasons).
• Write a file on the file store: PutContent

176 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• Remove a file from file store: DeleteContent


The read and write methods accept in input a parameter (contentNamespace) that determines the name of the
repository where you can store the file (Application or System). By default, this parameter is set to Application,
which means that the file will be stored inside the Opcenter EX FN database. If you set the value to System, the file
will be saved in a system database (the System File Store database, which is created during the product post-
installation procedure).
All commands that use IUnifiedSdkContentWriting interface are not in transaction. If you have add or delete a file
to the file store, the operation is persisted on the database, regardless of whether the entire command flow ends up
successfully or not. This means that before implementing a PutContent method or a retry of your command, to
avoid any failure, you should verify if a file name with the name you are using already exists in the file store. If a file
with the same identifier exists, the system returns an error.

Workflow

 All Opcenter EX FN machines that remotely connect to a SQL Server instance must be able to ping the SQL
machine by its hostname and IP address.

The following sections describe how you can manage files-to-entity associations in the data model and how you
can access the file repository once your solution has been deployed, by using a Functional Block Command (not a
Composite Command). Even if the APIs are available in a Composite Command Handler for creating a file/folder
directly, the association of the file to an entity is possible in a Functional Block Command only.
1. Data modeling
2. Command Handler implementation
3. File entity exposition on the Service Layer
4. UI project implementation

Data modeling
For each file you want to upload to the file store, you must create at least the following data model objects:
• an entity, which contains a FileType property defined as a value type.
• a Command, which contains at least two input parameters: a parameter defined as Blob type, and another
parameter representing the MIME type. The Blob system type will contain the file binary data. The MIME
type represents the file type. The possible values of MIME types are available on internet (for example at http://
www.freeformatter.com/mime-types-list.html). This Command can be invoked from the client side in order to
transmit a byte array, which will be internally handled in a temporary file store (System File Store) to optimize
performance.

Command Handler implementation


Once the data model is built, you can define the logic inside your Command Handler. If you want to pass a big
content to a Command (and not necessarily a file, as in the example described), you must use the Blob property
type in your Command parameter definition. In this way, Opcenter EX FN internally manages the message content
in a temporary file store (System File Store) and returns it to the handler.
In our use case, you have to assign to the ID field of the FileType property the Id (i.e. GUID) which is returned by the
PutContent method. The flow is the following:
1. Call the PutContent method, which adds the file to the file store and returns the Id of the file inside the
database.
2. Call a Create method, to create the entity instance.
3. Set the Id value of the entity.FileType.Id property to the Id returned by PutContent method.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 177


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 A code example is provided below in this page.

File entity exposition on the Service Layer


After solution deployment, Opcenter EX FN Service Layer exposes the custom defined entity (PnDefect in our
example) and its navigation properties towards the File system entity.
The value type property is converted into an object (File) and enriched with a Guid property whose name ends with
the "_Id" suffix. For more information, see Using Reference Value Type Properties.
The file payload can be retrieved by adding the keyword $value to the file navigation property, as in ~/entityset/
key/navigation/$value, where entitySet is the entity type, key is the entity Id
and navigation is the entity-to-file navigation property name.
To modify the limits for uploading files see Applying Custom Configurations to the Opcenter EX FN Service Layer.
The Command must be configured as a public Command of the POM Model.

Example
The model project contains an entity (PnDefect) and a Command (AssignDefectImg).
The PnDefect entity is decorated by the following properties:
• defectImg, which is a FileType system value type
• pnCode, which is a string

The AssignDefectImg Command contains the following parameters:


• imgBlob: type Blob
• mimeType: type string

178 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The AssignDefectImg Command Handler contains the following code:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 179


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

// Check if part number code exists //

var pn = Platform.Query<IPartNumber>().FirstOrDefault(p =>


p.Code.Equals(command.pnCode));
if (pn != null)
{
using (var blob = new MemoryStream(command.imgBlob))
{
var pn_code = command.pnCode;
var author = command.createdBy;
var img_id = command.imgId; var img_guid = Guid.Empty;
try
{
var img_guid = Platform.PutContent(new Content()
{ Name = img_id,
CreatedBy = author,
LastUpdatedBy = author,
Type = command.mimeType,
TagsNamesToAssociate = new List<String>()
},
blob);

var p = Platform.Create<IPnDefect>();
p.pnCode = pn_code;
p.defectImg.Id = img_guid;
Platform.Submit(p);
return new AssignDefectImg.Response() { };
}

catch (Exception ex)


{
if (img_guid != Guid.Empty)
{ Platform.DeleteContent(img_guid); }
var exp = ex.Message;
return new AssignDefectImg.Response()
{
Error = new ExecutionError(-1, exp)
};
}
}
}

else

{
// Part Number Code not found
return new AssignDefectImg.Response()
{
Error = new ExecutionError(-1, "Part number code not valid: " +
command.pnCode)
};
}

180 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

If the Data Segregation functionality is enabled, you can segregate the documents attached to an entity. The class
defining a document (Content) has been extended by adding the TagsNamesToAssociate property. This property
defines a list of tags that allows you to associate segregation tags to an instance/document. About its value:
• If the value is "null", then the system associates the selected tags of the current session to the document by
default.
• If the value is empty, no tags are associated to the document.
• If the value contains tags, then the system associates these tags the document.
When interactive users run queries from the Service Layer, they can see the documents only if they have the tags
associated to the document.

2.1.3.6.11 Creating Associations Among Entities


When creating associations among entities, there are some drawbacks in terms of time execution associated with
the Include method.
For example, if you want to associate entities that have a one-to-many relationship, you can avoid using it. If you
already have the Id of the parent entity, the following association strategy is the fastest:

child.Parent_Id = parentId;

If you do not have the Id of the parent entity, the following strategy would be still quite fast:

var parent = Platform.Query<WritingModel.IParent>().Single(x => x.Name == "MyParent")


;
child.Parent = parent;

But if you use the Include method as in the following code snippet, the time execution would be extremely slow
because the method actually retrieves all the data from the table of the related entities:

var parent = Platform.Query<WritingModel.IParent>().Include("Children").Single(x =>


x.Name == "MyParent");
parent.Children.Add(child);

If you want to associate entities that have a many-to-many relationship, you must always use the Include method.
Nevertheless, if you apply this method to the property that contains less elements, the code execution could be
extremely fast anyway. If we consider a relationship between some Users entities and Groups entities, we can
assume that a User entity will belong to few Groups entities while a Groups entity may contain a lot of Users.entities.
Consequently, the following piece of code:

var myUser = Platform.Query<WritingModel.IUser>().Include("Groups").Single(x =>


x.Name == "MyUser");
var myGroup = Platform.Query<WritingModel.IGroup>().Single(x => x.Name == "MyGroup");
myUser.Groups.Add(myGroup);

should be faster than the following:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 181


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var myUser = Platform.Query<WritingModel.IUser>().Single(x => x.Name == "MyUser");


var myGroup = Platform.Query<WritingModel.IGroup>().Include("Users").Single(x =>
x.Name == "MyGroup");
myGroup.Users.Add(myUser);

because in the former example the Include method retrieves a few amount of data while in the second example it
retrieves a lot of data.

2.1.3.6.12 Using Type Aliases


You can use a Type Alias as property type inside
• entities
• value types
• facets
• command parameters
• event parameters
If you consequently update any of the constraints of the Type Alias, the same constraints are applied to the
property that uses that type alias.
The following example contains a simple use case where a Type Alias is used within a command parameter. The
code snippets show how the Type Alias is handled within the generated C# classes.

Example of data model


1. Create a Type Alias (e.g. MyString, of string type), and add a constraint to it (e.g. MaxLength = 10 characters).
2. Create a command (e.g. MyCommand), add an input parameter (e.g. MyInput) and set its type by selecting
the MyString type from the Property Browser dialog box.

182 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

3. Compile the model project, import the handler class of MyCommand and implement the logic of the
MyCommand command.

Example of code snippets


The following code extract, which is taken from the MyCommand command class, shows how the TypeAlias is
handled within the C# class.
The type of MyInput object is not directly defined as a MyString type (this is actually not possible in C#). The
MyInput property, or more generally any object that uses a TypeAlias, is decorated with an additional attribute:
the UnifiedTypeAlias attribute. This attribute is used to map the object which is using the TypeAlias with the
constraints that you set on the TypeAlias itself (in our example, MaxLength = 10 characters).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 183


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Siemens.SimaticIT.DSL.Common;
using Siemens.SimaticIT.Unified.Common;
namespace TypeAliasDoc.MasterData.FBTADoc.MSModel.Commands
{
/// <summary>
/// My Command with TypeAlias
/// </summary>

[UnifiedAccessibility(true)]

public sealed class MyCommand : ICommand


{
/// <summary>
/// Constructor
/// </summary>
public MyCommand()
{
}
/// <summary>
/// Constructor with parameters
/// </summary>
public MyCommand( string input1)
: this()
{
this.Input1 = input1;
}
// Input parameters

/// <summary>
/// My Input with TypeAlias
/// </summary>
/// <summary> TypeAliasDoc.MasterData.FBTADoc.MSModel.Types.MyString
</summary>
[Siemens.SimaticIT.DSL.Common.UnifiedTypeAlias(typeof(MyCommand),
"Input1", "TypeAliasDoc.MasterData.FBTADoc.MSModel.Types.MyString")]
[Required()]
[MaxLength(10)]
public string Input1 { get; set; }
.....
}
}

184 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 Limitations
You cannot directly modify the annotations within the object instance that uses the TypeAlias (for
example, in the property of a command parameter), but you must modify it in the type alias definition
(TypeAlias).
A TypeAlias cannot be part of a logical key.
If you use an annotation that cannot be used inside a certain context, the system will allow you to define
the annotation in the TypeAlias definition, but will return an error when you will actually use it in a certain
object instance (for example, you can set the default annotation on the TypeAlias but when you try to use
it in a command you will receive an error).

2.1.3.6.13 Handling the CommittedEvent


Event sourcing can be defined as the capability to store all the changes that occur to an application state as a
sequence of events. Opcenter EX FN stores all the information related to the write operations performed at the end
of a successful transaction. If the transaction completes successfully, the system writes a list of the executed
operations (submit, delete or bulk import or insert, freeze/unfreeze, mark for cleaning, lock/unlock, import) and the
involved entities in the CommittedEvent event. This event conveys the following information:
• the list of the commands that have been executed,
• the entities that are involved
• the type of operation that has been executed (submit or bulk insert)
• the relationship among the various entities (only for many-to-many relationships)
• the time stamp of the commit operation
• the data segregation tags associated with the involved entity instances.

Handling the CommittedEvent through custom Event Handlers


The CommittedEvent is available as a referenced system event inside the model project of Functional Blocks, Apps
and Extension Apps. The model assembly reference required to handle the CommittedEvent (i.e.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 185


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

the Siemens.SimaticIT.SystemData.Foundation.Events.dll assembly which can be found


in %SITUnifiedSystemRoot%bin) is automatically inserted in the handler project, but if required it can be inserted
manually.
By implementing a custom event handler and then subscribing this handler to the CommittedEvent, you can
associate any logic with the latest changes made to the write data model (for example, in order to handle
the synchronization of a custom read data model).
To handle the CommittedEvent through an event handler you have to go through the following steps:
1. Create a custom event handler.
2. Import the custom handler.
3. Implement the custom event handler.
4. Subscribe the handler to the CommittedEvent.
Alternatively, you can also create a subscription to the CommittedEvent and implement custom logic in an
external application that uses the IUnifiedSdkLean public interface.
You cannot fire the CommittedEvent: an authorization error will be returned at runtime (ArgumentException).
See the following sections for the details on the parameters returned by the CommittedEvent so that you can
properly use it inside your code.
If you want to deduct the history of the executed operations, for example because you want to synchronize a
secondary database by reproducing exactly the same operations that have been executed on the production
database, you can follow the operation order which is returned by the Ordering property of the CommittedEvent.
Alternatively, to achieve the same use case, you can assign your Committed Event Handler to a Sequential Worker
Role in order to deliver the Committed Events in an ordered way.
If you are using the IUnifiedSdkLean interface, you can also order the received Committed Events by setting a
parameter of the subscription method (see Handling event subscriptions inside page Developing Third-Party
Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface).

CommittedEvent and Signal Rules


To receive information about modified entities, you can also configure Signal Rules to receive signals when these
entities occur and trigger the desired logic.

CommittedEvent data structure description


The system fires the CommittedEvent with the following input parameters:

Parameter Type Description

Commands string A JSON object containing the list of the commands


involved in the current transaction.

CommitedTimestamp datetime Timestamp of the commit operation.

186 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Parameter Type Description

Entities string A JSON object containing a list of elements (an


example is given below). The list of elements is always
present except for empty transactions, Bulk operations
(insert or import) or Import data operations. If the
transaction does not contain any entities, the system
serializes this parameter as an empty list of elements,
so that your deserialization logic does not return any
exceptions. If a Bulk or an Import operation occurred
in the transaction, this parameter is empty.
In case of Bulk operations, you can use the
GetCommittedEvent method to retrieve the required
information (as explained below).
In case of delete operations, this parameter only
returns the Id of the deleted entities and the entity
types.

EntityDomain string The domain in which the operation was executed.

EntityTypes string A JSON object containing the list of entity names.


The parameter returns a serialized empty list if there
are no entities.

Operation string The operation type. It can contain the following


values: Standard (i.e. related to a standard Submit
operation), Bulk (related to Bulk insert or Bulk import
operations) or Import (related to Import data
operation).

Ordering bigint An incremental Id (related to each entity domain).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 187


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Parameter Type Description

Relations string A JSON object containing a list of elements (an


example is given below). As for the Entities object, the
list of elements is always present except for empty
transactions, Bulk operations (insert or import) or
Import data operations. If the transaction does not
contain any entities, the system serializes this
parameter as an empty list of elements so that your
deserialization logic does not return any exceptions. If
a Bulk or an Import operation occurred in the
transaction, this parameter is empty.
In case of Bulk or Import operations, you can use the
GetCommittedEvent method to retrieve the required
information (as explained below).
In case of delete operations, this parameter does not
return any elements, unless there is a many-to-many
relationship or there is a one-to-many nullified
relationship (and a bulk insert did not occur in the
transaction): in these cases the parameter returns the
list of related elements.

SessionId string The event identifier.

Version string The value is set to 2.3.

EventFullName string The event complete name.

DataSegregationTags string A JSON representing the list of the tags for each entity
instance.

 Empty CommittedEvents
The CommittedEvent is fired as an empty structure in the following cases:
• after you have used the Query() method,
• if you have performed a creation and then a deletion of the same entity within the same transaction.
In these cases, Entities and Relations empty parameters are serialized as empty lists.

The described JSON elements are based on an example. This example shows the CommittedEvent that would be
fired if you committed two entities (IEntity1 and IEntity2), linked through a many-to-many relationship,
and containing the following set of properties:

Entity Name Property Annotation

Entity1 Code (string)

Name (string) LogicalKey

188 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Name Property Annotation

BlobProperty (blob) MaxLength = 1048756

ManyToMany Relation with Entity2

Entity2 Code (string)

Name (string) LogicalKey

Description for the Entities JSON object


The Entities JSON object contains the following elements:
• Action: The operation that has been executed, with one of the following values: Added (for entity instance
creation), Modified (for entity instance update), Deleted (for entity instance deletion), Frozen/Unfrozen (for
freeze/unfreeze operations on an entity), Locked/Unlocked (for lock/unlock operations on an
entity), MarkedForCleaning (for marking for cleaning operation on an entity).
• Entity: An object containing the entity properties (see below). These elements change according to the entities
involved.
The full JSON data structure will be returned for the following operations:
• entity creation
• entity update
• when you perform freeze/unfreeze, lock/unlock or mark for cleaning operations on an entity within the same
transaction as a create or update operation.

The following JSON example is returned if you create two entities and then freeze one of them:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 189


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The following JSON example is returned if you freeze an entity that has a related entity in composition (the action of
freezing is applied on all child entities in cascade):

The following JSON example is returned if you freeze a single entity:

190 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The following JSON example is returned if you unfreeze a single entity:

The following JSON example is returned if you lock a single entity:

The following JSON example is returned if you unlock a single entity:

The following JSON example is returned if you freeze and lock an entity:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 191


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The Entities object will return only the entity Id and the entity type if you have performed one of the following
operations on an entity: delete, freeze, unfreeze, lock, unlock, mark for cleaning:

If the deleted entity has related entities, the Relations object returns additional information (see below).

Description for the EntityTypes JSON object


The EntityTypes JSON object contains the list of entities.

An example of this object could be the following:

192 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Description for the Relations JSON object


The Relations JSON object returns the items that have been added to or deleted from the relationship if the
modified entities have a many-to-many relationship, or if an entity with one-to-many relationship has been
deleted with OnDeleteSetNull option.
This object contains the following elements:
• Action: The operation that has been executed, with one of the following values: Added/Modified/Deleted (for
many-to-many relationships) /Nullified (only for one-to-many relationships, see example below).
• Id: key of the entity involved in the relationship
• TypeName: entity types involved in the relationship
An example of this object could be the following:

If you have deleted an entity with one-to-many relationships with OnDeleteSetNull delete option selected, this
element returns a set of information with the following format:

Description for the DataSegregationTags JSON object


The DataSegregationTags JSON object returns the list of tags associated to each entity instance, which is
identified by its Id.

Envelope parameter description

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 193


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The envelope, on which you can set a filter, associated with the CommittedEvent contains the following
parameters:

Parameter Type Description

Category string The returned value is always set to Commit.

Topic string The domain name of the involved entity.

Tag string The returned value is set either to Standard (if the event
is fired at the end of a standard submit operation), Bulk
(if the event is fired at the end of a bulk insert/import
operation) or Import (if the event is fired at the end of an
Import data operation).

Methods for retrieving the CommittedEvent arguments


You can use specific methods to retrieve a CommittedEvent. Once you have the body of the event, you can
deserialize its JSON objects in order to access the returned data (see below).
The CommittedEvent is fired with the data structure described in this page, and the same data structure will be
accessible through a set of retrieve methods with some limited exceptions due to performance reasons.
The term payload, in the CommittedEvent data structure, indicates the Relations and the Entities JSON objects.

Method Name Description

GetCommittedEvent() This method retrieves a specific event associated with a certain event
identifier (SessionId) and the related data domain. The sessionId is
always related to a specific data domain and cannot be defined
as Guid.Empty. If you specify a data domain that does not correspond
to the data domain in which the event was actually fired, the system
raises an exception. The DataDomain parameter can assume one of
the three values defined in the EntityDomain class
(ReferenceData, MasterData, OperationalData).
For bulk insert, bulk import ad import data operations, this
method also returns the event payload (i.e. it also returns
the Relations and the Entities serialized objects).

194 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Method Name Description

GetCommittedEvents() This method retrieves the list of events that have been fired after a
certain event. This method could be useful if you want to implement
logic that retrieves all fired events at the startup of a client application,
or for example, if during system down time you were not notified of
CommittedEvents for a brief period. This method accepts the same
input parameters as
the GetCommittedEvent() method: SessionId and DataDomain.
The platform also offers an overload method which accepts in input
the PageSize parameter. This parameter specifies the maximum
number of the CommittedEvents you want to receive. Indeed, if the
number of the events were excessively high, performance issues might
be encountered. This method allows you to opportunely manage this
problem.
For bulk insert, bulk import ad import data operations, the returned
events have empty payloads (i.e. they do not contain the Relations or
the Entities objects).

GetCommittedEventsInRange() This method retrieves the list of events that have been fired between
two known event identifiers. This method can be useful for example for
recovery use cases, if any events are missing in the retrieved sequence
(see Ordering parameter). If in the specified range there are one or
more events that have not been fired yet, the method returns an
exception.
The method accepts three input parameters: the first
two SessionId parameters contain the identifiers of the first and the
last event in the range, and the DataDomain as explained for
the GetCommittedEvent() method.
For bulk insert, bulk import ad import data operations, the returned
events have empty payloads.

 If a CommittedEvent has been fired for a bulk operation, this means that for the given transaction there
may have been many submit operations but there must have been at least one bulk operation.
To use these methods from a client application developed through the IUnifiedSdkLean, remember that
the interactive user who will run the application must belong to the SIT_UNIFIED_LOW user group.
Further technical details are provided in the Opcenter Execution Foundation Platform Reference Online
Help.

Deserializing a JSON object to C# code


Within your event handler or Lean project, you need to deserialize the CommittedEvent body in order to
manipulate its data.
To achieve this, you can use the Json.NET library.
The following code snippets are some of the possible examples of using Json.NET library:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 195


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var json = JArray.Parse(entities);


var firstEntity = json[0];
string action = (string)firstEntity["Action"];

// How to extract an entity from the list (e.g. the first)


var selectedEntity = entities[0];

// How to extract the action done on the selected entity


var actionDoneOnEntity = selectedEntity["Action"];

// How to extract the "Id" property of the selected entity


var id = selectedEntity["Entity"]["Id"];

// How to extraxt a Value Type property from the selected entity


var valueType = selectedEntity["Status"];
var statusName = valueType["Name"];

// How to extract an element from the relation list and all of its properties
var relations = JArray.Parse(committedEvent.Relations);
var selectedRelation = relations[0];
var action = selectedRelation["Action"];
var id1 = selectedRelation["Id1"];
var id2 = selectedRelation["Id2"];
var typeName1 = selectedRelation["TypeName1"];
var typeName2 = selectedRelation["TypeName2"];

2.1.3.6.14 Managing the Event Store


Whenever an operation is executed on the Opcenter EX FN database (such as create, freeze, lock, bulk insert) a
CommittedEvent event is raised and saved in the Event Store.
For every transaction performed, a JSON format file is saved in the Event Store, which contains the payload of the
transaction.
CommittedEvent arguments can be retrieved from the Event Store, in order to perform further business logic on the
information provided.

Cleaning the Event Store


The Event Store increases in size, as operations are performed. Consequently it is strongly recommended to
perform regular cleaning and maintenance plans.
Currently these cleaning operations must be performed manually, using the following guidelines:
• You can delete events:
• according to the time they have been in the database, filtering by the CommittedTimestamp parameter.
• whose ordering is successive to a specific transaction, filtering by the Ordering parameter.
• The __HistoricalEventItems database table should be regularly cleaned so that is only contains data essential
for production.
• The __EventItems table must never be modified.
• Indexes should be recreated after cleaning.

196 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.6.15 Using Reference Value Type Properties


This page focuses on the C# classes generated for a value type. In particular, it focuses on the differences between
the writing and reading model and on the Reset extension method, which is added to the value type class and
allows you to reset the value type instance on which it is called.

Value Type properties


After you have configured a Reference Value Type in your model project, you can access the properties of the
related entity.
The accessibility of these properties depends on the data model you are querying.
In the writing model, only the properties you have exposed through the Value Type are available as denormalized
properties inside the target entity.
In the reading model, all the properties of the entity you linked through the Value Type are available in the target
entity.
The examples contained in this page describe this difference.

Example of Data model entities


The data model of the OperationalData domain has been defined as follows:

The data model of the MasterData domain has been defined as follows:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 197


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Example of Handler code


The CreateLot command handler code creates the ILot entity. Here, the MatDefVT Value Type allows you to directly
assign the Name of the retrieved IMaterialDefinition to the MaterialDefinition property of the ILot entity, after you
have explicitly linked the MaterialDefinition property to the Guid of the MatDef_VT Value Type.

public partial class CreateLotHandlerShell { /// <summary> /// This is the handler
the MES engineer should write /// This is the ENTRY POINT for the user in VS IDE ///
</summary> /// <param name="command"></param> /// <returns></returns>
[HandlerEntryPoint] private CreateLot.Response CreateLotHandler(CreateLot command)
{ var matdef = Platform.ProjectionQuery<IMaterialDefinition>().SingleOrDefault(x =>
x.Name == command.LotMaterial); var uom =
Platform.ProjectionQuery<IUoM>().SingleOrDefault(x => x.Name == command.UoM); var
mylot = Platform.Create<IOperationalLot>(); mylot.NId = command.LotCode;
mylot.MaterialDefinition.MatDefVT_MatDef = matdef.Id;
mylot.MaterialDefinition.MatDefVT_Name = matdef.Name; mylot.UOM.UoMVT_UoM = uom.Id;
mylot.UOM.UoMVT_Name = uom.Name; Platform.Submit(mylot); return new
CreateLot.Response { CreatedLotGuid = mylot.Id }; } }

The IOperationalLot entity is created in the writing model with the following structure:

public interface IOperationalLot : IEntity, IPrimitiveEntity


{
IList<IOperationalLotFacet> Facets { get; }
string LotName { get; set; }
IMatDefVT MaterialDefinition { get; set; }
string NId { get; set; }
decimal? Quantity { get; set; }
IUoMVT UOM { get; set; }
}

Here you can see that the type of the MaterialDefinition property of IOperationalLot is a IMatDefVT type, which is
made up only of the properties of the MatDefVT Value Type:

198 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

{
public interface IMatDefVT : IStructure
{
Guid? MatDefVT_MatDef { get; set; }
string MatDefVT_Name { get; set; }
int? MatDefVT_VMajor { get; set; }
int? MatDefVT_VMinor { get; set; }
}
}

In the reading model, the MaterialDefinition property is transformed into an Entity type property
(MaterialDefinition), together with the ValueType name (MaterialDefinition_MatDefVT_MatDef) and the Value Type
Guid (MaterialDefinition_MatDefVT_MatDef_Id), which allows you to directly link your entity with all the
MaterialDefinition entity properties (regardless of what you have included in the Value Type).

public class OperationalLot : Entity


{
public OperationalLot();
public IList<OperationalLotFacet> Facets { get; set; }
public string LotName { get; set; }
public MaterialDefinition MaterialDefinition_MatDefVT_MatDef { get; set; }
public Guid? MaterialDefinition_MatDefVT_MatDef_Id { get; set; }
public string NId { get; set; }
public decimal? Quantity { get; set; }
public UoM UOM_UoMVT_UoM { get; set; }
public Guid? UOM_UoMVT_UoM_Id { get; set; }
}

Consequently, from the OperationalLot entity you can now navigate to the MaterialDefinition properties through a
standard Include sub-method:

var readinglot =
Platform.ProjectionQuery<IOperationalLot>().Include(
"MaterialDefinition_MatDefVT_MatDef").Single(x => x.NId == command.LotCode);

If you browse the OperationalLot entity and then the MaterialDefinition entity, you will find all the properties you
have assigned to the MaterialDefinition entity (i.e. also Description and MaterialClass which have not been included
in the Value Type):

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 199


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

public class MaterialDefinition : Entity


{
public MaterialDefinition();
public string Description { get; set; }
public IList<MaterialDefinitionFacet> Facets { get; set; }
public string MaterialDefinitionClass { get; set; }
public string Name { get; set; }
public Guid? NId { get; set; }
public int? VMajor { get; set; }
public int? VMinor { get; set; }
}

Using the Reset method


Each C# class of a value type contains the Reset extension method.
When you instantiate an entity through the Create method, the system directly instantiates also its value types
(whether they are reference value types or simple value types, including the system FileType). Consequently, you
do not need to instantiate the value type class to assign values to its instance. Moreover, you cannot manually
instantiate a new value type class because inside command handlers you must always work with the interface of a
class and not with the class itself (as already described for the entity instance creation). Thus, even if the following
code snippet would be perfectly acceptable in standard C# to instantiate the value type class, here in Opcenter EX
FN command handlers you cannot use it:

Wrong code for value type instantiation

var e = Platform.Create<IEntityA>();
e.vt = new ValueType();
e.vt.Name = "MyValue";

The Reset method sets all the properties of a value type to null.
A scenario in which this method could be useful is when you have an optional Value Type with one or more
properties set to mandatory. In this situation if all the properties of the value type are set to null the validations
rules are skipped. However, if any of its properties are not null (not only the mandatory property), the validation
checks will be applied. In this case the Reset method can be used to set all properties to null, consequently
switching off the validation rules.
If the value type itself is mandatory, however, validation rules are always applied.

var myEntity = sdk.Query<IMyEntity>().Single(x => x.Id == entity.Id);


myEntity.myValueType.Reset();

2.1.3.6.16 Using the Query Methods and the Data Model Assemblies
The Opcenter Execution Foundation database is organized, according to the CQRS pattern, into two separate data
models that can be accessed through two different channels.
When you model entities in the Model project in Project Studio and then build the Model project, the system creates
the C# classes (interfaces) that allow you to access the write data model (transactional model) and the read data
model (Projection model).

200 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Query methods and data model domains


In the write data model, the domain context determines the entities you can access. This means that you can
execute read and write operations only within the same domain.
In the read data model, domains do not limit the queries you can execute.
The read data model of a Functional Block is represented in the [...].DataModel.ProjectionModel namespace,
contained in the <Prefix>.<DomainName>.<FunctionalBlockName>.<Acronym>Model.ProjectionModel assembly,
and must be used by accessing the interface of the entity you want to query on:
e.g. platform.ProjectionQuery<IMyEntity>.
The read data model of an App is represented in the [...].POMModel.DataModel.ReadingModel namespace,
contained in the <Prefix>.<AppName>.<AppName.AcronymPOMModel>.PublicModel assembly, and can only be
used by accessing the class of the entity you want to query on, and not the entity interface
(e.g. platform.ProjectionQuery<MyEntity>).
The write data model of a Functional Block is represented in the [...].DataModel namespace, contained in
the <Prefix>.<DomainName>.<FunctionalBlockName>.Acronym>Model assembly, and must be used by
accessing the interface of the entity you want to query on: e.g. platform.Query<IMyEntity>. The Query method
returns an IQueryable standard object. This object must be materialized inside the same Task in which it has been
requested (i.e. you must not pass it as a parameter among different Tasks).
When you start writing a query in the write data model you must consider in which domain you have modeled your
entities and in which handler you are writing your code:
• if the handler where you are writing the code and the entity to be queried belong to the same domain you can
use the Query method on the write data model;
• if the handler where you are writing the code and the entity to be queried belong to different domains you can
only use the ProjectionQuery method on the read data model.
If you want to implement remote queries, instead, go to How to Manage Remote Entity Queries.

Overview of the query methods


Method Description

Query Exposed by the IUnifiedSdk interface. The method allows you


to query entities that belong to the write data model. This method
reads only from entities that belong to the same domain.

ProjectionQuery Exposed by the IUnifiedSdk/IUnifiedSdkEvent/


IUnifiedSdkLean interfaces. The method allows you to execute cross-
domain queries on entities.
This method allows you to execute queries outside transaction. For
example, you can use it if you want to execute multiple queries only on
the read data model, without waiting for the end of the transaction.
From a consumer application or a third-party application, you cannot
read data from entities of the write data model. From a third-party
application, which uses the IUnifiedSdkLean interface, you can
execute queries through the ProjectionQuery method (exposed by
IUnifiedSdkLean) that can read cross-domain.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 201


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Method Description

OData standard queries From any consumer application, after the entire solution has been
deployed, you can use OData standard queries on the read data model
Public Object Model read data. See also Invoking Commands from UIs)

GetRemoteEntities Exposed by the IUnifiedSdk (IUnifiedSdk/IUnifiedSdkComposite/


IUnifiedSdkPreCheck/IUnifiedSdkPreCheckComposite/
IUnifiedSdkEventinterface), the method allows you to execute remote
queries.

Required Assemblies
If you need to manually add references to the required model assemblies inside your project (see also Manually
Adding Model Assemblies) keep in mind the following overview:

Handler Transactional Model and Assemblies Projection Model and Assemblies

(Base) Command Query method in the same domain ProjectionQuery method


Handlers
Query method in different domains Required assemblies:

Required assemblies: • xxx.<FunctionalBlockName><Acronym>


Model.ProjectionModel.dll
• xxx.<FunctionalBlockName><Acronym> • xxx.<FunctionalBlockName><Acronym>
Model.dll Model.Types.ProjectionModel.dll
• xxx.< • Siemens.SimaticIT.SystemData.Founda
FunctionalBlockName><Acronym>Mod tion.ProjectionModel.dll (**)
el.Types.dll • Siemens.SimaticIT.SystemData.Founda
• Siemens.SimaticIT.SystemData.Founda tion.Types.ProjectionModel.dll
tion

Composite Query method ProjectionQuery method


Command
Handler (App/Ext Required assemblies:
App) • xxx.<AppName.AcronymPOMModel>
.PublicModel.dll
• xxx.<FunctionalBlockName><Acronym>
Model.Types.ReadingModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.ReadingModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.Types.ReadingModel.dll

202 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Handler Transactional Model and Assemblies Projection Model and Assemblies

Pre-Check Handler Query method in the same domain ProjectionQuery method

Query method in different domains Required assemblies:

Required assemblies: • xxx.<FunctionalBlockName><Acronym>


Model.ProjectionModel.dll
• xxx.<FunctionalBlockName><Acronym> • xxx.<FunctionalBlockName><Acronym>
Model.dll Model.Types.ProjectionModel.dll
• xxx.< • Siemens.SimaticIT.SystemData.Founda
FunctionalBlockName><Acronym>Mod tion.ProjectionModel.dll
el.Types.dll • Siemens.SimaticIT.SystemData.Founda
• Siemens.SimaticIT.SystemData.Founda tion.Types.ProjectionModel.dll
tion

Post-Action Query method in the same domain ProjectionQuery method


Handler
Query method in different domains Required assemblies:

Required assemblies: • As documented for Base Command


Handlers / Composite Command
• As documented for Base Command Handlers (according to the solution
Handlers / Composite Command type)
Handlers (according to the solution
type)

Event Handler in Query Method ProjectionQuery method


Functional Block
Required assemblies:
• xxx.<FunctionalBlockName><Acronym>
Model.ProjectionModel.dll
• xxx.<FunctionalBlockName><Acronym>
Model.Types.ProjectionModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.ProjectionModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.Types.ProjectionModel.dll

Event Handler in Query method ProjectionQuery method


App/Extension
App Required assemblies:
• xxx.<AppName.AcronymPOMModel>
.PublicModel.dll
• xxx.<FunctionalBlockName><Acronym>
Model.Types.ReadingModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.ReadingModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.Types.ReadingModel.dll

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 203


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Handler Transactional Model and Assemblies Projection Model and Assemblies

Third-party Query method ProjectionQuery method (*)


applications
(IUnifiedSdkLean Required assemblies:
) • xxx.<AppName.AcronymPOMModel>
.PublicModel.dll
• xxx.<FunctionalBlockName><Acronym>
Model.Types.ReadingModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.ReadingModel.dll
• Siemens.SimaticIT.SystemData.Founda
tion.Types.ReadingModel.dll
(*) Any third-party data sources can be accessed only through the ProjectionQuery method after you have
imported the external data model through an appropriate Functional Block.
(**) Siemens.SimaticIT.SystemData.Foundation.xxx.dll are system-defined. They are available in the product bin
folder (e. g. C:\Program Files\Siemens\SimaticIT\Unified\bin) and provide the representation of a set of foundation
artifacts, such as the File, Folder, SegregationTag, SegregationLog entities and so on. For more information, see
the Foundation Model Reference Guide.

2.1.3.6.17 Querying on Referenced Entities


If you want to query on an entity and on its related entities (either cross-domain or within the same domain), you
can use the Include extension method, both in the ProjectionQuery and in the Query method, as follows:

Example of ProjectionQuery with Include

// Status and Lifecycle are associated entities. The Include method allows you to
filter also on the related entities.
// You must add a using reference to Siemens.SimaticIT.Unified.Common.Information to
use the Include method.
// The reference to the <FunctionalBlock>Model.ProjectionModel.dll has been added

using Siemens.SimaticIT.ReferenceData.Foundation.DataModel.ProjectionModel;
using Siemens.SimaticIT.Unified.Common.Information;
[…]
var status = Platform.ProjectionQuery<IStatus>().Include("LifeCycle").FirstOrDefault(
m => m.NId.Equals(StatusNId));

See Creating Associations Among Entities.


When using the Include method, bear in mind that in terms of time execution there are drawbacks associated with
this method. For example, if you want to associate entities that have a one-to-many relationship, you can avoid
using it. If you already have the Id of the parent entity, the following association strategy is the fastest:

child.Parent_Id = parentId;

If you do not have the Id of the parent entity, the following strategy would be still quite fast:

204 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var parent = Platform.Query<WritingModel.IParent>().Single(x => x.Name == "MyParent")


;
child.Parent = parent;

But if you use the Include method as in the following code snippet, the time execution would be extremely slow
because the method actually retrieves all the data from the table of the related entities:

var parent = Platform.Query<WritingModel.IParent>().Include("Children").Single(x =>


x.Name == "MyParent");
parent.Children.Add(child);

If you want to associate entities that have a many-to-many relationship, you must always use the Include method.
Nevertheless, if you apply this method to the property that contains less elements, the code execution could be
extremely fast anyway. If we consider a relationship between some Users entities and Groups entities, we can
assume that a User entity will belong to few Groups entities while a Groups entity may contain a lot of Users.entities.
Consequently, the following piece of code:

var myUser = Platform.Query<WritingModel.IUser>().Include("Groups").Single(x =>


x.Name == "MyUser");
var myGroup = Platform.Query<WritingModel.IGroup>().Single(x => x.Name == "MyGroup");
myUser.Groups.Add(myGroup);

should be faster than the following:

var myUser = Platform.Query<WritingModel.IUser>().Single(x => x.Name == "MyUser");


var myGroup = Platform.Query<WritingModel.IGroup>().Include("Users").Single(x =>
x.Name == "MyGroup");
myGroup.Users.Add(myUser);

because in the former example the Include method retrieves a few amount of data while in the second example it
retrieves a lot of data.

2.1.3.6.18 Troubleshooting Parallel Query Execution Commands


If you try to execute a high number of command requests for parallel query execution and some of these commands
fail, it may be necessary to modify the value for the max degree of parallelism option in SQL Server Management
Studio as explained in the following online documentation resources: Recommendations and guidelines for the
"max degree of parallelism" configuration option in SQL Server and Configure the max degree of parallelism Server
Configuration Option.
This error is disclosed by the following Trace Viewer trace, logged by the Siemens-SimaticIT-Trace-Information
provider:
Rethrowing unhandled exception: System.Data.SqlClient.SqlException (0x80131904): The query processor could not
start the necessary thread resources for parallel query execution [...]

2.1.3.7 Tracing Process Executions


This topic describes how you can enable tracing inside the code of your handlers (command handlers, event
handlers, pre-checks or post-actions).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 205


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

There are two possible ways for logging messages: either with Trace Viewer or with Application Log.

Differences between Trace Viewer and Application Log


You can check differences in the following paragraph before choosing the most suitable log method. For more
information, refer to Trace Viewer documentation or How To Manage Application Logs.

Trace Viewer Application Log Description

Traces all actions Traces only application level Trace Viewer logs all the actions carried out by
messages the platform (such as command execution,
authentication, queries on the database), while
Application Log traces only application level
messages.

Is more development Is more end-user oriented Trace Viewer is more suitable for advanced
oriented troubleshooting issues since it is highly verbose
and technical. Moreover it can contain logs
generated by the business logic, in terms of
command/event handlers, if the code uses them.
On the other hand Application Log is more
functional and end-user oriented. Consequently,
its messages are also more readable, and they
can be translated.

Stores logs in a database Stores logs in a database Both applications can store logs in a database,
but database maintenance and database maintenance but while Application Log can apply standard
is custom is standard provided maintenance procedures to clean old messages,
for Trace Viewer the database maintenance is
custom.

Logs can be filtered and Logs can be filtered by level, In Trace Viewer, logs are classified in levels (from
sorted out by level and business command and verbose to critical), and in providers (representing
provider source Functional Block or the "component" which has generated a certain
App log). Levels and providers can be used to filter
messages, both in view mode and in storage
mode (to avoid that logs let the database grow in
uncontrolled way). In Application Log, logs can be
defined as different levels (from verbose to
critical as in Trace Viewer), return the name of the
business command that generated them, as well
as the "owners" of the commands (typically
Functional Blocks, Apps or Extension Apps).

Enabling tracing in Trace Viewer


Inside the code of you handlers, you can enable trace operations for the execution of the required logic by using the
public ITracer Interface, documented in the Opcenter Execution Foundation Platform Reference Online Help.
This interface exposes Write methods that allow you to specify the message you want to write and a set of
additional information that allow you to set filters inside Trace Viewer (channel, category, verbosity level of the
trace).

206 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Example of setting the trace provider


You can use the Write method to set the same trace channel for all your traces and then filter inside Trace Viewer by
the same trace channels to filter on the executions to be monitored.
Note that the provider used inside the following example should be replaced by the proper provider that is
dedicated to the custom logic of Command and Event Handlers, as documented at page Choosing Trace Providers.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 207


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

using Siemens.SimaticIT.SDK.Diagnostics.Tracing;
[...]

ITracer tracer = Platform.Tracer;

[...]

//traces the creation of an entity


newMatDef = Platform.Create<IMaterialDefinition>();
newMatDef.Code = command.Code;
Platform.Submit(newMatDef);
tracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",

Siemens.SimaticIT.SDK.Diagnostics.Common.Category.Informational,
"MatDef. with Code {0} created",
command.Code);

//traces that an event is fired


var materialDefinitionEvent = new OnMaterialDefinitionCreated() { Code =
command.Code};
Platform.FireEvent(materialDefinitionEvent);
tracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",

Siemens.SimaticIT.SDK.Diagnostics.Common.Category.Informational,
"Event fired for Mat Def Code {0} created",
command.Code);

//traces that the event has called a command


var cmd = new WriteOnMaterialDefinitionEvent();
cmd.CreatedCode = evt.Code;
WriteOnMaterialDefinitionEvent.Response matDefEvent =
Platform.CallCommand<WriteOnMaterialDefinitionEvent,
WriteOnMaterialDefinitionEvent.Response>(cmd);
tracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",
Siemens.SimaticIT.SDK.Diagnostics.Common.Category.Informational,
"Command sent from event {0}",
evt.Code);

//traces that another command has been called


var matDefEvent = Platform.Create<IMaterialDefinitionEvent>();
matDefEvent.MaterialDefinitionCode = command.CreatedCode;
Platform.Submit(matDefEvent);
tracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",
Siemens.SimaticIT.SDK.Diagnostics.Common.Category.Informational,
"Code written in new event table {0}",
command.CreatedCode);

The ITracer Interface also exposes WriteEx methods that allow you to add the information of the calling class and
method name.

208 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

In the following example, the traced class name will be CommandHandlerExplicit1. You can call it with Generic
parameter <CommandHandlerExplicit1> or call it by the signature that exploits the this keyword:

Direct calls modifications original signs

using Siemens.SimaticIT.SDK.Diagnostics.Tracing;
[...]

public class CommandHandlerExplicit1 : BasicHandler, ICommandHandler, IHandlerShell


{
Category category = Category.Critical;
VerbosityLevel verbosity = VerbosityLevel.High;

[...]

public void Execute()


{
//example using Generics parameter
Platform.Tracer.WriteEx<CommandHandlerExplicit1>("Siemens-SimaticIT-Trace-
BusinessLogic", category, verbosity)("Message: {0} {1} {2}", "A", "B", "C");

//example using "this" keyword


Platform.Tracer.WriteEx(this, "Siemens-SimaticIT-Trace-BusinessLogic",
category, verbosity)("Message: {0} {1} {2}", "A", "B", "C");
}
}

If not set, the method name is automatically resolved by the compiler, because the WriteEx methods signature
relies on the [CallerMemberName] attribute:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 209


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Direct calls modifications original signs

public delegate void TraceWithParamsDelegate(string format, params object[] args);

public static Action<string> WriteEx<T>(this ITracer tracer, string channel,


[CallerMemberName] string methodName = "")
public static TraceWithParamsDelegate WriteEx<T>(this ITracer tracer, string channel,
Category category, [CallerMemberName] string methodName = "")
public static TraceWithParamsDelegate WriteEx<T>(this ITracer tracer, string channel,
Category category, VerbosityLevel verbosity, [CallerMemberName] string methodName =
"")

public static Action<string> WriteEx<T>(this ITracer tracer, T classInstance, string


channel, [CallerMemberName] string methodName = "")
public static TraceWithParamsDelegate WriteEx<T>(this ITracer tracer, T
classInstance, string channel, Category category, [CallerMemberName] string
methodName = "")
public static TraceWithParamsDelegate WriteEx<T>(this ITracer tracer, T
classInstance, string channel, Category category, VerbosityLevel verbosity,
[CallerMemberName] string methodName = "")

Filtering for the trace provider


Inside Trace Viewer, you can select the trace channel that you have set in your code (in our example, the Siemens-
SimaticIT-Trace-BusinessLogic provider).
At the end of the execution of the code reported in the example above, you can see the following trace related
messages:

Enabling Tracing with Application Log App


Inside the code of your handlers, you can enable trace operations for the execution of the required logic by using
the public ApplicationLog method, documented in the Opcenter Execution Foundation Platform Reference Online
Help.
This method allows you to specify the message you want to write and a set of additional information that allow you
to categorize your messages and set filters inside on them in the Application Log app (verbosity level).
This API allows you to store user defined application log messages to the runtime database and retrieve those
messages for displaying in runtime environment.
1. In Project Studio, open the solution of a model project for which you want to log and retrieve messages.

210 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2. In the CommandHandler project, refer the defined message using its Message ID and parameter values at the
appropriate context through the Application Log platform API. Refer to the sample code to understand how to
use the API.

IUnifiedSdkApplicationLog

using System.Collections.Generic;
namespace Siemens.SimaticIT.Unified.Common
{
/// <summary>
/// Provides an interface for handling Application Log messages.
/// </summary>
public interface IUnifiedSdkApplicationLog
{
/// <summary>
/// Stores user defined Application Log messages in the
ApplicationLog table in database.
/// </summary>
/// <param name="messageID">Specifies the identifier of
Application Log message.</param>
/// <param name="parameterValues">Specifies the parameters and its
values contained in the Application Log message.</param>
/// <param name="owner">Specifies the name of the Package from
which the message is logged.</param>
void ApplicationLog(int messageID, Dictionary<string, object>
parameterValues, string owner = null);

Sample Code

var dict = new Dictionary<string, object>


{
{ ParameterKey, ParameterValue }
};
platform.ApplicationLog(<messageID>, dict);

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 211


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 You must make sure:


• The passed MessageID has been defined. If the message ID does not exist, the API returns a
string stating that the message ID is not found.
• The passed ParameterKey is the same as those defined in the application log xml file. If a long/
short message has been specified with a ParameterKey as a placeholder in the ApplicationLog
XML and appropriate ParameterKey is not provided as an argument for the API, then the logged
message will not have an actualized value for the ParameterKey from runtime.
For Example, If "The Equipment Lot with %Eq_Id% is created" is the message defined,
if %Eq_Id% is not provided to the API then the long/short logged message will be "The
Equipment Lot with %Eq_Id% is created".
If the ParamterKey Eq_Id is provided with a value "EQU_234-864-892" to the API, then the logged
long/short message will be "The Equipment Lot with EQU_234-864-892 is created".
• Length of ParameterValue passed is less than 512 characters. If the length of the parameter
value exceeds 512 characters, the retrieved message will have the parameter value of 490
characters length and will be appended with a note "...[Truncated]".
• (Optional) Owner is the full name of the Functional Block / App / Extension App. For Example:
Siemens.SimaticIT.WorkInstruction.

2.1.3.8 Using Opcenter Execution Foundation C# Analyzer


The Opcenter Execution Foundation C# Analyzer is a live code analyzer, installed and enabled at set-up as a VSIX
file.
The tool checks the business logic implemented in the C# handler, while you are writing or building it, and makes
suggestions on how to implement improvements.

Selecting specific code rules


You can select which rules you want the C# Analyzer to apply.
1. In Project Studio right-click the References folder of the command or event handler project and
select Analyzers > Add Analyzer.
2. Browse the Siemens.SimaticIT.CSharp.Analyzers.dll file, available in %SITUnifiedSystemRoot%bin, and click
Add.
3. Open the References folder of the command or event handler project and select Analyzers > Open Active Rule
Set.
4. Open the Siemens.SimaticIT.CSharp.Analyzers rule set node by clicking the arrow to the left and unflag the
rules you don't want to include.

 If you unflag all the rules, the C# Analyzer will be disabled on the current project.

C# Analyzer Rules
UAF0001 - Platform.GetEntity usage

Description If the query you are performing only checks for the ID of the entity,
it is preferable to simply use a Get call instead of a complex query.

Type Warning

212 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Source example

Platform.Query<IMyEntity>().SingleOrDefault(s
=> s.Id == guidVar);

Best practice example

Platform.GetEntity<IMyEntity>(guidVar);

UAF0002 - Improper use of sendCommand

Description If you need to wait for feedback use the CallCommand instead of
the SendCommand.

Type Warning

Source example

var result = Platform.SendCommand<MyCommand,


MyCommand.Response>(new MyCommand()).Result;

Best practice example

var result = Platform.CallCommand<MyCommand,


MyCommand.Response>(new MyCommand());

UAF0003 - Projection Queries support only one condition

Description As Projection queries cannot support more than one condition, problems
may occur at runtime when any of the entities in the query (in the Include
clause or as a parameter in the ProjectionQuery) are in different
databases and the lambda expression contains one or more && or ||
operators.

Type Warning

Source example

// Example 1
Platform.ProjectionQuery<IMyEntity>().Include("p2")
.SingleOrDefault(s => s.p1 == "myType" &&
s.LastUpdatedOn == timeVar);

// Example 2
Platform.ProjectionQuery<IMyEntity>().Include("p2"
).First(s => s.EntityType == "myType" ||
s.LastUpdatedOn == timeVar);

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 213


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Best practice example

// Example 1
Platform.ProjectionQuery<IMyEntity>().Include("p2"
).Where(s => s.p1 == "myType").SingleOrDefault(s =>
s.LastUpdatedOn == timeVar);

// Example 2
var test1 =
Platform.ProjectionQuery<IMyEntity>().Include("p2"
).FirstOrDefault(s => s.EntityType == "myType") ??
Platform.ProjectionQuery<IMyEntity>().Include("p2"
).First(s => s.LastUpdatedOn == timeVar);

UAF0004 - System properties of entities are read-only

Description Certain properties cannot be hidden for technical reasons, but must
not be modified, as any modifications would then be overwritten.
For example, Last Modified Date or OptimisticVersion in IEntity

Type Warning

Source example

var myEntity =
Platform.Query<IMyEntity>().SingleOrDefault(m =>
true);
myEntity.ConcurrencyToken = 123;

UAF0005 - Entity property consistency

Description Checks if properties used in queries on entities actually exist in the


entities in question.

Type Error

Source example

Platform.Query<IMyEntity>().Include(
"NotExistingProperty");

UAF0006 - Fields of type BLOB cannot be used in queries

Description BLOB type properties must not be used in queries. This rules checks
that none are present.

214 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Type Warning

Source example

Platform.Query<IMyEntity>().SingleOrDefault(md =>
md.PropertyBlob == blob);

UAF0007 - Value type does not support the New operator

Description The New operator must not be used with Value types.
If you need to reset a Value Type use the reset method, as in the
example.

Type Warning

Source example

matDef.Lot = new LotType();

Best practice example

matDef.Lot.Reset();

UAF0008 - Check Reading Model Projection Queries request

Description The ProjectionQuery argument must be of Interface Type when it is


used inside a CommandHandler of a project Library.

Type Warning

Source example

// Example 1
Platform.ProjectionQuery<MaterialDefinition>().I
nclude(\"produced_material\").SingleOrDefault(s
=> new Guid() == s.Id);

// Example 2
Platform.ProjectionQuery(typeof
(MaterialDefinition)).Include(\"produced_materia
l\").SingleOrDefault(s => new Guid() == s.Id);

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 215


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Best practice example

// Example 1
Platform.ProjectionQuery<IMaterialDefinition>().
Include(\"produced_material\").SingleOrDefault(s
=> new Guid() == s.Id);

// Example 2
Platform.ProjectionQuery(typeof
(IMaterialDefinition)).Include(\"produced_materi
al\").SingleOrDefault(s => new Guid() == s.Id);

2.1.3.9 How to Handle Timers


Timers can be configured in Apps to fire events at specific times, and to implement configured business logic.
For example, in the Pharma Industry it may be necessary to implement a delay of 10 minutes after adding a specific
chemical component on the production line.
Timers are supported in a High Availability configuration (see Configuring Opcenter EX FN in High Availability of the
Opcenter Execution Foundation Installation Guide), so that if the host running the timer should fail, the execution will
be switched to an alternative host, to guarantee its execution. This may cause a brief delay in the execution of any
timers that were planned precisely in the short time frame when the switch took place. The recovery goes back just
to a certain time in the past, covering the timeline calculated once the system was shut down.

 Timers can be easily configured using an ad hoc configuration tool within the Business Process Workflow
(see Configuring Timer Intermediate Events in Process Definition Models of the Opcenter Execution
Foundation User Manual).

Timers have two main scheduling types:


• One shot schedule: to fire the event once, at a precise time or after a specified delay.
• Periodic schedule: to fire the event continuously, with a time interval between each event.

Workflow

The operations required to effectively use timers are as follows:


1. Creating Timers.
2. Implementing event handlers for the TimerEvent.

216 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

3. Subscribing to the TimerEvent in Solution Studio

 Available Operations
• You can delete timers from your solution, by using the Platform.DeleteTimer method.
• You can retrieve timers defined in the system by using the GetTimers and GetScheduledTimers
methods.
• You can debug custom event handlers for the TimerEvent.

2.1.3.9.1 Creating Timers


To use timer events in your solution, you must create and configure your timer using
the Platform.CreateTimer method.
The Platform.CreateTimer method requires an object representing the configuration of the timer schedule. Two
possibilities exist:
• OneShotTimerSchedule: to specify a One Shot schedule (i.e. the timer will be fired only once).
• PeriodicTimerSchedule: to specify a Periodic schedule (i.e. the timer will be fired several times according to the
configuration of the schedule).
For details on the parameters of the CreateTimer method in the Opcenter Execution Foundation Platform Reference
Online Help.

Procedure
1. Invoke the Platform.CreateTimer method from your command handler to create and configure your timer.
2. Build your solution.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 217


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 Implementation notes
• Do not insert sensitive information in the Context fields of the TimerContext parameter, as this
information can be retrieved through Get Timer methods from any application, and timers are not
securable.
• When invoking the Platform.CreateTimer method from the command handler, the related behavior is
not transactional. For this reason, timers may be created before the command is completed. If the
command fails after creating the timer and the Retry Manager instantiates a command retry, then the
timer is created a second time. If the TimerUniqueName is the same it will raise an exception that can
be managed by the application to continue the handler execution, in order for the command retry to
complete successfully. We suggest therefore to avoid specifying the TimerUniqueName with logics
that make it different at each command retry (i.e. new Guid() or similar logics), because in the scenario
where the same command is invoked more than once due to the internal retries, this would result in
the successful creation of two timers with the same schedule and context information but different
TimerUniqueNames.
• During runtime operations, timers are created but they are not deleted when they are no longer
used. In this case, the handler can check the timer validity when the TimerEvent event handler is
evoked by using either TimerID or TimerUniqueName properties. If the timer is no longer valid, we
suggest you delete it to avoid the handler being called.
• When you create a periodic timer at runtime, you should take the following limitations into account:
• the start time of the timer must occur at least two minutes after the time when the
CreateTimer is invoked, otherwise the method will fail.
• If the TimeZoneInfo of a timer is not specified, the UTC date is set by default.
• When the TimeZoneInfo of a timer is set, the StartTime, EndTime and SpecificTime will be interpreted
as local to that specific time zone. Moreover, in case of a periodic timer that also has the delay set to 1
or more days all the occurrences will be interpreted with the TimeZone settings, this means that DST
settings will apply and you need to consider the following edge cases:
• during spring forward transition to Daylight Saving Time, timers that are configured to trigger at
a time of the day that does not exist due to the shift will be skipped completely
• during fall back transition, timers that are configured to trigger at a time of the day that exists
twice will be fired only the first time

Code samples
The following is the signature of the CreateTimer method:

218 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

IUnifiedSdkTimeScheduler

public interface IUnifiedSdkTimeScheduler


{
/// <summary>
/// Creates a new Timer configured with a specific schedule associated to a
timer context
/// </summary>
/// <param name="timerUniqueName"></param>
/// <param name="schedule">timer scheduling mode: e.g. repeat interval, one
shot etc..</param>
/// <param name="timerContext">the context information for Time events
triggered by this Timer</param>
/// <returns>The id of the Timer instance created</returns>
Guid CreateTimer (string timerUniqueName, ITimerSchedule schedule,
TimerContext timerContext);
}

The following is a code sample that shows a command handler creating One Shot timer. This command creates two
timers:
• one that will fire after 5 hours,
• one that will fire on a specific date and time

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 219


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

private CreateOneShotTimer.Response CreateOneShotTimerHandler(CreateOneShotTimer


command)
{
TimerContext timerContext = new TimerContext("MaterialExtensionApp");
timerContext.GroupName = "AwakeningTimer";
timerContext.AppContext = new ApplicationContext();
timerContext.AppContext.UserField1 = "MaterialExpiration";

//The following schedule will trigger the timer 5 hours after its creation
OneShotTimerSchedule delayTimerSchedule = new OneShotTimerSchedule(new TimeSpan(5,
0, 0));

try
{
Guid oneShotDelayTimerGuid = Platform.CreateTimer("AwakeIn5Hours",
delayTimerSchedule, timerContext);
}
catch (UnifiedTimeSchedulerException ex)
{
switch (ex.PlatformCode)
{
case 9002:
// Timer creation failed due to a duplicated timer unique name.
// Command handler execution can continue...
break;

case 9003:
// Timer creation failed due to input parameters validation.
// In this case it is safe to stop the execution of the command logic by
returning an error response
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;

default:
// If any other failure should occur, the command execution logic should
be stopped
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;
}
}
catch (UnifiedException exc)
{

// Timer creation failed due to infrastructural issues


throw;
}

//The following schedule will trigger the timer on 2019-01-01 00:00:00 (UTC)
OneShotTimerSchedule specificTimeTimerSchedule = new OneShotTimerSchedule(new
DateTimeOffset(2019, 1, 1, 0, 0, 0, new TimeSpan(0, 0, 0)));

220 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

try
{
Guid oneShotSpecificTimeTimerGuid = Platform.CreateTimer("AwakeOnNewYear",
specificTimeTimerSchedule, timerContext);
}
catch (UnifiedTimeSchedulerException ex)
{
switch (ex.PlatformCode)
{
case 9002:
// Timer creation failed due to a duplicated timer unique name.
// Command handler execution can continue...
break;

case 9003:
// Timer creation failed due to input parameters validation.
// In this case it is safe to stop the execution of the command logic by
returning an error response
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;

default:
// If any other failure should occur, the command execution logic should
be stopped
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;
}
}
catch (UnifiedException exc)
{
// Timer creation failed due to infrastructural issues
throw;
}
}

The following is a code sample that shows a command handler creating a periodic timer, which is fired every hour
between two specific dates:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 221


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

private CreatePeriodicTimer.Response CreatePeriodicTimerHandler(CreatePeriodicTimer


command)
{
TimerContext timerContext = new TimerContext("MaterialExtensionApp");
timerContext.GroupName = "AwakeningTimer";
timerContext.AppContext = new ApplicationContext();
timerContext.AppContext.UserField1 = "MaterialExpiration";

//The following schedule will trigger the timer every hour


//From 2019-01-01 00:00:00 to 2019-01-02 00:00:00 (CET)
TimeSpan delay = new TimeSpan(1, 0, 0);
PeriodicTimerSchedule periodicSchedule = new PeriodicTimerSchedule(delay);
periodicSchedule.StartTime = new DateTimeOffset(2019, 1, 1, 0, 0, 0, new
TimeSpan(0, 0, 0));
periodicSchedule.EndTime = new DateTimeOffset(2019, 1, 2, 0, 0, 0, new
TimeSpan(0, 0, 0));
periodicSchedule.TimeZoneInfo = "Central Europe Standard Time";

try
{
Guid periodicTimerGuid = Platform.CreateTimer("AwakeEveryHour",
periodicSchedule, timerContext);
}
catch (UnifiedTimeSchedulerException ex)
{
switch (ex.PlatformCode)
{
case 9002:
// Timer creation failed due to a duplicated timer unique name.
// Command handler execution can continue...
break;

case 9003:
// Timer creation failed due to input parameters validation.
// In this case it is safe to stop the execution of the command logic by
returning an error response
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;

default:
// If any other failure should occur, the command execution logic should
be stopped
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;
}
}
catch (UnifiedException exc)
{
// Timer creation failed due to infrastructural issues
throw;

222 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

}
}

The following is a code sample that shows a command handler creating a periodic timer with daily scheduling,
between two specific dates. The StartTime and EndTime are interpreted as Hawaiian times; each occurrence is also
interpreted as Hawaiian time because the delay parameter is set to 1 day, this means that once a year the timer will
fire after 25 hours and once a year after 23 hours because of DST settings.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 223


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

private CreatePeriodicTimer.Response
CreatePeriodicDailyFilteredTimerHandler(CreatePeriodicTimer command)
{
TimerContext timerContext = new TimerContext("MaterialExtensionApp");
timerContext.GroupName = "AwakeningTimer";
timerContext.AppContext = new ApplicationContext();
timerContext.AppContext.UserField1 = "MaterialExpiration";

//The following schedule will trigger the timer once a day at 11 A.M. Hawaiian
Standard Time
//From 2019-01-01 11:00:00 to 2019-12-01 11:00:00 (Hawaiian Standard Time)
//Timer execution is restricted to Monday and Wednesday
TimeSpan delay = TimeSpan.Parse("1.00:00:00");
PeriodicTimerSchedule periodicSchedule = new PeriodicTimerSchedule(delay);
periodicSchedule.StartTime = new DateTimeOffset(2019, 1, 1, 11, 0, 0, new
TimeSpan(0, 0, 0));
periodicSchedule.EndTime = new DateTimeOffset(2019, 12, 1, 11, 0, 0, new
TimeSpan(0, 0, 0));
periodicSchedule.ActiveDays = WeekDays.Monday | WeekDays.Wednesday;
periodicSchedule.TimeZoneInfo = "Hawaiian Standard Time";

try
{
Guid periodicTimerGuid = Platform.CreateTimer("AwakeOnceADay",
periodicSchedule, timerContext);
}
catch (UnifiedTimeSchedulerException ex)
{
switch (ex.PlatformCode)
{
case 9002:
// Timer creation failed due to a duplicated timer unique name.
// Command handler execution can continue...
break;

case 9003:
// Timer creation failed due to input parameters validation.
// In this case it is safe to stop the execution of the command logic
by returning an error response
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;

default:
// If any other failure should occur, the command execution logic
should be stopped
return new CreateOneShotTimer.Response(new ExecutionError(-1, $"Timer
{timerUniqueName} cannot be created because {ex.Message}"));
break;
}
}
catch (UnifiedException exc)

224 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

{
// Timer creation failed due to infrastructural issues
}

2.1.3.9.2 Implementing Event Handlers for the TimerEvent


Every time a timer is triggered, a TimerEvent system event is fired. By subscribing to this event with an event
handler, custom logic can be implemented.
The event is available in all the three Functional Block domains (Reference Data, Master Data and Operational
Data), contained inside the SystemData.Foundation project. It is available as a referenced system event inside the
model project of Functional Blocks, Apps and Extension Apps.
The model assembly reference required to handle the TimerEvent (i.e.
the Siemens.SimaticIT.SystemData.Foundation.Events.dll assembly which can be found
in %SITUnifiedSystemRoot%bin) is automatically inserted in the handler project.
The TimerEvent has some application defined fields and some mandatory fields to be supplied when creating a
timer.
For further information, see the TimerEvent Event in the System Reference Guide.

Defining the TimerEvent Custom Event Handler


To define a custom event handler for the TimerEvent, you must follow the same operations documented for
creating and importing any event handler.
1. Select the required event in the Event node in the Model Explorer and drag it into the central Designer Model.
2. Right-click the event and select New Event Handler.
3. Enter a name for the new event handler and confirm: the new handler is displayed in the Handlers tab of
the Model Details pane.
4. Build the model project.

Importing the TimerEvent Event Handler


1. Right-click the EventHandler project and select Import from the Model.
2. Select the event handler you just created and click OK.
3. Expand the folder structure of the EventHandler project and open the <EventNameHandler>.cs file.
4. Implement the business logic you want to execute when receiving notification of the timer event.

 See Creating Event Handlers and then Importing Event Handlers.

2.1.3.9.3 Subscribing to the TimerEvent in Solution Studio


In order to receive notification on timers and implement the required subsequent business logic, it is necessary to
subscribe to the TimerEvent.
It is recommended to then assign this subscription to a dedicated worker role to optimize performance levels in
handling timer events, which might be impacted by other time-consuming processes that may be assigned to the
same worker role.
This operation can also be performed in Project Studio as a predefined event subscription in your App, but
predefined event subscriptions are assigned to the default worker role and cannot be assigned to specific worker
roles.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 225


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

For further information on the event data structure, see the TimerEvent in the System Reference Guide.

Procedure
1. In the App Management page, click on the arrow icon within the tile of the App that contains your timer
configuration.
2. In the App Configuration page, click on the Event Subscriptions tab.
3. Click Add Event Subscription Here.
4. In the Properties tab enter a name and description that identify the subscription.
5. Click on the Event browse button, select TimerEvent, and click Select.
6. Select from the Event Handler drop down one of the available handlers for the TimerEvent.
7. In the Filter (envelope) tab specify the desired filtering criteria on the envelope fields. The Mapping between
CreateTimer and Timer Event Envelope table shows the mapping between the information specified when
creating the timer and those received in a timer event. This helps you to configure a subscription properly.
8. In the Worker Role tab do either of the following:
• Create a new dedicated Worker Role.
• Select an existing dedicated Worker Role.

 We suggest to group all timer event subscriptions in a single and dedicated Worker Role. In this way,
you have a dedicated Worker Role to manage Timer Events.

9. Click Save.

Mapping between CreateTimer and Timer Event Envelope


CreateTimer() Input Corresponding Field in the Meaning
Parameters Event Envelope

TimerUniqueName Tag Unique name of the timer.

TimerContext.AppName Topic App Name. This identifies the name of the


App creating the timer. This is the primary
key to subscribe within an app.

TimerContext.GroupName Category App specific Grouping Name used by the


App internally. It can be left empty or it can
be used to distinguish timers inside each
app.

TimerContext.Context.UserFie UserField1 App specific Context Information.


ld1

TimerContext.Context.UserFie UserField2 App specific Context Information.


ld2

TimerContext.Context.UserFie UserField3 App specific Context Information.


ld3

TimerContext.Context.UserFie UserField4 App specific Context Information.


ld4

226 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

CreateTimer() Input Corresponding Field in the Meaning


Parameters Event Envelope

TimerContext.Context.UserFie UserField5 App specific Context Information.


ld5

TimerContext.Context.UserFie UserField6 App specific Context Information.


ld6

TimerContext.Context.UserFie UserField7 App specific Context Information.


ld7

TimerContext.Context.UserFie UserField8 App specific Context Information.


ld8

TimerContext.Context.UserFie UserField9 App specific Context Information.


ld9

TimerContext.Context.UserFie UserField10 App specific Context Information.


ld10

2.1.3.9.4 Deleting Timers


To delete timers from your solution, you must use the Platform.DeleteTimer method.
The Platform.DeleteTimer method requires the Guid returned by the Platform.CreateTimer event to identify the
timer to delete.
Consequently it is important to keep track of and store the Guids of the timers created in your solution, for example
by persisting the link between the TimerUniquename and Timer GUID.
For details, see DeleteTimer in the Opcenter Execution Foundation Platform Reference Online Help.

Procedure
1. Invoke the Platform.DeleteTimer method from your command handler to identify and delete the timer.
2. Build your solution.

Code samples
The following is a code sample of the DeleteTimer method:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 227


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Try
{
//Delete the timer specifying its GUID
Platform.DeleteTimer(timerGuid);
}
catch (UnifiedException exc)
{
//Timer deletion could fail in case of
//- infrastructural issues
//- wrong input timer GUID
}

2.1.3.9.5 Retrieving Timers


To retrieve timers from your solution, you must use the GetTimers and GetScheduledTimers methods, exposed by
the platform IUnifiedSdk interface.
These methods can be called within Functional Block command handlers and App Composite command handlers.
These methods retrieve timers defined in the system as follows: the GetTimers method returns the list of the timer
definitions in terms of scheduling rules while the GetScheduledTimers returns the list of the timers that are
actually scheduled and ready to start.
This allows you to develop screens to manage timers.

 Implementation notes
The TimerDefinition objects returned by the GetTimers method contain the timer identifier (GUID) only if
the name of the App to which they belong to (optional parameter) is passed in the input parameters of the
GetTimers call.

Procedure
1. Invoke the Platform.GetTimers and Platform.GetScheduledTimers methods from your command
handler to retrieve the timer.
2. Build your solution.

Code samples
The following is a code sample of the GetTimers and GetScheduledTimers methods:

228 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

/////////////////////////////////////////////////////////////////////////
//The following example searches for a specific Timer
//then looks for the scheduled timer events in a given time range
/////////////////////////////////////////////////////////////////////////

//Start time and end time are mandatory parameters


DateTimeOffset startTime = new DateTimeOffset(2018, 12, 1, 0, 0, 0, new TimeSpan(0, 0,
0));
DateTimeOffset endTime = new DateTimeOffset(2019, 2, 1, 0, 0, 0, new TimeSpan(0, 0, 0)
);

//The TimerOptionalFilters class allows to specify some further


//optional filters if required:
//in this example, the method will look for a OneShot timer
//called "AwakeEveryHour" and belonging to the App "AppTimer"
TimerOptionalFilters timerFilters = new TimerOptionalFilters();
timerFilters.TimerUniqueNameFilter = "AwakeEveryHour";
timerFilters.TimerModeFilter = TimerMode.Periodic;
timerFilters.ContextFilter = new TimerContext("AppTimer");

//The GetTimers method returns an IEnumerable of TimerDefinition objects


//matching the specified input parameters.
var result = Platform.GetTimers(startTime,
endTime,
timerFilters);

List<TimerDefinition> timerDefinitionsList = result.ToList<TimerDefinition>();

//In this example we expect only one item in the result


if (timerDefinitionsList.Count == 1)
{
//Now you can search for specific scheduled timer events belonging to the
retrieved timer
//Note: the Guid is returned only if the GetTimers is executed specifying one of
the two following optional parameters:
// - TimerOptionalFilters.ContextFilter.AppName
// - TimerOptionalFilters.TimerIdFilter
Guid timerId = timerDefinitionsList[0].Id;

//Start time and end time are mandatory parameters


DateTimeOffset scheduleStartTime = new DateTimeOffset(2019, 1, 1, 0, 0, 0, new
TimeSpan(0, 0, 0));
DateTimeOffset scheduleEndTime = new DateTimeOffset(2019, 1, 2, 0, 0, 0, new
TimeSpan(0, 0, 0));

//The TimerOptionalFilters class allows to specify some further optional filters


if required
//in this example we look for scheduled timers belonging exactly to the timer
retrieved above
ScheduledTimerOptionalFilters scheduledTimerFilters = new
ScheduledTimerOptionalFilters();
scheduledTimerFilters.TimerIdFilter = timerId;

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 229


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

//The GetScheduledTimers method returns an IEnumerable of ScheduledTimer objects


//matching the specified input parameters
var scheduledTimersResult = Platform.GetScheduledTimers(startTime,
endTime,
scheduledTimerFilters);

foreach (ScheduledTimer scheduledTimer in scheduledTimersResult)


{
//Implement here your logic for each Scheduled Timer
}
}

2.1.3.10 How To Exchange Messages with External Systems


Opcenter Execution Foundation allows you to exchange messages with external systems (such as systems for
Enterprise Resource Planning, Product Lifecycle Management, Advanced Planning and Scheduling, Data Integration
Systems and so on).
In particular, in a properly configured system, you can send and receive messages to and from Opcenter Connect
MOM (Opcenter CN MOM) (see Distributed Scenario in the Opcenter Execution Foundation Installation Guide).

Sending Messages
To send messages you can use specific APIs (such as the SendMessage and SendMessageAsynch methods) exposed
by the platform public Sdk interface, available from Command Handlers, Composite Command Handlers and Event
Handlers.
Messages can be sent both synchronously and asynchronously.
By sending a message asynchronously, you do not wait for the reply of the external system, nevertheless, you can
retrieve information about the message, such as its Id, the timestamp etc. Sdk methods accept in input some
parameters such as the message content, the content type (json, xml).
By sending a message synchronously, you wait for the reply of the external system. The reply can be either the
expected response, or a failure due to timeout. As for the asynchronous sending option, the method accepts in
input the message content and the content type (json, xml) and the message timeout. When you are in a Command
or in a Composite Command Handler, the platform respects anyway the maximum timeout defined in the worker
role (see page Creating a New Worker Role).
In case of a synchronous message, the reply contains a flag indicating whether the timeout has been reached or not.
If the flag is true, the reply contains the message Id and the timestamp (and not the reply message content) while if
the flag is false, the reply contains also the message content.

Receiving Messages
Incoming messages are received by the Opcenter EX FN Service Layer. This functionality is achieved by configuring
the external system (i.e the Opcenter CN MOM) by following the related implementation guidelines.

 For more information, see the IUnifiedSdkMessaging Interface in the Opcenter Execution
Foundation Platform Reference Online Help.

230 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.11 How to Read and Write on Automation Node Parameter Values


This chapter describes how to implement custom logic either inside Command Handlers, or Event Handlers or
Reading Function Handlers, in order to execute read and write operations on the Automation Node parameter
values.
Automation Nodes are copies in the Operational Data Domain of the Automation Node Instances you
have configured and activated in the Master Data Domain.
Automation Nodes are IAutomationEntity type entities.
Inside the code of your Handlers, you can use the platform functionalities exposed by the IUnifiedSdk public
interface that allow you to execute operations on the parameter values of the Automation Nodes through the
following methods:
• AutomationRead for read operations,
• AutomationWrite for write operations.

 The implementation details of these methods, such as parameter names and code examples, are provided
in the Opcenter Execution Foundation Platform Reference Online Help.
Also refer to How to Guarantee Consistency between Opcenter Execution Foundation and Automation
Gateway Data Changes for configuration guidelines.

Implementation flow
We suggest you execute the following configuration steps:
1. Check that you have enabled the Automation Gateway Server configuration as described in Configuring the
Engineering Host in a Distributed Environment of the Opcenter Execution Foundation Installation Manual or
modify the existing settings as described in Modifying the Environment Configurations of the Opcenter Execution
Foundation Installation Manual.
2. In Solution Studio, install the Automation Gateway App and deploy the Solution as described in How to Manage
a Manufacturing Solution in Solution Studio.
3. In the Automation Gateway App, go through the configuration flow described in How to Manage Automation
Nodes in the Opcenter Execution Foundation User Manual.
4. To read from or write to the Automation Node parameter values, create either a Functional Block, and/or an
App, which reference the ATN_OP Functional Block (as described in the following sections: How to Develop a
Manufacturing Functionality for the Functional Block, or How to Develop an App for a Manufacturing Use
Case for the App).
5. According to the logic you want to implement, model the required artifacts (Commands or Composite
Commands, Events or Reading Functions) and then write the code in the corresponding C# classes by using
the IUnifiedSdk interface as shown below.

Overview of Automation Gateway Server public interface


Within the code of Command Handlers, Composite Command Handlers, Event or Reading Function Handlers, the
platform IUnifiedSdk public interface exposes the following methods for implementing reading and writing
operations on Automation Gateway Server (as for all platform public functionalities, the write methods are only
available within Command and Composite Command Handlers).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 231


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Method Description

AutomationRead The platform exposes two overloads of the AutomationRead method for
executing read operations:
• The first method accepts in input a list of IAutomationEntity, and reads
all values defined for the Automation Parameters of the specified
entities.
• The second method accepts in input a list of strings corresponding to
the Ids of the Automation Nodes (i.e. the Ids specified when Creating
Automation Node Instances) and reads all values defined for
the Automation Parameters of these entities.

AutomationWrite Write operations can be performed on the automation parameter values of


the Automation Nodes.
Before you can write on the parameter values, you must first implement a
Read operation by invoking the AutomationRead method. This operation
allows you to access the automation parameters that decorate the
Automation Nodes. Then you can invoke the write method to set the values
of the retrieved parameters. Only the specified values will be overwritten.
The platform exposes the AutomationWrite method which accepts in input
a list of IAutomationEntity.

 This method directly writes on the automation parameter values


of the Automation Gateway Server process image. Consequently if
you have a chain of commands that update several parameter
values, and one of these commands fails, there is no rollback logic
which restores the initial values. This logic can be implemented
within custom commands.

Implementation guidelines can be found at Best Practices for Automation


Writing Operations.

2.1.3.11.1 How to Guarantee Consistency between Opcenter Execution


Foundation and Automation Gateway Data Changes
The AutomationWrite method, which is used to write on the Automation Parameter values, is immediately
effective and does not wait for the transaction to end successfully, unlike the platform Submit method, which is
used to write on the entities of the Opcenter Execution Foundation relational database and which writes on the
database only once the transaction has ended successfully.
Moreover, since the AutomationWrite method can only guarantee that the Automation Parameter value has been
passed to the driver (e.g. OPC UA), you can consider the write operation effectively completed only when a separate
asynchronous notification arrives from the driver.
Consequently, if your business logic needs to consistently update the entities of the relational database and the
Automation Parameter values, it is strongly recommended to implement business logic based on the intermediate
statuses of entities.

Example

232 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Suppose that you have an entity, for example Order, with the Status property, which can assume the
Started value.
When Order starts, the Order Id and some set points must be written on the Automation Parameter values.
If you want to guarantee consistency between relational and automation data, the business logic should ensure
that the status of Order can be set to Started only after the write operation has been acknowledged by the
automation driver.
To implement this use case, the Order entity could assume an intermediate status, for example Starting, before the
acknowledge message arrives from the Automation Gateway Server.
Consequently, you should implement a Composite Command, which will execute the following operations: first it
will call the Command that writes the Order Id and the set points on the Automation Gateway Server, then it will
call the Command that changes the Order status to Starting.
Then you should configure a Signal Rule that triggers the Command that sets the Order status to Started when the
Automation Gateway Server (e.g. the OPC Server) notifies, for example, the change of the value of a certain
Automation Parameter, which acts as an acknowledge notification.
In this way, the Order status is updated only when the Automation Gateway Server receives the new Order Id, and
the MES business logic, which is based on that status, can rely on the correct value.

Configuration guideline
This logic should implement a handshake with the Automation Gateway Server as follows:
1. Model the Automation Node as described in How to Manage Automation Nodes of the Opcenter Execution
Foundation User Manual.
2. Within a custom Functional Block, which references the ATN_OP Functional Block, link the Automation Node
entity to the required MES entity.
3. Configure the Automation Node Parameters written by MES, and the Automation Parameters notified by the
Automation Gateway Server.
4. Model the entity with a Status property, which can be used to store values that indicate both a final and
transient status.
5. Model and implement the code of the Commands that write the data on the Automation Gateway Server and
that set the transient status of the entity.
6. Configure a Signal Rule in the Signal App, which is triggered when a certain Automation Parameter value
changes and wire it to a Command that sets the entity to a final status.

2.1.3.12 How to Integrate Electronic Signature in Custom Applications


In order to enable and use an Electronic Signature Scenario that validates (approves or rejects) a Manufacturing
operation, you must integrate the Electronic Signature functionalities by implementing custom Functional Blocks
and Apps as described in this guideline.
For a general overview on the Electronic Signature in Opcenter Execution Foundation, see Electronic Signature in
the Opcenter Execution Foundation User Manual.
After you have fulfilled all the minimum required development steps, you can use Electronic Signature Scenarios
inside your custom Appsor as implemented in built-in platform Apps

Functional Block development workflow


1. Inside your custom Functional Block, add the references to the Electronic Signature Functional Blocks
according to the use case you want to implement.
2. Modify your custom entity/entities by adding the required Value Type properties.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 233


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

3. Implement or modify the create, update, delete commands for your custom entity and develop any other
required business logic.

App development workflow


1. Inside your custom App add the references to the custom Functional Block (and to any other required system
Functional Block).
2. Import the custom entity and the related custom commands to the POM Model.
3. Import the Electronic Signature Scenario entities and the CreateScenarioInstance command to the POM Model.
4. Implement the Composite Command that creates the Electronic Signature Scenario Instance and associates it
to the custom entity.
5. Modify the UI pages to include the engineering and the runtime UI Framework widgets, and add, if needed, any
custom logic in the UI page code that verifies if the Electronic Signature Scenario instance is completed or
rejected.
6. Modify or add the business logic that will be executed after the completion of the Electronic Signature Scenario
and that represents the action you are actually validating (e.g. the lot material consumption or the lot status
change). This command can verify that all the required Electronic Signatures have been inserted before
triggering the business logic.

Runtime workflow
To use the Electronic Signature functionalities:
1. Install the Audit Trail App in Solution Studio, any other required system Apps or custom Apps, and deploy the
Manufacturing Solution as documented in How to Manage the Solution.

 If the Audit Trail App is not installed, the Electronic Signature widgets are not visible in the UIs.

2. Create the Electronic Signature Scenarios and add the Electronic Signatures as described at Creating an
Electronic Signature Scenario in the Opcenter Execution Foundation User Manual.
At this point, operations that require the collection of the Electronic Signatures are ready to be started.

2.1.3.12.1 Electronic Signature Data Model Entities


The Electronic Signature Scenario data model is made up of the following artifacts:
• an engineering entity belonging to the ES_MS Functional Block, named ScenarioConfiguration, which acts as a
base configuration entity,
• a runtime entity, belonging to the ES_SD Functional Block, named ScenarioInstance entity, which contains the
actual signatures collected at runtime based on the configuration of the related ScenarioConfiguration.
To link a custom entity to the Electronic Signature Scenario entities you should use the predefined ValueType
property types, which provide a one-to-one cross-domain reference to the following entities:

ValueType Name and Referenced Description


Properties Entity

ScenarioConfiguratio ScenarioConfigur Provides a logical link (one-to-one) to the NId of the


nValueType ation ScenarioConfiguration entity. Moreover, it also contains the
ActionLabel property, which can be defined during the
configuration phase and then passed at runtime during the
generation of the ScenarioInstance entity (see notes below).

234 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

ValueType Name and Referenced Description


Properties Entity

ScenarioInstanceVal ScenarioInstance Provides a reference (one-to-one) to the Id of the


ueType ScenarioInstance and a reference to the ScenarioInstance NId.

What is the Scenario ActionLabel


The ActionLabel property is a custom string used to identify the context in which the Electronic Signature Scenario
is used and Signatures will be collected.
It is contained inside the ScenarioConfigurationValueType value type as well as inside the ScenarioInstace entity.
Typically, the ActionLabel property value is set at configuration time in the property of
the ScenarioConfigurationType value type.
The ActionLabel can be used in either of the following use cases:
• in a single-scenario use case where the string simply describes the ScenarioConfiguration that is associated with
the custom entity.
• in a multiple-scenario use case, where the string is used to identify the contexts in which the same custom entity
will be associated to different ScenarioConfigurations (e.g. for the ActionLabel = Approve, your custom entity
may need a Scenario Configuration with 2 signatures, and for the ActionLabel = Dismiss, your custom entity may
need a different Scenario Configuration with 3 signatures).

2.1.3.12.2 Examples of Electronic Signature Scenario Use Cases


Electronic Signature functionalities apply to Manufacturing Solution needs in many different ways and the
proposed use case scenarios are consequently not exhaustive and must be only considered as possible use
examples.

Single scenario instance with single engineering entity


In this scenario, you need to approve with Electronic Signatures an action on a custom engineering entity, for
example a Recipe.
The custom entity should be consequently modeled with two properties: a logical link (value type) to the
ScenarioConfiguration entity and a reference (value type) to the ScenarioInstance entity.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 235


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Single scenario instance with engineering and runtime entities


In this scenario, an entity belonging to the Master Data domain (for example a lot template) has one or more
corresponding entities in the Operational Data domain (for example the custom lots). Only the runtime entities
need to be validated through Electronic Signatures.
In this case, the engineering entity type (CustomLotTemplate) contains a logical link (value type) to the
ScenarioConfiguration entity (see the ESScenario property below), and the runtime entity (CustomLot) contains
the reference (value type) to the ScenarioInstance entity (see ESScenarioInstance property below).

236 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

This use case will be shown with snippet examples at the following pages:
• Configuring the Data Model for Electronic Signature Scenario Integration
• Implementing the Business Logic for Electronic Signature Scenario Integration

Multiple scenario instance with engineering and/or runtime entities


In this scenario, you may need to approve an entity through several validation steps that require different
Electronic Signature Scenarios.
The entity to be approved can be either an engineering entity (as described in the previous first use case, Single
scenario instance with single engineering entity) or a runtime entity based on an engineering entity as described in
the second use case (Single scenario instance with engineering and runtime entities).
The focus of this scenario is placed on how to model a one-to-many relationship between the custom entity and
multiple Scenario Configurations. The same pattern could be also applied if you wanted to model a one-to-many
relationship between the custom entity and the Scenario Instances.
For this purpose, the custom entity (see EquipmentType below) should be associated with a one-to-many
relationship with an additional entity (see EquipmentScenarioConfiguration below) that contains the reference
(value type) to the ScenarioConfiguration entity. In this way, the Equipment Type can have more Scenario
Configurations.
In the screenshot below, the mapping entity is EquipmentScenarioConfiguration and contains
the ScenarioConfigurations property of ScenarioConfigurationValueType type.
EquipmentScenarioConfiguration acts as 'list of' Scenario Configurations that will be instantiated at runtime.

 This additional entity is required because the value type property cannot be used as a list of value types
(List<ScenarioConfigurationValueType>).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 237


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The entity that is involved by the validation (e.g. EquipmentInstance), could also foresee modifications to its life
cycle in order to have a custom step for collecting and checking the signatures belonging to one Scenario
Configuration before passing to any other steps and collecting the signatures belonging to another Scenario
Configuration.
Moreover, be aware that compared to the single scenario use case where the ActionLabel property acts only as a
descriptive string, for this use case the ActionLabel property becomes highly important as it allows you to
determine the correct ScenarioInstance that is being used at runtime.

238 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.12.3 Configuring the Data Model for Electronic Signature Scenario


Integration
In order to use the Electronic Signature inside your custom operation, you must first modify the entities on which
the operation will be executed.
The entity involved by your command must be manually modified in Project Studio in order to be properly linked to
the Electronic Signature Scenario Configuration and/or Instance.
To do this, you have to modify the model project for your custom entities in Project Studio and add the
required reference properties as described in this page.

 The following examples refer to concepts and procedures already described Functional Block and App
development (e.g. data model with entities and value types, business logic and UI development) and are
not mentioned to be a step-by-step description from scratch.

Example of single scenario instance use case


As an example of single-scenario instance use case, you can either link a custom engineering entity to the custom
runtime entity or use a value type if these entities belong to different domains.
The link among the following entities is even unnecessary as the model is strictly dependent on the customer
scenario. Here the link is shown because it is used in the code snippets:

In this example, the custom engineering entity contains a logical link to the ScenarioConfiguration entity via
ScenarioConfigurationValueType value type property:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 239


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The custom runtime entity contains a reference to the ScenarioInstance entity Id


via ScenarioInstanceValueType value type property:

Once the model project is completed, you can build the model project of the Functional Block and proceed with the
business logic implementation.

Creating a Scenario Instance "on the fly"


There is another way to create a Scenario Instance without first creating the Scenario Configuration. This
functionality will help in speeding up the modeling phase. In this case you can use
the CreateScenarioInstanceWithSignatures command which allows you to create a Scenario Instance using
directly a list of users/roles and reason to sign. If while modeling your business logic you do not know which users
or business roles must sign a particular operation, you cannot create a Scenario Configuration. To avoid this, you
can directly create the Scenario Instance as soon as you receive the needed information, even right before entering
the runtime signature.

240 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.12.4 Implementing the Business Logic for Electronic Signature


Scenario Integration
After you have modified the data model in order to correctly link your entities to the required Electronic Signature
ScenarioConfiguration and Electronic Signature ScenarioInstance, you must implement the creation/update
logic for your entity instances in order to link them to the Id of the required Electronic Signature
ScenarioConfiguration and ScenarioInstance.
Typically, the Id of the ScenarioConfiguration is returned by a UI page, where the user can select the needed
scenario.
For the described integration use case, you have to implement the following commands:
• a command which creates/updates an instance of your custom entity (for instance, engineering entity) and
assigns the NId and the ActionLabel of the ScenarioConfiguration to the entity (via ValueType).
• a command which creates/updates an instance of your runtime entity and assigns a logical link to the
ScenarionInstance entity Id.
• a composite command which creates an instance of the ScenarioInstance entity and assigns it to the custom
runtime entity, by means of the previously described command. You need a composite command because this
is the only way to access cross-domain functionalities (the ScenarioInstance entity belongs to the System
Domain domain, which is not one of the Functional Block domains).
For the logic that you may want to implement in the UI pages, see Implementing the UI Screens for Electronic
Signature Integration.

Examples
The following command code snippet creates an instance of the custom engineering entity (in the example
CustomLotTemplate) and sets the added properties to the ScenarioConfiguration NId and ActionLabel.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 241


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Create Custom Lot Template Command

using [...] namespace [...]


{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class CreateLotTemplateHandlerShell
{
/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HandlerEntryPoint]
private CreateLotTemplate.Response CreateLotTemplateHandler(CreateLotTemplate
command)
{

var lotTemplate = platform.Create<ICustomLotTemplate>();


lotTemplate.NId = command.NId;
lotTemplate.Name = command.Name;
lotTemplate.Material = command.Material;
lotTemplate.ESScenario.NId = command.ESScenarioNId;
lotTemplate.ESScenario.ActionLabel = command.ActionLabel;
platform.Submit(lotTemplate);

//to be implemented
return new CreateLotTemplate.Response() { CreatedLotTemplateId =
lotTemplate.Id };
}
}
}

The following command code snippet creates an instance of the custom runtime entity (e.g. CustomLot).

 According to the business logic needs, you may need to create the ScenarioInstance entity either during
the custom entity creation or during the custom entity update. The current example creates the
ScenarioInstance entity in update and consequently both examples, for create and update, are provided
here below, together with the Composite command.

242 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Create Custom Lot Command

using [...]
namespace [...]

{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class CreateCustomLotHandlerShell
{

[HandlerEntryPoint]
private CreateCustomLot.Response CreateCustomLotHandler(CreateCustomLot
command)
{

var myTemplate = platform.Query<ICustomLotTemplate>().Single(x => x.Id ==


command.TemplateId);

var customLot = platform.Create<ICustomLot>();


customLot.NId = command.NId;
customLot.LotTemplate = myTemplate;
customLot.Material = command.Material;

platform.Submit(customLot);

return new CreateCustomLot.Response() {};


}
}
}

The following command code snippet updates the custom entity instance and sets the logical link to
the ScenarionInstance Id. Moreover, it retrieves the Scenario Configuration NId from the engineering entity.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 243


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Update Custom Lot Command

using [...]
namespace [...]

{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class UpdateCustomLotHandlerShell
{
/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HandlerEntryPoint]
private UpdateCustomLot.Response UpdateCustomLotHandler(UpdateCustomLot
command)
{
// Put your code here
// return new UpdateCustomLot.Response() { ... };

var customLot = platform.Query<ICustomLot>().Include("LotTemplate").First


OrDefault(x => x.Id == command.Id);

///associate the Instance Id returned from the UI


customLot.ESScenarioInstance.Id = command.ESScenarioInstanceId;
customLot.ESScenarioInstance.NId = customLot.LotTemplate.ESScenario.NId;
///customLot.ESScenario = customLot.LotTemplate.ESScenario.NId;

platform.Submit(customLot);
return new UpdateCustomLot.Response() { };
}
}
}

The following Composite Command code snippet creates an instance of the ScenarioInstance system entity by
retrieving the ScenarioConfiguration NId and Action Label from the parent Lot Template. Then it assigns the Id of
the created instance to the Custom Lot.
To do this, the command invokes the CreateScenarioInstance command and then the UpdateCustomLot
command which is documented above.

244 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Create Scenario Instance and Assign it to the Custom Lot Id

using [...]
namespace [...]
{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class CompositeCreateScenarioInstanceHandlerShell
{
/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
/// <remarks>This is a Composite Command Handler</remarks>
[HandlerEntryPoint]
private CompositeCreateScenarioInstance.Response
CompositeCreateScenarioInstanceHandler(CompositeCreateScenarioInstance command)
{

//Retrieves the related Custom Lot Template entity starting from the Id
of the Custom Lot (POM Model app entity) selected in the UI Screen
var lot = platform.ProjectionQuery<CustomLot>().Include("LotTemplate").Fi
rstOrDefault(x => x.Id == command.CustomLotId);

//Invokes the CreateScenarioInstanceCommand and pass some parameters from


the Custom Lot Template
var scenarioInstance = new CreateScenarioInstance
{
ActionLabel = lot.LotTemplate.ESScenario.ActionLabel,
ApplicationName="CustomApp",
SignedEntityId= command.CustomLotId,
SignedEntityType = lot.EntityType,
ScenarioConfigurationNId = lot.LotTemplate.ESScenario.NId,
ValidationMode = ValidationModeEnum.Approve
};

var returnedScenarioInstance =
platform.CallCommand<CreateScenarioInstance,
CreateScenarioInstance.Response>(scenarioInstance);

//Invokes the Update Custome Lot command to assign the Id of the


ScenarioInstance
var mylotTobeAssigned = new UpdateCustomLot();

mylotTobeAssigned.ESScenarioInstanceId =
returnedScenarioInstance.ScenarioInstanceId.Value;
mylotTobeAssigned.Id = command.CustomLotId;

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 245


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

var assignLot = platform.CallCommand<UpdateCustomLot,


UpdateCustomLot.Response>(mylotTobeAssigned);

return new CompositeCreateScenarioInstance.Response() {


ESScenarioInstanceId = returnedScenarioInstance.ScenarioInstanceId,
ESScenarionConfigurationNId = lot.LotTemplate.ESScenario.NId
};
}
}
}

 For more information on the code snippets and the mentioned concepts, see also:
• Creating and Updating Entity Instances via Submit method
• Adding and Removing Navigation Properties
• Creating Value Types
• Using Reference Value Type Properties

CreateScenarioInstance command parameters


• The ValidationMode parameter value, which accepts in input either Approve or ApproveOrReject, is passed to
the sit-rt-signatures widget and sets the collection mode at runtime of the signatures. See Implementing the UI
Screens for Electronic Signature Integration for the widget description.
• The ActionLabel parameter is explained at Configuring the Data Model for Electronic Signature Scenario
Integration.
• The SignedEntityId and SignedEntityType parameters provide a unique reference to the custom entity to
which the scenario instance is related. SignedEntityType is the name of the type which defined in the entity
model and it can be retrieved from the EntityType property of the entity.
• The ScenarioConfigurationNId is used to specify the ScenarioConfiguration entity item for which you want to
create a runtime snapshot entity.
For more information on the CreateScenarioInstance command parameters, you can refer to the Audit Trail App
reference guide (see CreateScenarioInstance command in the ES_SD Functional Block Reference Guide).

Note about unassigned ScenarioInstances


Due to errors that may be raised either during the runtime execution or because of a wrongly implemented business
logic, you may inadvertently create Scenario Instances that remain unassigned from any custom entities.
Though you cannot delete these entities from custom Functional Blocks or Apps (indeed, cross-domain operations
on the writing model are not allowed by the platform domain model), this does not negatively affect the usage of
Electronic Signatures at runtime.
Nevertheless, this issue must be taken into account when you need to directly query the ScenarioInstance entity.

2.1.3.12.5 Implementing the UI Screens for Electronic Signature Integration


The Opcenter EX FN UI Framework makes two widgets available for the Electronic Signature integration: the sit-es-
scenario-picker and the sit-rt-signatures widget.

246 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 These widgets will provide full functionalities at runtime only if the Audit Trail App is installed and
deployed.
If you want to test a custom UI page embedding the Electronic Signature widgets, see note at page How To
Debug UI Modules and Screens.

sit-es-scenario-picker widget overview


This widget displays an entity picker which helps you to select a ScenarioConfiguration entity instance. The widget
filters by ScenarioConfiguration entity instances that have been already associated to Electronic Signatures.
The widget can be integrated in any code-based UI Module by means of the following HTML code snippet:

<sit-es-scenario-picker
sit-config="vm.configESPicker" sit-filter="vm.filter"></sit-es-scenario-picker >

 For more information on the widget, see also the sit-es-scenario-picker widget in the UI Framework
Reference.

sit-rt-signatures widget overview


This widget provides you with Electronic Signature runtime functionalities.
The widget displays a button and a dialog box, and it can be integrated in any code-based UI Module by means of
the following HTML code snippet:

<sit-rt-signatures sit-scenario-instance="vm.ScenarioInstance"></sit-rt-signatures>

The vm.ScenarioInstance widget configuration object contains a structure with an input parameter as follows:

vm.ScenarioInstance =
{
ScenarioInstanceId: '<the scenario instance guid>',
}

The ScenarioInstanceId parameter containing the Id of the ScenarioInstance is mandatory.


In the UI screen, the embedded widget is displayed as a button with the following characteristics:
• the status of the Scenario Instance represented by icons (a green check for Approved, a red cross for Rejected
and a clock for Pending, if the widget is still waiting for missing signatures).
• a label that can be either Sign or View Signature:
• Sign is used to indicate that signatures still need to be collected (i.e. if the number of the collected
signatures is smaller than the number of the required signatures). In this case, the widget will open in
interactive mode.
• View Signature is used to indicate that no more signatures need to be collected either because the
scenario is rejected or because it is completed (i.e. if the number of the collected signatures is equal to
the number of the required signatures). In both cases, the widget will open in read-only mode to simply
show the collected signatures.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 247


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• a counter indicating the number of the collected signatures compared to the number of the required signatures
(e.g. 0/3, 1/3, 2/3, 3/3).
After clicking the Sign/View Signature button, the widget shows an accordion that contains the status of the
collected signatures (with the accordion body in read-only mode and the information related to the signers) as well
as the list of the signatures that still need to be collected (with the accordion body containing the signature form).
According to the value set for the ValidationMode property of the ScenarioInstance entity (see the example of
CreateScenarioInstance invocation used in the Composite command described at page Implementing the
Business Logic for Electronic Signature Scenario Integration), the widget shows (or hides), the validation buttons as
follows:
• if the ValidationMode value is ApproveOrReject, the Accept and Reject option buttons are available and you
must choose the proper validation option before inserting the Electronic Signature,
• if the value is Approve, no validation option buttons are shown and you can only enter Electronic Signatures
without approving/rejecting the action.
Each time the ScenarioInstance object is refreshed, the OnCloseSignatures(obj) event is fired and the object
status information is propagated to the hosting UI module.
The ScenarioInstance object is refreshed in the following cases:
• if the ScenarioInstance entity Id is associated to the widget for the first time,
• if the ScenarioInstance entity Id which is already associated to the widget, is modified,
• if a new signature is collected,
• if you close the widget (i.e. either by clicking on the Close button, or by clicking the X button on the top-right bar
of the dialog box).
According to the actions performed, the ScenarioInstance object status (corresponding exactly to the
ScenarioInstance entity status), may change and custom actions can be triggered. For the list of possible statuses
to which you can subscribe logic, see Handling the Electronic Signature Scenario Instance Status.
When the scenario instance is in Completed or Rejected status, the back-end OnCompleteScenarioInstance event
is also fired (see Handling the Electronic Signature Scenario Instance Status).

 For more information on the widget, see also the sit-rt-signatures widget in the UI Framework Reference.

2.1.3.12.6 Handling the Electronic Signature Scenario Instance Status


To handle the status returned by the Electronic Signature runtime widget, you have several possibilities. For
example, you can implement the following logic:
• you can make a subscription to the front-end OnCloseSignatures(obj) event from the code of the UI page (for
example, to enable a button in the custom UI page only if the scenario is completed),
• you can make a subscription to the back-end OnCompleteScenarioInstance event from the code of an Event
Handler (for example, to invoke business logic only if the scenario is completed)
• you can query the status of the ScenarioInstance entity, to make checks on the scenario status.

OnCloseSignatures(obj) event subscription example


From the code of your custom UI screen, you can handle the status changes of the Scenario Instance associated
with the custom entity by subscribing to the OnCloseSignatures(obj) event.
The OnCloseSignatures(obj) event contains the data object structure contains:
• the Id field, with the Id of the Scenario Instance that changed status.
• the Status field, with the Status of the Scenario Instance referred to data.Id field.

248 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The Scenario Instance is updated each time a new signature is collected, and assumes the following statuses:
• Initial
• InProgress
• Rejected (the scenario is completed)
• Approved (the scenario is completed)
The following UI container snippet provides an example of how to subscribe to the OnCloseSignatures(obj) event:

$rootScope.$on('OnCloseSignatures', vm.ChangeUIStatus);

function ChangeUIStatus(event,data)
{
vm.Id = data.Id;
vm.Status = data.Status; //Contains the Status of the last Scenario Instance that
changed status.
}

ScenarioInstance entity query example


Inside a Command/Event/Reading Function handler, you can implement a query to read values from the
ScenarioInstance entity.
Then, you may determine the invocation of the required business logic according to the retrieved status (this part is
not shown as it is highly custom dependent).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 249


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

[...]

namespace [...]

{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class CheckScenarioStatusHandlerShell
{

[HandlerEntryPoint]
private CheckScenarioStatus.Response
CheckScenarioStatusHandler(CheckScenarioStatus command)
{

//Retrieves the custom entity Id from the item selected on the UI screen
and uses the navigation property to retrieve the related Scenario Instance.
//ESScenarioInstance is the name assigned to the ScenarioInstanceValueType
in Project Studio and ESScenarioInstance_Id is the corresponding navigation property.

var customLot =
platform.ProjectionQuery<CustomLot>().Include("ESScenarioInstance_Id"
).FirstOrDefault(e => e.Id == command.CustomLotId);

//Returns information within the command response


return new CheckScenarioStatus.Response()
{
Status = customLot.ESScenarioInstance_Id.Status.ToString(),
ESScenarioConfigurationNId =
customLot.ESScenarioInstance_Id.ScenarioConfigurationNId,
ESScenarioInstanceId = customLot.ESScenarioInstance_Id.Id
};
}
}
}

Subscribing to the OnCompleteScenarioInstance Event


You can implement an event subscription (or a predefined event-subscription) as documented at How to
Implement Event Handlers for the OnCompleteScenarioInstance event.
The following code snippet shows an example of Event Handler, with the invocation of a custom command:

250 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

[HandlerEntryPoint]
private void AutoNextStepOnCompleteScenarioInstance (OnCompleteScenarioInstance evt,
EventEnvelope envelope)

{
if (envelope.module != "MyCustomApplication")
{
return;
}
var command = new AutoNextStep() { Id = evt.SignedEntityId };
var response = Platform.CallCommand<AutoNextStep,
AutoNextStep.Response>(command);
}

The OnCompleteScenarioInstance event is fired when the Scenario Instance has been completed and it is
in Approved or Rejected status.
The event has the following envelope data structure:

Envelope Property Property value

Category OnCompleteScenarioInstance

Module The name of application that uses the Electronic Signature functionality.

Tag The status of scenario instance.

Topic The type of entity associated to the Scenario Instance.

UserField1, UserField2, ... FOR INTERNAL USE


to UserField10
The input data structure of the OnCompleteScenarioInstance event is defined as follows:

Name Type Description

ApplicationName String The name of application that uses the functionality


of Electronic Signature. Maximum length: 255.

Context String Additional information on the context where the


runtime entity is used. Maximum length: 255.

ScenarioInstanceId Guid The primary key identifier of the Scenario Instance


completed.

ScenarioConfigurationNId String The natural key of Electronic Signature Scenario


Configuration. Maximum length: 255.

CompleteAction String The action associated to Scenario Instance final


state. Maximum length: 255.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 251


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Name Type Description

SignedEntityId Guid The primary key of the entity requiring Electronic


Signature.

SignedEntityType String The full type of the entity requiring Electronic


Signature. Maximum length: 255.

ActionLabel String The action label. Maximum length: 255.


For further information, refer to the Events section of the Events section of the ES_SD Reference Guide.

2.1.3.13 How to Use Semi-Automatic Acquisition in Work Instructions


You can implement the semi-automatic acquisition of values coming from third-party systems for Work Instructions
(see Work Instruction App in the Opcenter Execution Foundation User Manual).
Semi-automatic means that the acquisition is actually performed only after you interactively click a dedicated
button placed on the UI screen and then confirm and complete the Work Instruction in order to persist the acquired
data.
To enable this behavior you have to perform a custom implementation which allows you to specify which Data
Collection Step Items are defined as semi-automatic and implement the custom code (Post-Action) which allows
you to define the data you want to read from.

Implementation workflow
1. For each Work Instruction runtime instance (see also Creating Work Instructions in the Opcenter Execution
Foundation User Manual), you have to set the acquisition behavior of each Section Step Item.
2. When the Work Instruction is opened at runtime, the system automatically displays the acquisition button (if
there is at least one Step Item which is set as semi-automatic).
3. When you click the acquisition button, the system invokes the Post-Action containing the custom reading logic.

Implementation details
Implementation phase Description

Setting the Step Item acquisition mode From a custom application, implement the custom code to
invoke the following public commands exposed by the Work
Instruction App:
• invoke the RetrieveDCItems command to retrieve the Ids
of the Step Items of a Work Instruction runtime instance,
• invoke the SetAcquisitionBehavior command and pass
the list of Step Item Ids you want to define as semi-
automatic. The SetAcquisitionBehavior accepts in input
a list of <AcquisitionParameterType> Parameter Type,
containing Id (Guid, the Id of the Work Instruction Step
Items) and AcquisitionBehavior (Value Type, containing
the following enumeratives: Manual or SemiAutomatic).

252 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Implementation phase Description

Implementing the reading logic in the Post- Within a custom Functional Block, which extends the WI_OP
Action Functional Block, model a Post-Action to extend the platform
logic of the AcquireDCValues public command (exposed by
the Work Instruction App and contained in the WI_OP
Functional Block). The Post-Action handler must contain the
code to perform the following operations:
• retrieve the data source for each Step Item passed in the
input (a separate anagraphic for each Step Item and the
related data source should be available)
• retrieve the values for each Step Item from its data source
• invoke the SetDCItemValues command to persist the
acquired values (list of values) on the database. This step
allows the Work Instruction runtime instance to read and
display the retrieved values in the Work Instruction form.

Runtime workflow
1. Open the required Work Instruction runtime instance (see also Executing Work Instructions in the Opcenter
Execution Foundation User Manual).
2. When the Work Instruction is opened at runtime, the Acquire button is automatically displayed to permit the
semi-automatic acquisition of the required values. The button is displayed if there is at least one Step Item that
has been defined as semi-automatic.
3. Click the Acquire button: when you click this button, the system invokes the AcquireDCValues public command
together with the related custom Post-Action. The value retrieved from the Post-Action code is displayed in the
semi-automatic Step Item. You can either confirm the value as it is or modify it.
4. To actually store the collected value in the Work Instruction, confirm the Data Collection form.

2.1.3.14 How To Manage Application Logs


To log application messages related to a manufacturing command, you need to refer the log messages, which must
be defined in a proper xml file, inside the command handlers of a Functional Block / App / Extension App by means
of the ApplicationLog platform API and by installing the Application Log App in Solution Studio.
In the Application Log App UI screens, you can view the messages that are logged in the runtime environment of
your UI application. For more information on the Application Log App, see Application Log App in the Opcenter
Execution Foundation User Manual.
After you build and deploy packages in your Manufacturing Solution in Solution Studio, all application log messages
will be persisted to the engineering repository.
To properly configure log messages you need to go through the steps below.

Workflow
1. Manage the Application Log File, used to generate the log messages.
2. Associate Business Logic with Application Log Messages.
3. Retrieve Application Messages without Logging.
4. Localize Application Log Messages, if required to view log messages in multilanguage.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 253


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.14.1 Managing the Application Log File


The Application Log file is an xml file that allows you to define the application messages for a Functional Block /
App / Extension App. You can have an Application Log xml file for each Functional Block / App / Extension App.
If you are creating a new Functional Block, an empty xml file is automatically created under the Installer project.
But if you are modifying an existing Functional Block, you must manually add the xml file to the Installer project.
Then you can open this file in Project Studio and define the application log messages.

 In both cases, the default language of the xml file is English and the file name must be in the
format <prefix>.<functional block / app / extension app name>.ApplicationLog.en-US.xml.
You must not modify this file name pattern.

The system manages all the xml files and stores the catalog of messages in the database. By means of the
Application Log App, installed in Solution Studio, you can log the defined messages and view them in your UI
Application at runtime.
This section describes the structure of the xml file and its restrictions.

Application Log xml File Structure

File Structure

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


<messages>
<message>
<id></id>
<short></short>
<long></long>
<level></level>
<params>
<param>
<key></key>
<type></type>
</param>
</params>
</message>
</messages>

The table describes the message attributes:

Attribute Name Description

ID A unique identifier for the message.

ID is a mandatory attribute.

Short A short and understandable description of the message.

254 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Attribute Name Description

Long A long description of the message that provides further verbosity


than a short message.

Level The type of message. The system accepts only Critical, Error,
Warning, Informational or Verbose value.

Level is a mandatory attribute. Any value other than the


mentioned will result in error.

Parameter Key The primary key that stores the name of the parameter that repeats
multiple times for a message.

Parameter Type The type of the parameter that repeats multiple times for a message.
Example values for the Application Log File:

Id Short Message Advanced Message Level

-00001 Unable to start the operation Unable to start the operation Error
%op_name% because the work order
%wo_name% is on hold.

-00001 Unable to start the operation Unable to start the operation %op_id% Error
because the work order %wo_id% is on
hold and material lot %m_lot% is mark
to be cleaned.
The Application Log xml file requires certain restrictions that you must respect to avoid any errors during the
database update in Solution Studio:

 XML File Restrictions


• The name and structure of xml file are system defined and must not be modified.
• Every message must have a Message ID and Level, as they are mandatory fields.
• A message ID must be Numeric only and should not be repeated within the same xml file.
• The Level defined for a message must be either Critical/Error/Warning/Informational/Verbose.
• The Length of Short message must be less than 100 characters and the length of Long message must
be less than 400 characters.
• The Length of parameter key must be less than 512 characters.
• The possible values for parameter type
are string, byte, int, decimal, float, double, long, boolean, Guid and Datetime.
• If you delete a message for which a translation was provided and is already available in the deployed
solution, you must also delete the corresponding localized message from the resource package.
See Localizing Application Log Messages on how to manage a Localization resource package.

Manually Adding xml File


1. In Project Studio select the Functional Block/App/Extension App and open the solution.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 255


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2. Expand the Installer project, right-click Config folder and select Add > New Item.
3. Select Application Log class and click Add. This will add a new xml file to the Installer project that gets the
system-defined name and structure.

 Do not modify the file name, even though the system allows you to. If you rename, the system does not
take into account the custom name and returns an error while building the Installer project.

4. Build the Installer project to package the new xml file.

2.1.3.14.2 Associating Business Logic with Application Log Messages


To be able to log application messages related to a manufacturing command, you need to refer the defined
messages inside command handlers of a Functional Block / App / Extension App by means of Application Log
platform API (described in this section) and by installing the Application Log App in Solution Studio. The App lets
you view these logged messages in the runtime environment in UI application. For more information about the App,
see Application Log App in the Opcenter Execution Foundation User Manual.

Prerequisites
In Project Studio, application log messages are defined and packaged for every model project such as Functional
Block / App / Extension App, for which you wish to log.

Procedure
This API allows you to store user defined application log messages to the runtime database and retrieve those
messages for displaying in runtime environment.
1. In Project Studio, open the solution of a model project for which you want to log and retrieve messages.
2. In the CommandHandler project, refer the defined message using its Message ID and parameter values at the
appropriate context through the Application Log platform API. Refer to the sample code to understand how to
use the API.

256 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

IUnifiedSdkApplicationLog

using System.Collections.Generic;
namespace Siemens.SimaticIT.Unified.Common
{
/// <summary>
/// Provides an interface for handling Application Log messages.
/// </summary>
public interface IUnifiedSdkApplicationLog
{
/// <summary>
/// Stores user defined Application Log messages in the ApplicationLog
table in database.
/// </summary>
/// <param name="messageID">Specifies the identifier of Application Log
message.</param>
/// <param name="parameterValues">Specifies the parameters and its values
contained in the Application Log message.</param>
/// <param name="owner">Specifies the name of the Package from which the
message is logged.</param>
void ApplicationLog(int messageID, Dictionary<string, object>
parameterValues, string owner = null);

Sample Code

var dict = new Dictionary<string, object>


{
{ ParameterKey, ParameterValue }
};
platform.ApplicationLog(<messageID>, dict);

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 257


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 You must make sure:


• The passed MessageID has been defined. If the message ID does not exist, the API returns a
string stating that the message ID is not found.
• The passed ParameterKey is the same as those defined in the application log xml file. If a long/
short message has been specified with a ParameterKey as a placeholder in the ApplicationLog
XML and appropriate ParameterKey is not provided as an argument for the API, then the logged
message will not have an actualized value for the ParameterKey from runtime.
For Example, If "The Equipment Lot with %Eq_Id% is created" is the message defined,
if %Eq_Id% is not provided to the API then the long/short logged message will be "The
Equipment Lot with %Eq_Id% is created".
If the ParamterKey Eq_Id is provided with a value "EQU_234-864-892" to the API, then the logged
long/short message will be "The Equipment Lot with EQU_234-864-892 is created".
• Length of ParameterValue passed is less than 512 characters. If the length of the parameter
value exceeds 512 characters, the retrieved message will have the parameter value of 490
characters length and will be appended with a note "...[Truncated]".
• (Optional) Owner is the full name of the Functional Block / App / Extension App. For Example:
Siemens.SimaticIT.WorkInstruction.

What to do next
To properly log messages you need to deploy your custom solution, in which you have also installed the
Application Log App.
At this point the application log messages will be logged to the runtime repository and retrieved upon command
execution. However, if you wish to retrieve application log messages without logging to the runtime repository,
see Retrieving Application Messages without Logging

 If the ApplicationLog platform API is invoked from Pre-Check / Post-Action handlers, ensure you provide
the value of the owner parameter to log the message in the runtime database with the correct owner. If
the owner parameter is not provided, you may not be able to see the short and the long messages at
runtime because the logged message will not be assigned with a correct Functional Block / App / Extension
App name.

2.1.3.14.3 Retrieving Application Messages without Logging


If you need to retrieve a message in a particular language with the parameters actualized to their runtime values,
you can use Application Log platform APIs in the handlers of a Functional Block / App / Extension App as described
in this section.
For example, during the execution of a Command triggered by a user's action in the UI, any error encountered is
logged to the Tracer Viewer. By using the Application Log platform APIs in a handler, the resulting message can also
be shown to the end user.

Prerequisites
In Project Studio, application log messages are defined and packaged for every project such as a Functional Block /
App / Extension App.

Procedure
These APIs allow you to retrieve a localized message text from the ID and the value of the parameters.

258 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

1. In Project Studio, open the solution of a Functional Block / App / Extension App for which you want to log and
retrieve messages.
2. In the CommandHandler project, refer the defined message using its Message ID and appropriate parameter
values through the Application Log platform API. See the sample code below to understand how to use the API.

IUnifiedSdkApplicationLog

/// <summary>
/// Retrieves the short message content of Application Log message for a
given Message ID.
/// </summary>
/// <param name="messageID">Specifies the identifier of Application Log
message.</param>
/// <param name="parameterValues">Specifies the parameters and its values
contained in the Application Log message.</param>
/// <param name="languageCode">Specifies the language of Application Log
message.</param>
/// <param name="owner">Specifies the name of the Package from where the
message is to be retrieved.</param>
/// <returns>short message content</returns>
string GetApplicationLogShortMessage(int messageID, Dictionary<string, object>
parameterValues, string languageCode = null, string owner = null);

/// <summary>
/// Retrieves the long message content of Application Log message for a given
Message ID.
/// </summary>
/// <param name="messageID">Specifies the identifier of Application Log
message.</param>
/// <param name="parameterValues">Specifies the parameters and its values
contained in the Application Log message.</param>
/// <param name="languageCode">Specifies the language of Application Log
message.</param>
/// <param name="owner">Specifies the name of the Package from where the
message is to be retrieved.</param>
/// <returns>long message content</returns>
string GetApplicationLogLongMessage(int messageID, Dictionary<string, object>
parameterValues, string languageCode = null, string owner = null);

Sample Code

var parameterDictionary = new Dictionary<string, object>


{
{ ParameterKey, ParameterValue }
};
platform.GetApplicationLogShortMessage(messageID, parameterDictionary );

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 259


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 You must make sure:


• The passed MessageID has been defined. If the message ID does not, the API returns a string stating
that the message ID is not found.
• The passed ParameterKey is the same as those defined in the application log xml file. If a long/short
message has been specified with a ParameterKey as a placeholder in the ApplicationLog XML and
appropriate ParameterKey is not provided as an argument for the API, then the retrieved message will
not have an actualized value for the ParameterKey from runtime.
For Example, If the message is "The Equipment Lot with %Eq_Id% is created" and %Eq_Id% is not
provided to the API then the long/short retrieved message will be "The Equipment Lot with %Eq_Id% is
created".
If the ParamterKey Eq_Id is provided with a value "EQU_234-864-892" to the API, then the retrieved
long/short message will be "The Equipment Lot with EQU_234-864-892 is created".
• (Optional) Owner is the full name of the Functional Block / App / Extension App. For Example:
Siemens.SimaticIT.WorkInstruction

Retrieving the language code

var principal = sdk.Principal;


var identity = principal.Identities.FirstOrDefault();
var language = principal.Claims.Where(c => c.Type == "urn:language").Select(c =>
c.Value).First();

 When the Application Log platform APIs are invoked from Pre-check / Post-action Handlers, be sure to
provide the value to the parameter owner to retrieve an appropriate message. If the parameter owner is
not provided, the retrieved message may not be received from the intended Functional Block / App /
Extension App.

2.1.3.14.4 Localizing Application Log Messages


The default language configuration for the Application Log messages is English. However, you can provide localized
messages in multiple languages.

 You must have consistency between the message ID in the default message definition file (en_US) and the
localized files. For both, the IDs must match.

Prerequisites
To localize application log messages, the messages in English must be specified in the default file for application
log.

260 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

 For more information on


• defining application log messages in English and managing an application log file, see Managing the
Application Log File.
• logging messages see Associating Business Logic with Application Log Messages.

Localizing Application Log files


1. Create a new xml file with the defined file name and structure to localize the default Application Log file.
2. Create a new folder named config at any location on your computer and copy the localized file to
the config folder.
3. For each Functional Block / App / Extension App, for which you want to localize log messages, create a zip
package containing the just created config folder and name the zip as follows: <prefix>.<functional block /
app / extension app name>.Resources.<language code>.V<major version.minor version>.<patch version for
the resource package>.zip.

 If a resource package zip for the UI localization already exists, then copy the config folder to the
existing zip.

Parameter Description

prefix Specify the prefix of the Functional Block / App/ Extension App. For
example, Siemens.OpcenterEX.FN or Siemens.SimaticIT

functional block / app/ Specify the Functional Block / App / Extension App name. For example, Defect
extension app name or ALG_MS

language code The language code must be a four-letter code based on ISO 639 (e.g. ko-KR for
Korean)

major version.minor Specify the major and the minor version of the Functional Block. For example,
version 01.01

The major and the minor version must be separated with a period.

patch version for the Specify the version for the resource package. If multiple patch versions for the
resource package same functional block are available, then the highest patch version of the
resource package will be used.

 The resource package name must correspond to the functional block for which you want to publish log
messages. For example, if the functional block zip is Siemens.OpcenterEX.FN.DefectV01.00.00.zip,
the related resource zip file must be Siemens.OpcenterEX.FN.Defect.Resources.zh-
CN.V01.00.00 and if the functional block zip is Siemens.SimaticIT.ALG_MSV01.00.00.zip then
the resource zip file must be Siemens.SimaticIT.ALG_MS.Resources.zh-CN.V01.00.00.

4. Copy the zip package that you have created to:


%ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\Resources.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 261


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Application Log Translation XML File Structure


You must create the localized Application Log file with the following file name format: <prefix>.<functional block /
app / extension app name>.ApplicationLog.<language code>.xml.
The language code is a two letter/four letter code, which is the ISO 639-1 standard for representing languages.

File Structure

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


<messages>
<message>
<id></id>
<short></short>
<long></long>
</message>
</messages>

The table describes the message attributes. The following attributes have to be specified in the language the
message has to be localized.

Attribute Name Description

ID A unique identifier for the message.


The ID specified in the ApplicationLog.en-US.xml file must be used.

Short A short description of the message.


The length of Short message must be less than 100 characters.

Long A long description of the message that provides further verbosity than a short message.
The length of Long message must be less than 400 characters.

 If multiple messages have to be localized for the same language, then the above attributes have to be
replicated in the same format.

Deploying and retrieving log messages


As for any other Project Studio solution packages, to make messages available at runtime you have to build the
Installer project and then follow the Solution Studio build and deploy procedure documented at Creating the
Deployment Package and then Deploying the Solution Package to Hosts.
The Application Log platform API in the engineering phase uses these localized messages inside command handlers
to display the messages in runtime phase. For more information, see Retrieving Application Messages without
Logging.

262 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.15 How to Leverage Opcenter Execution Foundation Functional Blocks


As described at How to Extend Referenced Functional Blocks, you can reference Foundation functionalities in order
to develop custom manufacturing use cases.
At Overview of Functional Blocks section you can find the list of the Functional Blocks that you can find after
installing the Foundation Apps setup option.

2.1.3.15.1 Overview of Functional Blocks


Opcenter EX FN provides a set of Functional Blocks that model Entities and implement Commands, grouped by the
Opcenter EX FN data model domains: Reference Data, Master Data and Operational Data.
The predefined Functional Blocks are used as they are by the Opcenter EX FN Foundation Apps.
If additional use cases are required for business reasons, you can extend the data model provided within
the Functional Blocks and create new custom Apps which reference the Functional Blocks containing both the base
data model as well as the extended entities, and the custom business logic developed on the custom extended
entities.
A set of basic commands are provided for the management of entity instances of all Functional Blocks.

Available Functional Blocks


If the Foundation Apps option was selected during the product installation, the predefined Functional Blocks are
provided inside zip files that are copied to %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
Refer to the following tables if you want to know which Functional Blocks you have to reference to extend the
required entities and the related business logic:

Functional Block Zip Domain Modeled Artifacts Referenced Functional Blocks


Name

Siemens.SimaticIT.AGW_ Master This Functional Block is for • Siemens.SimaticIT.UDM_RF


MS Data internal use only and does • Siemens.SimaticIT.ATN_MS
not provide any reference
documentation. It is installed
and used by the Automation
Gateway app.

Siemens.SimaticIT.ALG_MS Master Application Log maintenance


Data configuration.

Siemens.SimaticIT.ALG_OP Operation Application Log (runtime • Siemens.SimaticIT.ALG_MS


al Data configurations)

Siemens.SimaticIT.ATN_MS Master Engineering configuration of • Siemens.SimaticIT.UDM_RF


Data Automation Node Types and
Instances.

Siemens.SimaticIT.ATN_OP Operation Runtime configurations of • Siemens.SimaticIT.ATN_MS


al Data Automation Node Instances. • Siemens.SimaticIT.UDM_RF

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 263


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Functional Block Zip Domain Modeled Artifacts Referenced Functional Blocks


Name

Siemens.SimaticIT.BPF_MS Master Business Process Flow • Siemens.SimaticIT.TSK_MS


Data (engineering configurations) • Siemens.SimaticIT.UDM_RF

Siemens.SimaticIT.BPF_OP Operation Business Process Flow • Siemens.SimaticIT.BPF_MS


al Data (runtime configurations) • Siemens.SimaticIT.TSK_MS
• Siemens.SimaticIT.TSK_OP
• Siemens.SimaticIT.UDM_RF
• Siemens.SimaticIT.EQU_MS
• Siemens.SimaticIT.EQU_OP

Siemens.SimaticIT.CHR_MS Master Characteristic Specifications • Siemens.SimaticIT.UDM_RF


Data (engineering configurations)

Siemens.SimaticIT.CHR_OP Operation Characteristic Specifications • Siemens.SimaticIT.CHR_MS


al Data (runtime configurations) • Siemens.SimaticIT.UDM_RF

Siemens.SimaticIT.DSG_SD System (This domain is for internal


Data use only) Functional Block
artifacts are defined to be
used for Data Segregation
management.

Siemens.SimaticIT.EQU_M Master Equipment • Siemens.SimaticIT.UDM_RF


S Data management (engineering
configurations)

Siemens.SimaticIT.EQU_O Operation Equipment • Siemens.SimaticIT.EQU_MS


P al Data management (runtime config • Siemens.SimaticIT.UDM_RF
urations)

Siemens.SimaticIT.ES_MS Master Electronic Signature • Siemens.SimaticIT.UDM_RF


Data (engineering configurations)

Siemens.SimaticIT.ES_SD System (This domain is for internal • Siemens.SimaticIT.UDM_RF


Data use only) Electronic Signature • Siemens.SimaticIT.ES_MS
(runtime signatures)

Siemens.SimaticIT.LBM_MS Master Label Management • Siemens.SimaticIT.UDM_RF


Data (engineering configurations)

Siemens.SimaticIT.LBM_OP Operation Label Management (runtime • Siemens.SimaticIT.LBM_MS


al Data operations). • Siemens.SimaticIT.UDM_RF

Siemens.SimaticIT.MAT_M Master Material Management • Siemens.SimaticIT.UDM_RF


S Data (engineering configurations)

264 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Functional Block Zip Domain Modeled Artifacts Referenced Functional Blocks


Name

Siemens.SimaticIT.MAT_OP Operation Material Management • Siemens.SimaticIT.UDM_RF


al Data (runtime operations). • Siemens.SimaticIT.MAT_MS
• Siemens.SimaticIT.EQU_MS
• Siemens.SimaticIT.EQU_OP

Siemens.SimaticIT.OPCUAC Master Equipment Management • Siemens.SimaticIT.UDM_RF


onnect_MS Data (engineering configurations) • Siemens.SimaticIT.EQU_MS
• Siemens.SimaticIT.ATN_MS

Siemens.SimaticIT.OPCUAC Operation Equipment Management • Siemens.SimaticIT.UDM_RF


onnect_OP al Data (runtime operations) • Siemens.SimaticIT.EQU_MS
• Siemens.SimaticIT.EQU_OP
• Siemens.SimaticIT.ATN_MS
• Siemens.SimaticIT.OPCUACo
nnect_MS
• Siemens.SimaticIT.ATN_OP

Siemens.SimaticIT.PRM_M Master Personnel Management


S Data (engineering configurations)

Siemens.SimaticIT.SGN_MS Master Signal Management • Siemens.SimaticIT.UDM_RF


Data

Siemens.SimaticIT.SITUA System Management of User


Sys Data Preferences (see Setting User
Preferences

Siemens.SimaticIT.TSK_MS Master Task • Siemens.SimaticIT.UDM_RF


Data Management (engineering
configurations)

Siemens.SimaticIT.TSK_OP Operation Task Management (runtime • Siemens.SimaticIT.UDM_RF


al Data configurations) • Siemens.SimaticIT.TSK_MS
• Siemens.SimaticIT.EQU_MS
• Siemens.SimaticIT.EQU_OP

Siemens.SimaticIT.UDM_RF Reference • Units of Measure


Data • State Machines
• Autonumbering

Siemens.SimaticIT.WI_MS Master Work Instruction • Siemens.SimaticIT.UDM_RF


Data management (engineering • Siemens.SimaticIT.ES_MS
configurations).

Siemens.SimaticIT.WI_OP Operation Work Instruction • Siemens.SimaticIT.UDM_RF


al Data management (runtime • Siemens.SimaticIT.ES_MS
instance management). • Siemens.SimaticIT.WI_MS
• Siemens.SimaticIT.ES_SD

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 265


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Functional Block Zip Domain Modeled Artifacts Referenced Functional Blocks


Name

Siemens.SimaticIT.WI_TAS Master Task Definition management • Siemens.SimaticIT.UDM_RF


K_MS Data of Work Instruction Task Type • Siemens.SimaticIT.ES_MS
(engineering configurations). • Siemens.SimaticIT.WI_MS
• Siemens.SimaticIT.TSK_MS

Siemens.SimaticIT.WI_TAS Operation Task Definition management • Siemens.SimaticIT.UDM_RF


K_OP al Data of Work Instruction Task Type • Siemens.SimaticIT.ES_MS
(runtime operations). • Siemens.SimaticIT.EQU_MS
• Siemens.SimaticIT.TSK_MS
• Siemens.SimaticIT.WI_MS
• Siemens.SimaticIT.WI_OP
• Siemens.SimaticIT.EQU_OP
• Siemens.SimaticIT.TSK_OP
• Siemens.SimaticIT.WI_TASK_
MS
• Siemens.SimaticIT.ES_SD

Siemens.OpcenterEX.FN.BR Master Barcode Rules and Rule Parts • Siemens.SimaticIT.UDM_RF


C_MS Data

Siemens.OpcenterEX.FN.BR Operation Barcode Rules Validation and • Siemens.SimaticIT.UDM_RF


C_OP al Data Barcode History • Siemens.OpcenterEX.FN.BRC
_MS

Siemens.OpcenterEX.FN.DE Master Failures and Quality Actions • Siemens.SimaticIT.UDM_RF


F_MS Data

Siemens.OpcenterEX.FN.Q Master Migration of existing Failures • Siemens.SimaticIT.CHR_MS


EMigration_MS Data and their association with
Visual Characteristics from
the Work Instruction App to
the Defect App.

Related documentation
Reference documentation is available as HTML files or within the Documentation Center after the you have
completed the Opcenter EX FN environment configuration (see Configuring the Documentation Center in the
Opcenter Execution Foundation Installation Guide).
Starting from How to Extend Referenced Functional Blocks and then How to Model a Functional Block, you can find
guidelines on how to extend Functional Blocks, create custom Apps and UIs and reference other Functional Blocks.
Opcenter Execution Foundation reference documentation comes provided for each Foundation Functional Block
with the description of all model artifacts (e.g. entities, commands, events and so on).

2.1.3.15.1.1 ALG_MS Functional Block


ALG_MS is a Functional Block, belonging to the Master Data domain.
Its Functional Block artifacts are defined to be used for cleaning the application log messages in the runtime
environment.

266 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entities
The ALG_MS Functional Block contains the following entities:

Entity Function Relationships

Rule Defines a Rule for the ApplicationLog A Rule entity can be related to a
maintenance configuration. single CleaningCondition entity
and / or a single Schedule entity.

CleaningCondition Defines a CleaningCondition for the A CleaningCondition entity can


ApplicationLog maintenance be related to a single Rule entity.
configuration.

Schedule Defines a Schedule for the ApplicationLog A Schedule entity can be related
maintenance configuration. to a single Rule entity.
For further information, refer to the Entities section of the ALG_MS Reference Guide.

Commands
The ALG_MS Functional Block contains the following commands:

Command Function

CreateRule To create a new Rule for ApplicationLog maintenance


configuration.

UpdateRule To update a Rule for ApplicationLog maintenance


configuration.

ActivateRule To enable a scheduled Rule for ApplicationLog maintenance


configuration.

DeactivateRule To disable an activated schedule for ApplicationLog


maintenance configuration.

DeleteRule To delete a Rule for ApplicationLog maintenance


configuration.

UpdateSchedule To update a Schedule for ApplicationLog maintenance


configuration.

DeleteSchedule To delete a Schedule for ApplicationLog maintenance


configuration.

UpdateCleaningCondition To update a CleaningCondition for ApplicationLog


maintenance configuration.

DeleteCleaningCondition To delete a CleaningCondition for ApplicationLog maintenance


configuration.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 267


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

For further information, refer to the Commands section of the ALG_MS Reference Guide.

2.1.3.15.1.2 ALG_OP Functional Block


ALG_OP is a Functional Block, belonging to the Operational Data domain.
Its Functional Block artifacts are defined to be used for displaying application log messages during runtime
environment.

Entities
The ALG_OP Functional Block contains the following entities:

Entity Function

ApplicationLog Represents the storage of attributes of each application log


message to the database in the runtime environment.

ApplicationLogParameters Represents the storage of a parameter that repeats multiple times


for an application log message. This is a composite entity of the
ApplicationLog entity.

RuleExecution Represents the storage of the details rule execution.


For further information, refer to the Entities section of the ALG_OP Reference Guide.

Commands
The ALG_OP Functional Block contains the following commands:

Command Function

CreateApplicationLog To create application log messages.

RunNow To run a Rule manually.

Events
The following events are fired each with a specific envelope, on which you can filter while configuring the
subscription.
• When a Run Now button is clicked , the event RunNowEvent will be fired.
The RunNowEvent event has the following envelope data structure:

Envelope property Property value

Topic ApplicationLog
For further information, refer to the Commands section of the ALG_OP Reference Guide.

2.1.3.15.1.3 ATN_MS Functional Block


ATN_MS is a predefined Functional Block of the Automation App, belonging to the Master Data domain.

268 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Its Functional Block artifacts are defined to be used in the management of Automation Nodes.
It references the UDM_RF Functional Block.

Entities
The ATN_MS Functional Block provides the following entities:

Entity Definition Relationships

Automation Channel The communication channel between the An Automation Channel


Automation Gateway (the Engineering layer) and entity can be related to one
the Automation Gateway Server. or more Automation Node
Instance Parameters.

Automation Node Type Sets of data that can be connected to control An Automation Node Type
systems. These data structures can represent entity:
abstract equipment types, machines, tools, or
• can be related to one or
any other automation data grouping. They
more Automation Node
contain automation parameters, which contain
Type Parameters.
the connection information required to execute
• can be related to one or
read and write operations on automation data.
more Automation Node
Instances.

Automation Node Type An automation parameter associated to an An Automation Node Type


Parameter Automation Node Type entity. Parameter entity:
• must be related to only
one Automation Node
Type
• can be related to one or
more Automation Node
Instance Parameters.

Automation Node Each instance, based on Automation Node An Automation Node


Instance Types, contains the parameter values and map Instance entity:
real-world plant objects, such as machines, tools
• must be related to one or
or sensors. Their main function is to model these
more Automation Node
plant objects and enable data exchange with the
Type
field. Any changes made to Automation Node
• can be related to one or
Types will be propagated to all related
more Automation Node
Automation Node Instances.
Instance Parameters.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 269


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Definition Relationships

Automation Node An automation parameter associated to an An Automation Node


Instance Parameter Automation Node Instance entity. Instance Parameter entity:
• can be related to only
one Automation
Channel
• must be related to only
one Automation Node
Instance
• must be related to only
one Automation Node
Type Parameter.
For further information, refer to the Entities section of the ATN_MS Reference Guide.

Commands
The ATN_MS Functional Block contains the generic basic commands and the following functional block specific
commands for automation node management:

Command Function

Activate To activate all the Automation Node Types and Automation


Node Instances in status Approved or Dismissed to the
Automation Gateway Server.

ActivateAutomationChannel To activate all the Automation Channels in status Approved or


Dismissed to the Automation Gateway Server.

ApproveAutomationChannel To set the status of an Automation Channel to Approved, so


that the Automation Channel can be activated onto the
Automation Gateway Server.

ApproveAutomationNodeInstance To set the status of an Automation Node Instance to


Approved, so that the Automation Node Instance can be
activated onto the Automation Gateway Server.

ApproveAutomationNodeType To set the status of an Automation Node Type to Approved, so


that the Automation Node Type can be activated onto the
Automation Gateway Server.

ExportAutomationConfig To export the current Automation configuration in CSV format.

FreezeAutomationNodeInstance To configure the Automation Node Instance to be read-only by


setting the attribute IsLocked to True.

FreezeAutomationNodeType To configure the Automation Node Type to be read-only by


setting the attribute IsLocked to True.

ImportAutomationConfig To import an Automation Configuration in CSV format.

270 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

ResetEnvironment To reset the configuration of the Automation Gateway Server.

RevertAutomationNodeInstance To revert the selected Automation Node Instance to the


activated version.

RevertAutomationNodeType To revert the selected Automation Node Type and its instances
to the activated version.

UnfreezeAutomationNodeInstance To remove the read-only setting from the Automation Node


Instance by setting the attribute IsLocked to False.

UnfreezeAutomationNodeType To remove the read-only setting from the Automation Node


Type by setting the attribute IsLocked to False.
For further information, refer to the Commands section of the ATN_MS Reference Guide.

Events
The Automation Gateway App fires the following system events:
• ActivateFinished, after the activation of either Automation Node Types, or Automation Node Instances or
Automation Channels (see Activate and ActivateAutomationChannel commands) and it is associated to the
ActivateFinishedSignal signal;
• ImportFinished, after the import of a configuration file (see ImportAutomationConfig command) and it is
associated to the ImportFinishedSignal signal.
• ResetFinished, after the reset of the Automation Gateway Server configuration (see ResetEnvironment
command) and it is associated to the ResetFinishedSignal signal.
The ActivateFinished event has the following envelope data structure:

Envelope attribute Value

Category Activation

Module AutomationGatewayManagement

Tag ActivateFinished

Topic One of the following values:


• AlignActivatedAutomationTypesAndInstances: if the
activation refers to Automation Node Types and Instances
• AlignActivatedAutomationChannels: if the activation refers
to Automation Channels.
The ImportFinished event has the following envelope data structure:

Envelope attribute Value

Category Import

Module AutomationGatewayManagement

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 271


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Envelope attribute Value

Tag ImportFinished

Topic ImportAutomationConfig
The ResetFinished event has the following envelope data structure:

Envelope attribute Value

Category ResetEnvironment

Module AutomationGatewayManagement

Tag ResetFinished

Topic ResetEnvironmentDone
For further information, refer to the Events section of the ATN_MS Reference Guide.

2.1.3.15.1.4 ATN_OP Functional Block


ATN_OP is a predefined Functional Block of the Automation App, belonging to the Operational Data domain.
Its Functional Block artifacts allow you to keep the Automation Nodes aligned with the Automation Gateway Server
configuration and to perform reading and writing operations.
It references the following Functional Blocks:
• ATN_MS
• UDM_RF

Entities
The ATN_OP Functional Block contains the following entity:

Entity Description Relationships

Automation Node The entity (of IAutomationEntity type) An Automation Node entity must
representing the operational copy of the be related to only one
configuration activated into the Automation Automation Node Instance and
Gateway Server. to only one Automation Node
Type.

For further information, refer to the Entities section of the ATN_OP Reference Guide.

Commands
The ATN_OP Functional Block contains only the generic basic commands.
For further information, refer to the Commands section of the ATN_OP Reference Guide.

2.1.3.15.1.5 BPF_MS Functional Block


BPF_MS is a predefined Functional Block, belonging to the Master Data domain.

272 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Its Functional Block artifacts allow you to manage Business Processes, specifically in the Business Process Flow
App.
It references the following Functional Blocks:
• UDM_RF
• TSK_MS

Entities
The BPF_MS Functional Block contains the following entities:

Entity Description Relationships

Process Context Definition Defines the structure of a context for a


Work Process.

Process Context Definition Defines the User Field that makes up a A Process Context Definition can
User Field Work Process Context. be related to many Process Context
Definition User Fields. Backward
navigation is possible between these
two entities through the
ProcessContextDefinition
property.

Process Definition Defines the structure of a set of Work Many Process Context Definitions
Processes, including its execution can be related to many Process
model. Definitions. Backward navigation is
possible between these two entities
through the
ProcessContextDefinitions
property.

Process Definition Defines the structure of an input/ A Process Definition can be related
Parameter output parameter for a set of Work to many Process Definition
Processes. Parameters. Backward navigation is
possible between these two entities
through the ProcessDefinition
property.

Process Template The template used to create the


Process Definition.

Process Template Parameter The template used to create the A Process Template can be related
Process Definition Parameter. to many Process Template
Parameters. Backward navigation is
possible between these two entities
through the ProcessTemplate
property.
For further information, refer to the Entities section of the BPF_MS Reference Guide.

Commands

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 273


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The BPF_MS Functional Block contains the generic basic commands and the following functional block specific
commands for business process management:

Commands Function

AssociateProcessContextDefinitionsWithProces To associate a Process Definition to a list of Process


sDefinition Context Definitions.

CreateProcessDefinitionByImport To create a Process Definition starting from an imported


BPMN model.

DisassociateProcessContextDefinitionsFromPr To remove the association between one or more Process


ocessDefinition Context Definitions and a Process Definition.

ExportProcessDefinition To export a Process Definition.

SetExecutable To perform the consistency check on the Process


Definition model. The XML schema is validated as well as
several constraints.
If no errors are returned, the IsExecutable flag is set to
true, otherwise a list of messages is returned.

SetProcessDefinitionDesign To update the Design of an existing Process Definition.

SetProcessTemplateAsDefault To set a Process Template as default.


For further information, refer to the Commands section of the BPF_MS Reference Guide.

2.1.3.15.1.6 BPF_OP Functional Block


BPF_OP is a predefined Functional Block, belonging to the Operational domain.
Its Functional Block artifacts allow you to manage Business Processes, specifically in the Business Process Flow
App.
It references the following Functional Blocks:
• UDM_RF
• TSK_MS
• TSK_OP
• BPF_MS

Entities
The BPF_OP Functional Block contains the following entities:

Entity Description Relationships

Work Process A runtime Work Process instance. One WorkProcess entity can be related to
many WorkProcess entities. Backward
navigation is possible between these two
entities through the ParentWorkProcess
property.

274 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description Relationships

Work Process Context A base context for a Work Process. A Work Process Context can be related
to one or more Work Process Context
User Fields.

Work Process Context User The User Field for the Work Process A Work Process Context can be related
Field Context. to many Work Process Context User
Fields. Backward navigation is possible
between these two entities through the
Context property.

Work Process Element For internal use only. A Work Process Model can be related to
many Work Process Elements.
A private Work Process Flow
Backward navigation is possible between
Element.
these two entities through the Model
property.

Work Process Element For internal use only. A Work Process Element can be related
Data Association to many Work Process Element Data
A private Work Process Flow
Associations. Backward navigation is
Element Data binding variables,
possible between these two entities
expressions and constant values.
through the Element property.

Work Process Flow For internal use only. A Work Process can be related to many
Element Token Work Process Flow Element Tokens.
A private Work Process Flow
Element Token.

Work Process Link For internal use only. • A Work Process Element can be
related to many Work Process Links.
A private Work Process Link
Backward navigation is possible
between Flow Elements.
between these two entities through
the FromElement property.
• A Work Process Element can be
related to many Work Process Links.
Backward navigation is possible
between these two entities through
the ToElement property.

Work Process Model For internal use only.


A private Work Process BPMN
model.

Work Process Sequence For internal use only. A Work Process can be related to many
Flow Token Work Process Sequence Flow Tokens.
A private Work Process Sequence
Flow Token.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 275


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description Relationships

Work Process Variable For internal use only. A Work Process can be related to many
Work Process Variables. Backward
A private Work Process Variable.
navigation is possible between these two
entities through the WorkProcess
property.
For further information, refer to the Entities section of the BPF_OP Reference Guide.

Commands
The BPF_OP Functional Block contains the generic basic commands and the following functional block specific
commands for business process management:

Commands Function

AbortWorkProcess To terminate a Work Process, by either cancelling or aborting it,


depending on its status.

CancelElement For internal use only.


Cancels the execution of a private Work Process Flow Element.

EnterElement For internal use only.


To enter a private Work Process Flow Element.

ExitElement For internal use only.


To exit a private Work Process Flow Element.

FailToken For internal use only.


To set the error status of a Token.

PauseElement For internal use only.


To pause a private Work Process Flow Element.

PauseWorkProcess To pause a Work Process.

RecoverWorkProcess To recover a Work Process.

ResumeElement To resume the single execution of an element within a Work


Process.

ResumeWorkProcess To resume a Work Process.

StartNewWorkProcess To create and run a new Work Process.


For further information, refer to the Commands section of the BPF_OP Reference Guide.

276 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Events
The WorkProcessTokenStatusChanged event is fired by the Business Process Flow App when the status of a Work
Process Flow Element token changes and the Work Process proceeds.
The StatusChanged of WorkProcess event has the following envelope data structure:

Envelope Property Property value

Category WorkProcessStatusChanged

Module BPFlow

Tag StatusChanged

Topic WorkProcess

UserField1 The natural key identifier of the State Machine

UserField2 The natural key identifier of the Source Status

UserField3 The natural key identifier of the Target Status

UserField4 The natural key identifier of the Process Definition

UserField5 The Revision of the Process Definition

UserField6 True, if target status is meant as a final status (the outcome of the
status is not 0), false otherwise.

UserField7 The natural key identifier of the Process Definition Template or


empty string.

UserField8 The natural key identifier of the Work Process.

UserField9 The identifier of the chain execution.

UserField10 FOR INTERNAL USE


and the event StatusEventArgs Parameter Type:

Name Type Description

StateMachineNId String The natural key identifier of the State Machine.


Maximum length: 255.

PreviousStatusNId String The natural key identifier of the previous


Status. Maximum length: 255.

CurrentStatusNId String The natural key identifier of the current Status.


Maximum length: 255.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 277


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Name Type Description

EntityId Guid The primary key identifier of the Entity.

EntityType String The type of the Entity. Maximum length: 255.

StatusOutcome StatusesOutcome The status outcome of the Current Status.

CurrentStatusColor String The hexadecimal code of color.

CurrentStatusName String The name of the current Status.

CreatedOn DateTimeOffset The date time of the Work Process creation.

LastUpdatedOn DateTimeOffset The last date time of the Work Process update.
For further information, refer to the Events section of the BPF_OP Reference Guide.

2.1.3.15.1.7 BRC_MS Functional Block


BRC_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts allow you to manage Barcode Rules and Rule Parts.
It references the following Functional Block:
• UDM_RF

Entities
The BRC_MS Functional Block contains the following entities:

Entity Description

BarcodeItemType Contains information on Item Types which can be included in the


Barcode Rule.

BarcodeRule Contains information on the Rules used to validate the Barcode.

BarcodeRulePart Contains information on the Rule Parts making up the Barcode


Rule.
For further information, refer to the Entities section of the BRC_MS Reference Guide.

Commands
The BRC_MS Functional Block contains the following commands:

Command Function

CalculateBarcodeRuleExpression To update the regular expression each time a Rule Part is


added or edited.

CreateBarcodeRule To create a Barcode Rule.

278 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

CreateBarcodeRulePart To create a Barcode Rule Part.

DeleteBarcodeRule To delete an existing Barcode Rule.

DeleteBarcodeRulePart To delete an existing Barcode Rule Part.

MoveBarcodeRulePart To move the Rule Part within the Rule sequence.

UpdateBarcodeRule To update an existing Barcode Rule.

UpdateBarcodeRulePart To update an existing Barcode Rule Part.


For further information, refer to the Commands section of the BRC_MS Reference Guide.

2.1.3.15.1.8 BRC_OP Functional Block


BRC_OP is a predefined Functional Block, belonging to the Operational Data domain.
Its artifacts allow you to validate Barcode Rules and manage the Barcode History.
It references the following Functional Blocks:
• UDM_RF
• BRC_MS

Entities
The BRC_OP Functional Block contains the following entities:

Entity Description

BarcodeHistory Contains information on the Barcode History.

ValidationCheckHistory Contains information on the validation of each rule which can be


applied to the Barcode.
For further information, refer to the Entities section of the BRC_OP Reference Guide.

Commands
The BRC_OP Functional Block contains the following commands:

Command Function

CreateBarcodeHistory To create the Barcode History.

CreateValidationCheckHistory To create one or more records of the Barcode History.

GetBarcodeRules To validate a Barcode against the list of all possible rules.

ValidateBarcode To validate a Barcode against valid rules only.


For further information, refer to the Commands section of the BRC_OP Reference Guide.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 279


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.15.1.9 CHR_MS Functional Block


CHR_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts allow you to manage Quality Characteristics.
It references the following Functional Blocks:
• UDM_RF

Entities
The CHR_MS Functional Block contains the following entities:

Entity Description

AttributiveCharacteristicSp Contains information on Attributive Characteristics.


ecification

CharacteristicFailureAssocia Contains information on the possible failures to be associated with a Quality


tion Characteristic.

CharacteristicRepresentatio Contains information on Inspection Definitions.


n

CharacteristicSpecification Contains general information on Quality Characteristics.

Criticality Contains information on criticality of a Quality Characteristics.

FailureReference Contains information on Failures associated with Quality Characteristics.

VariableCharacteristicSpecif Contains information on Variable Characteristics.


ication

VisualCharacteristicSpecific Contains information on Visual Characteristics.


ation
For further information, refer to the Entities section of the CHR_MS Reference Guide.

Commands
The CHR_MS Functional Block contains the following commands:

Command Function

AssociateFailuresWithCharacter To associate Quality Characteristics with Failures.


isticSpecification

CreateAttributiveCharacteristic To create Attributive Characteristics.


Specification

CreateCharacteristicRepresenta To create Inspection Definitions.


tion

280 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

CreateCharacteristicSpecificati To create Quality Characteristics.


on

CreateCriticality To create Quality Characteristic criticality.

CreateVariableCharacteristicSp To create Variable Characteristics.


ecification

CreateVisualCharacteristicSpeci To create Visual Characteristics.


fication

DeleteCharacteristicFailureAsso To delete the association between Failures and Quality Characteristics.


ciation

DeleteCharacteristicRepresenta To delete Inspection Definitions.


tion

DeleteCharacteristicSpecificati To delete Quality Characteristics.


on

UpdateAttributiveCharacteristi To update Attributive Characteristics.


cSpecification

UpdateCharacteristicFailureAss To update the association between Failures and Quality Characteristics.


ociation

UpdateCharacteristicRepresent To update Inspection Definitions.


ation

UpdateCharacteristicSpecificati To update Quality Characteristics.


on

UpdateVariableCharacteristicSp To update Variable Characteristics.


ecification

UpdateVisualCharacteristicSpec To update Visual Characteristics.


ification
For further information, refer to the Commands section of the CHR_MS Reference Guide.

2.1.3.15.1.10 CHR_OP Functional Block


CHR_OP is a predefined Functional Block, belonging to the Operational domain.
Its artifacts allow you to manage Inspection Definitions.
It references the following Functional Blocks:
• UDM_RF
• CHR_MS

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 281


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entities
The CHR_OP Functional Block contains the following entities:

Entity Description

InspectionAcquisitionContex Contains information on the Context of the Inspection Acquisition.


t

InspectionSample Contains information on the acquired samples of a runtime Inspection


Definition.

InspectionValue Contains information on the measured values of a runtime Inspection


Definition.

RuntimeCharacteristicRepre Contains general information on a runtime Inspection Definition.


sentation

RuntimeCharacteristicRepre Container of runtime Inspection Definition.


sentationContainer

VisualDetectedFailure Contains information on failures detected in a runtime Inspection Definition.


For further information, refer to the Entities section of the CHR_OP Reference Guide.

Commands
The CHR_OP Functional Block contains the following commands:

Command Function

CreateInspectionAcquisitionCo To create an inspection acquisition context.


ntext

CreateInspectionValue To create an inspection value.

CreateRuntimeChrReprContain To create a runtime Inspection Definition container with its


er runtime Inspection Definition entities.

CreateSample To create an inspection sample.

CreateVisualDetectedFailure To create visual detected failures.

DeleteRuntimeChrReprContain To delete an existing Inspection Definition container.


er

DeleteRuntimeChrRepresentati To delete an existing Inspection Definition.


on

UpdateInspectionValue To update the value of an inspection value.

282 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

UpdateVisualDetectedFailure To update the value of a visual detected failure.


For further information, refer to the Commands section of the CHR_OP Reference Guide.

2.1.3.15.1.11 DEF_MS Functional Block


DEF_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts allow you to manage Failures and Quality Actions.
It references the following Functional Block:
• UDM_RF

Entities
The DEF_MS Functional Block contains the following entities:

Entity Description

Attachment Contains information on attachments which can be linked to Failures.

Failure Contains information on Failures, which are potential problems which can
occur during the life cycle of a product or process.

FailureChild Contains information on child Failures in the hierarchy.

FailureParent Contains information on parent Failures in the hierarchy.

GeneralQualityAction Contains information on general Quality Actions.

QualityAction Contains information on Quality Actions, which are operations required to


resolve the detected Failures.

QualitySubAction Contains information on groups of Quality Sub-Actions.


For further information, refer to the Entities section of the DEF_MS Reference Guide.

Commands
The DEF_MS Functional Block contains the following commands:

Command Function

AssociateAttachmentsWithFailu To associate attachments with a Failure.


re

AssociateFailuresWithFailure To associate more Failures with a Failure.

AssociateQualityActionsWithFai To associate one or more Quality Actions with a Failure.


lure

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 283


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

CopyFailureRevision To copy a Failure revision.

CreateAttachment To create an attachment storing the uploaded file.

CreateFailure To create a new Failure.

CreateGeneralQualityAction To create a general Quality Action.

CreateHierarchy To create a Failure hierarchy.

CreateNewFailureRevision To create a new Failure revision.

CreateQualityAction To create a Quality Action.

CreateSubQualityAction To create a Quality Sub-Action.

DeleteAttachment To delete an attachment removing the file.

DeleteFailure To delete an existing Failure.

DeleteGeneralQualityAction To delete an existing general Quality Action.

DeleteQualityAction To delete an existing Quality Action.

DeleteSubQualityAction To delete an existing Quality Sub-Action.

DisassociateAttachmentsFromF To remove the association between Attachments and Failures.


ailure

DisassociateFailuresWithFailure To remove the association between Failures.

DisassociateQualityActionsFro To remove the association between Quality Action and Failure.


mFailure

LockFailure To lock a failure.

SetFailureRevisionCurrent To set a Failure as current.

UnlockFailure To unlock a failure.

UnsetFailureRevisionCurrent To unset a Failure as current.

UpdateAttachment To update an existing attachment.

UpdateFailure To update an existing Failure.

UpdateGeneralQualityAction To update an existing general Quality Action.

UpdateQualityAction To update an existing Quality Action.

284 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

UpdateSubQualityAction To update an existing Quality Sub-Action.


For further information, refer to the Commands section of the DEF_MS Reference Guide.

2.1.3.15.1.12 DSG_SD Functional Block


DSG_SD is a predefined Functional Block, belonging to the System Data domain.
Its artifacts are defined to be used for managing Data Segregation in the Data Segregation App. See Data
Segregation App in the Opcenter Execution Foundation User Manual.

Entities
The SegregationTag entity is part of the Foundation Functional Block. See the Foundation Model Reference
Guide for details on this entity.

Commands
The DSG_SD Functional Block contains the following commands:

Command Function

CreateSegregationTag To create a segregation tag.


Set the Color input parameter to define the color to be
assigned to segregation tags. If you insert a not allowed
value, then the segregation tags will be displayed with a
Grey color when you create segregation tags (see Creating
Segregation Tags in the Opcenter Execution Foundation User
Manual) or assign Segregation Tags to entity instances in
Apps (see Assigning Segregation Tags to Entity Instances in
Apps using Default Values in the Opcenter Execution
Foundation User Manual).

DeleteSegregationTag To delete a segregation tag.

UpdateSegregationTag To update a segregation tag.


Set the Color input parameter to define the color to be
assigned to segregation tags. If you insert a not allowed
value, then the segregation tags will be displayed with a
Grey color when you edit segregation tags (see How to
Manage Segregation Tags in the Opcenter Execution
Foundation User Manual) or assign Segregation Tags to
entity instances in Apps (see Assigning Segregation Tags to
Entity Instances in Apps using Default Values in the Opcenter
Execution Foundation User Manual).

SetSessionSegregationTagsSelection To select or deselects segregation tags received in input.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 285


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

ReplaceSegregationTagAssociation To replace the segregation tags association in a generic


instance.
For further information, refer to the Commands section of the DSG_SD Reference Guide.

Events
The DSG_SD Functional Block contains the following events:

Event Function

ReplacedSegregationTagAssociation Event triggered to notify the replaced segregation tag


association.

SegregationTagDeleted Event triggered when a segregation tag is deleted.

SessionSelectedChanged Event triggered when the selection of Session Segregation


Tags is changed.

For further information, refer to the Events section of the DSG_SD Reference Guide.

2.1.3.15.1.13 EQU_MS Functional Block


EQU_MS is a predefined Functional Block, belonging to the Master Data domain.
Its Functional Block artifacts are defined to be used for performing engineering configurations on Equipment in
the Equipment App.

Entities
The EQU_MS Functional Block contains the following entities:

Entity Description

EquipmentConfiguration Represents the Equipment in the engineering environment.

EquipmentConfigurationProperty Represents a property of the Equipment Configuration.

EquipmentConfigurationPropertyAttribut Represents an attribute of an Equipment Configuration Property.


e The Equipment Configuration Property Attribute can be used to
enrich the information contained in the Equipment
Configuration Property.

EquipmentConfigurationStateMachine Represents State Machines associated to the Equipment


Configuration.

EquipmentGraphConfiguration Represents the Configuration of an Equipment Graph. The type


of the Equipment Graph Configuration is specified by the Type
property.

286 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description

EquipmentGraphLinkConfiguration Represents the configuration of a Link, which is the connection


between two nodes, in an Equipment Graph. The nodes may
represent either an Equipment or a Group of Equipment.

EquipmentGraphNodeConfiguration Represents the configuration of a Node in an Equipment Graph.


The node may represent either an Equipment or a group of
Equipment. If you give a value to both
EquipmentConfigurationNId and
EquipmentGroupConfigurationNId, the Equipment
Configuration you specify must belong to the specified
Equipment Group Configuration.

EquipmentGraphType Represents the Type of an Equipment Graph. The types provided


by the system are Hierarchy and Flow; you can use this entity to
define a custom type.

EquipmentGroupConfiguration Represents a collection of Equipment in the engineering


environment.

EquipmentLevel Represents the Equipment Level in the engineering


environment.

EquipmentType Represents a template for an Equipment Configuration.

EquipmentTypeProperty Represents a Property of an Equipment Type.

EquipmentTypePropertyAttribute Represents an attribute of an Equipment Type Property. The


Equipment Type Property Attribute can be used to enrich the
information contained in the Equipment Type Property.

EquipmentTypeStateMachine Represents State Machines associated to the Equipment Type


For further information, refer to the Entities section of the EQU_MS Reference Guide.

Commands
The EQU_MS Functional Block contains the following commands:

Command Function

AddEquipmentConfigurationStateMachin To add a list of State Machines to an Equipment Configuration.


es

AddEquipmentTypeStateMachines To add a list of State Machines to an Equipment Type.

AssociateChildrenEquipmentGroupConf To associate a Equipment Group Configuration with a list of


WithEquipmentGroupConf children Equipment Group Configuration.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 287


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

AssociateEquipmentConfigurationsWith To add a list of Equipment Configurations to a specified


EquipmentGroupConfiguration Equipment Group Configuration.

AssociateEquipmentGroupConfiguration To add the specified Equipment Configuration to different


s Equipment Group Configurations.
WithEquipmentConfiguration

AssociateParentsEquipmentGroupConfW To associate a Equipment Group Configuration with a list of


ith parents Equipment Group Configuration.
EquipmentGroupConf

BulkImportEquipmentGraphConfiguratio To manage an Equipment Graph Configuration. If the Equipment


n Graph Configuration, specified by NId, exists, the command
updates its name and/or description, the lists of its node and its
links; otherwise, it creates a new Equipment Graph
Configuration.
In this latter case, if the EquipmentGraphLinkConfigurations
list contains links, the EquipmentGraphNodeConfigurations list
must not be empty.

BulkImportEquipmentHierarchy To import a json file containing the structure of the Hierarchy to


be associated to the Equipment Graph Configuration identified
by EquipmentGraphConfigurationId. If the structure is empty,
the data contained in the json file will be used to build the
Hierarchy; otherwise the data will be used to modify the existing
structure.

CreateEquipmentConfiguration To create an Equipment Configuration using an Equipment Type


as template.

CreateEquipmentConfigurationByDefaul To create an Equipment Configuration using the default


t Equipment Type, if the EquipmentTypeNId is not specified.
EquipmentType

CreateEquipmentGraphConfiguration To create a new Equipment Graph Configuration. The type of


Equipment Graph Configuration is specified by the type
parameter, whose possible values are Hierarchy and Flow.

CreateEquipmentGraphLinkConfiguratio To create the Configuration of a Link, which is the connection


n between two Equipment Graph Nodes, in an Equipment Graph.
The Equipment Graph Nodes may represent either an Equipment
or an Equipment Group.

CreateEquipmentGraphNodeConfigurati To create the Configuration of an Equipment Graph Node. If you


on specify both the parameters EquipmentConfigurationNId and
EquipmentGroupConfigurationNId, the specified Equipment
Configuration must belong to the specified Equipment Group
Configuration.

288 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

CreateEquipmentGraphType To create a new Equipment Graph Type.

CreateEquipmentGroupConfiguration To create an Equipment Group Configuration.

CreateEquipmentLevel To create an Equipment Configuration Level

CreateEquipmentType To create an Equipment Type.

CreateHierarchyEquipment To create one or more Node Configurations of an Equipment


NodeConfigurations Hierarchy.

DeleteEquipmentConfiguration To delete an Equipment Configuration.

DeleteEquipmentConfigurationProperty To delete an Equipment Configuration Property.

DeleteEquipmentConfigurationProperty To delete an Equipment Configuration Property Attribute.


Attribute

DeleteEquipmentConfiguration To delete a State Machine from an Equipment Configuration.


StateMachine

DeleteEquipmentGraphConfiguration To delete an Equipment Graph Configuration.

DeleteEquipmentGraphLinkConfiguratio To delete an Equipment Graph Link Configuration.


n

DeleteEquipmentGraphNode To delete the Equipment Graph Node Configuration. The


Configuration command execution succeeds only if the Equipment Graph Node
Configuration you are deleting is not linked to other Equipment
Graph Node Configurations.

DeleteEquipmentGraphType To delete an Equipment Graph Type.

DeleteEquipmentGroupConfiguration To delete the specified Equipment Group Configuration.

DeleteEquipmentLevel To delete an Equipment Level.

DeleteEquipmentType To delete an Equipment Type. It is not possible to delete the


Equipment Type if it has been used to create an Equipment
Configuration.

DeleteEquipmentTypeProperty To delete an Equipment Type Property.

DeleteEquipmentTypePropertyAttribute To delete an Equipment Type Property Attribute.

DeleteEquipmentTypeStateMachine To delete a State Machine from an Equipment Type.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 289


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

DeleteHierarchyEquipment To delete a Hierarchy Equipment Node Configuration.


NodeConfiguration

DisassociateChildrenEquipmentGroup To remove the association between one or more children


ConfFromEquipmentGroupConf Equipment Group Configuration and an Equipment Group
Configuration.

DisassociateEquipmentConfigurations To remove a list of Equipment Configuration from a specified


FromEquipmentGroupConfiguration Equipment Group Configuration.

DisassociateEquipmentGroupConfigurati To remove the specified Equipment Configuration from the


ons specified list of Equipment Group Configuration.
FromEquipmentConfiguration

DisassociateParentsEquipmentGroupCon To remove the association between one or more Parents


f Equipment Group Configuration and an Equipment Group
FromEquipmentGroupConf Configuration.

FreezeEquipmentConfiguration To configure the Equipment Configuration to be read-only by


setting the IsFrozen attribute to True. This means that the
Equipment Configuration cannot be edited and modified.

FreezeEquipmentGroupConfiguration To configure the Equipment Group Configuration to be read-only


by setting the IsFrozen attribute to True. This means that the
Equipment Group Configuration cannot be edited and modified.

FreezeEquipmentLevel To configure the Equipment Configuration Level to be read-only


by setting the IsFrozen attribute to True. This means that the
Equipment Configuration Level cannot be edited and modified.

FreezeEquipmentType To configure the Equipment Type to be read-only by setting the


IsFrozen attribute to True. This means that the Equipment Type
cannot be edited and modified.

SetEquipmentTypeAsDefault To set the specified Equipment Type as default template for the
creation of the Equipment Configuration.

UnfreezeEquipmentConfiguration To remove the read-only setting from the Equipment


Configuration by setting the IsFrozen attribute to False. This
means that the Equipment Configuration can be edited and
modified.

UnfreezeEquipmentGroupConfiguration To remove the read-only setting from the Equipment Group


Configuration by setting the IsFrozen attribute to False. This
means that the Equipment Group Configuration can be edited
and modified.

290 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

UnfreezeEquipmentLevel To remove the read-only setting from the Equipment


Configuration Level by setting the IsFrozen attribute to False.
This means that the Equipment Configuration Level can be
edited and modified.

UnfreezeEquipmentType To remove the read-only setting from the Equipment Type by


setting the IsFrozen attribute to False. This means that the
Equipment Type can be edited and modified.

UpdateEquipmentConfiguration To update one or more properties of an Equipment


Configuration.

UpdateEquipmentConfigurationProperty To update the value of an Equipment Configuration Property.


This command can also be used to add Attributes to the
Equipment Configuration Property.

UpdateEquipmentConfiguration To update the Attribute Value of an Equipment Configuration


PropertyAttribute Property Attribute.

UpdateEquipmentGraphConfiguration To update one or more properties of an Equipment Graph


Configuration.

UpdateEquipmentGraphLinkConfiguratio To update one or more properties of an Equipment Graph Link


n Configuration.

UpdateEquipmentGraphType To update one or more properties of an Equipment Graph Type.

UpdateEquipmentGroupConfiguration To update one or more properties of an Equipment Group


Configuration.

UpdateEquipmentLevel To update one or more properties of an Equipment Level.

UpdateEquipmentType To update one or more properties of an Equipment Type. When


you launch this command with the State Machine NId set, the
State Machine List will be empty.

UpdateEquipmentTypeProperty To update the type and/or the value of an Equipment Type


Property. This command can also be used to add Attributes to
the Equipment Type Property.

UpdateEquipmentTypePropertyAttribute To update the type and/or the value of an Equipment Type


Property Attribute.

UpdateHierarchyEquipment To update the link of a Hierarchy Equipment Node Configuration.


NodeConfiguration
For further information, refer to the Commands section of the EQU_MS Reference Guide.

Events

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 291


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The EQU_MS Functional Block contains the following events:

Event Function

EquipmentConfigurationGroupUpdated Event fired when an Equipment Configuration Group is


changed, for example on creation, deletion, association and
disassociation.

EquipmentConfigurationPropertyAttributeU Event fired when the value of an Equipment Configuration


pdated Property Attribute is changed.

EquipmentConfigurationPropertyUpdated Event fired when the value of an Equipment Configuration


Property is changed.

EquipmentConfigurationStateMachineUpdat Event fired when an Equipment Configuration State Machine


ed is changed, for example on creation, deletion.

EquipmentConfigurationUpdated Event fired when an Equipment Configuration is changed, for


example on creation, and deletion.

EquipmentGraphConfigurationUpdated Event fired when an Equipment Graph Configuration is


updated.

EquipmentGraphLinkConfigurationUpdated Event fired when an Equipment Graph Link Configuration is


updated.

EquipmentGraphNodeConfigurationUpdated Event fired when an Equipment Graph Node Configuration is


changed, for example on creation, update and deletion.
For further information, refer to the Events section of the EQU_MS Reference Guide.

2.1.3.15.1.14 EQU_OP Functional Block


EQU_OP is a predefined Functional Block, belonging to the Operational domain.
Its Functional Block artifacts are defined to be used for performing runtime configurations on Equipment in
the Equipment App.

Entities
The EQU_OP Functional Block contains the following entities:

Entity Description

Equipment Represents the Equipment in the runtime environment.

EquipmentGraphLink Represents a Link in an Equipment Graph, that is the connection


between two graph Nodes.

EquipmentGraphNode Represents a Node of an Equipment Graph. The node may


represent an Equipment or an Equipment Group.

292 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description

EquipmentGroup Represents a Group of Equipment, which is a collection of


Equipment with similar capabilities or which can be used as
alternatives in a routing node.

EquipmentProperty Represents a Property of a piece of Equipment.

EquipmentPropertyAttribute Represents an attribute of an Equipment Property: it can be used


to enrich the information contained in the Equipment Property.

EquipmentStateMachine Represents the State Machines associated to the Equipment.


For further information, refer to the Entities section of the EQU_OP Reference Guide.

Commands
The EQU_OP Functional Block contains the following commands:

Command Function

CreateEquipment To create an instance of Equipment, starting from the specified


Equipment Configuration. One instance can be created from
each Equipment Configuration.

CreateEquipmentStateMachines To create a list of State Machines associated to the Equipment,


taking the data from the source Equipment Configuration.

DeleteEquipment To delete the Equipment Configuration identified by the id


passed as input, along with its Equipment instance, if one has
been created.

DeleteEquipmentStateMachine To delete the Equipment State Machine identified by the id


passed as input.

ForceEquipmentStatus To set the status of the Equipment, without checking the validity
of the transition.

FreezeEquipment To configure the Equipment to be read-only by setting the


IsFrozen attribute to True. The Equipment is identified by the
Equipment Configuration Id, starting from which it has been
created.

FreezeEquipmentGroup To configure the Equipment Group to be read-only by setting


the IsFrozen attribute to True.

SetEquipmentPropertyAttributeValue To modify an Equipment Property Attribute if the Operational


value is set to true.

SetEquipmentPropertyValue To modify an Equipment Property if its Operational value is set


to true.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 293


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

SetEquipmentStatus To set the status of the Equipment, checking the validity of the
transition.

UnfreezeEquipment To remove the read-only setting from the Equipment by setting


the IsFrozen attribute to False. The Equipment is identified by
the Equipment Configuration Id, starting from which it has been
created.

UnfreezeEquipmentGroup To remove the read-only setting from the Equipment Group by


setting the IsFrozen attribute to False.

UpdateEquipment To update an existing Equipment instance. The Equipment is


identified by the Equipment Configuration Id, starting from
which it has been created.

UpdateEquipmentGraph To synchronize the Equipment Graph links and nodes with the
Equipment Graph Configuration links and nodes.

UpdateEquipmentGraphLink To synchronize the Equipment Graph link with the Equipment


Graph Link Configuration.

UpdateEquipmentGraphNode To synchronize the Equipment Graph Node with the Equipment


Graph Node Configuration.

UpdateEquipmentGroup To synchronize the Equipment Group with the Equipment Group


Configuration.

UpdateEquipmentProperty To update the value of an Equipment Property.

UpdateEquipmentPropertyAttribute To update the value of an Equipment Property Attribute. The


Equipment is identified by the Equipment Configuration Id,
starting from which it has been created.
For further information, refer to the Commands section of the EQU_OP Reference Guide.

2.1.3.15.1.15 ES_MS Functional Block


ES_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts are defined to be used for managing engineering Electronic Signature functionalities, as provided in the
system-defined UI Screen released for creating an Electronic Signature Scenario (see Creating an Electronic
Signature Scenario in the Opcenter Execution Foundation User Manual).

Entities
In particular, the provided commands are aimed at creating, updating, deleting, freezing/unfreezing the following
entities:

294 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Name Description

ScenarioConfiguration The Electronic Signature Scenario containing the list of signatures


defined in SignatureConfiguration entity.

SignatureConfiguration The list of signatures associated to an Electronic Signature


ScenarioConfiguration entity.

Events
The ScenarioConfigurationDeleted event is fired with a specific envelope when a Electronic Signature Scenario
Configuration is deleted.
The ScenarioConfigurationDeleted event has the following envelope data structure:

Envelope property Property value

Category ScenarioConfigurationDeleted

Module ScenarioConfiguration

Tag ScenarioConfigurationDeleted

Topic ScenarioConfiguration

UserField1 The natural key identifier of the Electronic Signature Scenario


Configuration which is deleted.

For further information, see the ScenarioConfiguration Entity section of the ES_MS Reference Guide.
For an overview of the artifacts related to the runtime functionalities, see ES_SD Functional Block and
ScenarioInstance Entity section of the ES_SD Reference Guide.

2.1.3.15.1.16 ES_SD Functional Block


ES_SD is a predefined Functional Block, belonging to the System Data domain.
Its artifacts are defined to be used for managing runtime Electronic Signature functionalities.

Entities
The ScenarioInstance entity and the SignatureInstance entity are part of the Foundation model and can be used
in custom code to implement custom logic. The ESTicketInformation is for internal use. See the SignatureInstance
Entity in the ES_SD Reference Guide for details on the system data domain entities.

Commands
The ES_SD Functional Block contains a set of public commands that are internally used by the sit-rt-
signatures widget in order to handle signatures. These commands are PrepareSignature, AbortSignature
and AddSignature.
The Functional Block also contains:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 295


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• CreateScenarioInstance command which must be used in custom composite commands to create instances of
the ScenarioInstance and SignatureInstance entities, based on the ScenarioConfiguration and its
SignatureConfiguration entity.
• CreateScenarioInstanceWithSignatures command allows the user to create a ScenarioInstance using directly
a list of users/roles and reason to sign, bypassing the Engineering phase (i.e. not using ScenarioConfiguration).

 For further information, refer to the Commands section of the ES_SD Reference Guide and to
the Implementing the Business Logic for Electronic Signature Scenario Integration topic of the current
manual.

Events
The OnCompleteScenarioInstance event is fired when the Scenario Instance has been completed and it is
in Approved or Rejected status.
The event has the following envelope data structure:

Envelope Property Property value

Category OnCompleteScenarioInstance

Module The name of application that uses the Electronic Signature functionality.

Tag The status of scenario instance.

Topic The type of entity associated to the Scenario Instance.

UserField1, UserField2, ... FOR INTERNAL USE


to UserField10
The input data structure of the OnCompleteScenarioInstance event is defined as follows:

Name Type Description

ApplicationName String The name of application that uses the functionality


of Electronic Signature. Maximum length: 255.

Context String Additional information on the context where the


runtime entity is used. Maximum length: 255.

ScenarioInstanceId Guid The primary key identifier of the Scenario Instance


completed.

ScenarioConfigurationNId String The natural key of Electronic Signature Scenario


Configuration. Maximum length: 255.

CompleteAction String The action associated to Scenario Instance final


state. Maximum length: 255.

SignedEntityId Guid The primary key of the entity requiring Electronic


Signature.

296 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Name Type Description

SignedEntityType String The full type of the entity requiring Electronic


Signature. Maximum length: 255.

ActionLabel String The action label. Maximum length: 255.


For further information, refer to the Events section of the Events section of the ES_SD Reference Guide.

2.1.3.15.1.17 LBM_MS Functional Block


LBM_MS is a predefined Functional Block, belonging to the Master Data domain.
Its Functional Block artifacts are defined to be used for managing entities in the Label App. See Label App in the
Opcenter Execution Foundation User Manual.

Entities
The LBM_MS Functional Block contains the following entities:

Entity Description

LabelPrinter Defines a Label Printer.

LabelPrintHistory Defines a Label Print History.

LabelPrintHistoryTag Defines a Label History Print Tag used at print.

LabelTag Defines a Label Tag.

LabelTemplate Defines a Label Template.

LabelType Defines a Label Type.


For further information, refer to the Entities section of the LBM_MS Reference Guide.

Commands
The LBM_MS Functional Block contains the following commands:

Command Function

AddPrinterToTemplate To add a Label Printer to a Label Template.

CopyLabelPrinter To create a copy of an existing instance of Label Printer.

CopyLabelType To create a copy of an existing instance of Label Type, including


its associated Label Tags and Label Templates.

CreateLabelPrinter To create a Label Printer.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 297


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

CreateLabelTag To create a Label Tag.

CreateLabelTemplate To create a Label Template.

CreateLabelType To create a Label Type.

DeleteLabelPrinter To delete a Label Printer.

DeleteLabelTag To delete a Label Tag.

DeleteLabelTemplate To delete a Label Template.

DeleteLabelType To delete a Label Type.

FreezeLabelType To freeze an instance of a Label Type and its child relations.

GetCultures To return all available cultures from the system.

PrintLabel To invoke the Label Printing microservice at runtime.

RemovePrinter To remove an instance of a Label Printer from the parent Label


Template.

ReprintLabels To invoke the Label Printing microservice.

SetDefaultLabelPrinter To set the Label Printer as default.

SetDefaultLabelTemplate To set the Label Template as default.

UnfreezeLabelType To unfreeze an instance of a Label Type and its child relations.

UpdateLabelPrinter To update a Label Printer.

UpdateLabelTag To update a Label Tag.

UpdateLabelTemplate To update a Label Template.

UpdateLabelType To update a Label Type.


For further information, refer to the Commands section of the LBM_MS Reference Guide.

2.1.3.15.1.18 LBM_OP Functional Block


LBM_OP is a predefined Functional Block, belonging to the Operational domain.
Its Functional Block artifacts are defined to be used for managing entities in the runtime configuration phase in the
Label App. See What is Label Management? in the Opcenter Execution Foundation User Manual.

Commands

298 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The LBM_OP Functional Block contains the following commands:

Command Function

PrintLabel To invoke the Label Printing microservice at runtime.


For further information, refer to the Commands section of the LBM_OP Reference Guide.

Events
Event Function

LabelPrintRequested Fired when the PrintLabel command is called.


For further information, refer to the Events section of the LBM_OP Reference Guide.

2.1.3.15.1.19 MAT_MS Functional Block


MAT_MS is a predefined Functional Block, belonging to the Master Data domain.
Its Functional Block artifacts are defined to be used for managing materials in the engineering configuration phase
in the Material App. For more information see, How to Manage Engineering Materials in the Material App in the
Opcenter Execution Foundation User Manual.

Entities
The MAT_MS Functional Block contains the following entities:

Entity Description

Material Contains information on Materials.

MaterialGroup Contains information on group of Materials.

MaterialProperty Contains information on the Property related to a Material.

MaterialTemplate Contains information on the Material Definition template.

MaterialTemplateProperty Contains information on the Property related to a Material


Template.
For further information, refer to the Entities section of the MAT_MS Reference Guide.

Commands
The MAT_MS Functional Block contains the following commands:

Command Function

AssociateChildrenMaterialGroupWithMaterialGr To associate a Material Group with a list of children


oup Material Group.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 299


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

AssociateMaterialGroupWithMaterial To associate one or more Material Groups with a Material.

AssociateMaterialsWithMaterialGroup To associate a Material Group with a list of Materials.

AssociateParentsMaterialGroupWithMaterialGro To associate a Material Group with a list of parents


up Material Group.

CopyMaterialRevision To copy a Material revision.

CreateMaterial To create a Material.

CreateMaterialGroup To create a Material Group.

CreateMaterialProperties To create the Properties of a Material.

CreateMaterialTemplate To create a Material Template.

CreateMaterialTemplateProperties To create the Properties of a Material Template.

CreateNewMaterialRevision To create a new Material revision.

DeleteMaterial To delete an existing Material.

DeleteMaterialGroup To delete an existing Material Group.

DeleteMaterialProperties To delete the Properties from a Material.

DeleteMaterialTemplate To delete an existing Material Template.

DeleteMaterialTemplateProperties To delete the Properties from a Material Template.

DisassociateChildrenMaterialGroupFromMateria To remove the association between one or more children


lGroup Material Groups and a Material Group.

DisassociateMaterialGroupsFromMaterial To remove the association between one or more Material


Groups and a Material.

DisassociateMaterialsFromMaterialGroup To remove the association between one or more


Materials and a Material Group.

DisassociateParentsMaterialGroupFromMaterial To remove the association between one or more parent


Group Material Groups and a Material Group.

FreezeMaterialGroup To configure the Material Group as read-only by setting


the IsFrozen attribute to True.

FreezeMaterialTemplate To configure the Material Template as read-only by


setting the IsFrozen attribute to True.

300 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

LockMaterial To lock a Material.

SetMaterialRevisionCurrent To set a Material revision as current.

SetMaterialTemplateAsDefault To set a Material Template as default.

SetMaterialTemplateUoM To set a new Material Template Unit of Measure.

SetMaterialUoM To set a new Material Unit of Measure.

UnfreezeMaterialGroup To remove the read-only setting from the Material Group


by setting the IsFrozen attribute to False.

UnfreezeMaterialTemplate To remove the read-only setting from the Material


Template by setting the IsFrozen attribute to False.

UnlockMaterial To unlock a Material.

UnsetMaterialRevisionCurrent To remove the setting of a Material as current.

UnsetMaterialTemplateAsDefault To remove the setting of a Material Template as default.

UpdateMaterial To update a Material.

UpdateMaterialGroup To update a Material Group.

UpdateMaterialProperties To update the Properties of a Material.

UpdateMaterialTemplate To update a Material Template.

UpdateMaterialTemplateProperties To update the Properties of a Material Template.


For further information, refer to the Commands section of the MAT_MS Reference Guide.

2.1.3.15.1.20 MAT_OP Functional Block


MAT_OP is a predefined Functional Block, belonging to the Operational domain.
Its Functional Block artifacts are defined to be used for managing materials in the runtime configuration phase in
the Material App. For more information see, How to Manage Runtime Materials in the Material App in the Opcenter
Execution Foundation User Manual.

Entities
The MAT_OP Functional Block contains the following entities:

Entity Description

MaterialLot Contains information on Material Lots.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 301


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description

MaterialLotProperty Contains information on Properties of the Material Lot.

MaterialLotTemplate Contains information on the Material Lot Template.

MaterialLotTemplateProperty Contains information on Properties of the Material Lot


Template.

MaterialTrackingUnit Contains information on the Material Tracking Unit.

MaterialTrackingUnitAggregate Contains information on the Material Tracking Unit


Aggregate.

MaterialTrackingUnitAggregateProperty Contains information on Properties of the Material


Tracking Unit Aggregate.

MaterialTrackingUnitAggregateTemplate Contains information on the Material Tracking Unit


Aggregate Template.

MaterialTrackingUnitAggregateTemplatePropert Contains information on Properties of the Material


y Tracking Unit Aggregate Template.

MaterialTrackingUnitProperty Contains information on Properties of the Material


Tracking Unit.

MaterialTrackingUnitTemplate Contains information on the Material Tracking Unit


Template.

MaterialTrackingUnitTemplateProperty Contains information on Properties of the Material


Tracking Unit Template.
For further information, refer to the Entities section of the MAT_OP Reference Guide.

Commands
The MAT_OP Functional Block contains the following commands:

Command Function

AssociateMaterialTrackingUnitsWithMaterialLot To associate Material Tracking Units to a Material Lot.

CreateMaterialLot To create a Material Lot.

CreateMaterialLotProperties To add Properties to a Material Lot.

CreateMaterialLotTemplate To create a Material Lot Template.

CreateMaterialLotTemplateProperties To add Properties to a Material Lot Template.

302 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

CreateMaterialTrackingUnit To create a Material Tracking Unit.

CreateMaterialTrackingUnitAggregate To create a Material Tracking Unit Aggregate.

CreateMaterialTrackingUnitAggregatePropertie To add Properties to a Material Tracking Unit Aggregate.


s

CreateMaterialTrackingUnitAggregateTemplate To create a Material Tracking Unit Aggregate Template.

CreateMaterialTrackingUnitAggregateTemplate To add Properties to a Material Tracking Unit Aggregate


Properties Template.

CreateMaterialTrackingUnitProperties To add Properties to a Material Tracking Unit.

CreateMaterialTrackingUnitTemplate To create a Material Tracking Unit Template.

CreateMaterialTrackingUnitTemplateProperties To add Properties to a Material Tracking Unit Template.

DeleteMaterialLot To delete an existing Material Lot.

DeleteMaterialLotProperties To delete Properties from a Material Lot.

DeleteMaterialLotTemplate To delete an existing Material Lot Template.

DeleteMaterialLotTemplateProperties To delete Properties from a Material Lot Template.

DeleteMaterialTrackingUnit To delete an existing Material Tracking Unit.

DeleteMaterialTrackingUnitAggregate To delete an existing Material Tracking Unit Aggregate.

DeleteMaterialTrackingUnitAggregatePropertie To delete Properties from a Material Tracking Unit


s Aggregate.

DeleteMaterialTrackingUnitAggregateTemplate To delete an existing Material Tracking Unit Aggregate


Template.

DeleteMaterialTrackingUnitAggregateTemplate To delete Properties from a Material Tracking Unit


Properties Aggregate Template.

DeleteMaterialTrackingUnitProperties To delete Properties from a Material Tracking Unit.

DeleteMaterialTrackingUnitTemplate To delete an existing Material Tracking Unit Template.

DeleteMaterialTrackingUnitTemplateProperties To delete Properties from a Material Tracking Unit


Template.

ForceMaterialLotStatus To force the status of a Material Lot.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 303


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

ForceMaterialTrackingUnitAggregateStatus To force the status of a Material Tracking Unit Aggregate.

ForceMaterialTrackingUnitStatus To force the status of a Material Tracking Unit.

FreezeMaterialLot To configure a Material Lot as read-only by setting the


attribute IsFrozen to True.

FreezeMaterialLotTemplate To configure a Material Lot Template as read-only by


setting the attribute IsFrozen to True.

FreezeMaterialTrackingUnit To configure a Material Tracking Unit as read-only by


setting the attribute IsFrozen to True.

FreezeMaterialTrackingUnitAggregate To configure a Material Tracking Unit Aggregate as read-


only by setting the attribute IsFrozen to True.

FreezeMaterialTrackingUnitAggregateTemplate To configure a Material Tracking Unit Aggregate Template


as read-only by setting the attribute IsFrozen to True.

FreezeMaterialTrackingUnitTemplate To configure a Material Tracking Unit Template as read-


only by setting the attribute IsFrozen to True.

LoadMaterialTrackingUnitAggregateToEquipme To load a Material Tracking Unit Aggregate into a given


nt Equipment.

LoadMaterialTrackingUnitAggregateToMaterial To load a Material Tracking Unit Aggregate into a given


TrackingUnitAggregate Material Tracking Unit Aggregate.

MoveMaterialTrackingUnitToEquipment To move a Material Tracking Unit in a given Equipment.

MoveMaterialTrackingUnitToMaterialTrackingU To move a Material Tracking Unit in a given Material


nitAggregate Tracking Unit Aggregate.

SetMaterialLotMaterial To set a new Material of a Material Lot.

SetMaterialLotQuantity To set the quantity of a Material Lot.

SetMaterialLotStateMachine To set a new State Machine of a Material Lot.

SetMaterialLotStatus To set the status of a Material Lot.

SetMaterialLotTemplateAsDefault To set the Material Lot Template as default.

SetMaterialLotTemplateStateMachine To set the State Machine of a Material Lot Template.

SetMaterialTrackingUnitAggregateMaterial To set the Material of a Material Tracking Unit Aggregate.

SetMaterialTrackingUnitAggregateQuantity To set the Quantity of a Material Tracking Unit Aggregate.

304 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

SetMaterialTrackingUnitAggregateStateMachin To set the State Machine of a Material Tracking Unit


e Aggregate.

SetMaterialTrackingUnitAggregateStatus To set the status of a Material Tracking Unit Aggregate.

SetMaterialTrackingUnitAggregateTemplateAsD To set the Material Tracking Unit Aggregate Template as


efault default.

SetMaterialTrackingUnitMaterial To set the Material of a Material Tracking Unit.

SetMaterialTrackingUnitQuantity To set the Quantity of a Material Tracking Unit.

SetMaterialTrackingUnitStateMachine To set the State Machine of a Material Tracking Unit.

SetMaterialTrackingUnitStatus To set the status of a Material Tracking Unit.

SetMaterialTrackingUnitTemplateAsDefault To set the Material Tracking Unit Template as default.

UnfreezeMaterialLot To remove the read-only setting from the Material Lot by


setting the IsFrozen attribute to False.

UnfreezeMaterialLotTemplate To remove the read-only setting from the Material Lot


Template by setting the IsFrozen attribute to False.

UnfreezeMaterialTrackingUnit To remove the read-only setting from the Material


Tracking Unit by setting the IsFrozen attribute to False.

UnfreezeMaterialTrackingUnitAggregate To remove the read-only setting from the Material


Tracking Unit Aggregate by setting
the IsFrozen attribute to False.

UnfreezeMaterialTrackingUnitAggregateTempla To remove the read-only setting from the Material


te Tracking Unit Aggregate Template by setting
the IsFrozen attribute to False.

UnfreezeMaterialTrackingUnitTemplate To remove the read-only setting from the Material


Tracking Unit Template by setting
the IsFrozen attribute to False.

UnsetMaterialLotTemplateAsDefault To remove the setting of a Material Lot Template as


default.

UnsetMaterialTrackingUnitAggregateTemplate To remove the setting of a Material Tracking Unit


AsDefault Aggregate Template as default.

UnsetMaterialTrackingUnitTemplateAsDefault To remove the setting of a Material Tracking Unit


Template as default.

UpdateMaterialLot To update a Material Lot.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 305


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

UpdateMaterialLotProperties To update one or more Properties of a Material Lot.

UpdateMaterialLotTemplate To update a Material Lot Template.

UpdateMaterialLotTemplateProperties To update one or more Properties of a Material Lot


Template.

UpdateMaterialTrackingUnit To update a Material Tracking Unit.

UpdateMaterialTrackingUnitAggregate To update a Material Tracking Unit Aggregate.

UpdateMaterialTrackingUnitAggregatePropertie To update one or more Properties of a Material Tracking


s Unit Aggregate.

UpdateMaterialTrackingUnitAggregateTemplate To update a Material Tracking Unit Aggregate Template.

UpdateMaterialTrackingUnitAggregateTemplate To update one or more Properties of a Material Tracking


Properties Unit Aggregate Template.

UpdateMaterialTrackingUnitProperties To update one or more Properties of a Material Tracking


Unit.

UpdateMaterialTrackingUnitTemplate To update a Material Tracking Unit Template.

UpdateMaterialTrackingUnitTemplate To update one or more Properties of a Material Tracking


Properties Unit Template.
For further information, refer to the Commands section of the MAT_OP Reference Guide.

2.1.3.15.1.21 OPCUAConnect_MS Functional Block


OPCUAConnect_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts are defined to be used for performing engineering configurations on Equipment in
the OPCUAConnect App.

Entities
The OPCUAConnect_MS Functional Block contains the following entities:

Entity Description

EquipmentTypeToAutomationNodeType Represents the binding between an Equipment Type and


an Automation Node Type.

EquipmentConfigurationToAutomationNodeIn Represents the binding between an Equipment


stance Configuration and an Automation Node Instance.

306 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

For further information, refer to the Entities section of the OPCUAConnect_MS Reference Guide.

Commands
The OPCUAConnect_MS Functional Block contains the following commands:

Command Function

AssociateAutomationNodeTypesWit Binds one or more Automation Node Types to an Equipment Type.


hEquipmentType

DisassociateAutomationNodeTypes Unbinds one or more Automation Node Types from an Equipment


FromEquipmentType Type.

AssociateAutomationNode Binds one or more Automation Node Instances to an Equipment


InstancesWithEquipmentConfigurati Configuration.
on

DisassociateAutomationNode Unbinds one or more Automation Node Instances from an Equipment


InstancesFromEquipmentConfigurat Configuration.
ion
For further information, refer to the Commands section of the OPCUAConnect_MS Reference Guide.

Events
The OPCUAConnect_MS Functional Block contains the following events:

Event Function

AutomationNodeInstancesAssociatedWithEquip This event is raised when one or more Automation Node


mentConfiguration Instances are bound to an Equipment Configuration.

AutomationNodeInstancesDisassociatedFromEq This event is raised when one or more Automation Node


uipmentConfiguration Instances are unbound from an Equipment Configuration.
For further information, refer to the Events section of the OPCUAConnect_MS Reference Guide.

2.1.3.15.1.22 OPCUAConnect_OP Functional Block


OPCUAConnect_OP is a predefined Functional Block, belonging to the Operational domain.
Its artifacts are defined to be used for turning the engineering configurations on Equipment in runtime
environment, in the OPCUAConnect App.

Entities
The OPCUAConnect_OP Functional Block contains the following entities:

Entity Description

EquipmentToAutomationNode Represents the binding between a piece of Equipment and an


Automation Node.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 307


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

For further information, refer to the Entities section of the OPCUAConnect_OP Reference Guide.

Commands
The OPCUAConnect_OP Functional Block contains the following commands:

Command Description

AssociateAutomationNodesWithEqu Binds one or more Automation Nodes to a piece of Equipment.


ipment

DisassociateAutomationNodesWithE Unbinds one or more Automation Nodes from a piece of Equipment.


quipment
For further information, refer to the Commands section of the OPCUAConnect_OP Reference Guide.

2.1.3.15.1.23 PRM_MS Functional Block


PRM_MS is a predefined Functional Block, belonging to the Master Data domain.
Its Functional Block artifacts are defined to be used for managing Persons and Person Groups in the Personnel
App. For more information see, How to manage Persons and How to manage Person Groups in the Opcenter
Execution Foundation User Manual.

Entities
The PRM_MS Functional Block contains the following entities:

Entity Description

Person Contains information on each single Person.

PersonGroup Contains information on Group of Persons.

PersonSegregationTag Contains information on the tags assigned to a Person.

PersonGroupSegregationTag Contains information on the tags assigned to a Person


Group.

For further information, refer to the Entities section of the PRM_MS Reference Guide.

Commands
The PRM_MS Functional Block contains the following commands:

Command Function

AssignUserToPerson To associate a UMC user to a Person.

AssociatePersonsWithPersonGroup To associate Persons with Person Groups.

CreatePerson To create a new Person.

308 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

CreatePersonGroup To create a new Person Group.

DeletePerson To delete a previously created Person.

DeletePersonGroup To delete a previously created Person Group.

DisassociatePersonsFromPersonGroup To remove the association between Persons and Person Groups.

ImportUsers To create a new Person from specified UMC Users.

ImportUsersByGroup To create a new Person from each User provided by the specified
UMC Group.

ImportUsersByUserList To create a new Person for each specified UMC User.

ManageSegregationTagsToPersonsAss To manage the association between one or more tags and a list of
ociation Persons.

ManageSegregationTagsToPersonGrou To manage the association between one or more tags and a list of
psAssociation Person Groups.

PopulateSessionSegregationInfo To populate the Session Segregation Info table with specified


Segregation Tags.

SetCanViewUnsegregatedData To view not segregated data.

UnassignUserFromPerson To remove the association between a UMC user and a Person.

UpdatePerson To modify the details of a previously created Person.

UpdatePersonGroup To modify the details of a previously created Person Group.


For further information, refer to the Commands section of the PRM_MS Reference Guide.

Events
The PRM_MS Functional Block contains the following events:

Event Function

StartUserImport This event is raised when starting the Import of Users.

UserImportCompleted This event is fired when the User Import has been completed.
For further information, refer to the Events section of the PRM_MS Reference Guide.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 309


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.3.15.1.24 QEMigration_MS Functional Block


QEMigration_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts allow you to migrate existing Failures, created in the platform version 3.0, and their association with
Visual Characteristics from the Work Instruction App to the Defect App.
It references the following Functional Block:
• CHR_MS
• DEF_MS
• UDM_RF

Commands
The QEMigration_MS Functional Block contains the following command:

Command Function

MigrateCharacteristicFailureAss To migrate Failures, created in version 3.0 of Opcenter Execution


ociation Foundation, and their association with Visual Characteristics from the
Work Instruction App to the Defect App.

For further information, refer to the Commands section of the QEMigration_MS Reference Guide.

2.1.3.15.1.25 SGN_MS Functional Block


SGN_MS is a predefined Functional Block of the Signals App, belonging to the Master Data domain.
Its Functional Block artifacts are defined to be used for managing signals in the Signals App. For more information
see, Signals App in the Opcenter Execution Foundation User Manual.

Entities
The SGN_MS Functional Block contains the following entities:

Entity Description

SignalRule Contains information on each single signal rule, such as its name,
description and revision number.

SignalRuleTemplate Contains information on the template on which the signal rule is


based.

SignalRuleConfiguration Contains the configuration information of the corresponding


signal rule.
For further information, refer to the Entities section of the SGN_MS Reference Guide.

Commands
The SGN_MS Functional Block contains the following commands:

310 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

ApproveSignalRules To approve an existing signal rule.

CheckSignalRuleConsistency To check if the signal rule configuration is consistent and can


consequently be approved.

CopySignalRule To create a copy of an existing signal rule structure.

CreateSignalRule To create a signal rule.

DeleteSignalRuleConfigurations To delete the signal rule configuration.

DeleteSignalRules To delete a signal rule.

DeploySignalRules To deploy a previously approved signal rule.

 The command execution timeout for this command


should be set to 600 seconds.

ExportSignalRules To export a signal rule as a json file.

ImportSignalRules To import a previously exported signal rule.

ResumeSignalRule To resume a list of signal rules.

SetSignalRuleRuntimeStatus For internal use only.

StopSignalRule To stop a list of signal rules.

UpdateDeployedSignalRulesStatus For internal use only.

UpdateSignalRule To update a signal rule.

UpdateSignalRuleConfiguration To update the signal rule configuration.


For further information, refer to the Commands section of the SGN_MS Reference Guide.

2.1.3.15.1.26 TSK_MS Functional Block


TSK_MS is a predefined Functional Block, belonging to the Master Data domain.
Its Functional Block artifacts are defined to be used for managing tasks in the engineering configuration phase.
It references the UDM_RF Functional Block.

Entities
The TSK_MS Functional Block contains the following entities:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 311


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description Relationship

Task Type A logical group of Task Definitions sharing common characteristics in


terms of configuration and execution.
Task management provides a standard Task Type but you can also create
custom Task Types by specifying the related UI pages to be shown and
used when creating a new Task Definition or when running a new Task.
The custom Task Type definition is managed in Project Studio during the
modeling phase (i.e. it cannot be performed during runtime operations).

Task Defines a task. Task Definition entities have standard Revision behavior. Task Definitions :
Definition
• must be related
to a Task Type
• can be related
to one or more
Task
Definition Para
meters
• can be
associated to
one or more
Task Context
Definitions

Task A parameter associated to a Task Definition. A Task Parameter can be set


Definition as read-only. In this case, the parameter value configured in the Task
Paramete Definition cannot be modified in the runtime Task.
r

Task Defines a base relational context for the Task Definition entity. Task Context
Context Definitions are
Definition related to:
• one or more
Task Context
Definition User
Fields

Task Defines the User Field related to a Task Context Definition entity.
Context
Definition
User Field
For further information, refer to the Entities section of the TSK_MS Reference Guide.

Commands
The TSK_MS Functional Block contains the generic basic commands and the following functional block specific
commands for task management:

312 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

AssociateTaskContextDefinitionsWithTaskDefi To associate a Task Definition to a list of Task Context


nition Definitions.

DisassociateTaskContextDefinitionsFromTaskD To remove the association between one or more Task


efinition Context Definitions and a Task Definition.

For further information, refer to the Commands section of the TSK_MS Reference Guide.

2.1.3.15.1.27 TSK_OP Functional Block


TSK_OP is a predefined Functional Block, belonging to the Operational domain.
Its Functional Block artifacts are defined to be used for managing tasks in the runtime configuration phase.
It references the following Functional Blocks.
• UDM_RF
• TSK_MS

Entities
The TSK_OP Functional Block contains the following entities:

Entity Description Relationship

Task Defines a runtime task. Runtime tasks can be A Task can be related to one or
created either: more Task Parameters.
• manually (using a web page)
• automatically when creating a Work Order. In
this case Tasks directly inherit the Task
Definition properties (the user fields, in
particular) and represent Task Definition
instances, with additional runtime-specific
properties, such as equipment, location and
order data.

Task Parameter Defines a parameter associated to a Task.

Task Context Defines a base relational context for the Task entity. A Task Context can be related
to one or more Task Context
Task Context User Defines a user field related to a Task Context entity. User Fields.
Field
For further information, refer to the Entities section of the TSK_OP Reference Guide.

Commands
In order to use some of the following commands you must subscribe to certain events, which are specified in the
following table.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 313


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function Event Subscription required

AbortTask To set the task status to Aborted. ActionOnTaskRequested

ActivateTask To set the task status to Ready ActionOnTaskRequested

CancelTask To set the task status to Canceled ActionOnTaskRequested

CompleteTask To set the task status to Completed ActionOnTaskRequested

FailTask To set the task status to Failed ActionOnTaskRequested

PauseTask To set the task status to Paused ActionOnTaskRequested

RecoverTask To set the task status to In Progress ActionOnTaskRequested

ResumeTask To set the status of a paused task to In ActionOnTaskRequested


Progress

SkipTask To set the task status to Skipped ActionOnTaskRequested

StartTask To set the status of a Ready task to In ActionOnTaskRequested


Progress

SuspendTask To set the task status to Suspended ActionOnTaskRequested

RepeatTask To repeat a task for a maximum number of


iterations (if the outcome of the status,
which is currently associated to the Task, is
not NoOutcome) by creating a new instance
of the same Task Definition, to which the
task was associated.

ActivateSequenceStep To start the tasks for the given sequence


number within the given Task Flow
identifier.

SetErrorCount To set the value of the Error Count and fires


the event ErrorCountChanged.

RemoveTaskFromTaskFlo To reset task flow information in order to


w remove a Task from a Task Flow.

SetTaskStatus To set the status of a Task, checking the


validity of the transaction.
Subscriptions can be performed as follows:
• ActionOnTaskRequested event: either with the event handler ChangeTaskStatusOnAction or with a custom
event handler.
For further information, refer to the Commands and the Events sections of the TSK_OP Reference Guide.

314 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Events
The following events are fired each with a specific envelope, on which you can filter while configuring the
subscription.
• When an action on the task is requested by means of the pre-defined commands provided by Task Management
(such as ActivateTask, PauseTask, CompleteTask), the event ActionOnTaskRequest will be fired.
• When a status is successfully changed, through the commands SetTaskStatus and ForceTaskStatus, the
events StatusChanged, and StatusForced will be fired.
• When a status of a task has changed, through the command SetTaskStatus, the event TaskStatusChanged will
be fired. It also contains information on the Equipment to which the Task belongs to.
• When an entire sequence step has completed, regardless whether successfully or not, the
event SequenceStepCompleted will be fired.
• When the Complete action on the Task of Work Instruction Task type is requested, the event
ActionOnCompleteWITask will be fired.

The ActionOnTaskRequest event has the following envelope data structure:

Envelope property Property value

Category ActionRequested

Module TaskManagement

Tag ActionRequested

Topic Task

UserField1 The natural key identifier of the State Machine

UserField2 The natural key identifier of the source Status

UserField3 The natural key identifier of the Verb used.

UserField4 The natural key identifier of the Task Type

UserField5 The natural key identifier of the Task Definition

UserField10 FOR INTERNAL USE

 If WITask App is installed in your Solution and you want to subscribe ActionOnTaskRequest event for the
execution of the Tasks, other than WI Task type, filter the event with the appropriate value of UserField4.
Example:
• For Standard Task, UserField4 = TSKType
If WITask App is installed in your Solution and you want to execute the standard tasks subscribe
to ActionOnTaskRequest event by filtering using UserField4 envelope parameter. To execute WI task
types an additional subscription is not required.
Example:
• For Standard Task, UserField4 = TSKType

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 315


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

and the event TaskActionEventArgs Parameter Type:

Name Type Description

ActionName String The name of the verb applied and the name of the user
requesting the operation. Maximum length: 255

UserName String Maximum length: 255


Both StatusChange, StatusForced and TaskStatusChanged events have the following envelope data structure:

Envelope property Property value

Category StatusChanged

Module TaskManagement

Tag StatusChanged

Topic Task

UserField1 The natural key identifier of the State Machine

UserField2 The natural key identifier of the Source Status

UserField3 The natural key identifier of the Target Status

UserField4 The natural key identifier of the Task Type

UserField5 The natural key identifier of the Task Definition

UserField6 True, if target status is meant as a final status (the outcome of the
status is not 0), false otherwise.

UserField10 FOR INTERNAL USE


and the event StatusEventArgs Parameter Type:

Name Type Description

StateMachineNId String The natural key identifier of the State Machine.


Maximum length: 255.

PreviousStatusNId String The natural key identifier of the previous


Status. Maximum length: 255.

CurrentStatusNId String The natural key identifier of the current Status.


Maximum length: 255.

EntityId Guid The primary key identifier of the Entity.

EntityType String The type of the Entity. Maximum length: 255.

316 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Name Type Description

StatusOutcome StatusesOutcome The status outcome of the Current Status.

CurrentStatusColor String The status color of the Current Status.

CurrentStatusName Name The status name of the Current Status.

LastUpdatedOn DateTimeOffset The last update date time of the Entity.

CreatedOn DateTimeOffset The created date time of the Entity.


The TaskStatusChanged event has one more parameter of TaskEventArgs Parameter Type:

Name Type Description

TaskId Guid The key identifier of the Task.

TaskNId String The natural key identifier of the Task.

TaskTypeNId String The natural key identifier of the Task Type.

TaskDefinitionNId String The natural key identifier of the Task Definition.

TaskDefinitionRevision OptionalRevision The revision of the Task Definition related to the


Task.

ErrorCount Int32 The value of the Error Count to be set.

IsSkippable Boolean Defines if the Task can be skipped. The default


value is True.

EquipmentNId String The natural key identifier of the Equipment.

Sequence Int32 The sequence number of the Task.

MaxIterations Int32 Maximum number of allowed Iterations.

IterationGroupId Guid Used to group tasks created by iterations.

ContinueOnSuccess Boolean The task sequence proceeds with the execution,


when the value is set to true and if the previous
task is successfully completed.

ContinueOnFailure Boolean The task sequence proceeds with the execution,


when the value is set to false and if the previous
task is a failure.

TaskFlowIdentifier String The identifier of the Task Flow.

The SequenceStepCompleted event has the following envelope data structure:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 317


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Envelope property Property value

Category StageCompleted

Module TaskManagement

Tag StageCompleted

Topic Task

UserField1 The sequence number of the Task

UserField2 The identifier of the Task Flow.

UserField3 True, if at least one of the tasks within the sequence step did not
match the exit policy, false otherwise.

UserField4 True, if all the tasks within the sequence step matched the exit
policy, false otherwise.

UserField5 True, if the completed sequence step is the last sequence step in the
Task Flow.

UserField6 True, if the completed sequence step is not the last sequence step
in the Task Flow.
and the following event SequenceStepCompletedEventArgs Parameter Type applies:

Name Type Description

TaskFlow String The identifier of the Task Flow.

Sequence Int The sequence number of the Task.

SequenceStepSuccess Bool True, if all the tasks within the sequence step matched
the exit policy, or false if at least one of the tasks within
the sequence step did not match.

IsLastStep Bool True, if the completed sequence step is the last


sequence step in the Task Flow, false otherwise.
The ActionOnCompleteWITask event has the following envelope data structure:

Envelope property Property value

Category CompleteWorkInstructionTask

Module TaskManagement

Tag ActionRequested

318 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Envelope property Property value

Topic WorkInstructionTask

UserField1 The natural key identifier of the State Machine.

UserField2 The natural key identifier of the Source Status.

UserField4 The natural key identifier of the Task Type.

UserField5 The natural key identifier of the Task Definition.

 The event ActionOnCompleteWITask has pre-defined subscription whenever the extension app of the
Work Instruction, i.e. WITask app, is installed in the Solution Studio.

For further information, refer to the Events section of the TSK_OP Reference Guide.

2.1.3.15.1.28 UDM_RF Functional Block


UDM_RF is a predefined UDM Functional Block, belonging to the Reference Data domain.
It is the central Functional Block, referenced by all other UDM Functional Blocks.
The Functional Block artifacts are defined to be used in the following areas:
• Autonumbering
• State Machines
• Units of Measure
It does not reference any other Functional Blocks.
For further information, refer to the Entities, Commands and other sections of the UDM_RF Reference Guide.
Autonumbering Management
Autonumbering is managed within the UDM_RF Functional Block.

Entities
The UDM_RF Functional Block contains the following entities for autonumbering:

Entity Description Relationships

Counter A progressive numeric value, which can A Counter can be referenced by one
be used within the Numbering or more Numbering Pattern Parts
Pattern.

Numbering Pattern The complete pattern to be used in the A Numbering Pattern is associated to
autogeneration of a string. only one entity type,
which is associated to one or more
specific parameters.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 319


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description Relationships

Numbering Pattern Part One of the parts which make up the A NumberingPatternPart:
Numbering Pattern.
• is related to the Numbering
Pattern it belongs to.
• can be related to one of the
following:
• Counter
• Constant
• Parameter
• Timestamp

Commands
The UDM_RF Functional Block contains the generic basic commands and the following functional block specific
commands for autonumbering:

Commands Function

IncrementCounter To get the next incremental value of a Counter.

MoveNumberingPatternPart To move the Numbering Pattern Part within the


Numbering Pattern sequence

ResetCounter To reset a Counter to its initial value (seed).


State Machine Management
State machines are managed within the UDM_RF Functional Block.
A predefined State Machine is provided for Task management. For more information see, How to Customize Task
Management in the Opcenter Execution Foundation User Manual.

Entities
The UDM_RF Functional Block contains the following entities for state machine management:

Entity Description Relationships

State Machine A status lifecycle, defined by a set of Status


entities and the related Status Transition
entities.

320 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description Relationships

Status A significant milestone in the lifecycle of Each Status :


business entities.
• must be related to the State
The Status is created from the Status Machine it belongs to.
Definition template. • must be related to the Status
Definition, from which it is
generated.
 Each Status has the same natural
identifier (NId) as the Status • can be associated to one or
Definition it is created from, in order more Status Behaviors.
to guarantee uniformity in the logical
keys of the statuses. For example,
from the In progress Status
Definition you can create two
different Status entities, applied
to two different work order
types (transport order and
production order). These Status
entities will have the same NId,
derived from the common Status
Definition, but they belong to
different State Machines (related to
the lifecycles of transport
orders and of production orders).

Status Behavior A business relevant behavior of a status A Status Behavior can be


Definition belonging to a state machine. associated to one or more Status.

Status Definition The template used for the creation of a Status.

Status Transition A transition, or change of status between two A Status Transition must be
different statues that belong to the the same related to:
State Machine.
• a target Status
A Status Transition is defined by the source • a source Status
status and by the verb (i.e. the action), which
represents the specific transition
The Status Transition is created from the
Status Transition Definition template.

Status Transition The template used for creation of Status


Definition Transition.

Commands
The UDM_RF Functional Block contains the generic basic commands and the following functional block specific
commands for state machine management:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 321


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Command Function

AssociateStatusBehaviorDefinitionsWithStatus To associated one or more Status Behavior


Definitions to a Status.

DisassociateStatusBehaviorDefinitionsFromStatus To remove the association of one or more Status


Behavior Definitions from a Status.

SetStatusAsInitial To set the selected Status as the initial status of the


State Machine.
Units of Measure Management
Units of measure are managed within the UDM_RF Functional Block.

Entities
The UDM_RF Functional Block provides the following entities for unit of measure management:

Entity Description Relationships

Unit of The physical category such as length, time,


Measure Dimension ( volume.
UoM Dimension)
Within the same UoM dimension, different sub-
groups of UoM (systems) can be defined. Each
system is made up of a base UoM (mandatory)
and by multiples and submultiples of the base
UoM. For example, in the UoM dimension length,
the metric system with base UoM meter, and the
metric system with base UoM yard, are defined.

Unit of Measure (UoM) The base unit for measuring a physical quantity. A base UoM must:
Units of measure belonging to same physical • be related to a UoM
category are related to the same Dimension.
UoM dimension. • belong to a defined
physical category.
A multiple/submultiple
UoM must be related to its
base UoM.

Unit of Measure The conversion factor between a target UoM and A UoM Factor must be related
Factor (UoM Factor) a source UoM, belonging to the same category. to:
• a target UoM (base or
multiple/submultiple) and
• a base source UoM.

Commands
The UDM_RF Functional Block contains the generic basic commands and the following functional block specific
commands for unit of measure management:

322 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Commands Function

ConvertQuantity To convert a given quantity, expressed in the source UoM, into the
corresponding quantity, expressed in the target UoM.

UoM Conversion
Multiples and submultiples of a base UoM are defined through conversion factors (UoM Factor).
Base UoMs of different systems, belonging to the same UoM dimension, are related by proper conversion factors.
For these reasons, the only admitted conversions are between two UoMs belonging to the same system (for
example cm to meter) or between two UoMs belonging to different systems with base UoM belonging to the same
UoM dimension (for example cm to inches).
The UoM conversion is calculated according to the following formula:

TargetUoM = K0 (K1 * SourceUoM)n + A

For example, to convert m in km, as 1 km = 103 m, the parameters of the conversion formula will be:
• TargetUoM = km
• SourceUoM = m
• K0 = 103
• K1 = 1
• n=1
• A=0
The following data, as instances of UoM management entities, are provided by the system.

UoM Dimension Base Uom Submultiples/Multiples

Length Meter (m) millimeter micrometer, nanometer,


kilometer

Yard (yd)

Mass Kilogram (kg) gram, milligram, microgram, ton

Pound (lb)

Time Second (s) millisecond, microsecond, nanosecond,


minute, hour, day

Electric current Ampere (A)

Temperature Kelvin (K)

Surface Square meter (m2)

Hectare (ha)

Acre (ac)

Volume Cubic meter (m3)

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 323


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

UoM Dimension Base Uom Submultiples/Multiples

Liter (l) centiliter, milliliter

Fluid Once (fl oz)

Gallon (gal)

Counting Pieces (pcs)


In addition the following UoM conversion factors are provided:
• the factors to convert multiples/submultiples to the related base UoM.
• the factors to convert the base quantities belonging to the same UoM dimension.

 Predefined data, such as UoMs, UoM Dimensions, and UoM factors, cannot be deleted and cannot be
modified except for their name and description, in order to maintain universally known symbols and ratio
among UoMs.

2.1.3.15.1.29 WI_MS Functional Block


WI_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts allow you to manage Work Instructions, specifically in the Work Instruction App.
It references the following Functional Blocks:
• UDM_RF
• ES_MS

Entities
The WI_MS Functional Block contains the following entities:

Entity Description Relationships

WI_ESScenario Represents the relationship between a


Work Instruction Step and an
Electronic Signature Scenario.

WorkInstructionDefinition Defines the structure of a set of Work


Instructions, including its execution
model.

WorkInstructionDefinition Defines the structure of an input/ A WorkInstructionDefinition entity


Parameter output parameter for a set of Work can be related to
Instructions. many WorkInstruction
DefinitionParameter entities.
Backward navigation is possible
between these two entities through
the WorkInstructionDefinition
property.

324 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Entity Description Relationships

WorkInstructionTemplate The template used to create the Work


Instruction Definition.

WorkInstruction The template used to create the Work A WorkInstructionTemplate entity


TemplateParameter Instruction Definition Parameter. can be related to
many WorkInstruction
TemplateParameter entities.
Backward navigation is possible
between these two entities through
the WorkInstructionTemplate
property.
For further information, refer to the Entities section of the WI_MS Reference Guide.

Commands
The WI_MS Functional Block contains the generic basic commands and the following functional block specific
commands for work instruction management:

Commands Function

AssignESScenarioToWI To create a WI_ESScenario entity representing the association


between Work Instruction Step and Electronic Signature
Scenario.

CreateWorkInstructionDefinitionByImport To create a Work Instruction Definition starting from an


imported model in json format.

DeleteESScenarioFromWI To delete the WI_ESScenario which has information of


Electronic Signature Scenario assigned to Work Instruction
Step.

ExportWorkInstructionDefinition To export a Work Instruction Definition to a JSON file.


Note: Electronic Signature Scenario associated to the Work
Instruction Definition Steps will not be exported along with
their structures.

SaveWorkInstructionDesign To update the design of an existing Work Instruction Definition


and assign/unassign the Electronic Signature Scenarios to the
Work Instruction Steps.

SetWorkInstructionTemplateAsDefault To set an existing Work Instruction Template as default.


For further information, refer to the Commands section of the WI_MS Reference Guide.

2.1.3.15.1.30 WI_OP Functional Block


WI_OP is a predefined Functional Block, belonging to the Operational domain.
Its artifacts allow you to manage Work Instructions, specifically in the Work Instruction App.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 325


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

It references the following Functional Blocks:


• UDM_RF
• WI_MS
• ES_MS
• ES_SD

Entities
The WI_OP Functional Block contains the following entities:

Entity Description Relationships

WorkInstruction A runtime Work One WorkInstruction entity can be related to many


Instruction WorkInstructionSection entities.
instance.

WorkInstructionSecti A Section of a One WorkInstruction Section entity can be related to many


on Work Instruction WorkInstructionStep entities.
instance at
One WorkInstructionSection entity can be related to one
runtime.
WorkInstruction entity. Backward navigation is possible between
these two entities through the WorkInstruction property.

WorkInstructionStep A Step of a Work One WorkInstructionStep entity can be related to one


Instruction WorkInstructionSection. Backward navigation is possible
Section. between these two entities through the WorkInstructionSection
property.

WorkInstructionStep An Item of a data One WorkInstructionStepItem entity can be related to one


Item collection Work WorkInstructionStep. Backward navigation is possible between
Instruction Step. these two entities through the WorkInstructionStep property.

WorkInstructionStep Describes the One WorkInstructionStepItemLimit entity can be related to one


ItemLimit limits for the WorkInstructionStepItem. Backward navigation is possible
value of a Work between these two entities through the
Instruction Step WorkInstructionStepItem property.
Item.

WorkInstructionPara Describes the A WorkInstruction can be related to


meter properties of a many WorkInstructionParameter. Backward navigation is
Work Instruction. possible between these two entities through the WorkInstruction
property.
For further information, refer to the Entities section of the WI_OP Reference Guide.

Commands
The WI_OP Functional Block contains the generic basic commands and the following functional block specific
commands for work instruction management:

326 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Commands Function

AbortWorkInstru To set the status of Work Instruction to Abort.


ction

AcknowledgeWo To acknowledge a Work Instruction Step.


rkInstruction
Step

AcquireDCValues This command offers a way of persisting the Work Instruction Step Item values coming
from external systems, if configured correctly using a Post Action (For example, reading
values from the field using the Automation Gateway).

AutoSaveWorkIn To save the Work Instruction Step Item value.


structionStep
ItemValue

ConfirmDataColl To confirm a data collection Work Instruction Step.


ectionStep

CompleteWIStep To complete the linked WI Step when Scenario Instance is completed.


OnComplete
ScenarioInstance

CompleteWorkIn To complete a Work Instruction.


struction

InEditingWorkIns To set the status of a Work Instruction to InEditing.


truction

RetrieveDCItems To retrieve the values of Section NId, Step NId, Step Item Id, and Step Item NId for the
given Work Instruction.

SetAcquisitionBe To set the value of Acquisition Behavior property of Work Instruction Step Items. This
havior command receives a list of Work Instruction Step Item Ids and their corresponding
Acquisition Behavior.

SetDCItemValues To set values of the Work Instruction Step Items. This command receives a list of Work
Instruction Step Item Ids and values.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 327


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Commands Function

UpdateStepItem To update the existing Work Instruction Step Item Limits. The command receives in input
Limits an Id, related to the item to be updated, and the LimitValues parameter.
The LimitValues StepItemLimitValueType Parameter Type values are handled as follows,
according to the type of the object identified by the Id parameter:

Graphic Control LowLimit HighLimit Target property


Type property property

Single Input Only in the following


Numeric formats:
• negative numbers must
be preceded by
"-" (minus sign)
• decimal numbers must
be separated by "." (dot
character)

Checkbox (true or false)

Multiple Choice You must only use one of


the previously defined
values.

DateTime Only in the following


ISO-8601 format:
• UTC with milliseconds:
yyyy-MM-
ddTHH:mm:ss.fffZ
• UTC without
milliseconds: yyyy-MM-
ddTHH:mm:ssZ
For example:
• UTC with milliseconds:
2018-10-17T09:24:29.209
Z
• UTC without
milliseconds:
2018-10-17T09:24:29Z
where,
means that if the value is specified, the system stores the specified value
means that the value is not considered.

UpdateWorkInstr To update the value of an existing Work Instruction Parameter. The command receives in
uction input the Id and ParameterValue to be updated.
ParameterValue

328 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

For the complete list of commands and the related information, refer to the Commands section of the WI_OP
Reference Guide.

Events
The following events are fired each with a specific envelope, on which you can filter while configuring the
subscription.
• When a Work Instruction Section is completed, the event WorkInstructionSectionCompleted will be fired.
• When a Work Instruction Step is acknowledged/confirmed, the event WorkInstructionStepCompleted will be
fired.
• When a Work Instruction Step is acknowledged/confirmed and is associated with an Electronic Signature
Scenario, the event OnWorkInstructionStepInPending will be fired.
The WorkInstructionSectionCompleted event has the following envelope data structure:

Envelope property Property value

Category WorkInstructionSectionCompleted

Module WorkInstruction

Tag SectionCompleted

Topic WorkInstruction

UserField1 The natural key identifier of the Work Instruction.

UserField2 The natural key identifier of the Work Instruction Section.

UserField3 The name of the user completing the Section.


The WorkInstructionStepCompleted event has the following envelope data structure:

Envelope property Property value

Category WorkInstructionStepCompleted

Module WorkInstruction

Tag StepCompleted

Topic WorkInstruction

UserField1 The natural key identifier of the Work Instruction.

UserField2 The natural key identifier of the Work Instruction Step.

UserField3 The name of the user completing the Section.

UserField4 The acknowledgement/confirmation date and time of the Work


Instruction Step.
The OnWorkInstructionStepInPending event has the following envelope data structure:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 329


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Envelope property Property value

Category OnWorkInstructionStepInPending

Module WorkInstruction

Tag StepWithPendingSignature

Topic WorkInstruction

UserField1 The natural key identifier of the Work Instruction.

UserField2 The natural key identifier of the Work Instruction Step.

UserField3 The name of the user completing the Section.

UserField4 The acknowledgement/confirmation date and time of the Work


Instruction Step.

 Both the events, WorkInstructionSectionCompleted and WorkInstructionStepCompleted, have pre-


defined subscriptions whenever the Work Instruction app is installed in the Solution Studio.

For further information, refer to the Events section of the WI_OP Reference Guide.

2.1.3.15.1.31 WI_TASK_MS Functional Block


WI_TASK_MS is a predefined Functional Block, belonging to the Master Data domain.
Its artifacts allow you to manage Task Definition of Work Instruction Task Type.
It references the following Functional Blocks:
• UDM_RF
• WI_MS
• TSK_MS

Commands
The WI_TASK_MS Functional Block contains the following specific commands for Work Instruction Task
Management:

Commands Function

CreateWITaskDefiniton To create a Task Definition of type Work Instruction Task.

UpdateWITaskDefinition To update a Task Definition of type Work Instruction Task.


For further information, refer to the Commands section of the WI_TASK_MS Reference Guide.

2.1.3.15.1.32 WI_TASK_OP Functional Block


WI_TASK_OP is a predefined Functional Block, belonging to the Operational domain.

330 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Its artifacts allow you to manage Tasks of Work Instruction Task Type.
It references the following Functional Blocks:
• UDM_RF
• WI_MS
• WI_OP
• TSK_MS
• TSK_OP
• WI_TASK_MS

Entities
The WI_TASK_OP Functional Block contains the following entities:

Entity Description Relationships

WIReference Defines a Work Instruction during the A Task entity can be related to many
runtime phase. WIReference entities.

For further information, refer to the Entities section of the WI_TASK_OP Reference Guide.

Commands
The WI_TASK_OP Functional Block contains the following specific commands and post commands for Work
Instruction Task Management:

Commands Function

ChangeTaskStatusOnDeleteWI Changes the status of WI Task to aborted/cancelled/failed


according to its current status when the linked Work Instruction is
deleted.

CheckTaskStatusOnAcknowledge Post Action of AcknowledgeWorkInstructionStep command to


check whether the linked WI Task is in InProgress state.

CheckTaskStatusOnConfirm Post Action of ConfirmDataCollectionStep command to check


whether the linked WI Task is in InProgress state.

CreateWIFromTask To create a Work Instruction from Task.

ForceToCompleteWITask To complete Work Instruction Task when the Work Instruction is


completed.
For further information, refer to the Commands section of the WI_TASK_OP Reference Guide.

2.1.3.15.1.33 Functional Block Basic Commands


As already explained in the dedicated sections (see Overview of Functional Blocks), Functional Blocks contain
commands that are specific to their area of application, such as for example material management for MAT_MS
Functional Block or task management for TSK_MS Functional Block.
However, a set of basic commands, which are common to all Functional Blocks, are provided for each Functional
Block to perform the following basic operations on their Functional Block entities.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 331


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Crud operations
The following commands are provided in order to manage CRUD operations on entity instances:
• Create<Entity>
• Update<Entity>
• Delete<Entity>.

Revision behavior
Specific commands are provided, only for Master Data domain entities, to manage the revision behavior of each
entity instance, such as creating, copying, setting a revision or locking an entity instance.
For more information on the revision behavior, refer to Managing Revisions of Entity Instances.
• Copy<Entity>Revision
• CreateNew<Entity>Revision
• Lock<Entity> or Unlock<Entity>
• Set<Entity>RevisionCurrent or Unset<Entity>RevisionCurrent

Entity instance lifecycle


The lifecycle of any entity instance is based on the standard Opcenter EX FN platform lifecycle.
The following attributes are included:
• IsFrozen: entity instances are visible in the database and can be queried but cannot be updated.
• IsDeleted:entity instances are no longer visible and cannot be queried or modified, but are present in the
database.
• IsHidden temporarily hides entity instances from the configuration environment. When the IsHidden property
is set to true, the data is still present in the system and can be updated or deleted. The hide/unhide functionality
does not affect the IsDeleted entity property.
For more information on the lifecycle management, refer to Managing Revisions of Entity Instances.
The following commands are available:
• Freeze<Entity> or Unfreeze<Entity>
• Hide<Entity> or Unhide<Entity> (available only for the Reference Data domain entities)

2.1.4 How to Create a Functional Block Package


After defining the artifacts required for a Functional Block and implementing the relative business logic, it is
necessary to perform some final steps in order to create a Functional Block package, which can then be used to
develop a manufacturing use case.

Workflow
1. Add Third-Party Files to the Functional Block Installer Project, if needed.
2. Compile the database initialization file (Dbinit.xml) if you want to initialize the database with default values.
3. Manage the Application Log file, if you need to provide any application log messages.
4. Generate reference documentation, if required.
5. Define the build order (recommended).
6. Add automatic update function for referenced Functional Blocks, if required.
7. Generate the Functional Block package

332 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.4.1 Adding Third-Party Files to the Functional Block Installer Project


You can include third-party files, such as configuration files, XML or DLL, required by your Functional Block to the
Functional Block package zip.
This procedure should not be used for files already present on the target machine or for files that have their own
set-up. In this case the files should be installed directly on the target machine.

Limitations
• Subfolders are not supported
• There must not be two files with the same name.

Procedure
1. From the Installer project, right-click the ExternalDependenices folder and select Add > ExistingFile.
2. Browse to the files you want to include in the Functional Block package and click OK.

Result
These files will be included in the External Dependencies folder of the Functional Block package zip.

2.1.4.2 Compiling the Database Initialization File


You can populate the Dbinit.xml file to initialize the database before you release the Functional Block package.
If you want to provide basic information when you create the Opcenter EX FN database, such as units of measure,
lifecycles, status transitions, you can compile the Dbinit.xml file and manually enter the default data that the
system will use to initialize the Opcenter EX FN database. The procedure for doing this is described in this page.
The first time you create your model project, an empty file is provided in the Installer project. You can manually
populate this file with an .xml representation of your data model and type in the related default values. To facilitate
this task, Project Studio provides you with a tool, which automatically generates the .xml template corresponding
to the data model defined both inside the current model project and inside the referenced Functional Blocks. You
must then manually copy the elements you need and type the required values. When you use the tool to create
the .xml template, the system does not directly overwrite the Dbinit.xml file but displays the template inside a
temporary file.
If you do not need to insert any information, leave the file empty.

 Both if you are in a Functional Block and if you are in App, the tool generates an .xml representation of the
data model present in your model project and in the referenced Functional Blocks.

 To initialize the Automation App data, you cannot use the dbinit.xml file because it does not perform data
checks but you must follow the configuration workflow documented at How to Manage Automation
Nodes in the Opcenter Execution Foundation User Manual

Prerequisites
• The model project has been compiled and any required referenced Functional Blocks have been included.
• The entity types you want to initialize with default values must contain a logical key, otherwise they cannot be
imported inside the initialization file.
• You have used Reference Manager to manage relationships between Functional Blocks. If you have manually
added references to other Functional Blocks, the template will not be generated.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 333


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Compiling the initialization file


1. From the Solution Explorer in Project Studio, open the Installer Project.
2. In the Config folder, right-click the Dbinit.xml file and select the Generate DBInit schema command: the
generated .xml template file contains a sample entity element for each entity type. In this way, you do not have
to write the .xml file from scratch.
3. Copy and paste the elements for the entity types you want to initialize from the template to the Dbinit.xml file,
and then type in the property values.
4. Save changes.

Updating the model project and reimporting the initialization file

 You cannot update an entity instance whose logical key has the same value in the database as the one you
are specifying in the initialization file.

1. Apply the required changes to the model project.


2. Compile the model project.
3. From the Solution Explorer in Project Studio, open the Installer Project.
4. Right-click the Dbinit.xml file project and select the Generate DBInit schema command. A new representation
of the modified data models is displayed inside the temporary .xml template.
5. Copy and paste the elements for the entity types you want to initialize from the template to the Dbinit.xml file,
and type in the property values.
6. Save changes.

 Integrity check and validation errors


During package creation, the system executes a validation task. If errors occur, the package is not created
and error details are shown in the build details pane. This check does not involve any runtime checks on
the database. It is only a formal check if the file is well formed (if entity names, entity types and related
entities are correctly compiled). Runtime checks will be executed during database update operations.
As there is no validation schema for the Dbinit.xml file, low level Information messages may be
generated when you open the file in Project Studio. However, this does not imply that the file is invalid.
You should not initialize the same entity in different Functional Blocks or App with different values
because the system cannot assign any priority to the different initialization layers. This means that it
cannot guarantee that the actually required value will be inserted.
If you manually add entities that do not have any logical key, the records will be always appended to the
database at each update operation.

Initialization file description: elements and attributes


Element Name & Element Attributes Inner elements
Description

Sections None This element can contain


multiple Section elements
Root element. Used to
(note the missing s for plural).
contain the sections.

334 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Element Name & Element Attributes Inner elements


Description

Section • engineeringLevel, which describes the It can contain multiple Entity


abstraction level of the data model. elements.
Used to describe entities
• implementationName, which is a
belonging to a certain
custom-defined label used to identify
domain.
the specific implementation/version.
• domainName, attribute, which
specifies the name of the domain to
which the entities that are contained in
the section belong.

Entity type, which describes the type of the entity It can contain multiple
(corresponding to the Fullname displayed Property elements.
Used to describe an entity.
in the Properties pane of the entity in
Project Studio).

Property • name, which describes the name of the • If the described property
property. specifies a reference to a
Used to describe a property
• kind, which specifies if the property is a parent (i.e. the kind is
of an entity.
plain property, a value type property SingleReferenceToParent)
or a reference property (see notes) the element has one inner
• value, which contains the value of the LogicalKey element
property if the property defined for indicating the referenced
kind is plain. The value representation parent entity.
follows the C# • If the described property
System.Globalization.CultureInfo.Invari specifies a many-to-many
antCulture format, except for Guid relationship (i.e. the kind is
values, which are represented in the ManyToManyReference)
following example format: the element contains
"0b0e9810-096f-4864- multiple LogicalKey
b8e0-0dca91f6ff0f". If the property is elements indicating the
enumeration type the value to be linked entities.
specified must be the enumerator • If the described
name and not its numerical value. If the property specifies a
property defined for kind is not plain, value type (i.e. the
this attribute is not present. kind is Complex),
the element should
contain the inner
properties of the
value type, which
can be either Plain
or
SingleReferenceTo
Parent.

LogicalKey entityType, which specifies the type of the It contains a Property element
Specifies the key used to link linked entity. for each property that is part of
an entity to a referenced the logical key of the referenced
entity. entity.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 335


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Notes
• The kind attribute can assume the following
values: Plain, SingleReferenceToParent, ManyToManyReference, Complex.
• Relationships among entities are always specified by the forward navigation property.
• You cannot add part entities to a composite entity when it is Frozen, Locked or Marked for Cleaning.
• Null values are indicated by specifying the NULL reserved string (upper case).
• The LogicalKey elements can be nested if the logical key of an entity type includes a navigation property.
• Blob and FileType property types cannot be initialized and should not be present in the .xml.

336 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Example of dbinit.xml file

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


<Sections>
<Section engineeringLevel="LibraryFunctionalBlock" implementationName="MyTestImplem
entation_v1" domainName="ReferenceData">
<Entity type="MyCompany.DataModel.MyTestEntity1">
<Property name="StringProperty" kind="Plain" value="A" />
<Property name="BoolProperty" kind="Plain" value="true" />
<Property name="DateTimeProperty" kind="Plain" value="12/31/2015 23:59:59
+02:00" />
<Property name="GuidProperty" kind="Plain" value="0b0e9810-096f-4864-
b8e0-0dca91f6ff0f" />
<Property name="BigintProperty" kind="Plain" value="-9223372036854775808 " />
<Property name="IntProperty" kind="Plain" value="-100000" />
<Property name="SmallintProperty" kind="Plain" value="-32767" />
<Property name="TinyintProperty" kind="Plain" value="255" />
<Property name="DecimalProperty" kind="Plain" value="1.234" />
<Property name="TimeSpanProperty" kind="Plain" value="01:02:03" />
<Property name="MyNullableProperty" kind="Plain" value="NULL" />
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity2">
<Property name="MyProp1" kind="Plain" value="NULL" />
<Property name="ParentProp" kind="SingleReferenceToParent">
<LogicalKey entityType="MyCompany.DataModel.MyTestEntity3">
<Property name="Name" kind="Plain" value="TestName" />
<Property name="Version" kind="Plain" value="1" />
</LogicalKey>
</Property>
<Property name="MyValueTypeProp" kind="Complex">
<Property name="Ref" kind="SingleReferenceToParent">
<LogicalKey entityType="MyCompany.DataModel.MyTestEntity4">
<Property name="A" kind="Plain" value="NULL" />
</LogicalKey>
</Property>
</Property>
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity3">
<Property name="Name" kind="Plain" value="TestName" />
<Property name="Version" kind="Plain" value="1" />
<Property name="MyProp1" kind="Plain" value="qwerty" />
<Property name="MyValueTypeProp" kind="Complex">
<Property name="A" kind="Plain" value="zxcv" />
<Property name="B" kind="Plain" value="NULL" />
</Property>
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity4">
<Property name="Name" kind="Plain" value="A" />
<Property name="MyProp1" kind="Plain" value="qwerty" />
<Property name="Z" kind="ManyToManyReference">
<LogicalKey entityType="MyTestEntity5">

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 337


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

<Property name="Name" kind="Plain" value="a" />


</LogicalKey>
<LogicalKey entityType="MyTestEntity5">
<Property name="Name" kind="Plain" value="b" />
</LogicalKey>
</Property>
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity5">
<Property name="Name" kind="Plain" value="A" />
</Entity>
</Section>
</Sections>

2.1.4.3 Compiling Application Log Message Files


The Application Log file is an xml file that allows you to define the application messages for a Functional Block /
App / Extension App. You can have an Application Log xml file for each Functional Block / App / Extension App.
If you are creating a new Functional Block, an empty xml file is automatically created under the Installer project.
But if you are modifying an existing Functional Block, you must manually add the xml file to the Installer project.
Then you can open this file in Project Studio and define the application log messages.

 In both cases, the default language of the xml file is English and the file name must be in the
format <prefix>.<functional block / app / extension app name>.ApplicationLog.en-US.xml.
You must not modify this file name pattern.

The system manages all the xml files and stores the catalog of messages in the database. By means of the
Application Log App, installed in Solution Studio, you can log the defined messages and view them in your UI
Application at runtime.
This section describes the structure of the xml file and its restrictions.

Application Log xml File Structure

338 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

File Structure

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


<messages>
<message>
<id></id>
<short></short>
<long></long>
<level></level>
<params>
<param>
<key></key>
<type></type>
</param>
</params>
</message>
</messages>

The table describes the message attributes:

Attribute Name Description

ID A unique identifier for the message.

ID is a mandatory attribute.

Short A short and understandable description of the message.

Long A long description of the message that provides further verbosity


than a short message.

Level The type of message. The system accepts only Critical, Error,
Warning, Informational or Verbose value.

Level is a mandatory attribute. Any value other than the


mentioned will result in error.

Parameter Key The primary key that stores the name of the parameter that repeats
multiple times for a message.

Parameter Type The type of the parameter that repeats multiple times for a message.
Example values for the Application Log File:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 339


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

Id Short Message Advanced Message Level

-00001 Unable to start the operation Unable to start the operation Error
%op_name% because the work order
%wo_name% is on hold.

-00001 Unable to start the operation Unable to start the operation %op_id% Error
because the work order %wo_id% is on
hold and material lot %m_lot% is mark
to be cleaned.
The Application Log xml file requires certain restrictions that you must respect to avoid any errors during the
database update in Solution Studio:

 XML File Restrictions


• The name and structure of xml file are system defined and must not be modified.
• Every message must have a Message ID and Level, as they are mandatory fields.
• A message ID must be Numeric only and should not be repeated within the same xml file.
• The Level defined for a message must be either Critical/Error/Warning/Informational/Verbose.
• The Length of Short message must be less than 100 characters and the length of Long message must
be less than 400 characters.
• The Length of parameter key must be less than 512 characters.
• The possible values for parameter type
are string, byte, int, decimal, float, double, long, boolean, Guid and Datetime.
• If you delete a message for which a translation was provided and is already available in the deployed
solution, you must also delete the corresponding localized message from the resource package.
See Localizing Application Log Messages on how to manage a Localization resource package.

Manually Adding xml File


1. In Project Studio select the Functional Block/App/Extension App and open the solution.
2. Expand the Installer project, right-click Config folder and select Add > New Item.
3. Select Application Log class and click Add. This will add a new xml file to the Installer project that gets the
system-defined name and structure.

 Do not modify the file name, even though the system allows you to. If you rename, the system does not
take into account the custom name and returns an error while building the Installer project.

4. Build the Installer project to package the new xml file.

 For the whole configuration procedure, see How To Manage Application Logs.

2.1.4.4 Generating the Reference Documentation of a Functional Block


In Project Studio whenever you create a new element, such as a new entity, or a new argument for a command, you
can provide a multi-line description using mark up.
If you have provided information from which documentation can be generated, for example descriptions of
artifacts, when your project is compiled a file is generated with these descriptions, and is saved in the Functional
Block zip.

340 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

This udoc file can then be imported into the Documentation Center via the Documentation Center Administrator
Tool consequently providing reference documentation for each Functional Block.

 Output files should be always generated by default when compiling the project.

Elements you can document


You can provide descriptions all the artifacts you model in Project Studio:
• Entities and their properties
• Facets and their properties
• Commands and their parameters
• Events and their parameters
• Value types and their properties
• Parameter types and their properties
• Type aliases
• Enumeration types and their enumerators.

 Sensitive data
• Access to the documentation service layer is anonymous. Consequently the documentation center
store must not include sensitive data. If this is strictly necessary, suitable security measures must be
implemented (e.g. restrict access to the network where the documentation service layer is deployed).
• HTTPS communication is recommended.

Inserting comments
1. In Project Studio, in the Object Model (or Public Object Model for Apps), double-click the artifact for which you
want to enter comments.
2. In the Model Details pane, in the General tab, type the required description in the Description edit box.

3. In the Properties window, enter the required descriptions for each artifact parameter or property.

Generating output files

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 341


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

The custom documentation .udoc file should be generated by default when you compile your project. If this does
not happen perform the following steps to check your configuration options, which are valid both for Functional
Blocks, Apps or Extension Apps:
1. In Solution Explorer right-click the Model project (or POMModel project) and select the Properties command.
2. Click the Compiler tab.
3. Make sure the Enable Documentation Compiler check box is enabled.
4. If you want to optimize the compilation process, select the Enable Parallel Compiler check box.
5. Build the Model project.
6. Check that the <Prefix>.<DomainName>.<FunctionalBlockName>.<DomainAcronym>.Model.udoc file (or
<Prefix>.<DomainName>.<AppName>.<Acronym>.POMModel.udoc) is saved under the
currently configured output folder (by default, the bin folder) of the Model (or POMModel) project. If you are
compiling the Installer project, the file will be placed under the output folder which is currently set for the
solution configuration you are using (e.g. bin\Debug or bin\Release or any other output folder).

2.1.4.5 Defining the Build Order of a Functional Block


The build order in which projects are built within a solution in Project Studio is important to ensure errors do not
occur, for example, the model project should be compiled before the command handler project.
The alternative procedure provides a more complex solution, used in previous versions of Visual Studio, but still
valid if preferred.

Procedure
1. In the Solution Explorer pane, right-click your Command Handler project and select Build
Dependencies > Project Dependencies.
2. Click on the Dependencies tab.
3. Select your Command Handler project from the Projects drop down list.
4. In the Depends on pane select your model project and click OK.
5. Select your Event Handler project from the Projects drop down list.
6. In the Depends on pane select your model project and click OK.

 If build errors persist when building from the command line, open .sln file from the solution folder, and
make sure the model project (.umproj) is the first project in the list.

Alternative Procedure
To set the build order perform the following procedure, first for the command handler project, then for the event
handler and then for the installer project:
1. Create a reference to the model project from the command handler project by right-clicking
the CommandHandler project node in Solution Explorer and clicking Add > Reference.
2. In the Reference Manager window (of Visual Studio) select Projects > Solution in the left hand pane, select the
model project and click OK.
3. Right-click the CommandHandler project and select Build.
4. Right-click the CommandHandler project node in Solution Explorer and select Open Folder in File Explorer.
5. Open the file <FunctionalBlockName>.CommandHandler.csproj with a text editor.
6. In the <ProjectReference> node including the model project reference you have added at step 2,
type <ReferenceOutputAssembly>false</ReferenceOutputAssembly>.

342 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

<ProjectReference Include-".. \FBLibraryxxx.MSModel\FBLibraryxxx.MSModel.umproj.>


<Project>{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}</Project>
<Name>FBLibraryxxx.MSModel</Name>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>

7. Click Save.
8. Repeat the whole procedure for the Event handler project and then for the Installer project, according to the
following:
Source Project Referenced Project

Command Handler Model Project

Event Handler Model Project

Installer Model Project


Command Handler
Event Handler

2.1.4.6 Automatically Updating Referenced Functional Blocks


You can automatically update referenced Functional Blocks every time you build your solution using the
RestoreSimaticITUAFPackage target, which is found in Siemens.SimaticIt.ReferenceManager.targets.

Prerequisites
The build order must have been defined.

Procedure
The RestoreSimaticITUAFPackage target can be added to your solution as follows:
1. Right-click the model project node in Solution Explorer and select Open Folder in File Explorer.
2. Open the file <FunctionalBlockName>_<Acronym>Model.umproj with a text editor.
3. At the end of the file add the following nodes:

<Import Project="$(SITUnifiedVSToolingPlatformBin)
\Siemens.SimaticIt.ReferenceManager.targets" />

<Target Name="BeforeBuild">
<CallTarget Targets="RestoreSimaticITUAFPackage"/>
</Target>

4. Click File > Save.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 343


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

2.1.4.7 Generating a Functional Block Package


To deploy and use the Functional Block functionalities, you must generate the Functional Block output package.
The package will then be ready to be referenced either by another Functional Block or by an App in order to be
deployed in the Manufacturing Solution.

Prerequisites
• If the Functional Block contains the definition of commands or events, you must also have imported the related
command or event C# classes (these classes must not necessarily contain implemented code, but they must be
present in the Functional Block).
• If you want to enter default values for the initialization of the Opcenter EX FN database, the Dbinit.xml file has
been compiled.
• If you want to add/edit the application log messages for the Functional Block, Application Log file has been
managed.
• If you want to use the Copy to Engineering Target Folder (see explanation below), the user that is currently
running MS Visual Studio must have write permissions on the target folder (either the user himself or by means
of a dedicated Windows group).

 If your Functional Block contains references to other Functional Blocks, Reference Manager will ensure
that this Functional Block will also be included in the Functional Block Package. However, if you added a
reference manually, without using Reference Manager, you must have
modified the <Prefix>.<FunctionalBlockName>.References.xml file contained in the Installer
project > Config folder.

Procedure
1. Right-click the Installer project and select Properties.
2. Select the Copy to Engineering Target Folder check box to automatically copy the generated zip file to the
Engineering target folder (%ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks).
3. Build the Installer Project in either of the following ways:
• by building the entire Solution
• by building the Installer project.

 The output files are saved by default in the bin\Debug folder of the Installer project (for example,
MyFBLibrary\MyFBLibrary.Installer\bin\Debug). You can define the location of the project as
its Location when you create the solution in MS Visual Studio.
If you do not select the Copy to Engineering Target folder check box, you must manually copy the
generated output zip file to the Engineering target folder.

Details on the Functional Block package


The system assigns by default the name <Prefix>.<FunctionalBlockName>V<FunctionalBlockVersion>.zip to the
Functional Block output package.
The package has a fixed folder structure:
• config folder, with the configuration and log files
• ExternalDependencies folder, with the files required by third-party
• handlers folder, with the dlls produced by command and event handler projects
• model folder:

344 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop a Functional Block for a Manufacturing Functionality

• bin, .dlls for entities, types and the definition of commands, post-actions, pre-checks and events
• manifacturingmodel, with the .um and .umd files
• manifest.xml, which includes:
• the metadata created in the Functional Block (relative to the model and the business logic)
• any referenced library Functional Blocks.
• udoc file, present if custom documentation has been generated from descriptions provided in the Functional
Block.

Model project assemblies


The package contains the following model assemblies:

Assembly name Description

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the commands, post-


Acronym>Model.Commands.dll actions and pre-checks.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the private commands.


Acronym>Model.Commands.Internal.dll

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definition of the entity interfaces that


Acronym>Model.dll are required to execute writing and transactional
reading operations.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the events (required for


Acronym>Model.Events.dll example, if you are working on referenced events
inside custom event handlers).

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the classes where the committed event


Acronym>Model.PlainModel.dll JSON can be deserialized.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definition of the entity interfaces that


Acronym>Model.ProjectionModel.dll are required to execute read operations on the
reading model using the ProjectionQuery method.

<Prefix>.<DomainName>.<FunctionalBlockName>< It is for internal use only.


Acronym>Model.ReadingModel.dll

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definitions of the types (value types,


Acronym>Model.Types.dll type aliases, enumeration types) that are required to
execute writing and transactional reading
operations, and of the types (parameter types,
enumeration types) that are required to handle the
events, commands and reading functions.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the classes of the types where the


Acronym>Model.Types.PlainModel.dll committed event JSON can be deserialized.

<Prefix>.<DomainName>.<FunctionalBlockName>< It contains the definition of the type interfaces that


Acronym>Model.Types.ProjectionModel.dll are required to execute read operations on the
reading model using the ProjectionQuery method.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 345


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Assembly name Description

<Prefix>.<DomainName>.<FunctionalBlockName>< It is a deprecated model maintained only for


Acronym>Model.Types.ReadingModel.dll compatibility. It contains the definition of the type
classes that are required to execute read operations
on the reading model using the ProjectionQuery
method.

2.2 How to Develop an App for a Manufacturing Use Case


An App represents a manufacturing use case, which includes the artifacts of several Functional Blocks, each of
which represents a basic manufacturing functionality, and the entities imported from multiple data sources (SQL or
Oracle) through a set of views.
The App contains a public reading model, called the Public Object Model, which defines the artifacts that will be
available from the Service Layer.
The App contains user interfaces.

Workflow
The App is developed in four main steps:
1. Create the App.
2. Model the Public Object Model (POM) and define the Data Model
3. Implement the business logic.
4. Develop the user interface.
5. Create the App package to be loaded in Solution Studio.

2.2.1 How to Create an App


The creation of an App is the first step in the development of a manufacturing use case.
The App is an empty structure, which can be populated with artifacts from referenced existing Functional Blocks or
from SQL or Oracle views (once you have deployed the App).

346 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Selected artifacts are then imported into the Public Object Model, which will be exposed on the Service Layer.

Workflow
The creation phase involves the following steps:
1. Create a new App.
2. Create references to existing Functional Blocks.
3. (Optional) Import entities from an external data source, such as SQL or Oracle.

2.2.1.1 Creating a New App


Apps are developed in the same way as basic Functional Blocks.
The only difference is that they always belong to the Public Object Model domain, for which you can only specify an
acronym in the Wizard, and an additional project is provided for the creation of a user interface.

Procedure
1. In Project Studio select the File > New > Project command.
2. In the left pane, click Installed and then expand the Simatic IT node.
3. Select FunctionalBlock.App.
4. Enter a name for the App, which will then be used in the solution. The name can contain only alphanumeric
characters (20 characters maximum), and it cannot be modified once inserted.

 The name of the App must not be identical to the name of any referenced Functional Blocks or artifact
types (e.g. "event", "commands" etc) and must not contain C# reserved keywords.

5. Enter the location where the App will be created. The location name cannot contain the following special
characters: < (less than), > (greater than), : (colon), " (double quote), / (forward slash), \ (backslash), | (vertical
bar or pipe), ? (question mark), * (asterisk), & (ampersand), # (hashtag), % (percentage), , (comma).
6. Click OK: the creation process is simplified by an integrated wizard which guides you through the necessary
steps.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 347


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

7. Click Next.

8. Enter a prefix for the App (see constraints below). The prefix is then appended to the App name in order to easily
identify it within the development and configuration process.

 Prefix naming constraints


• The prefix cannot start with a number.
• The prefix cannot contain:
• special characters (< (less than), > (greater than), : (colon), " (double quote), / (forward
slash), \ (backslash), | (vertical bar or pipe), ? (question mark), * (asterisk), ! (exclamation
mark)
• underscore (_) or hyphens (-)
• C# keywords
• accented characters (for example à, ò, é, ù and so on)
• dots (.) as the first or last characters
• commas
• spaces
• non-latin characters (for example, 新浪网 or ‫)ﻣﺆﺳﺴﺔ‬.

9. Modify the App version if the default value (01.00.00) does not correspond to your requirements.
10. Insert a description providing other users with additional and exhaustive information on the functionality
provided by the App.
Note During the modeling phase, it will be possible to modify the description of the App at any time, right-
clicking the Installer project and selecting the Properties command.
11. Enter a two digit acronym for the Public Object Model (POM) which must be different from the acronyms
assigned to the standard domains (i.e. not RF, OP, MS). The acronym must not start with a number.
12. Click Next.
13. Select which elements (called projects in the Solution Explorer in Project Studio) your App will contain:
• Public Object Model (POM) Project (always selected by default) which contains the public reading data
model.
• Reading Function Project: from which you can implement the query expression for reading functions.
• Command Handler Project: from which you can implement the business logic for composite
commands.

348 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Event Handler Project: from which you can implement the business logic for referenced events.
• UI Project: from which you can develop a user interface for your App.
• Installer Project (always selected by default): where the files required to create the App package are
contained.

 Once you have created your App solution, you can subsequently remove or add projects from Visual
Studio.
Bear in mind that you cannot add any projects (such as Functional Block solutions) which are not
supported by the App wizard.

Result
If you have selected all available projects the structure displayed in the Solution Explorer pane is the following:

The <Prefix>_<Acronym>_<AppName>.dm file, which will contain the graphical representation of the data model
(in the Diagrams sub-folder), is created within the model project folder.

Additional operations

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 349


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• To remove a project, right-click it and then select the Remove command.


• To add a new project, right-click the App root, select the Add > New Project command, select
the Installed\Templates\Simatic IT node and then select the proper option. The following restrictions apply
when adding a new project:
• there can be only one POMModel Project
• there can be only one UserInterface Project
• there can be only one Installer Project
• it is not possible to add a Model Project to an App solution
• it is not possible to add an External Data Source Project to an App solution.
There can be several Reading Function Projects, Command Handler Projects, Event Handler Projects.

2.2.1.2 Creating a New Version of an App


Each Project Studio solution (Functional Block, App or Extension App) applies semantic versioning to indicate the
types of changes contained in a specific version. This helps other developers, whose code depends of the
Foundation solution, to understand modifications and adjust their own code, if necessary.
Each Solution has a specific version made up of three numbers, where each number represents the following:

When you create a new App its version is 01.00.00.


If you then modify this App after its deployment you must create a new version.
The type of version (Patch, Minor or Major) depends on the modifications you intend to make:

Version Types Add Element Remove Element Change Element Change Handlers

Patch

Minor

Major

Elements may be composite commands, signals, value types, type aliases, enumeration types and roles, and their
related arguments.
UI elements may be:
• UI Module definitions and metadata
• UI Screen definitions and metadata
• UI Component definitions, metadata, and public interfaces such as events and functions and their related
parameters.

350 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Elements that are already part of the model cannot be modified or deleted in Patch and Minor versions.

Patch
When you create a new patch no changes can be made to the model, manifest or public APIs.
A Patch version is basically intended for bug fixing. Only the business logic at C# level in the command and event
handlers and the UI source files can be modified.
All options that allow additions and changes to the data model will be disabled in Project Studio.
No constraints are applied to UI files in Project Studio, but you must not change the manifest or Public APIs to
ensure compatibility.

Minor Version
When you create a new minor version you can add elements:
• to your model, such as entities imported from external data source views, composite commands, parameter
types, enumeration types or roles, and related arguments;
• to your UI, such as UI Modules, UI Components, APIs, DPCs, events, functions and relative parameters.
You cannot delete or modify any elements present in the model in the previously released minor version.
None of the added elements can be set as mandatory, as this would break compatibility with the existing version.
All options that allow changes to and deletion of elements in the data model will be disabled in Project Studio. You
can however modify and delete elements that have been added in the minor version itself.
No constraints are applied to UI files in Project Studio, but you must not modify or delete elements that would
change the manifest or Public APIs to ensure compatibility.
A new minor version will reset the patch number to 00 (e.g. a new minor version 02 could be for example 01.02.00).

Major Version
A new Major version leaves you with complete freedom to delete and modify elements and destroy compatibility.
A new Major version will reset the patch and minor version numbers to 00 (e.g. a new major version 02 would be
02.00.00).

Procedure
1. Right-click the Installer project in the Solution Explorer pane and select Properties.
2. Click the Version Information button and enter the new version, noting that:
• If you enter a new Major version the Minor and Patch versions will be set to 00.
• If you enter a new Minor version the Patch version will be set to 00.

2.2.1.3 Referencing Functional Blocks from an App


You can populate the Public Object Model (POM) by referencing other Functional Blocks by using Reference
Manager.

Referenced and imported artifacts


You can automatically access all the referenced entities, types, events and protected commands of the Functional
Blocks from your App.
Events and types (e.g. parameter types, enumerations) are automatically imported in the Public Object Model
(POM), whilst you must select which entities and protected commands you want to import.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 351


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Referenced artifacts cannot be modified or deleted, however, a number of operations can be performed from the
Public Object Model on imported artifacts:
• Imported entities:
• Import and rename referenced entities
• Hide properties and relationships of imported entities
• Unpublish entities, removing them from the Public Object Model
• Create relationships from imported entities to referenced entities
• Imported protected commands:
• Import and rename a referenced protected command, consequently exposing them on the Service Layer.
• Unpublish protected commands, removing them from the Public Object Model

 Although events cannot be modified, you can create new handlers for referenced events.

Reference Manager
Functional Blocks should be always referenced with Reference Manager, because it automatically performs a series
of useful operations including:
• copying the selected Functional Block package in the Solution Folder of the current project;
• unzipping the folder of the referenced Functional Block and saving its files locally;
• adding the model assembly .dll files to the command and event handlers;
• ensuring that the referenced Functional Block is included in the Functional Block package.
Information on the referenced Functional Blocks is then saved in the packages.reference file:

packages.reference content
<functionalblocks>
<functionalblock>
<name>RefMan.FBLibRM</name>
<version>01.00.00</version>
<type>Library</type>
</functionalblock>
</functionalblocks>

 Although not recommended, you can alternatively manually manage solution references by using the
standard Visual Studio Add Reference command. This procedure has the following drawbacks:
• you will have to manually add the model assembly .dll files of the Functional Block to the command
and event handler project.
• you will have to add the details of the referenced Functional Block to the installer project so that it will
be included in the Functional Block package.
• Project Studio will not disable operations according to the type of version you are working on, with the
consequent risk of incompatibilities.

Available operations
The operations you can perform in Reference Manager depend on the current version of the Functional Block you
are working on.
For more information on versions see Creating a New Version of Functional Block or App.
The possible operations inside Reference Manager are:

352 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Install a Functional Block


• Update the version of a previously installed Functional Block
• Restore the files of a previously installed Functional Block

Version Add Reference/Install Remove Reference/ Update Restore Package


Uninstall

Patch

Minor

Major

2.2.1.3.1 Installing a Functional Block from an App


When you install a new Functional Block with Reference Manager you are creating a new reference to a Functional
Block.
This operation can be performed when you are working on a Minor or Major version.

Prerequisites and constraints


• The output zip file of the Functional Block you want to reference, created during the Functional Block
generation, must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
• The Functional Block packages must have been created in at least version 2.0 of SIMATIC IT UAF or migrated to
this version. If you try to install a Functional Block from a prior version an error message will be displayed.

 If two referenced Functional Blocks themselves reference the same Functional Block (i.e. A and B both
reference C) Reference Manager checks to see whether they reference the same version.
If they differ by patch or minor version the highest version is loaded.
For example:
• A references version 01.00.01 of Functional Block C
• B references version 01.00.02 of Functional Block C
Reference Manager will load version 01.00.02 as this should not cause compatibility issues.
If they differ by major version an error is returned and the operation will not be possible.

Procedure
1. In the Solution Explorer pane, double-click the packages.reference file in the Solution Items folder.
2. If enabled, click Restore packages, in order to be sure to correctly update all solution references.
3. Click on the Browse tab and select the Functional Block you want to reference. If it can be installed, its details
will be displayed in the pane on the right, otherwise an error message will be displayed.
4. Click Install. If the Functional Block contains references to other Functional Blocks, these will be displayed
under Dependencies and will automatically be installed if their .zip files are available in the folder, otherwise
you will receive an error message.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 353


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Result
• The packages you have installed will be displayed in the Installed tab and will have a green tick icon next to
them.
• According to the projects contained in the referenced Functional Block, the Solution Explorer tree view will
contain, under the References folder of each project, the .um, .umd and .dlls of the referenced projects. The
folder SimaticITPackages, if it does not already exist, will be created in the folder where your project files are
saved. A subfolder will be created for each referenced Functional Block, its name is comprised of the name and
version of the referenced Functional Block. The files contained in the .zip file are saved in this folder, with the
following structure:
• config folder, with the Dbinit.xml file for initializing the database
• handlers folder, with the command and event handlers
• model folder, with the data model files and assemblies
• ExternalDependencies folder, with third-party files required by the Functional Block you are referencing
• Manifest.xml file
• The .um file of the original Functional Block displays all the referenced artifacts in the Model Explorer.

Removing referenced Functional Blocks from your solution


You can remove references if you are working on a Major version.
If you are working on a Minor version you can remove references that you have created during the current version
itself.
1. Double-click the packages.reference file in the Solution Items folder of the Solution Explorer.
2. Click Restore packages, in order to be sure to correctly update all solution references.
3. Click on the Installed tab.
4. Select the Functional Block you want to remove and click Uninstall.

354 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.1.3.2 Updating a Functional Block from an App


The references you can update depend on the version you are working on:
• Patch version - you can update your reference to a new Patch version. For example, if you referenced version
01.00.00. of Functional Block x, and 01.00.01 is available in Reference manager you can update the reference.
You could not update to version 01.01.00 as this would imply a new minor version.
• Minor version - you can update your reference to a new Patch or Minor version. For example, if you referenced
version 01.00.00. of Functional Block x, and 01.01.00 is available in Reference manager you can update the
reference. You could not update to version 02.00.00 as this would imply a new major version.
• Major version - you can updates all references to any version.
You can also update your reference and keep the same version of the referenced Functional Block. For example, if
you add a dll in the package of your referenced Functional Block and update its reference, the reference section of
the Functional Block's handler project is automatically recalculated , i.e. the reference is added to the new dll.

Prerequisite
The output zip file of the original version we want to upgrade from, together with the zip of the new version we
want to upgrade to must be already present in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

 If a referenced Functional Block is missing in the file system repository (i.e. %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks), and the system prevents you from
building the solution, we suggest that you perform the procedure described in the
document Troubleshooting: How to fix a Project Studio Solution if a referenced Functional Block is missing
available on GTAC site. The article will help you to manually remove the missing references from the
project and be able to install or restore the packages you need.

Procedure
1. In the Solution Explorer pane, double-click the packages.reference file in the Solution Items folder.
2. Click Restore packages, in order to be sure to correctly update all solution references.
3. Click on the Installed tab and select the Functional Block you want to update. If it can be updated, its details
will be displayed in the pane on the right, otherwise an error message will be displayed.
4. Click Update. If the Functional Block contains references to other Functional Blocks, they will be automatically
installed if their .zip files are available in the folder, otherwise you will receive an error message.

 If two referenced Functional Blocks themselves reference the same Functional Block (i.e. A and B both
reference C) Reference Manager checks to see whether they reference the same version.
If they differ by patch or minor version the highest version is loaded.
For example:
• A references version 01.00.01 of Functional Block C
• B references version 01.00.02 of Functional Block C
Reference Manager will load version 01.00.02 as this should not cause compatibility issues.
If they differ by major version an error is returned and the operation will not be possible.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 355


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.1.3.3 Restoring a Functional Block from an App


If you need to replace the files of the same version of a previously referenced Functional Blocks you can restore your
reference.
This may be necessary if:
• you have accidentally deleted some of the files, or
• your solution configuration is under source control, and another user has created a reference to which you must
align your solution, or
• you are creating a new machine.
The Restore operation simply unzips the folder of the referenced Functional Block in the local folder without adding
references (e.g. .um, .dll files) and can be performed whether you are working in a Patch, Minor or Major version.
This procedure can also be performed automatically.

Prerequisites
The new output zip file of the Functional Block you want to restore, created during the Functional Block generation,
must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

 If a referenced Functional Block is missing in the file system repository (i.e. %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks), and the system prevents you from
building the solution, we suggest that you perform the procedure described in the
document Troubleshooting: How to fix a Project Studio Solution if a referenced Functional Block is missing
available on GTAC site. The article will help you to manually remove the missing references from the
project and be able to install or restore the packages you need.

Procedure
1. Double-click the packages.reference file in the Solution Items folder of the Solution Explorer.
2. Click Restore packages. If the zips of the referenced Functional Blocks have been saved in the correct folder the
referenced Functional Blocks will be restored on the user's machine, otherwise an error message will be
displayed.

2.2.1.4 Importing Views from Opcenter EX FN Databases


If you need to create views with complex relationships between artifacts you can create these relationships outside
of Project Studio, in the Opcenter EX FN database, and then import these views into your App using SQL or Oracle.
To perform this operation, you must expose source entities according to your needs, creating a set of views on top
of these data sources. For a procedure that describes how to create views, refer to the standard SQL Server or
Oracle documentation.
Once you have imported the view you must then decide which entities will effectively be included in the POM
reading model, which will then be consequently exposed on the Service Layer.

Workflow
To correctly import entities from external databases you must perform the following steps
1. Follow guidelines on how to create a view that will allow you to correctly import entities in your App.
2. Import views from the external database into your App.

356 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 During the deployment phase, the system automatically creates a set of views on top of the newly created
database. You cannot use these views to import entities into the POM, but only custom created views

2.2.1.4.1 Guidelines for Creating Views


Views imported into an App must respect certain conditions that are described in this page. This page does not
describe how to create views.

Prerequisites
• If you are creating views on SQL Server/Oracle database, all newly created views must be granted with reading
permissions through an appropriate script (in particular for the Project Studio user). This script must be run
after all views have been created. See Configuring a Third-Party MSSQL Database and Configuring a Third-Party
Oracle Database in the Opcenter Execution Foundation Installation Guide.
• You must have deployed your App and created an Opcenter EX FN database before importing complex views.
• Views must be custom views (created by the user) and not system views (i.e. views created by the deploy
operation).
• Views must be imported from Opcenter EX FN databases only.

General rules for fields


• Views must not contain fields ending with _id and fields containing dots "." (e.g. use "StatusId" instead of
"Status.StatusId").
• The view must contain (at least) the Id field (case insensitive) and the data returned by the view must guarantee
the uniqueness of the Id field. Its type can be Int, Guid, Bigint or String. The column property must be non-
NULL-able in SQL Server while it can be both non-NULL-able and NULL-able in Oracle. Note Sometimes you may
not realize that MSSQL Server/ Oracle treats your columns as NULL-able. For example, CAST (col1 AS
bigint) produces a NULL-able column. While ISNULL (CAST (col1 AS bigint), 1) produces a non-NULL-able
column. Bear in mind that at runtime you cannot have a NULL value in the Id field.

Third-party types
Views can contain only Opcenter Execution Foundation supported types and the conversion from third-party to
supported types is performed as follows:
Oracle

Oracle type Is Supported Project Studio System .NET Corresponding


Type Type

NUMBER(19) bigint System.Int64

NUMBER(1) bool System.Boolean

CHAR String System.String

Date Cast to TIMESTAMP(6) Datetime System.DateTimeOffse


WITH TIMEZONE t

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 357


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Oracle type Is Supported Project Studio System .NET Corresponding


Type Type

TIMESTAMP(6) WITH Datetime System.DateTimeOffse


TIMEZONE t

NUMBER(x, y) Decimal System.Decimal

Decimal types with Scale = 0


are not supported.

NUMBER Decimal System.Decimal

Considered as a number
(38,19)

BINARY_FLOAT Cast to NUMBER Decimal System.Decimal

NUMBER(10) Int System.Int32

NCHAR String System.String

NVARCHAR2 (CLOB in case String System.String


of length MAX)

NUMBER(5) Smallint System.Int16

NUMBER(3) Tinyint System.Byte

VARCHAR2 String System.String

RAW(16) Guid System.Guid

RAW (BLOB in case of Blob System.Byte


length MAX)
Data is imported according to C# type precision and not to Oracle type precision. For example NUMBER(10) accepts
a value between -2147483648 and 2147483647 instead of 10 digits
MSSQL

Microsoft SQL Server Is Supported Project Studio System .NET Corresponding Type
Type

bigint bigint System.Int64

bit bool System.Boolean

char String System.String

358 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Microsoft SQL Server Is Supported Project Studio System .NET Corresponding Type
Type

date Cast to Datetime System.DateTimeOffset


datetimeoffset

datetime Cast to Datetime System.DateTimeOffset


datetimeoffset

datetime2 Cast to Datetime System.DateTimeOffset


datetimeoffset

datetimeoffset Datetime System.DateTimeOffset

decimal Decimal System.Decimal

float Cast to decimal Decimal System.Decimal

int Int System.Int32

nchar String System.String

nvarchar String System.String

smallint Smallint System.Int16

tinyint Tinyint System.Byte

varchar String System.String

Uniqueidentifier Guid System.Guid

varbinary Blob System.Byte

 The person in charge of creating the views must know both the logic and the semantic of the source tables,
in order to correctly use the C# types while implementing the handlers that use as reading model the
corresponding entities. The TimeSpan C# type is not supported into the Public Object Model.

2.2.1.4.2 Connecting to Views


Prerequisites
The Opcenter EX FN database views must have been created following specific guidelines.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 359


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Limitations
• Views can be imported from different databases, as long as they belong to the same data source provider, but
these views must then be present on the same database which will be used when you deploy the project.
• Once you drag and drop or import a view from a particular data source provider (e.g. SQL) you cannot at that
point add views from other data source providers (e.g. Oracle).
• To switch data source provider you must delete all the entities from the previous provider in the model, and
then import new views from the new provider.

Procedure
1. Open the POMModel project within the App and then double-click the .um or .dm project file.
2. In the Model Explorer click the Public Object Model Configuration tab.
3. Right-click the required data source provider (either SQL or Oracle) and then select Add Oracle/MSSQL Server.
4. Set the following parameters:
Parameter Description

Server The name of the server. Only for MSSQL, click on the drop-down list box to automatically
Name populate it with the available servers.

Initial (Only for MSSQL) The database name.


Catalog

Schema (Only for Oracle) The schema name.

Authentica The authentication mode of the user. The available options are:
tion
• Windows Authentication: in this case the database connection is made using the
credentials of the interactive user who is running Visual Studio (and consequently
Project Studio) and who must also have the necessary grants to access the SQL/
Oracle views.
• (Only for MSSQL) Sql Authentication: in this case the database connection is
made using the credentials of the user who must have the necessary grants to
access the SQL views.
• (Only for Oracle) Oracle Authentication: in this case the database connection is
made using the credentials of the user who must have the necessary grants to
access the Oracle views.
For more information, see How To Configure Third-Party Databases in the Opcenter Execution
Foundation Installation Guide.

User Name (Only in case of database authentication) The name of the user who must have the necessary
grants to access the SQL/Oracle views.

Password (Only in case of database authentication) The password associated with the user who must
have the necessary grants to access the SQL/Oracle views.
5. Click Test Connection to make sure the data external source is viable.
6. Click OK.
7. Check if there is a green plug icon below the connection node which indicates you are correctly connected to
the data provider.
8. You can now import your required entities in the POM.

360 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Editing a connection
You can edit your database connection, as long as it uses the same data source provider, by right-clicking the
connection node in the External Data Source view and selecting Edit.
The system connects to the target repository and loads its views.
• If the name of a new database view corresponds to a previously imported entity, and differences are found, the
corresponding view is marked with an asterisk and an exclamation mark. The view can then be updated.
• Any views that were previously imported and that are not present in the new database connection will still be
displayed as artifacts in the central work pane, but a warning message will be displayed.

Refreshing a connection
If you know changes have been made to the MSSQL/Oracle database views, you can incorporate these changes into
your imported views by refreshing the connection.
This is simply done by right-clicking the connection node in the External Data Source view and selecting Refresh.
Any inconsistencies between the source database views and imported views will be marked by an asterisk and an
exclamation mark. At this point you can update the corresponding database views.

Changing provider
If you want to change provider you must first remove any views you imported from the initial provider.
Imported views can be deleted either by right-clicking any entities that have been dragged and dropped into the
central pane and selecting Delete, or by deleting the corresponding entities from the Object Model view.
You then add the new connector following the standard procedure.

2.2.2 How to Model the Public Object Model


When you have created your App and populated it with any required artifacts you can start modeling its Public
Object Model.
The Public Object Model (POM) is the public exposition of the App, which aggregates the models of referenced
Functional Blocks from different domains.
The models that shape the POM include the reading model and commands. You can choose to expose only selected
entities and commands, or the entire referenced models, in a secure and controlled way.
The events, parameter types, value types, enumeration types and type aliases of the Functional Blocks you
referenced from the App are always available in the POM.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 361


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Functionalities
The POM offers the following functionalities:
• Projection, whereby you can select which public entity properties you want to include in the POM.
• Aggregation, where you can define additional relationships between entities.

Workflow
1. Modeling entities.
2. Modeling parameter types.
3. Modeling enumeration types.
4. Modeling commands.
5. Modeling Pre-Checks (as described for the Functional Blocks).
6. Modeling Post-Actions (as described for the Functional Blocks).
7. Modeling signals.
8. Creating event handlers.
9. Configuring event subscriptions.
10. Building the Public Object Model project.

 You can manually:


• restore an erroneously deleted AssemblyInfo.cs file
• deprecate artifacts. Note that artifacts deprecated in the Functional Block are automatically set as
deprecated in the referenced App as well, where they are displayed as read-only.

362 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.2.1 Working in the Public Object Model project


To display the contents of your model double-click the .dm file in the POMModel project, the Model
Explorer pane displays the following tabs that allow you to access the Public Object Model pane and its
configuration environment (Public Object Model Configuration pane):

Public Object Model Configuration pane


From the Public Object Model Configuration pane you can select exactly which artifacts you want to include in the
POM and import them.
The pane includes:
• SQL/Oracle imported views from Opcenter EX FN databases.
• protected commands belonging to referenced Functional Blocks
• entities belonging to referenced Functional Blocks and imported views.
• events belonging to referenced Functional Blocks
Artifacts displayed in bold are those that have already been imported into the POM, and are consequently also
displayed in the Public Object Model tab.

Public Object Model pane

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 363


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

The Public Object Model pane contains a set of artifacts that are directly referenced from Functional Blocks (if any
have been referenced) and a set of artifacts that have been explicitly imported or created inside the Public Object
Model.
The tab contains the following nodes:
• Data Model node:
• entities (belonging to the referenced Functional Blocks) only if they have been imported from the Public
Object Model Configuration tab.
• Reading Functions node:
• newly created reading functions
• Commands node:
• public commands (belonging to the referenced Functional Blocks) only if they have been imported from
the Public Object Model Configuration tab.
• newly created composite commands
• Events node:
• all the events that either newly created in the Public Object Model or that belong to the referenced
Functional Blocks
• Types node:
• all the types that are either newly created in the Public Object Model or that belong to the referenced Functional
Blocks (value types, parameter types, type aliases and enumeration types)
• Roles node:
• newly created roles, that can be associated to entities, commands, events and signals.

364 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 All Apps contain a reference to an internal functional block, which exposes two events,
the CommittedEvent and the DebugStartupEvent, which are visible in the POM Project of your App as
referenced events.

Model Designer
The central model designer pane graphically displays the artifacts you have imported into the POM, along with
their corresponding relations and extensions, so you can easily see and check the relationships that exist between
different elements.
The graphical representation is saved as a DM file, which can be versioned in source control systems, but not
merged. A default DM file with the name of the App is created, which you can modify as required, but you cannot
rename or delete it.
You can also create additional model diagrams by right-clicking the Diagram folder in your model, selecting Add
New Item > Add New Diagram and providing a name for the new Model Diagram Class you will create. These
additional files will be saved in the Diagrams folder, together with the default DM file. They can be deleted but not
renamed.
Each DM model can display a different part of the data model, which may be particularly useful if the data model
contains many artifacts, or if you want to display only a particular part of the model. DM files are graphical
representations of the same underlying data model, so if, for example, you delete an artifact from the model it will
be removed from all the DM files where it was present. In this case each DM file will display the dirty asterisk in its
title bar, indicating that the file must be saved as the underlying model has changed.
Right-clicking in any empty area within the model designer pane allows you to perform a series of useful operations
involving the model artifacts, such as:
• adding new composite commands, parameter types, enumeration types, roles and reading functions,
• deleting artifacts,
• collapsing and expanding the view,
• exporting the view as an image,
• hiding specific artifacts,
• increasing/decreasing the size of the tiles (zooming in/out).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 365


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.2.2 Modeling Entities in the POM


In the App it is not possible to create new entities, but you can:
• import entities from referenced Functional Blocks or from views imported from Opcenter EX FN databases
• hide selected properties of entities and relationships between, so they are not imported into the POM
• create relationships between imported entities

Operations that can be performed on imported entities


Operation Type Allowed

Create relationships between entities

Write a description for an entity and for each single property of an entity

Delete an entity

Rename an entity

Assign tags to an entity

Modify the Securable attribute

Import only a subset of properties by hiding some properties

Chose whether to import related entities or not by hiding the relationship

Modify entity properties

Create a facet

Extend an entity

Create indexes

Workflow
• Import the entities you want to include in the Public Object Model
• Hide entity properties or relationships
• Create relationships between entities in the Public Object Model

2.2.2.2.1 Importing Entities into the POM


In the Public Object Model Configuration pane you can see all the entities imported from:
• referenced Functional Blocks
• Opcenter EX FN database views.

366 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

From this list you must decide which entities you want to import into your Public Object Model.

Constraints on importing operations


Project Studio allows you to import the entities you require, without needing to worry about any derived or
extended entities, or any relationships that may exist with other entities.
However, when you deploy the solution, if other entities are required, you will receive an error message which
informs you which entities you must import into your model to be able to continue.
The following constraints apply:
• If you import an extended entity or a facet its root parent entity is automatically imported too. If the parent
entity is also derived from another entity, the "grandfather" is also imported, and so on.
• If you import an entity that has been extended (physically or logically via facet), its child entities are not
imported automatically, and are not required to successively build your model.
• If the entity you import is part of a relationship, and its visibility has not been hidden, the following rules apply:
• In a OneToMany relationship you can import the One entity without importing the Many entity if
a Backward Navigation property has not been specified.
• In a OneToMany relationship, if you import the Many entity you will be required to import the One entity
when you build the solution.
• In a ManyToMany relationship you will always be required to import both entities in the
relationship when you build the solution.

Importing entities
1. In the tree list expand the SQL/Oracle or Functional Block node, select the entity you want to import and either:
• drag and drop the view into the central working area,
• right-click the required entity and select Import.
2. If you select an entity that has the same name as an entity that has already been imported into the Public Object
Model (but belonging to a different referenced Functional Block), an error message is displayed prompting you
to define an alternative name to uniquely identify it within the POM. You can subsequently modify the entity
name by right-clicking the entity in the Public Object Model pane and selecting Rename. Certain reserved
keywords should not be used in the entity name.

 You cannot change the system properties of referenced Functional Blocks (you can only change the
description).

Result
The imported entities are displayed in the Public Object Model tab, from where relationships can be created with
other entities and some basic modifications can be made.
You can also chose if you want to hide or publish all the entity properties and its related entities.

Deleting entities
To delete an entity, you must simply right-click and select Delete.
However, it may be necessary to enable the Delete On Cascade option in order to perform this operation:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 367


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Relationship Delete On Cascade required Notes

Extended Entity Delete On Cascade is applied


automatically when the base entity is
deleted.

Facet Delete On Cascade is applied


automatically when the base entity is
deleted.

Entity with extended child entities

The Many entity in a OneToMany


relationship

The Many entity in a OneToMany


relationship, with Backward
Navigation property specified

The One entity in a OneToMany


relationship

Entities in a ManyToMany
relationship

2.2.2.2.2 Hiding Entity Properties and Relationships


In the Public Object Model you can select to further specify the level of visibility of the entities you publish through
two main operations:
• hiding some of the properties of entities or facets, so they are not exposed on the service layer and will not be
included in any OData queries.
• hiding simple and composite relationships, so that you will not be obliged to import all the entities that are
linked to your entity through relationships in the POM.

Constraints and Propagation


Properties of entities and facets
• You cannot hide the properties of entities that have been imported in the App from the Opcenter EX FN
database.
Propagation:
• Signal visibility property is automatically updated with the source property visibility value.
• The visibility value set on base entity properties is propagated to the properties of derived entities.
• The visibility value set on derived entity properties is propagated to base entity properties.
Simple and composition relationships
• To perform an expand query both the navigation property and the related entity must be published.
• You cannot set the visibility behavior on the backward navigation property; the visibility behavior will be
automatically inherited from the corresponding forward navigation property.
• You cannot hide relationships that have been created in the POM.

368 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Procedure
1. Select the entity in the central working pane of the Public Object Model.
2. In the Model Details pane select one of the following:
• the entity property in the Properties tab.
• the simple relationship in the Relationships tab
• the composite relationship in the Composition tab.
3. Select Hidden as the Visibility option in the Properties pane of Visual Studio.

2.2.2.2.3 Creating Relationships between Entities in the POM


While modeling entities in the Public Object Model of an App, you can create relationships between entities in order
to enhance the reading model.
Relationships can be created between any entities, extended entities and facets that have been imported into the
Public Object Model.
Relationships that already exist between imported entities can be hidden in the POM, but they cannot otherwise be
modified.

Constraints
• Relationships are created between a property of the first entity and the ID of the second entity.
• Relationships can be created between properties of type Guid, Int, String, however, the data types used for the
relationship must be identical.
• The GUID is always used as an ID for entities from referenced Functional Blocks that belong to the Opcenter EX
FN data model domain (OP, RF, MS), so to create a relationship with these entities you must also select the GUID
of the first entity.
• The ID of entities that have been imported from Opcenter EX FN databases or user domain Functional Blocks
could be GUID, Int or String, so to create a relationship with these entities you must select a property that has
this same data type in the first entity.
• You cannot create a relationship from an entity that has been hidden and you cannot hide relationships that
have been created directly in the POM.

Procedure
1. Open the POMModel project and double-click the .um or .dm project file.
2. In the Public Object Model tab, select the entity whose property you want to use to create the relationship.
3. In the Model Designer pane, right-click the property (of type Guid, Int or String) that will be used for the
relationship, and select Create Relationship.

4. In the Parent Artifact Name edit box browse to the entity to which you want to create the relationship.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 369


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

5. Optionally insert in the Navigation Property edit box a name which will be included in the parent entity, so that
a list of child entities will be available from the parent entity.
6. Click OK: the relationship is displayed in the central pane and the property used to create the relationship is no
longer displayed in the list of properties.
7. To remove an relationship:

a. Click the tab in the Model Details pane.


b. Right-click the row corresponding to the relationship you want to delete.
c. Select Remove relationship.

Characteristics of relationship

The characteristics of the relationship, which are visible in the tab in the Model Details pane, cannot be
modified and are:

Characteristic Value

cardinality ManyToOne

deletion option OnDeleteNoAction

2.2.2.3 Modeling Parameter Types in the POM


After creating a reference from an App to a Functional Block, the system automatically populates the Public Object
Model tab of the POMModel project with all parameter types defined within the referenced Functional Block.
Parameter Types can be made up of one or more property types, and are used as arguments for composite
commands in the Public Object Model.
You cannot modify or delete referenced parameter types but you can create new parameter types to be used with
the referenced ones to implement business logic within the App.

Creating a new Parameter Type


Parameter types can be either created from scratch or as a copy of existing ones.
1. Right-click the Types node in the Public Object Model tab and select New Parameter Type.
2. Enter a name and description for the parameter type. The name can subsequently be modified using the
Rename operation. Certain reserved keywords should not be used in the parameter type name.

 The Description edit box supports markdown formatting, thus allowing you to correctly format the
information to be included in the reference documentation file.

Adding Properties to Parameter Types


Properties and property attributes are added to parameter types in the same way as they are added to entities
within a Functional Block. The properties of parameter types can also be made up of lists of properties, such as
strings, or types.
The following property types can be used for a parameter type:

370 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description

System Types Possible simple properties are: int, bigint, smallint, tinyint, decimal,
bool, datetime, Guid

Entity Properties You can use the type of an entity property (not the property itself) by
browsing to the entity object and then to one of its properties.

Lists Lists of:


• system properties
• parameter types
• entity properties

Using Parameter Types in Command Handlers


The model assembly of the DLL that contains the parameter types (*.Types.dll), required to use parameter types in
command handlers, will be automatically added to your command handler project after you have imported the
handler template. However, if required it can be added manually.

Deleting Parameter Types


If the parameter type has been used in a composite command, the Delete on Cascade option must be selected,
otherwise it will not be possible to delete the parameter type.

2.2.2.4 Modeling Enumeration Types in the POM


After creating a reference from an App to a Functional Block, the system automatically populates the Public Object
Model tab of the POMModel project with all enumeration types defined within the referenced Functional Block.
Enumeration types can be made up of one or more enumerators, and are used as arguments for composite
commands in the Public Object Model.
You cannot modify or delete the referenced enumeration types but you can create new enumeration types to be
used with the referenced ones to implement business logic within the App.

Creating a new enumeration type


Enumeration types can be either created from scratch or as a copy of existing ones.
1. Right-click the Types node in the Public Object Model tab and select New Enumeration Type.
2. Enter a name and description for the enumeration type. The name can subsequently be modified using
the Rename operation. Certain reserved keywords should not be used in the enumeration type name.

 The Description edit box supports markdown formatting, thus allowing you to correctly format the
information to be included in the reference documentation file.

3. You can now add enumerators to the enumeration types in the same way as properties are added to entities in a
Functional Block.

Using enumeration types in command handlers


The model assembly of the .dll that contains the enumeration types (*.Types.dll) will be automatically added to
your command handler project after you will have imported the handler template. However, if required it can be
added manually.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 371


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Deleting Enumeration Types


If the enumeration type has been used in a composite command, the Delete on Cascade option must be selected,
otherwise it will not be possible to delete it.

2.2.2.5 Modeling Commands in the POM


Modeling commands in the POM means performing different operations:
• Importing protected commands in the POM
• Creating composite commands in the POM

What are Composite and Public Commands


Being part of the POM means that these commands will be 'public' and thus available on the Service Layer.
In the Public Object Model (POM) you cannot create new simple (protected) commands: you can only create cross
domain composite commands.
Inside the handlers of the composite commands you can call either other composite commands or the protected/
published commands that belong to the Functional Blocks you have referenced.
While composite commands are directly created in the POM Model (and are contained in the
<Prefix>.<AppName>.<AppName>.<Acronym>POMModel.Commands namespace), referenced commands must be
imported in order to include them in the POM.
When you import a referenced command, you can either keep its original command name or assign a new name to
the command name.
For each command imported into the POM, you have two separate command classes: a class belonging to the App
(and contained in the <Prefix>.<AppName>.<AppName>.<Acronym>POMModel.Commands.Published namespace)
and a class belonging to the original Functional Block
(<Prefix>.<DomainName>.<FunctionalBlockName>.<Acronym>.Model.Commands>).
Consequently, from the code of Composite Command Handlers and from the code of Lean applications you will be
able to invoke public (imported) commands by using both these classes.
The <Prefix>.<AppName>.<AppName>.<Acronym>POMModel.Commands.Published namespace and the
<Prefix>.<AppName>.<AppName>.<Acronym>POMModel.Commands namespace are contained in the same App
output assembly (i.e.<Prefix>.<AppName>.<AppName>.<Acronym>POMModel.Commands.dll).

Pre-Checks
Pre-Checks can be used to implement conditions that determine the execution, or the non execution, of a
command.
When you import a referenced command, the related Pre-Checks are imported as well. Pre-Checks can be also
modeled and implemented inside the Apps. For more information, see Modeling Pre-Checks (as described for the
Functional Blocks).

Post-Actions
Post-Actions can be implemented to extend the business logic of Commands belonging to Functional Blocks (both
Referenced and not Referenced), as well as the business logic of Composite Commands belonging to Base Apps/
Extension Apps.
Post-Actions represent additional code that will be executed at the end of the Handler of the Command/Composite
Command.

372 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

When you import a referenced command, the related Post-Actions are imported as well. Post-Actions can be also
modeled and implemented inside the Base Apps/Extension Apps. For more information, see Modeling Post-Actions
(as described for the Functional Blocks).

2.2.2.5.1 Composite Commands


Opcenter Execution Foundation distinguishes between two types of commands: Simple Commands (Private and
Protected Commands) and Composite Commands.
While Simple Commands are modeled in Functional Block and their handlers can only invoke other commands that
belong to the same domain (be they of the same Functional Block or in a referenced Functional Block that belongs
to the same domain), Composite Commands are modeled in the App and their handlers can invoke commands that
belong to different domains.
Opcenter Execution Foundation organizes its data model in domains. Domains are autonomous components, with
their own data models and their own business logic. Each domain can be potentially deployed on a different
database. Thus transactions must be mono-domain and each chain of commands must be part of the same
transaction. Consequently, Simple Commands can only be used to invoke other private and protected
commands of the same domain because they must be part of the same transaction and cannot be used to
communicate cross-domain. Simple Commands are transactional while Composite Commands are not
transactional.
To exchange information across domains, you can use both Events and Composite Commands.
If you use events, a domain can respond to the events that are raised by another domain, but in a large system
scenario, where several domains are involved, communication based only on event subscriptions may not be
sufficient.
If you use Composite Commands, you can invoke Commands belonging to different domains. But since you use
Composite Commands to call logic cross-domain, you must remember that these Commands are not transactional
(see section below).

Command invocation rules


Composite Commands can be modeled only in an App. When you compile the model project, the project compiler
generates the handler classes, as for Simple Commands. You cannot declare a Composite Command as
private. After you have imported the handler in the command handler project, you can implement the handler class
with some limitations (for example, you can execute projection queries on the reading model entities of the POM
but you cannot perform writing operations).
The following table shows which command types can be invoked according to the code you are implementing:

Invoker (Invoked) Composite (Invoked) Protected (Invoked) Private


command command command

Composite
Command handler

Command handler (same Functional Block) (same Functional Block)

(different Functional (different Functional


Block belonging to the same Block belonging to the same
domain) domain)

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 373


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Invoker (Invoked) Composite (Invoked) Protected (Invoked) Private


command command command

Event handler (if associated to a (if imported into Public


Worker Role) Object Model and associated
to a Worker Role)

Code using (if associated to a (if imported into Public


IUnifiedSdkLean Worker Role) Object Model and associated
instances to a Worker Role)

Composite Command use case


A Composite Command could be implemented to trigger and aggregate logic residing in different systems.
Examples of use cases could be:
• to create an order in Opcenter Execution Foundation
• to schedule an order in an Advanced Planning System
• to send the order in execution to the line in a Machine Control system.
The related flow of the command invocations in the composite command handler could be outlined as follows:
1. Call command that creates an order.
2. Perform projection query that retrieves the created order.
3. Call command that schedules the order.
4. Perform projection query that retrieves the scheduled order with its new details.
5. Call command that sends the part program a numeric control machine for order execution.
6. Perform projection query that retrieves the execution details from the line.

Choosing between a Command and a Composite Command


In some situations you could use either a standard Command or a Composite Command to implement a use case.
Both options have their pros and cons.

374 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Let's assume you want to create many entities, for example orders, using an XML file and then implement business
logic that reads the entity details from the file and saves them in a database.
If you create a Composite Command, you can develop logic where:
• the input is an XML file as a blob type
• you identify the n entities that must be created
• you then pass each entity instance to the subcommands with an asynchronous call.
In this scenario the subcommands are called in parallel. Each subcommand opens and closes a single transaction
and if one subcommand fails it does not determine the failure of the other subcommands. The execution time of
this code is reduced because each transaction does not wait for the end of the other transactions. This scenario
would be appropriate when you must insert a large amount of data in a database and possible errors on single
entities are not a priority.
If you develop the same logic in a standard Command, all the submit operations are serialized within a unique
transaction. The execution time of this type of logic would be longer and the risk of generating an optimistic
concurrency error would also be higher.
Consequently, Composite Commands are much faster in terms of execution time, and thus they should be used
when you do not need to stop and rollback the entire call chain for a single error.

Composite Command transaction and error management


When a root (protected or private) command handler is executed, the system handles its operation chain within the
same transaction. Composite command handlers behave differently, as the composite commands themselves are
not transactional.
A transaction is opened when the composite command handler calls a protected command. This protected
command is the root command of a potential chain of sub-commands. From that point on, all the sub-commands in
the chain are part of the same transaction and must be modeled within the same domain. A composite command
can call several root commands. For all these commands the system opens the related transactions, which are
completely independent from each other.
This behavior affects the way you must handle errors in your composite commands. While for protected and private
command handlers the system executes a rollback if the transaction is not committed, for composite command
handlers the logic is different. If you have a composite command that invokes n root commands, and one of these
commands crashes, all the other root commands are committed, except for the crashed command. This means that
in the composite command handler code you must handle a possible partial failure of its calls by managing the
possible errors returned by the invoked root commands.
Retries for composite commands are not implemented.

Example
In the following example the composite command creates a Product Production Rule (PPR) and its logically linked
associated Product Segment (PS).
In order to carry out this operation two protected commands are invoked:
• one to create the PPR
• one to create the PS.
If the PS creation fails for any reason, the previously created PPR is deleted with an appropriate command.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 375


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

private CompositeCommandCreatePPR.Response
CompositeCommandCreatePPRHandler(CompositeCommandCreatePPR command)
{
string pprName = null;

try
{
// Creation of PPR
var result = Platform.CallCommand<CreatePPR, CreatePPR.Response>(new
CreatePPR()); // first transaction

if (result.Succeeded)
{
pprName = result.PPRName;
// Creation of PS associated to PPR
Platform.CallCommand<CreatePS, CreatePS.Response>(new
CreatePS(pprName)); // second transaction
}
}
catch (UnifiedException exception)
{
if(pprName != null )
{
Platform.CallCommand<DeletePPR, DeletePPR.Response>(new
DeletePPR(pprName));
}

throw;
}
}

2.2.2.5.2 Importing Protected Commands


After creating a reference to a Functional Block, all its protected commands can be automatically accessed from the
App.
In order to include these commands in the POM so that they are available on the Service Layer you must import
them, making them public with a unique public name (unique inside the POM).
After importing the Command, the Securable property cannot be changed.

 Copying Commands
Once you have imported a protected Command, if you copy it, the copied artifact will be a Composite
Command and not a public Command. This is required because inside the POM Model, only Composite
Commands that can be created from scratch.

Procedure
1. Open the POMModel project and then double-click the .um or .dm project file.
2. In the Public Object Model Configuration tab select the required commands and then do either of the
following:

376 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• drag and drop them to the central working area (multi-selection is allowed).
• right-click and then select Import.

 Naming conventions
If you select a command that has the same name as a command that has already been imported into the
Public Object Model (but belonging to a different referenced Functional Block), you are prompted
to define an alternative name to uniquely identify it within the POM.
In case of commands imported to Extension Apps, the name of the Extension App is automatically added
to the command name and cannot be removed.
For all commands, you can subsequently modify the command public name in the command properties.

2.2.2.5.3 Creating Composite Commands


In the App it is not possible to create new simple commands in addition to those imported from the referenced
Functional Blocks, but you can create composite commands which aggregate referenced protected commands.
Composite commands are always public because they are directly created inside the POM.

Procedure
Composite commands can be either created from scratch or as a copy of existing ones.
1. Right-click the Commands node in the Public Object Model tab and select New Composite Command.
2. Enter a name for the new command, which cannot be successively modified. Certain reserved keywords should
not be used in the composite command name.
3. Enter a description for the command. The Description edit box supports markdown formatting, thus allowing
you to correctly format the information to be included in the reference documentation file.
4. Clear Securable if you want to allow all authorized users to execute the composite command, instead of
assigning it to a role.
5. Click OK: the new composite command is displayed in the central Designer Model pane and in the Public
Object Model tab with a specific icon.
6. Right-click the name or the icon of the command in the central Designer Model pane and select either of the
following:
• Add new Input Parameter
• Add new Output Parameter.
7. In the Properties

tab of the Model Details pane enter a user-friendly name for the property.
8. Click on the browse button and select the property from the Property Browser, which can be either a System
Type property or a Parameter Type (both referenced and created within the App).
9. Click OK.
10. In the Properties pane enter the attributes for your selected parameters (see table below).
11. If necessary, in the General tab of the Model Details pane add tags to the command to facilitate search
operations (by clicking Add and either entering a new tag or selecting one from the list).
12. Build the POMModel project, by right-clicking it and selecting Build.

Command parameter annotations

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 377


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Optional Allow Empty Length Scale From - To Precision


String

String

Integer
(int, tinyint,
smallint, bigint)

DateTime

Guid

Bool

Decimal

ParameterType

TimeSpan

Blob

The Allow Empty String annotation (which accepts True or False) allows you to pass an empty string as parameter
value. It can only be used with String types and if Optional is set to False.

Adding logic to commands


When you have created the structure of a command with its input and output parameters, the related C# classes (i.
e. handlers) are automatically created for the commands when you build the project.
You can then import and complete these handlers in the implementation phase.

2.2.2.6 Modeling Reading Functions


Reading Functions allow you to perform complex queries that can be developed in order to retrieve, manipulate
and aggregate data.
Reading Functions have input and output parameters. The input parameters are used as filtering inputs of the
query. The output parameters describe the structure of the data to be returned. At least one output parameter must
be defined.
Reading Functions are by default defined as securable objects, meaning that you can limit their runtime execution
to specific users while configuring user roles (either at App level or at Solution level).
The logic of the queries is defined within the Reading Function handler, which can be imported from the model
template after building the model project (as for Commands and Events).

Creating Reading Functions


Reading Functions can be either created from scratch or copied from existing ones.

378 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1. Right-click the Reading Function node in the Public Object Model tree and select New Reading Function.
2. Enter a name for the new Reading Function. This name cannot successively be modified. Certain reserved
keywords should not be used in the role name.
3. (Optional) Enter a description for the Reading Function. The Description edit box supports markdown
formatting, thus allowing you to correctly format the information to be included in the reference
documentation file.
4. Clear Securable if you do not want to assign the Reading Function invocation to any roles.
5. Click OK: Reading Functions are displayed in the central Designer Model pane.
6. Add input and output parameters to the Reading Function.
7. If necessary, in the General tab of the Model Details pane add tags to the Reading Function to facilitate search
operations (by clicking Add and either entering a new tag or selecting one from the list).

Implementing the Reading Function Handler


When you have created the structure of a Reading Function with its parameters, the related C# classes (handlers)
are automatically generated when you build the Model project.
You can then import and complete these handlers in the implementation phase.

2.2.2.6.1 Adding Input and Output Parameters to the Reading Functions


After you have modeled a Reading Function, you can specify its input and the output parameters. The output
parameter is mandatory.

Adding parameters
1. Right-click the name or the icon of the artifact in the central Designer Model pane and select either Add new
Input Parameter or Add new Output Parameter.

2. In the Properties tab of the Model Details pane, enter a user-friendly name. Certain reserved keywords
should not be used in parameter names.
3. Click on the browse button and select the property from the Property Browser dialog box, which can belong to
three distinct categories:
• properties of other entities (from Data Model node),
• System Types: simple types, such as string, bool, int etc..,
• Types: Parameter Types, Type Aliases, Enumeration Types.

Configuring parameter attributes

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 379


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

You can define parameter attributes to set validation criteria or data dimension.
If you set validation attributes on output parameters, these attributes are used for data structure validation at the
end of the handler execution (see Implementing Command and Event Handlers or Importing and Implementing
Reading Function Handlers).
You can also assign a description to the parameters in this pane. The Description edit box supports markdown
formatting, thus allowing you to correctly format the information to be included in the reference documentation
file.
1. Select the parameter of your artifact in the Parameters tab of the Model Details pane.
2. In the Properties pane enter the attributes for your selected properties:

Option Allow MaxLen Scal From - IsList Precisio UseDefault


al Empty gth e To n IfNotSet
String

String

Integer
(int, tinyint,
smallint, bigint)

DateTime

Guid

Bool

Decimal

ParameterType

TimeSpan

Blob (only for


commands and
reading
functions)

EnumerationTy
pe

380 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 • The Reading Function output parameters for which the Optional attribute has been set to False, are
mandatory at runtime only if the Response does not contain an error code.
• If, for any artifact type, the MaxLength attribute for String and Blob types is not specified (i.e. empty
value) the maximum length possible for the type will be automatically applied (i.e. 2GB (-1 byte)),
regardless of whether your underlying system is x32 or x64. If specified, the value must be between 1,0
and 2GB (-1 byte).
• The Allow Emtpy String annotation (which accepts True or False) allows you to pass an empty string
as parameter value. It can only be used with String types and if Optional is set to False.

2.2.2.7 Modeling Signals in the POM


Signals are messages that inform web clients when an entity is modified or when a business event is fired.
Currently through Opcenter Execution Foundation you cannot subscribe web clients to any type of events. With
signals, you can retrieve information from custom business events or from system events, which are fired when
write operations are executed (CommittedEvents), and then update the web client pages, although these events are
not directly exposed on the web.
If a client is subscribed to a signal, when the event of interest occurs, the system sends a signal to the client and the
client page can be automatically refreshed with the incoming information. This simplifies the way you implement
the code of your UI pages because you do not need to send requests to check if certain events occurred: this
information will reach your client pages as a flow of information and the pages will be constantly updated as in a
real time display environment.
To configure the system so that signals can be sent, you must first promote certain artifacts to signals. This means
that you must define for which entity changes and for which events you want signals to be sent. This modeling
phase is executed inside the Public Object Model.
Then, in Solution Studio, you must give permission to the user (or user group) that will log in on the client
application, to subscribe to specific signals.
From the code of your UI application you must register to a specific Opcenter Execution Foundation service, and
subscribe to the signals you want to receive (here you can also apply filters on signal metadata to restrict the
signals you receive).

Signal configuration workflow


1. Publish an artifact as a signal.
2. Subscribe your client application to a signal.

2.2.2.7.1 Publishing Artifacts as Signals


You can model signals by promoting entities and events to signals. You cannot promote all entities or events. The
prerequisites section indicates these constraints. The signal that will be generated for the selected entity, or event,
will return a data structure which maps the information of the source artifact, except for parameter types contained
in parameter types, blobs and system properties (which will be automatically renamed).
A preview of this data structure is displayed in the Model Details pane (as for the entity properties).

Constraints

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 381


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Artifact Description

Entity In order to be published as a signal, an entity must have been imported into
POM and must be contained in a Functional Block defined in Reference
Data, Master Data, or Operational Data domains (i.e. user-defined domains
and Opcenter Execution Foundation internal views cannot be used).
Entities that have been imported via SQL/Oracle from Opcenter EX FN views
repositories cannot be published as signals.

Event In order to be published as a signal, an event must be present in the


POM as a referenced event from a Functional Block (Reference Data, Master
Data, Operational Data or user-defined domain). System events, such as
CommittedEvent or DebugStartEvent cannot be published as signals.

Procedure
1. In the Public Object Model tab, right-click the entity or the event for which you want to create a signal and
select New Signal.
Enter a name and description for the signal. The name can subsequently be modified using
the Rename operation. Certain reserved keywords should not be used in the signal name.

 The Description edit box supports markdown formatting, thus allowing you to correctly format the
information to be included in the reference documentation file.

2. Clear Securable if you want to make this signal visible to all authorized users, without assigning it to any
specific roles.

Renaming signal properties


The properties inherited from the source entity/events are displayed in the Model Details pane.
Apart from the property name and type, the following information is provided for each property:

382 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Source Description

IsNullable Defines whether the property can have a null value in the signal.
• Local entity properties can be null.
• System properties cannot be null.
• Mandatory event parameters cannot be null.

Source Defines whether the property was created in the entity/event (local) or is a
system property.
System properties are read-only, cannot be null and cannot be renamed.
If one of the properties corresponds to a signal system property, a prefix is
automatically added to the property name to render it unique
(e.g. <EntityName>_<PropertyName>).

Visibility Defines whether an entity property has been hidden in the POM or not.
• Signal properties based on entities inherit their visibility from the
underlying entity property.
• Signal properties based on events are always visible.
Hidden properties cannot be renamed.

To rename properties:
1. Select the signal in the Model Designer pane.
2. Select the property in the Model Details pane and enter a new name.

Signal output format in JSON


Each event or entity you have promoted to signal will be transformed into a signal once the App solution is
compiled.
A signal is represented by a JSON object which contains the properties of the source object (i.e. an entity or an
event). Simple type properties and complex type properties are directly accessible at the first structure level while
properties that are nested inside complex properties are returned with some constraints, for example, nested
parameter types are ignored (see Event transformation details table for details).

 Blob types are not returned.

The details of the data structure transformations are displayed in the following sections.
Event transformation details
The table below compares the parameters of the source event with the members of the signal. It also indicates how
the Mandatory property, which is used for validation criteria in the generated class of the event, is used in the
Signal.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 383


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Event parameter Signal member Example

Simple type property The same property is returned. • Event: e1 with


• Name (type
string),
• Description
(type string)
• Signal s1:
• Name (type
string)
• Description
(type string)

List of simple type properties The same properties are returned. • Event: e1 with
• Name (type
string),
• Groups (type
List Of strings)
• Signal s1:
• Name (type
string)
• Groups (type
List Of strings)

Parameter type containing simple Each simple type of the parameter • Event: e1 with
type properties type is returned. • Prop1 (type
pt1)
• Parameter Type: pt1,
with
• Name (type
string),
• Count (type int)
• Signal s1:
• Prop1 (type
pt1) with
• Name
(type
string)
• Count
(type
string)

384 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Event parameter Signal member Example

Parameter type containing The simple type of the parameter type • Parameter Type: pt1
parameter types is returned. with
• Name (type
The nested parameter types are string),
ignored. • Count (type int)
• Parameter Type: pt2
with
• Description
(type string),
• Param1 (type
pt1)
• Event: e1,
• with Prop1
(type pt2)
• Signal s1:
• Prop1 (type
pt2) with
• Descript
ion (type
string)

Parameter type with list of simple The simple type of the parameter type • Parameter Type: pt1
type properties is returned. with
• Groups (type
The nested list of simple types is List Of strings),
returned. • Count (type int)
• Event e1 with
• Prop1 (type
pt1)
• Signal s1:
• Prop1 (type
pt1) with
• Groups
(type List
Of
strings)
• Count
(type
string)

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 385


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Event parameter Signal member Example

Envelope parameters All envelope parameters are returned • Event: e1 with


at the same level as the event parameters. • Category as
envelope
All the returned members are non-NULL- parameter
able. • Signal s1:
• EnvelopeCateg
ory

 If you have named the event


arguments in the same way as
these envelope parameters, the
system will rename them
automatically.

Enumeration type The enumeration type is returned.

Entity transformation details (CommittedEvent parameters)


The information related to the entity involved in a transformation and the details of the executed operation are
retrieved from the parameters of the CommittedEvent, which is fired at the end of a transaction.
If the CommittedEvent contains multiple entities inserted by a Submit operation, the system generates one single
signal for each promoted entity contained in the CommittedEvent and ignores the others for which no promotion
has been modeled.
If the CommittedEvent involves a Bulk operation, the system generates one single signal for each promoted entity
without returning any property values for entities or relations parameters. This means that in your client page you
must refresh all the data.
The table below compares the properties of the source entity with the members of the signal. It also indicates how
the Mandatory property, which is used for validation criteria in the generated class of the entity, is used in the
Signal.

Entity property Signal member Example

System property: Entity Id (Guid) The Id system property is


returned.

The other entity system


properties are not returned.

386 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Entity property Signal member Example

Simple type property The same property is returned. • Entity: e1 with


• Name (type string)
• Description (type
string)
• Signal s1:
• Name (type string)
• Description (type
string)

Enumeration type The enumeration type is


returned.

Value Type containing simple types Value type simple properties • Value Type: vt1, with
are returned with the format • Name (type string),
expressed in the following example. • Count (type int)
• Entity: e1 with
• Prop1 (type vt1)
• Signal s1:
• Prop1 (type vt1) with
• Name (type
string)
• Count (type
int)

Value Type containing reference to The signal will contain only • Entity: e2 with
another entity those entity properties that have • Description (type
been explicitly mapped inside the string),
value type • Quantity (decimal)
• Value Type: vt1 with
An entity property which has • Name (type e2.Id)
been not included in the value type (corresponding to the
is not returned by the signal (e.g. entity in brackets in
Quantity in the example). the Property Browser
dialog box in Project
Studio),
• Description (type
e2.Description)
• Entity: e1, with
• Prop1 (type vt1)
• Signal s1 (referring to e1):
• Prop1 (type vt1) with
• Name (type
Guid)
• Description
(type string)

Blob property This property is not returned.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 387


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Entity property Signal member Example

Entity with relationships towards If the cardinality of an entity • Entity: Order with
other entities: one-to-many or involved in a One-To-Many • Description (type
many-to-many (see the screenshot relationship is Many (for example, string),
below with project model the Entry entity in the example), • Quantity (type
configuration example) and you have subscribed to this decimal)
entity, the signal returns the Id • Entity: Entry with
(Guid) of the related entity (Order, • Name (type string),
in the example). • Order navigation
property towards
Entry and Cardinality
Many-To-One
If the cardinality of an entity
• Signal for Entry:
involved in a One-To-Many
• Name (type string)
relationship is One (for example,
• Order_Id (type Guid)
the Order entity in the example),
• Signal for Order:
and you have subscribed to this
• Description (type
entity, the signal does not return
string)
the relationship towards the Many
• Quantity (type
relationship (Entry).
decimal)
If two entities are involved in a
Many-To-Many relationship, the
related signals do not return any
information about the referenced
entities.

Entity A with Facet Entity A is returned.

Its facet is ignored.

388 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Entity property Signal member Example

CommittedEvent parameters The following parameters of the


CommittedEvent are returned in
the Signal:
• EntityDomain
• Operation
• Ordering
• SessionId
• TimeStamp
• Action (for the possible values
of this parameter see Handling
the CommittedEvent).
• UafEntityName (contains the
name of the entity that has
been published as a signal).

 If you have named the


entity properties in the
same way as these system
parameters (e.g. Action),
the system will rename
them automatically (for
example, to
<EntityName>_<
FunctionalBlockFullName
>_Action).

 In case of Delete and Bulk operations (Action = Deleted, or Operation = Bulk) the returned data is
different. See the CommittedEvent description for all the parameter descriptions.

Example of entities with navigation properties


The following entities have been modeled, with the following properties: Entry (containing two properties of string
type, a reference value type and a blob property type) and Order (containing two properties of string type, a
reference value type, a blob property type and a datetime). These entities are linked in a Many-To-One
relationship.
Entry

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 389


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Order

Relationship configuration

390 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Signal preview example


For the entities described above the following signals will be generated.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 391


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Example of event
An example of signal data structure for an event is the following.
Event example

Signal preview example


For the event just described the following signal will be generated.

392 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.2.8 Modeling Roles


A role describes a set of runtime actions (such as executing commands or running queries) that specific users (or
groups of users) can execute.
Opcenter EX FN objects (entities, reading functions, commands, events, signals and UI screens) can be defined as
securable. You can control the actions that are performed on securable objects, and the users that will perform
these actions.
Consequently you can only assign roles to objects that have been defined as securable.
The following table describes which operations can be permitted according to the chosen object type. All the
permitted actions can be executed through the Service Layer or the IUnifiedSdkLean public interface. If an artifact is
set as securable and it is not associated with any role, all actions will be permitted on it.

Object type Operations

Entity Execute queries on entities.


The permission is set at root entity level: physically derived entities and
facets inherit the Securable property as well as the permission. Entities in
composition inherit neither the Securable property nor the permission.
Entities imported both from external databases as well as from Opcenter
EX FN database views can be also secured.

Reading Functions Execute reading functions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 393


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Object type Operations

Command Invoke commands.


In a command chain, if a root command (Protected or Composite) is
assigned to a user role, all the commands of the chain can be invoked
(you do not have to assign permissions to each of them).
Composite commands and POM imported protected commands are
included. Imported commands are displayed with their original
Functional Block name as well as with the name provided when they were
imported in to the POM Model. In this way, you can assign different roles
in different Apps to the same command handler execution.

Event • Fire events


• Subscribe to events

Signal Subscribe your application to signals.

UI Screens View UI screens from UI Applications.

Workflow
You can create roles and assign rights to roles in either of the following ways:
• by creating pre-defined roles in the App / Extension App (these roles will be imported into Solution Studio in
read-only mode)
• or by creating roles directly in Solution Studio

2.2.2.8.1 Creating and Configuring Roles


This page describes how to create and configure a role (in the App) by selecting securable objects, assigning
permissions on operation types and selecting the users (or groups) that can execute the chosen operation types.

Prerequisites
• Artifacts have been configured as securable objects.
• Artifacts are present in the POM Model (i.e. they have been imported to the POM Model or they have been
directly created inside it).

Creating user roles


Once created, user roles can be also copied and deleted.
1. Right-click the Roles node in the Public Object Model tree and select New Role.
2. Enter a name for the new role. Certain reserved keywords should not be used in the role name.
3. (Optional) Enter a description for the role.

Assigning permissions
Once created, roles can be assigned to permissions.

394 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1. From the Public Object Model pane, double click the role you want to configure.
2. In the Model Designer, click Permissions to open the security details.
3. Right-click in the security details area and select one of the following commands according to the permissions
you want to assign:
• Associate Entity to Role
• Associate Command to Role
• Associate Event to Role
• Associate Signal to Role
4. In the displayed dialog box, after filtering either by source domain or searching by artifact name, select the
artifact/s you want to secure and the required actions. Note: If you choose a Functional Block source domain,
the system returns all the POM commands or entities that have been imported from the specified Functional
Block domain. If you choose an App source domain, the system returns all the Composite commands created in
the specified App or the entities imported from external views.
5. If you are assigning permissions to a published command (i.e. a command imported into an App from a
Functional Block), you can specify whether permissions will be propagated also to the original Functional Block
command or whether they will be assigned only to the selected published command.
6. Click OK to save changes.

 You can also assign UI screens to roles, but you must perform this operation in the UI Module manifest.

Solving compilation errors


In the Model Details pane, in the Select Category list box, you can filter by all artifacts (entities, commands, events
and signals).
If there are consistency issues in the roles, these will be displayed in the Inconsistencies column as either
unavailable or not securable objects. This information is useful to search for artifacts that are still associated with
the role, but that have been either removed from a referenced Functional Block (Object unavailable) or that are no
longer securable and cannot be correctly linked to the role (Object not securable).
In this configuration, Project Studio returns a compilation error ("The following elements are contained in the Role
'{Role Name}' but they have been removed or they are no longer securable") that you must manually solve by
removing the association to the missing artifacts or by modifying the Securable annotation of the associated entity
in the referenced Functional Block.

2.2.2.9 Handling Referenced Events in an App


Although you cannot create new events within an App, you can perform the following operations within an App:
• create and implement event handlers for events that have been defined in the referenced Functional Blocks
• configure predefined event subscriptions

2.2.2.9.1 Creating Event Handlers in an App


Event handlers contain the business logic that will be executed when the corresponding referenced event, to which
your handler has subscribed, is raised.
You can create and implement event handlers for events that have been defined in the referenced Functional
Blocks.

System Events

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 395


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

All Apps contain a reference to an internal Functional Block. This Functional Block exposes a set of events, which
are visible in the Model Project of your App as referenced events:
• AuditTrailRecordCreated (see How to Retrieve Audit Trail Information and Apply Custom Logic in the Opcenter
Execution Foundation User Manual)
• CommittedEvent
• DebugStartupEvent
• SessionAligned, SessionAlignment, SessionCreated, SessionDeleted, SessionPopulated and
SessionUpdated.
• TimerEvent
• SignalRuleStatusChangedEvent (an internal event, to which handlers cannot be added, used only by
the Signals App, see Signals App in the Opcenter Execution Foundation User Manual).

Procedure
1. Right-click the referenced Event (identified by a lock icon) in the Public Object Model tab of
the POMModel project and select Open.
2. Click on the Handlers

tab of the Model Details pane.


3. Right-click in the Handlers area and select New Event Handler.
4. Enter a name for the custom event handler.
5. If required, define subscriptions.

Result
The event handlers are displayed in the Handlers tab, together with the following information:

Column Description

Handler Name The short name of the event handler

Source Domain The name of the Functional Block or App where the event
handler was defined.

Source Referenced if the event handler was defined in a Functional


Block, otherwise Local.

Predefined Subscription True if the event handler has been associated to a subscription,
otherwise false.

2.2.2.9.2 Configuring Predefined Event Subscriptions in an App


An event subscription represents a one-to-one relationship between an event and an event handler, which can then
be assigned to the worker role in Solution Studio. Event subscriptions can be defined directly in Solution Studio,
however if the subscription is particularly important for the correct use of the App, it may be useful to create
predefined subscriptions at App level, which will then be automatically assigned to the default worker role when
the solution is deployed in Solution Studio
Event subscriptions (created at App level) are removed whenever:
• an event is no longer available, after reloading a Functional Block, or installing a new version.

396 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• a handler is no longer available, after reloading a Functional Block, installing a new version, or simply removing
an App Event Handler.
Version constraints on event subscriptions are as follows:
• the subscription name can be renamed either within the version in which it was created, or in a new major
version.
• envelope parameters can be modified either within the version in which they was specified, or in a new minor or
major version.

Procedure
If required, you can define subscriptions between events and event handlers, to be imported by default into
Solution Studio together with the App as follows:
1. With the referenced Event opened in the Public Object Model tab of the POMModel project, click on
the Handlers

tab of the Model Details pane.


2. Select the required Event Handler.
3. In the Properties pane, set Predefined Subscription to true.
4. If required, modify the default name assigned to the subscription, which corresponds
to <EventName>_<HandlerName>. Bear in mind, however, that the name must be unique.
5. If required, insert a description for the subscription.
6. If you want to filter which events will trigger the event handler logic, in the Envelope section enter values for the
required envelope properties. Consequently the event handler you are subscribing to will not receive all the
events, but only the events that correspond to the values specified for the envelope. For more information on
how to use the event envelope to filter events see How to Configure Event Subscriptions (section Setting Filters
on received Events).

2.2.2.10 Building the Public Object Model Project


When you have completed the modeling phase you must build your model in Project Studio.
This intermediate build of the project will allow you to create the model assemblies and implement the business
logic of your commands and events.
At this phase you can build only the model, not the entire solution. If you compile the entire solution now, you will
receive a blocking error because command and event handlers have not been imported yet.

 If you have previously deleted the AssemblyInfo.cs file, the build will return a blocking error: manually
restore the file to solve the error.

Performing the Build operation


The build operation can be performed in one of two ways:
• select the model project and choose command Build > Build <AppName>.<AppAcronym>POMModel;
• right-click the POM Model project and select Build from the shortcut menu.

Performing the Rebuild operation

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 397


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

If you have performed one of the following operations, you must use the Rebuild command (instead of
the Build command) to correctly regenerate the model output assemblies (otherwise a compilation error is
returned):
• you have deleted all POMModel entities (imported from Opcenter EX FN views and/or referenced from
Functional Blocks),
• you have deleted all Composite Commands,
• you have deleted all Types.

Result
All the compiled files are saved by default in the bin\Debug folder of the Model project (for example
Projects\<AppName>\<AppName>\<Acronym>POMModel\bin\Debug). These are the assemblies that contain the
namespaces for POM Model artifacts. Note that, unlike the model project of the Functional Block, in this model
project there are not any assemblies for the writing model.

Assembly name Contents

<Prefix Composite command definitions, as well as the protected


>.<DomainName>.<AppName>.<Acronym>POMM commands that have been pubished to the POM Model.
odel.Commands.dll

<Prefix>.<DomainName POM Model reading entity definitions.


>.<AppName>.<Acronym>POMModel.PublicModel
.dll

<Prefix>.<DomainName Parameter type definitions.


>.<AppName>.<Acronym>POMModel.Types.dll

Reference Management
Inside your Composite Command handler or Custom Event handler code you may want to perform reading
operations on entities that have been modeled either inside the App (by using [...]POMModel.PublicModel.dll) or
inside a referenced Functional Block (by using [...].Model.ProjectionModel.dll).
These references are automatically managed in Project Studio by Reference Manager. Reference Manager
automatically adds assemblies both for referenced Functional Blocks as well as for POMModel assemblies.
However, you can manually perform this operation. This is essential, for example, if you have referenced Functional
Blocks without using Reference Manager.

2.2.3 How to Implement Business Logic in an App


Once you have finished the modeling phase and you have built the Public Object Model project you can implement
the logic to be executed in the command and event handlers.
You carry out this implementation phase by writing code in the C# handler classes you can import in the App
project.
The Opcenter Execution Foundation C# Analyzer dynamically checks the syntax of your code, and can be configured
as required.
Apps can execute business logic of other Apps via remote calls.

Possible Operations to develop Business Logic in an App

398 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

You can perform several operations during the implementation phase of an App, such as:
• Implement Composite Command Handlers
• Implement Event Handlers
• Implement Reading Function Handlers
• Implement Pre-Checks (as described for the Functional Blocks)
• Implement remote calls.
• Debug the code for
• Commands and Reading Functions (via Debugging Tool)
• Commands and Event Handlers (via a debug system Event)

2.2.3.1 Importing Composite Command Handlers into an App


Composite command handlers contain the business logic required to reach a specific manufacturing target.
You must insert the code describing this logic in the class corresponding to the modeled composite command. This
class, which you can import through a wizard only after you have built the model project, is made up of two partial
classes that are contained in two separate files. These files are automatically generated and named by the App
compiler.
Only the <CommandName>Handler.cs file must be modified.
In order to write your code, you must import the template classes into your Command Handler project.

2.2.3.1.1 Importing the C# class of the composite command handler


After you have compiled the POMModel project at the end of the command modeling phase, import the
required .cs files, with the relative relative manifest and .dll files, in the Solution Explorer as follows:
1. Right-click the CommandHandler project and then select the Import from the Model command.
2. Select the composite commands to be imported from the list.
3. Expand the following folder structure (automatically created at the end of the import
procedure): CommandHandler project > <AppName>.POMModel > Commands sub-folder. Here you will find
the imported C# files.
4. Open the <CommandName>Handler.cs file of interest and write the required code.

2.2.3.1.2 Manually adding command handlers to the project


In some cases, for example if a CS file has been removed by mistake, it may be necessary to manually add command
handler templates to your project instead of using the import functionality:
1. Expand the command handler project.
2. Right-click on the Commands sub-folder and select Add > Existing Item.
3. Browse to the .cs files that you want to use in your project.
But this procedure must not be used as an alternative to the previous one, since in that case, the system
automatically imports the relative manifest and .dll files, which should be manually imported in this case.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 399


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Command handler Execute() method (not to be modified)

using System;
using Siemens.SimaticIT.Unified.Common;
using Siemens.SimaticIT.Unified;
namespace Siemens.FBApp.FBApp.BVPOMModel.Commands
{
/// <summary>
/// Class initialize
/// </summary>
public partial class MyCommandHandlerShell : ICompositeCommandHandler
{
private IUnifiedSdkComposite Platform;

/// <summary>
/// Execute
/// </summary>
/// <param name="unifiedSdkcomposite"></param>
/// <param name="command"></param>
/// <returns></returns>
public Response Execute(IUnifiedSdkComposite unifiedSdkcomposite, ICommand
command)
{
this.Platform = unifiedSdkcomposite;
return MyCommandHandler((MyCommand)command);
}
/// <summary>
/// Retrieve the type of the command
/// </summary>
public System.Type GetCommandType()
{
return typeof(MyCommand);
}
}
}

400 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Command handler implementation

{
/// <summary>
/// Partial class init
/// </summary>
[Handler(HandlerCategory.BasicMethod)]
public partial class MyCommandHandlerShell
{
/// <summary>
/// This is the handler the MES engineer should write
/// This is the ENTRY POINT for the user in VS IDE
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
/// <remarks>This is a Composite Command Handler</remarks>
[HandlerEntryPoint]
private MyCommand.Response MyCommandHandler(MyCommand command)
{
// Put your code here
// return new MyCommand.Response() { ... };
throw new NotImplementedException();

}
}
}

2.2.3.2 Importing Event Handlers into an App


Event handlers contain the business logic that will be executed when the corresponding referenced event, to which
your handler has subscribed, is raised.
Once created, custom event handlers must be imported to the Event Handler project and implemented as
described for the Functional Blocks.

 If an event handler is removed from the model, you must manually delete the corresponding C# class,
otherwise it will be included in the App manifest.

Workflow
1. Define the Custom Event Handler
2. Import the Event Handler

Defining the Custom Event Handler


1. Select the required event in the Event node in the Model Explorer and drag it into the central Designer Model.
2. Right-click the event and select New Event Handler.
3. Enter a name for the new event handler and confirm: the new handler is displayed in the Handlers tab of
the Model Details pane.
4. Build the model project.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 401


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Importing the Event Handler

Importing Event Handlers

1. Right-click the EventHandler project and select Import from the Model.
2. Select the event handler you just created and click OK.
3. Expand the folder structure of the EventHandler project and open the <EventNameHandler>.cs file.

 The assemblies can be found in


<AppProjectFolder>\SimaticITPackages\<Prefix>.<FunctionalBlockName>_<version>\model\bin.
If you have not used Reference Manager you must manually add a file reference to the assembly file
containing the definition of the source event in order to implement the code inside the event handler
within the App
(<Prefix>.<DomainName>.<FunctionalBlockName><FunctionalBlockAcronym>Model.Events.dll). The
assembly is found in %ProgramData%\Siemens\SimaticIT\Unified\Engineering\Dev\ModelBin.

Implementing the Event Handler


After you have imported the template, you can implement the code of the Event Handler (for more information,
see Implementing Event Handlers in an App).

2.2.3.3 Implementing Composite Command Handlers in an App


You can implement the logic of composite commands after you have imported the Composite Command Handlers
into an App.
From the code of the Handlers you can invoke and use Opcenter Execution Foundation public
functionalities exposed by the IUnifiedSdkComposite interface of the Opcenter Execution Foundation Platform
Reference Online Help.
At the end of the handler implementation, you can debug your code directly from Project Studio either by using the
Opcenter EX FN App Debugging tool or by writing additional code.
The Opcenter Execution Foundation C# Analyzer checks the syntax of your code while you write it. This tool can be
modified or disabled if required.

Command Handler description


When you define a new command and then build the Model project, the system generates the following C# classes
for each Composite command:
• <CompositeCommand>Handler.cs, which you must modify, is already configured to expose the method that
you have to implement. This method has been automatically configured to receive the input of the related
command and to return the expected response.
• <CompositeCommand>HandlerExecution.cs, which you must not modify, is automatically configured to
expose:
• the Execute method that will be invoked by the Worker.
• the Platform variable, on which an instance of an object that implements
the IUnifiedSdkComposite interface is injected.

402 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

When you import commands in the relative handler project from Project Studio, only the modifiable file
(<Command>Handler.cs) is displayed for each command.
At runtime the worker invokes the code of the handler by calling the Execute method of
the <Command>HandlerExecution.cs class. When this method is invoked, the worker executes the handler logic
with the input from the received command request and then it prepares the reply to be returned.

Input, Output and Command Response


The input parameters define the input data structures that will be passed to the Command.
The Response Class of the Command returns the Command output parameter and two properties: a boolean
property regarding the execution result (Succeeded) and an Error property containing the error code and the error
message.

Using Model Assemblies in Composite Command handlers


When compiled, the model project generates a set of assemblies containing the definitions of all the objects you
have modeled, such as entities, commands, events etc.
Inside the code of your Composite Command handler you can perform read operations on the entities that have
been imported into the POM reading model. If you want to execute operations on the writing data model (i.e. on the
entities modeled in the referenced Functional Blocks), you can directly invoke the commands developed in the
referenced Functional Blocks (as well as the corresponding commands imported in the POM Model).
All references to the model assemblies are automatically managed by Project Studio if you have used Reference
Manager to add references to the Functional Blocks. Otherwise you can always add model assemblies manually.

Possible operations inside composite command handlers


The following table contains the operations that you can execute from the code of a composite command handler.

Operation Type Composite Command Handler

Read data from entities of the POM reading model


via ProjectionQuery method

Read data from entities of the POM reading model via Query
method

Read data from entities of referenced Functional Blocks


via ProjectionQuery method

Read data from entities of referenced Functional Blocks


via Query method

Read data from archived entities

Write data on Automation entities

Read data from Automation entities

Call protected commands to execute write operations

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 403


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Operation Type Composite Command Handler

Call published commands to execute write operations

Call remote commands

Get remote entities

Invoke reading functions

Trigger events

Subscribe to events

Write trace logs

Access the current user identity (Principal property)

Send messages to Opcenter Connect MOM

Get data segregation session information

 Automation Gateway functionalities, exposed by the platform IUnifiedSdk interface, can be accessed only
if you compile the Command Handler by choosing the 64-bit compilation option.

2.2.3.4 Implementing Event Handlers in an App


You can implement the logic of referenced events after you have imported the Event Handlers into the App.
From the code of the Event handlers you can invoke and use Opcenter Execution Foundation public
functionalities exposed by the IUnifiedSdkEvent interface documented in the Opcenter Execution
Foundation Platform Reference Online Help.
At the end of the handler implementation, you can debug your code directly from Project Studio by writing the
proper code.
The Opcenter Execution Foundation C# Analyzer checks the syntax of your code while you write it. This tool can be
modified or disabled if required.

Event handler description


When you define a new event and then build the Model project, the system generates the following C# classes for
each event:
• <EventName>Handler.cs, which you must modify, is already configured to expose the method that you have to
implement. This method has been automatically configured to receive the input of the related event.
• <EventName>HandlerExecution.cs, which you must not modify, is automatically configured to expose:
• the Execute method that will be invoked by the Worker.

404 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• the Platform variable, on which an instance of an object that implements the IUnifiedSdkEvent
interface is injected.
When you import the events in the relative handler project from Project Studio, only the modifiable file
(<EventName>Handler.cs) is displayed for each event.
At runtime the worker invokes the code of the handler by calling the Execute method of
the <EventName>HandlerExecution.cs class. When this method is invoked, the worker executes the handler logic
with the input of the fired event.

Using Model Assemblies in Event handlers


When compiled, the model project generates a set of assemblies containing the definitions of all the objects you
have modeled, such as entities, commands, events etc.
Inside the code of your Event Handler you can perform read operations on the entities that have been imported into
the POM reading model. If you want to execute operations on the writing data model (i.e. on the entities modeled in
the referenced Functional Blocks), you can invoke the commands developed in the referenced Functional Blocks (as
well as the corresponding commands imported in the POM Model).
All references to the model assemblies are automatically managed by Project Studio if you have used Reference
Manager to add references to the Functional Blocks. Otherwise you can always add model assemblies manually.

Possible operations inside Event Handlers


The following table contains the operations that you can execute from the code of an event handler:

Operation Type Event Handler

Read data from entities of the POM reading model


(ProjectionQuery method)

Read data from entities of referenced Functional Blocks


(ProjectionQuery method)

Read data from entities of the POM reading model (Query method)

Read data from entities of referenced Functional Blocks (Query


method)

Read data from archived entities

Write data on Automation entities

Read data from Automation entities

Call protected commands to execute write operations

Call published commands to execute write operations

Invoke reading functions

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 405


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Operation Type Event Handler

Trigger events

Subscribe to events

Write trace logs

Access the current user identity (Principal property)

Send messages to Opcenter Connect MOM

Get data segregation session information

 Automation Gateway functionalities, exposed by the platform IUnifiedSdk interface, can be accessed only
if you compile the Event Handler by choosing the 64-bit compilation option.

2.2.3.5 Importing and Implementing Reading Function Handlers


You can implement the logic of the Reading Functions inside the Reading Function Handler projects of the App by
using the IUnifiedSdkReadingFunction Interface interface of the Opcenter Execution Foundation Platform Reference
Online Help.
In order to write your code, you must first import the template classes into your Reading Function Handler project.
At the end of the Handler implementation, you can debug your code directly from Project Studio.
Reading Functions must implement input and output parameters (at least one output parameter is always
mandatory).

Importing the C# class of the Reading Function Handler


After you have compiled the POMModel project at the end of the modeling phase, import the required .cs files, with
the relative manifest and .dll files, in the Solution Explorer as follows:
1. Right-click the Reading Function project and then select the Import from the Model command.
2. Select the Reading Functions to be imported from the list.
3. Expand the following folder structure (automatically created at the end of the import
procedure): ReadingFunction project > <AppName>.POMModel > Reading Functions sub-folder. Here you will
find the imported C# files.
4. Open the <ReadingFunctionName>Handler.cs file of interest and write the required code.

Description of Reading Function Handlers


When you define a new Reading Function and then build the Model project, the system generates the following C#
classes:
• <ReadingFunctionName>Handler.cs, which you must modify, is already configured to expose the method that
you have to implement. This method has been automatically configured to receive the input of the related
ReadingFunction and to return the expected response.

406 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• <ReadingFunctionName>HandlerExecution.cs, which you must not modify, is automatically configured to


expose:
• the Execute method that will be invoked by the Opcenter EX FN platform infrastructure.
• the Platform variable, on which an instance of an object that implements
the IUnifiedSdkReadingFunction interface.
When you import the Reading Functions in the relative handler project from Project Studio, only the modifiable file
(<ReadingFunctionName>Handler.cs) is displayed.
At runtime, the platform infrastructure invokes the code of the handler by calling the Execute method of
the <ReadingFunctionName>HandlerExecution.cs class. When this method is invoked, the platform
infrastructure executes the handler logic with the input received from the function request and then it prepares the
response to be returned.

 Reading Function Handlers can be only compiled by choosing the 64-bit compilation option.

Input, Output and Reading Function Response


The input parameters define the input data structures that will be passed to the Reading Function.
The output parameters, which are contained in the Reading Function Response class, describe the data structure of
each returned record, collected in a list of values. Each of these records contains the properties that have been
defined as output parameters in the Reading Function.
Moreover, the Response class also returns an error field and the related description.

 For an example of Reading Function Handler implementation, see IReadingFunctionHandler Interface in


the Opcenter Execution Foundation Platform Reference Online Help.

The reading function can be invoked from a Lean application as well as from a web application.
When the invocation is performed from a Lean application, the function can be called by adding filtering criteria to
the returned values (see page Developing Third-Party Applications Integrated with Opcenter EX FN via
IUnifiedSdkLean interface).
When the invocation is performed from a web application, the Function can be called by adding OData filtering
criteria (see page Invoking Reading Functions).

Using Model Assemblies in Reading Function Handlers


When compiled, the model project generates a set of assemblies containing the definitions of all the objects you
have modeled, such as entities, commands, events etc.
Inside the code of your Reading Function Handler you can only perform read operations on the entities that have
been imported into the POM reading model.
Bear in mind that you cannot execute operations on the writing data model (i.e. on the entities modeled in the
referenced Functional Blocks), neither directly nor by invoking commands.
All references to the model assemblies are automatically managed by Project Studio if you have used Reference
Manager to add references to the Functional Blocks. Otherwise you can always add model assemblies manually
(see Building your Model or Reference a Functional Block without Reference Manager).

Operations available inside the Reading Function Handler


The following table sums up the operations that you can execute from the code of a Reading Function Handler.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 407


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Operation Type Reading Function Handler

Read data from the writing model, if the entity is inside the same
domain

Read data from the writing model, if the entity is inside another
domain

Read data from the reading model, if the entity is inside the same
domain (IUnifiedSdkDataReading interface)

Read data from the reading model, if the entity is inside another
domain (IUnifiedSdkDataReading interface)

Read data from the reading model, if the entity is inside a user
domain, i.e. legacy system data (IUnifiedSdkDataReading
interface)

Read data from archived entities

Read data from Automation entities

Get the properties and the content of the file as a data stream by
specifying the file GUID (IUnifiedSdkContentReading interface)

Get CommittedEvents (IUnifiedSdkInformationRetrieving


interface)

Call Reading Functions (IUnifiedSdkFunctionInvocation interface)

Write trace logs (IUnifiedSdkDiagnostics interface)

Access to the current user identity through the Principal property


(IUnifiedSdkQoS interface)

Write data (create, update, delete entity instance), if the domain of


the entity and the domain of the Reading Function Handler are the
same

Write data (create, update, delete entity instance), if the domain of


the entity and the domain of the Reading Function Handler are
different

Write data (create, update, delete entity instance), if the entity


belongs to a user domain

408 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Write data on Automation entities

Call published in role commands (synchronously/asynchronously)

Call commands (synchronously/asynchronously)

Call remote commands (synchronously/asynchronously)

Get remote entities

Trigger events

Subscribe to events

Send messages to Opcenter Connect MOM

Get data segregation session information


(see How to Use Data Segregation in Custom and Third-Party
Integration Apps in the Opcenter Execution Foundation User
Manual)

 Automation Gateway functionalities, exposed by the Automation Sdk interface, can be accessed only if you
compile the Command Handler, or the Event Handler, or Reading Function by choosing the 64-bit
compilation option.

2.2.3.6 How to Debug Business Logic


You can debug your Handlers as follows:
• Command handlers (either via App Debugging Tool or alternatively via DebugStartupEvent)
• Event handlers (via DebugStartupEvent)
• Reading Function handlers (via App Debugging Tool)
• UI Modules and UI Screens.

2.2.3.6.1 Debugging Command and Event Handlers via DebugStartupEvent


After implementing Command and Event Handlers, you can test your code in the development environment in
order to evaluate if the developed logic works properly.

 This debugging mode does not allow you to debug Reading Function Handlers.
For Command Handlers we suggest that you follow Debugging Commands and Reading Functions via App
Debugging Tool, which uses the Opcenter Execution Foundation App Debugging Tool.
For Event Handlers, you can only use this debugging mode.

This debugging mode applies to the following projects:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 409


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Handlers of all types of Commands: Protected Commands of Functional Blocks, Commands imported into the
POM Model of an App, and Composite Commands,
• Event Handlers.
The following Visual Studio debugging functionalities are available within Project Studio:
• Call Stack - to display the list of functions currently called.
• Immediate Window - to execute program statements separately from the running program.
• Breakpoint - to stop the execution of a program at a defined point either in all instances or according to a
specific set of criteria.
• Watch Window - to watch the contents of a variable or series of variables.
• Output Window - to write out a series of text messages during the execution of the program so that users can
monitor what happens during the program lifecycle
• Attaching to Process - to attach to a process running somewhere on the computer.

Limitation
If you have an environment configured in HTTPS, debugging functionalities on Business Logic and UI Modules are
not available.

Workflow
To correctly execute debugging operations, you must go through the following steps:

Prerequisites and user configuration


• Project Studio is installed on the Engineering host.
• Runtime Services have been stopped from Solution Studio.
• The SIT_UNIFIED_MEDIUM_H group must have reading rights on the folders (and subfolders) containing the
project you are developing in Project Studio.
• The user running Visual Studio, which can be either a Windows local user or a Windows domain user (and not a
pure UMC user as this user cannot launch Visual Studio), must be imported in User Management Component
(see page Import Windows Local Users or Import Active Directory Users inside the UMC UMX User Manual), and
associated with the UMC SIT_UAF_SYSADMIN group and the UMC UMC Viewer role by using the UMC UI
Interface. If you have not used the Opcenter Execution Foundation Configuration tool to configure your
environment, you must assign the Opcenter EX FN SysAdmin role to the SIT_UAF_SYSADMIN group as
described in the Opcenter Execution Foundation Installation Manual.
• The user running Visual Studio must also be assigned to the SIT_UNIFIED_MEDIUM_L Windows group.
• If you need to debug handlers that access Opcenter EX FN databases on Oracle, the user running Visual Studio
must exist on the Oracle database machine and the following conditions must be satisfied:
• if you want to use Windows authentication, the user must be specified as high_profile_user on the
Oracle databases by launching the ConfigureORACLE.ps1 script (low_profile_user can be left blank) .
• if you want to use Database authentication, the user must exist on the Oracle databases and must be
properly configured as described in How to Configure an Oracle Database for Database Authentication of
the Opcenter Execution Foundation Installation Guide)

Creating the database


To debug the code that implements your business logic, it is necessary to have a database that contains the
involved entities. For this reason, before performing the procedure below, you must:
1. Create the package of the Functional Block containing the code you want to debug.

410 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2. Create an App.
3. Reference the Functional Block from the App.
4. Create and release the App package.
5. Create a solution in Solution Studio loading the previously created App.
6. Deploy the Solution without restarting the runtime services.

 It is necessary to repeat the procedure above only if you modify the Functional Block by adding new
entities, but not if you model additional commands and events.
If the code you want to debug is contained in the App, you can repeat the above procedure starting from
step 4.

Setting the Debug Options


1. Right-click the Handler project and then select the Properties command.
2. Click the Debug tab.
3. Verify that the Start External Program radio button is selected and that the absolute path of the debug worker
is displayed in the edit box on the right. For example C:\Program
Files\Siemens\SimaticIT\Unified\bin\Worker.exe (for a 32 bit handler project C:\Program
Files\Siemens\SimaticIT\Unified\bin\Worker32.exe).
4. The Command line arguments area displays:
• the following arguments with the relative values:
Argument Value Description

/name "%COMPUTERNAME%.Default The name of the debug worker role.


WorkerRoleDefinition (x64).0"

/debug true Flag indicating if the debug mode is


enabled (true) or not (false). If enabled:
• the system disables the
command timeout and
automatic retry management
for both execution errors and
optimistic concurrency errors.
• the debug worker is subscribed
to
the DebugStartupEvent event
that is automatically fired.
• the self-host Service Layer starts
in debug mode.
• the following arguments must be set as shown in the example below:
Argument Description

/debugPath The absolute path of the assemblies generated when the solution is
compiled. If not specified, the system will use the following:
• C:\ProgramData\Siemens\SimaticIT\Unified\Deploy\bin
• C:\Program Files\Siemens\SimaticIT\Unified\bin
Environment variables can be used.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 411


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Argument Description

/registryPath The path of the debug governance registry which is generated


when the Functional Block package is created. If not specified the
system uses %ProgramData%
\Siemens\SimaticIT\Unified\Deploy\Governance. Environment
variables can be used.

Example

/name:"%COMPUTERNAME%.Default WorkerRoleDefinition (x64).0"


/debug:true
/debugPath:" C:
\tfsroot\DebugPrjStudio\PPRLibrary\PPRLibrary\PPRLibrary.Installer\bin\Debug"
/registryPath:"C:
\tfsroot\DebugPrjStudio\PPRLibrary\PPRLibrary\PPRLibrary.Installer\bin\Debug\Debugger
"

 If you copy and paste this example configuration, you must properly modify the project names and then
remove the end of line breaks.

Debugging the code

 You can debug the code of a handler subscribed to the TimerEvent as long as you fire the TimerEvent
only for debug purposes from a debug event handler. If the event is fired in a handler at runtime an error
will be returned.

1. In the EventHandler project, create a custom event handler for the DebugStartupEvent event and then import
the relative .cs files (Siemens.SimaticIT.SystemData.Foundation.EventsDebugStartupEvent).
2. Open the <CustomDebugStartupEventHandlerName>.cs file and implement a call to the command whose
handler you want to debug, or fire the event whose handler you want to debug.
Note Alternatively you can debug your code by sending an HTTP request through the self-hosted Service Layer,
for example using a custom UI. The base address is http://localhost:9000/runtime/odata/.
3. If the code you want to debug contains a call to a method of a referenced Functional Block, extract the .pdb files
from the relative output package located in %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
4. Compile the solution.
5. Insert a break point where required in the code.
6. Right-click the project you want to debug and select Set as StartUp Project.
7. Build the Installer project: if the active configuration is set to Debug (and not to Release), the
DebugRegistryGenerator process that synchronizes the debug environment is started. This operation must be
executed the first time you prepare the debugging environment since you must publish all your artifacts to the
debug governance.
8. Press F5 to start debugging. If the handler execution stops (for example, at a break point or for an exception),
ensure that you complete the execution of the current handler before starting another debug operation.
Alternatively, you can directly clean the RabbitMQ queues as described in the Stopping the debug
operation section below, if you then want to execute another debug operation.

412 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

9. If required, modify the code of the handler. If the corresponding command or event has been already published
to the debug governance, you can either recompile the entire solution (or the Installer project) as usual (but
this operation is rather time consuming) or you can configure a build post-action in the handler project as
described in the Modifying the code without recompiling the entire solution section below.

Modifying the code without recompiling the entire solution


If all artifacts have been deployed to the governance debug environment as described in the previous section
(Debugging the code section), and you have changed only the code inside a command or event handler of an
already deployed command/event, you can avoid recompiling the entire solution (or the Installer project) by
configuring a build post-action as follows:
1. Right-click the command handler (or event handler project), and select Properties.
2. Click the Build Events tab.
3. In the Post-build event command line edit box type the following code snippet:

copy /Y "$(TargetDir)*.dll" "$(SolutionDir)$(SolutionName)\$


(SolutionName).Installer\$(OutDir)"
copy /Y "$(TargetDir)*.pdb" "$(SolutionDir)$(SolutionName)\$
(SolutionName).Installer\$(OutDir)"

4. Compile the modified command handler or event handler project.

Stopping the debug operation and cleaning RabbitMQ queues


You can stop the debug operation at any point by clicking the Stop button in the command bar. However,
commands or events you launched during the debug operation could remain queued.
Consequently it is preferable to clean the queue before starting another debug operation using the RabbitMQ
Management Plugin:
1. Open the RabbitMQ web UI page, which is by default at http://server-name:15672/ (on a local machine
installation: http://127.0.0.1:15672/).
2. Click the Queues tab.
3. Select the queues of the worker role you are debugging (one at a time).
4. Click the Purge button at the bottom of the screen.

 You can install the RabbitMQ Management Plugin as follows:


1. Open a command prompt.
2. In the RabbitMQ installation folder browse to the sbin folder.
3. Run the following command line:

rabbitmq-plugins enable rabbitmq_management

For further details see: https://www.rabbitmq.com/management.html

Troubleshooting
During debug, Trace Viewer traces the path of the project assemblies:
• that have been successfully loaded.
• whose loading failed.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 413


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

If the worker crashes, you can check the dump files.

2.2.3.6.2 Debugging Commands and Reading Functions via App Debugging


Tool
After implementing Command Handlers, Composite Command Handlers, Post-Action Handlers, Pre-Checks
Handlers and Reading Function Handlers, you can debug the developed logic directly within the development
environment by using the Opcenter Execution Foundation App Debugging Tool inside Apps or Functional Blocks.
To start debugging, you must simply define the solution configuration within your Functional Block or App, and
when you press F5, the Opcenter Execution Foundation App Debugging Tool will open. This tool allows you to easily
invoke Commands and Reading Functions without writing any additional code and to automatically open the
corresponding Handler.
The tool supports the Edit and Continue standard functionality of MS Visual Studio.

 This debugging mode, which does not include the possibility to debug Event Handlers, represents an
alternative to Debugging Command and Event Handlers via DebugStartupEvent, for which additional code
must be implemented.

Debugging referenced Commands, Post-Actions and Pre-Checks


In each Project Studio solution you can directly debug the code which actually belongs to this solution (e.g. from an
App you can debug the code of a Composite Command Handler).
If Handlers are defined in a referenced Functional Block (for example, the code of a Protected Command), PDB files
have to be stored in symbol file locations (Debug\Options in Visual Studio) and source files have to be opened in the
current Visual Studio instance. The PDB files and the source files you use must be perfectly aligned with the
deployed Functional Block assemblies.
If you want to debug a Post-Action or a Pre-Check, bear in mind that the base Command, to which the Post-Action
or Pre-Check refers, is contained in another Functional Block. Consequently, if you want to debug also the code of
the Base Command Handler together with the Post-Action or Pre-Check, you have to retrieve the PDB and the
source files for the base Command. You can invoke the referenced Base Command directly with the Opcenter
Execution Foundation App Debugging Tool if the Base Command is published in the Service Layer within an App
project.
Hence:
• From an App debug solution, you can directly debug Composite Command and Reading Function Handlers. You
can also invoke Public Commands but to debug their Handlers, you must have the related PDB and the source
files.
• From a Functional Block debug solution, you can invoke Protected Commands and debug their Command
Handlers. To debug also the related Post-Actions or Pre-Checks, you must have the PDB and the source files of
the Post-Actions or Pre-Checks.

Limitation
If you have an environment configured in HTTPS, debugging functionalities on Business Logic and UI Modules are
not available.

Prerequisites and user configuration


• An App that publishes the required Commands, Composite Commands or Reading Functions has been deployed
in Solution Studio.

414 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Project Studio is installed on the Engineering host.

 If Project Studio has been installed after the system was already configured with the Opcenter Execution
Foundation Configuration tool, or via scripts, the debug certificate is not installed on the Engineering host
and must be manually created (see note below).

• Runtime Services have been stopped from the Host Management page of Solution Studio.
• The SIT_UNIFIED_MEDIUM_H group must have reading access rights to the folders and subfolders containing
the project you are developing in Project Studio.
• The user running Visual Studio, which can be either a Windows local user or a Windows domain user (and not
a pure UMC user as this user cannot launch Visual Studio), must be imported in User Management Component
(see Import Windows Local Users or Import Active Directory Users inside the UMC UMX User Manual), and
associated via UMC UI Interface with the following UMC artifacts: the SIT_UAF_SYSADMIN group and the UMC
Viewer role. If you have not used the Opcenter Execution Foundation Configuration tool to configure your
environment, you must assign the Opcenter EX FN SysAdmin role to the SIT_UAF_SYSADMIN group as
described in the Opcenter Execution Foundation Installation Manual.
• The user running Visual Studio must also be assigned both to the SIT_UNIFIED_MEDIUM_L and to the
SIT_UNIFIED_LOW Windows group. Remember that if you add a user to a group you must logoff and logon
again in Windows to make the configurations active.
• If you need to debug handlers that access Opcenter EX FN databases on Oracle, the user running Visual Studio
must exist on the Oracle database machine and the following conditions must be satisfied:
• if you want to use Windows authentication, the user must be specified as high_profile_user on the
Oracle databases by launching the ConfigureORACLE.ps1 script (low_profile_user can be left blank) .
• if you want to use Database authentication, the user must exist on the Oracle databases and must be
properly configured as described in How to Configure an Oracle Database for Database Authentication of
the Opcenter Execution Foundation Installation Guide).

Managing debug settings for Apps and Functional Blocks


To debug Apps and Functional Blocks, specific debug settings must be defined in the solution configuration
(see Understanding Build Configurations page in the online MSDN library). These settings include the general build
settings (such as the solution platform or the build option) and some project-specific settings, such as the App
name and the certificates, which extend the solution configuration.
You can either use one of the standard Visual Studio solution configurations (such as debug or release) or add
custom configurations. In the release configuration, the debug option is not automatically available and you must
manually set it by adding a configuration step (as described in this procedure below). You can add custom
configurations in the standard Visual Studio Configuration Manager (in Visual Studio, choose Build > Configuration
Manager command). Here you can create, modify or delete all solution configurations (if you delete a
configuration, all the defined debug settings will be deleted as well).
Proceed as follows:
1. With the required solution configuration selected (either in the Configuration Manager window or from the
Solution Configurations drop-down list box), right-click the Installer project of your Functional Block \ App
solution and select Properties.
2. In the Settings tab, type the short name (case sensitive) of the App that references the Functional Block for
which you want to start debugging (while if you want to debug inside an App, the App name is automatically
defined and cannot be modified).
3. Choose either of the following authentication modes:
• Debug Certificate, to use the Opcenter Execution Foundation installed certificate for generating an
access token (see note below).
• Certificate, if you want to specify the name of a custom certificate, used to generate a valid access
token.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 415


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

4. Only if you are in release configuration, you need to perform the following extra steps, otherwise the debugging
cannot run:
a. Right-click the Installer project and select Unload project.
b. With the Installer project selected, right-click it again, select Edit <FunctionalBlock>.Installer.proj and
then add <RunDebugRegistry>true</RunDebugRegistry> to the first available<PropertyGroup>
section (for example, the one that contains information such as the Functional Block name and so on,
without conditions).

 Creating a debug certificate


If you have set the Debug Certificate authentication mode, but the debug certificate is not present, you
can manually create it by following the procedure described in Creating a Debug Certificate on the
Engineering Host of the Opcenter Execution Foundation Installation Guide.

Starting the debug with the App Debugging Tool


1. With the required solution configuration selected, right-click the handler project you want to debug (e.g.
Command Handler Project) and select Set as Startup Project.
2. If you have added or deleted Post-Actions or if you have modified the Post-Actions configuration in Solution
Studio by changing the order in which the Post-Actions will be executed:
• In Solution Studio, build your Solution ( button, see Creating the Deployment Package).
• In the Host Management page, deploy the Solution on the Engineering host ( button, see Deploying
the Solution Package to Hosts).
• In Project Studio, perform the Rebuild operation of the Project Studio solution to avoid misalignments
between the App Debugging tool and the configuration you have just deployed.
3. Press F5 (or click the Debug button in Visual Studio) to start debugging. The system starts the required debug
process (i.e. the Debug Worker to debug Commands/Composite Commands, or the debug Service Layer to
debug Reading Functions) and opens the App Debugging tool on a new tab directly inside Project Studio. In the
UI of the tool you can browse the artifacts (Commands and Reading Functions) to be tested.
4. Should the App Debugging tool show an error stating that the App metadata could not be retrieved, wait until a
successful message (such as Server started) is displayed on the command prompt and then refresh the
Debugging tool.
5. In the App Debugging tool, select the artifact you want to invoke, set the required parameter values in the code
editor below and the send the request.

 If you want to choose a Public Command instead of a Composite Command, clear the Show only
composite commands check box, which is selected by default. If you are debugging a Functional Block
Command whose name is the same as an App Command name, the Functional Block command will be
identified in the artifact list by the _debug suffix (e.g. CreateOrder_debug for the Functional Block
Command name and CreateOrder for the App Command Name).

6. The system opens the Handler project and stops at the required breakpoints: here you can directly insert the
required changes and continue debugging.

416 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 • If the Handler execution stops (for example, at a break point or for an exception), ensure that you
complete the execution of the current Handler before starting another debug operation. Alternatively,
you can directly clean the RabbitMQ queues as described in the Stopping the debug operation section
below, if you then want to execute another debug operation.
• If required, modify the code of the inspected Handler. If the corresponding Command / Reading
Function has already been deployed, you can either recompile the entire solution (or
the Installer project) as usual (but this operation is rather time consuming) or you can configure a
build post-action in the Handler project as described in the Modifying the code without recompiling
the entire solution section below.
• Should the debug process not correctly start, see section Handler project configuration below.

Handler project configuration


The Handler projects are configured in order to start the debug processes. If you unintentionally delete these
configurations, or for any other reasons these configurations are removed, the debug process cannot start. In such
a case, you must manually reconfigure your handler projects as follows:
1. In Solution Explorer, right-click the Handler you want to debug and select Properties.
2. Click the Debug tab and enter the following values, according to the selected handler type:

Project Argument Value (example)

CommandHandler Start external program • %SITUnifiedSystemRoot%bin\Worker.ex


e for 64bit or
• %SITUnifiedSystemRoot%bin\Worker32.
exe for 32bit

Command line arguments /name:"%COMPUTERNAME%.Default


WorkerRoleDefinition (x64).0" /debug:true
debugPath:"C:
\Projects\App1\App1\App1.Installer\bin\Deb
ug"
/registryPath:"C:
\Projects
\App1\App1\App1.Installer\bin\Debug\Debu
gger"
/debugPathFile:"C:
\Projects\App1\App1Paths.xml"

ReadingFunctionHandler Start external program %SITUnifiedSystemRoot%bin\ServiceLayer.


Host.exe

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 417


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Project Argument Value (example)

Command line arguments /mode:RUNTIME /debug:true /


debugPath:"C:
\Projects
\App1\App1\App1.Installer\bin\Debug" /
debugPathFile:"C:
\Projects\App1\App1Paths.xml" /
registryPath:"C:
\Projects
\App1\App1\App1.Installer\bin\Debug\Debu
gger"

 If you copy and paste these example configurations, you must properly modify the project names and
paths.

Modifying the code without recompiling the entire solution


If all artifacts have been deployed to the governance debug environment as described in the previous section
(Debugging the code section), and you have changed only the code inside a command or event handler of an
already deployed command/event, you can avoid recompiling the entire solution (or the Installer project) by
configuring a build post-action as follows:
1. Right-click the command handler (or event handler project), and select Properties.
2. Click the Build Events tab.
3. In the Post-build event command line edit box type the following code snippet:

copy /Y "$(TargetDir)*.dll" "$(SolutionDir)$(SolutionName)\$


(SolutionName).Installer\$(OutDir)"
copy /Y "$(TargetDir)*.pdb" "$(SolutionDir)$(SolutionName)\$
(SolutionName).Installer\$(OutDir)"

4. Compile the modified command handler or event handler project.

Stopping the debug operation and cleaning RabbitMQ queues


You can stop the debug operation at any point by clicking the Stop button in the command bar. However,
Commands you invoked during the debug operation could remain queued.
Consequently it is preferable to clean the queue before starting another debug operation using the RabbitMQ
Management Plugin:
1. Open the RabbitMQ web UI page, which is by default at http://server-name:15672/ (on a local machine
installation: http://127.0.0.1:15672/).
2. Click the Queues tab.
3. Select the queues of the worker role you are debugging (one at a time).
4. Click the Purge button at the bottom of the screen.

418 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 You can install the RabbitMQ Management Plugin as follows:


1. Open a command prompt.
2. In the RabbitMQ installation folder browse to the sbin folder.
3. Run the following command line:

rabbitmq-plugins enable rabbitmq_management

For further details see: https://www.rabbitmq.com/management.html

Edit and Continue mode


The tool supports the Edit and Continue standard functionality of MS Visual Studio. The Edit and Continue
functionality makes it possible to directly modify the code in debug without stopping the debug process.

Troubleshooting
During debug, Trace Viewer traces the path of the project assemblies:
• that have been successfully loaded.
• whose loading failed.
If the worker crashes, you can check the dump files.

2.2.4 How to Develop UIs


The final goal of UI development is to deploy the UI parts required to configure the UI Application from Solution
Studio.

UI Modules, Mashup UI Modules and Model-Driven UI Modules


UI Applications are collections of UI Modules, that you can develop in one of the following environments:
• Project Studio

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 419


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Mashup Editor
• Model-Driven UI Module Editor
The choice between them does not depend only on developer preferences, but it is conditioned by the
characteristics of the UI Module itself.
If, for example, you want to create a set of pages with a similar layout and behavior, such as master data
engineering pages, it would be preferable to work in Project Studio, creating the first page and then using it as a
template to develop the others. If you want to create a page, such as an operator page or a dashboard, with a
simple one-shot layout, it would be better to use the Mashup Editor. This tool, which is based on graphical and user
friendly working environment, can be used by less skilled users, thus allowing you to postpone the page
configuration phase (for example before the deployment phase after collecting specific feedback from the final
users).
If you choose to create Mashup Modules in the Mashup Editor, you must combine UI Components and/or UI
Components and third-party SWAC Components developed in Project Studio.
If you choose to develop the UI Modules and UI Screens directly in Project Studio, you do not need to develop UI
Components, but you can simply associate the widgets with the business logic directly within the page. It may also
be useful in some circumstances to create a UI Component to be used with different pages in Project Studio (for
example a grid displaying orders to be processed that can be used both in the order management page and in the
entry management page).
As an alternative to the Project Studio code-based choice, you can use the Model-Driven UI Module Editor, which
allows you to create UI Modules and UI Screens without writing code.

Code-based development in Project Studio (UI Modules, UI Components, UI


Screens)
The UI interface project contains the files relative to the user interface. This project includes by default a set of core
widgets and the folders in which, starting from these widgets, you can develop the UI Components and UI
Modules to be included in the final user interface (UI Application).

420 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Code-free development with Model-Driven UI Editor (UI Modules and UI Screens)


The Model-Driven UI Editor is a user-friendly tool, embedded in the UI interface project, which allows you to create
UI Modules and develop UI Screens without writing code, starting from the implemented data model and business
logic.

Graphic development with Mashup Editor (UI Modules and UI Screens)


The Mashup Editor is a tool provided in Solution Studio, which allows you to graphically combine the UI
Components in order to configure the layout, structure and behavior of the UI Modules and UI Screens.
This option is an alternative to the UI Module standard development as well as to the Model-Driven Editor tool.

Graphic development with UI Application Editor (UI Application)


Once you have all the UI Modules you need (either Mashup Modules, or Project Studio standard Modules or Model-
Driven UI Modules), you must combine them in order to configure a Single Page Application.
You must perform these operations from Solution Studio after loading Apps within your Manufacturing Solution.

2.2.4.1 Concepts You Need to Know About UI Development


The following topics could be beneficial before starting to develop your UIs:
• What Is the Open Data Protocol?
• Guidelines for Code Structuring in UI Development
• Using Third-Party Components
• UI Theme Color Definition
• Executing Queries from UIs
• Invoking Commands from UIs
• Subscribing to a Signal
• Uploading Files from UIs
• Exposing UI Modules and UI Components as SWAC Components
• Integrating Custom Widgets
• Localizing Custom UI Apps and UI Framework Resources
• Managing Locales
• Applying Custom Configurations to the Opcenter EX FN Service Layer
• Setting User Preferences

2.2.4.1.1 What Is the Open Data Protocol?


The Open Data Protocol (OData) represents an abstract data model and protocol that permits any client to access
information which is exposed by any data source.
The Open Data Protocol (OData) allows you to create HTTP-based data services, which enable resources to be
published and edited by Web clients, using simple HTTP messages. These resources are identified using Uniform
Resource Identifiers (URIs) and they are defined in an abstract data model.
Any OData client can access any OData data source. OData can be used to expose and access information from a
variety of sources including relational databases, content management systems, file systems, and traditional Web
sites.
OData technology basically relies on:
• The OData data model, which provides a way to organize and represent data. OData uses the Entity Data Model
(EDM). The same approach is used by Microsoft's Entity Framework (EF).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 421


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• The OData protocol, which lets a client make requests to and get responses from an OData service. The OData
protocol is a set of REST interactions based on HTTP. Representational State Transfer (REST) is a software
architecture style consisting of guidelines and best practices for creating scalable web services. REST
interactions include CRUD operations (such as create/read/update/delete operations), along with an OData-
defined query language.

How does Opcenter Execution Foundation use OData?


Opcenter Execution Foundation uses ASP.NET Web API 2.2 for the OData v4.0 protocol.
The Service Layer is an OData service that exposes an endpoint allowing you to access data and send commands.
This service implements the OData protocol.
Opcenter Execution Foundation exposes its data model entities as OData resources. To perform read operations on
these resources, Opcenter Execution Foundation relies on standard OData GET instructions and it represents the
piece of data which is sent back to the client through a format defined in JavaScript Object Notation (JSON).
For create, update and delete operations, Opcenter Execution Foundation relies on OData actions. In particular,
it maps the OData commands to the commands defined by the developer in Opcenter Execution Foundation data
model. Then, the Opcenter EX FN Service Layer converts the OData commands into the corresponding Opcenter EX
FN commands, activates them and then sends back the responses.
If you want to know more about OData you can check the official site at www.odata.org where you can find the
complete specifications of the protocol and features. In particular, refer to the OData v4.0 documentation section.
Since Opcenter EX FN uses the Microsoft implementation of OData v4.0, which represents a subset of OData
v4.0 functionalities, you must refer to the Microsoft official documentation of ASP.NET Web API 2.2 (http://
www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint), if you
want to know the different formats supported and information about existing OData clients you can use in your
applications.

Restrictions to Microsoft Web API usage


Some limitations are still in use for the current version of Opcenter Execution Foundation.
For example, Opcenter Execution Foundation controllers, which are the components that perform queries and send
commands, do not use the standard navigation property as documented at point 2 of http://www.asp.net/web-api/
overview/odata-support-in-aspnet-web-api/odata-v4/entity-relations-in-odata-v4.

2.2.4.1.2 Guidelines for Code Structuring in UI Development


Storing code within the same folder
All the code necessary for the UI Modules and UI Components distributed with an App must be stored in the same
folder, which, when deployed within an Application, will have the same name as the App itself.
This includes, for example:
• low level UI artifacts (widgets, services, etc.)
• third-party scripts
• custom stylesheets.

Grouping UI artifacts by type


To group artifacts by type, locate them within the proper subfolder in the <AppName> folder.
For example:
• components/

422 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• myComponent1/
• myComponent2/
• config/
• fonts/
• images/
• modules/
• myModule1/
• resources/
• scripts/
• ThirdPartyScript1/
• services/
• styles/
• CompanyX.FunctionalBlockY-light.css
• CompanyX.FunctionalBlockY-dark.css
• widgets/
• myWidget1/
• myWidget2/
Additionally:
• Create at least one main custom stylesheet per theme (in this case two, one for the light and one for the dark
theme), and name the CSS files according to the following naming convention: <Prefix><AppName>-
<Theme>.css
• The functionalBlock.js file must contain the definition of the main AngularJS module used by the App.

Defining a main AngularJS module for the App


By design, an AngularJS module is only identified by its name, and there is no out-of-the-box concept of
namespace. However, it is crucial that when developing UI code for a specific App all the AngularJS modules are
grouped within one AngularJS module, with the same name as the App.
For example, if your App is called "Siemens.Core", the module.js file placed in the <AppName> folder within the
UserInterface project, must contain the following module definition:

1 (function(){
2 'use strict';
3 angular.module('Siemens.Core', [
4 'Siemens.Core.UoM',
5 'Siemens.Core.MyComponent1',
6 'Siemens.Core.SomethingElse',
7 'Siemens.Core.myWidget1',
8 'Siemens.Core.myWidget2',
9 // ... other feature modules
10 ]);
11 }())

In this case:
• The main AngularJS Module representing the App (Siemens.Core) is defined.
• All other AngularJS Modules defined in other files are specified as injected dependencies for this module. These
"logical submodules" should be called <AppName>.<ModuleName>.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 423


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 Note that the dot character (".") within a module name has no special meaning in AngularJS and it is not
used by AngularJS for namespacing. The example above "simulates" namespacing using dependency
injection, but injected modules may have completely different names from the name of the "parent"
module.

2.2.4.1.3 Using Icons


In Project Studio and Solution Studio, SVG icons can be specified for:
• UI Components
• SWAC Components
• UI Modules.
The following sets of icons are deprecated and maintained only for compatibility:
• FontAwesome
• Sit icons

SVG icons
The set of SVG icons, which is currently in use, is available at %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\UIFramework\common\icons.
To have a preview of the icons available in this folder you must autonomously proceed by installing any third-party
software which provides you with the SVG preview. For example, you could install https://github.com/maphew/svg-
explorer-extension/releases extension from the Windows 10 shell. But bear in mind that this software is mentioned
only as an example and does not represent a product prerequisite.
SVG icons are semantically classified in the following types:

Icon Pre Purpose Usage Sty Exam Pixel


Type fix le ple Size
Na
me

Com cmd Performs a command or an Command bars, toolbars, Ou 24 * 24


man action when clicked/selected. navigation bars, other command tlin
d locations. e

Data typ Represents a type of object. It is Main icon identifying an object in Ric 48 * 48
type e not selectable, does not a list of cells, a row in a table or a h
perform any action. home title.

Indic indi Indicates the status of the main Secondary icons in a cell or a Ou 16 * 16
ator cato object. table row. tlin
r e
fill
ed

424 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 The icon to be inserted can be specified by removing the prefix, the dimension and the extension from its
name. For instance, if the SVG icon name is cmdAppInstall24.svg, it can be inserted as AppInstall.
When icons are used for screens and modules, the following rule must be followed:
• svg cmd icons must be used for any Module,
• svg type icons must be used for any Screen.
If this rule is not followed, the Runtime app will display a default icon indicating the error, in the navigation
bar.

FontAwesome (deprecated)
FontAwesome is a third-party software, which provides icons that can be used in UIs.
See http://fontawesome.github.io/Font-Awesome/cheatsheet/ for the full list of icons that are currently supported
(currently only the icons included in the currently supported release of FontAwesome, see Using Third-Party
Components).

Sit icons (deprecated)


Sit icons can be used in components and modules.
The sit class must always be specified, followed by the icon class, for example:

sit sit-active

They are currently displayed in:

Area Where

Item Tiles In the image property of the tileContent object.

Command Bar In the sit-icon attribute.


The following icons are provided by default:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 425


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

426 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.1.4 Using Third-Party Components


To develop Opcenter Execution Foundation user interfaces, you can use the UI Framework (automatically installed
during the Opcenter Execution Foundation installation) which is built on top of key third-party software.

Technology you must know about


It is essential you know about this third-party technology to develop UIs:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 427


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Third Party Software Supported Details


Version

AngularJS 1.6.9 AngularJS is the web-application framework on which


the UI architecture is based and is used to build single-
page applications.
If you want to know how to use AngularJS, go to
https://code.angularjs.org/1.6.9/docs/api.

Angular UI Bootstrap 3.0.6 Angular UI Bootstrap provides a set of AngularJS


directives for the common Bootstrap javascript
component. For further information go to http://
angular-ui.github.io/bootstrap/.
From SIMATIC IT UAF 1.2, the new versions of Angular
UI Bootstrap included in the UI Framework introduces
some incompatibilities with previous versions, as the
uib prefix has been added to all directives and
services, so, for example, the accordion directive
becomes uib-accordion, and so on.
If users used these third-party components directly in
their custom UI Components and UI Modules, they
have to migrate their code following UI Bootstrap's
own migration guide: https://github.com/angular-ui/
bootstrap/wiki/Migration-guide-for-prefixes.
A wrapper is provided by the UI Framework for the
uib-tab and uib-tabset widgets.

Angular UI Router 0.4.3 UI Router is a library that substitutes the router


supplied by Angular by default. The UI Router allows
you to manage your application as a group of states,
by specifying for each state which parts of interface
must change and how.
All UIs use the UI Router to define the states of the
various UI Modules.

FontAwesome 4.7.0 FontAwesome is a font that defines all icons that can
be used inside UIs.
If you want to know how to use FontAwesome go to
http://fortawesome.github.io/Font-Awesome/.

Beneficial technology
It may be beneficial for you to know about this technology, as it could be useful for more fine-grained
customization:

428 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Third Party Software Supported Details


Version

angular-nvd3 1.0.9 angular-nvd3 may be useful for implementing


particular functionalities, such as rendering
different types of charts.

Angular Translate 2.17.0 Angular Translate may be useful for localizing UIs.

Bootstrap 4.4.1 Bootstrap is a free collection of tools for creating


websites and web applications.
Bootstrap may be useful for implementing
particular functionalities, such as customizing the
layout.

CodeMirror 5.34.0 Javascript web-based code editor.

moment 2.20.1 moment may be useful for implementing


particular functionalities, such as managing dates
and time.

Moment Timezone 0.5.14 Javascript library for timezone management.

Common Siemens Components


Third Party Software Supported Details
Version

SWAC 1.5.1 The Siemens Web Application Collaboration (SWAC)


library is a JavaScript library designed to simplify
and standardize the development of Siemens
“mash-up” web applications.
SWAC may be useful for integrating third-party SWAC
components.

2.2.4.1.5 UI Theme Color Definition


You will need to create at least one main custom stylesheet per theme (in this case two, one for the light and one for
the dark theme), and name the CSS files according to the following naming convention: <Prefix>.<AppName>-
<Theme>.css, for example Siemens.DemoApp-Light.css.
You can use the LESS variables below as bases for your own stylesheet if you plan to use the LESS pre-processor.

Standard Color Palette


This is the color palette used for both dark and light themes.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 429


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

@natural-blue-light: #55a0b9;
@natural-blue-dark: #006487;
@natural-blue-2: #004664;
@natural-blue-5: #2882a0;
@natural-blue-7: #73b4c8;
@natural-blue-8: #8cc3d2;
@natural-blue-9: #afd7e1;
@natural-blue-10: #cde6eb;
@pure-white: #ffffff;
@pure-black: #000000;
@pure-black-1: #1e1e1e;
@pure-black-2: #323232;
@pure-black-3: #464646;
@pure-black-4: #5a5a5a;
@pure-black-6: #828282;
@pure-black-8: #AAAAAA;
@pure-black-9: #bebebe;
@pure-black-10: #dcdcdc;
@pure-black-11: #f0f0f0;

Light Theme
These are the LESS variables that can be used for the light theme.

430 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

@main-background: @pure-white;
@chromeless-toolbar-background: @pure-white;
@toolbar-background: @pure-black-11;
@appbar-background: @pure-black-11;
@card-background: @pure-black-11;
@dialog-background: @pure-black-11;
@panel-background: @pure-black-11;
@low-contrast-toolbar-background: @pure-black-11;
@dialog-header-background: @natural-blue-light;
@panel-header-background: @natural-blue-light;
@dialog-header-text-foreground: @pure-white;
@panel-header-text-foreground: @pure-white;
@high-contrast-toolbar-background: @pure-black-10;
@chromeless-selected-tab-text-foreground: @natural-blue-5;
@chromeless-unselected-tab-text-foreground: @natural-blue-light;
@line-foreground-1: @pure-black-8;
@line-foreground-2: @pure-black-6;
@line-foreground-3: @pure-black-4;
@line-foreground-4: @pure-black-2;
@high-contrast-table-header-background: @main-background;
@high-contrast-table-primary-row-background: @pure-white;
@high-contrast-table-alternate-row-background: @pure-black-11;
@high-contrast-table-divider-line-foreground: @pure-black-8;
@high-contrast-table-header-divider-line-foreground: @pure-black-8;
@low-contrast-table-header-background: @main-background;
@low-contrast-table-primary-row-background: @pure-white;
@low-contrast-table-alternate-row-background: #fafafa;
@low-contrast-table-divider-line-foreground: @pure-black-8;
@low-contrast-table-header-divider-line-foreground: @pure-black-8;
@drop-shadow-background: @pure-black;
@page-title-text-foreground: @natural-blue-2;
@group-title-read-only-text-foreground: @pure-black-4;
@group-title-clickable-text-foreground: @natural-blue-dark;
@clickable-text-foreground: @natural-blue-dark;
@body-text-foreground: @pure-black-1;
@read-only-text-foreground: @pure-black-4;
@disabled-text-foreground: @pure-black-8;
@pressed-selection-background: @natural-blue-10;
@hover-selection-background: @natural-blue-9;
@secondary-selection-background: @natural-blue-8;
@primary-selection-background: @natural-blue-7;
@primary-selection-text-foreground: @pure-black-1;
@focus-selection-background: @natural-blue-7;
@button-inactive-background: @pure-black-10;
@button-inactive-text-foreground: @pure-black-8;
@button-inactive-border-foreground: @pure-black-8;
@button-default-background: transparent;
@button-default-text-foreground: @pure-black-1;
@button-default-border-foreground: @pure-black-8;
@button-primary-background: @natural-blue-light;
@button-primary-text-foreground: @pure-white;
@button-primary-border-foreground: @pure-black-8;

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 431


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

@button-hover-background: @hover-selection-background;
@button-hover-text-foreground: @pure-black-1;
@button-hover-border-foreground: @pure-black-8;
@button-pressed-background: @pressed-selection-background;
@button-pressed-text-foreground: @pure-black-1;
@button-pressed-border-foreground: @pure-black-8;
@link-text-foreground: @natural-blue-dark;
@link-text-hover-foreground: @natural-blue-light;
@link-text-active-foreground: @natural-blue-9;
@input-default-text-foreground: @pure-black;
@input-default-background: @main-background;
@input-default-border-foreground: #e6e6e6;
@input-hover-border-foreground: @natural-blue-9;
@input-focus-border-foreground: @natural-blue-7;
@input-invalid-border-foreground: @status-error;
@input-dirty-background: #fff7bd;
@input-readonly-background: @pure-black-10;
@warning-background: @status-caution;
@warning-text-foreground: @pure-black-1;
@title-text-foreground: @natural-blue-dark;
@logo-text-foreground: #009999;
@admonition-color: @functional_gray_dark;
@admonition-warning-background: #FFDCD7;
@admonition-warning-border: #C55D3F;
@admonition-note-background: #FFF1D7;
@admonition-note-border: #EC9415;
@admonition-info-background: #D7E3FF;
@admonition-info-border: #659AF7;
@admonition-tip-background: #D7FFD9;
@admonition-tip-border: #54BD51;

Dark Theme
These are the LESS variables that can be used for the dark theme.

432 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

@main-background: @pure-black-4;
@chromeless-toolbar-background: @pure-black-4;
@toolbar-background: @pure-black-3;
@appbar-background: @pure-black-3;
@card-background: @pure-black-6;
@dialog-background: @pure-black-3;
@panel-background: @pure-black-3;
@low-contrast-toolbar-background: @pure-black-3;
@dialog-header-background: @pure-black-2;
@panel-header-background: @pure-black-2;
@dialog-header-text-foreground: @pure-white;
@panel-header-text-foreground: @pure-white;
@hight-contrast-toolbar-background: @pure-black-2;
@chromeless-selected-tab-text-foreground: @natural-blue-9;
@chromeless-unselected-tab-text-foreground: @pure-black-9;
@line-foreground-1: @pure-black-10;
@line-foreground-2: @pure-black-8;
@line-foreground-3: @pure-black-6;
@line-foreground-4: @pure-black-4;
@high-contrast-table-header-background: @pure-black-2;
@high-contrast-table-primary-row-background: @pure-black-4;
@high-contrast-table-alternate-row-background: @pure-black-3;
@high-contrast-table-divider-line-foreground: @pure-black-2;
@high-contrast-table-header-divider-line-foreground: @pure-black-2;
@low-contrast-table-header-background: @pure-black-3;
@low-contrast-table-primary-row-background: @pure-black-4;
@low-contrast-table-alternate-row-background: #555555;
@low-contrast-table-divider-line-foreground: @pure-black-3;
@low-contrast-table-header-divider-line-foreground: @pure-black-4;
@drop-shadow-background: @pure-black;
@page-title-text-foreground: @pure-white;
@group-title-read-only-text-foreground: @pure-black-8;
@group-title-clickable-text-foreground: @pure-black-9;
@clickable-text-foreground: @pure-black-9;
@body-text-foreground: @pure-white;
@read-only-text-foreground: @pure-black-8;
@disabled-text-foreground: @pure-black-6;
@pressed-selection-background: @natural-blue-5;
@hover-selection-background: @natural-blue-light;
@secondary-selection-background: @natural-blue-8;
@primary-selection-background: @natural-blue-10;
@primary-selection-text-foreground: @pure-black-1;
@focus-selection-background: @natural-blue-10;
@button-inactive-background: @pure-black-8;
@button-inactive-text-foreground: @pure-black-6;
@button-inactive-border-foreground: @pure-black-6;
@button-default-background: transparent;
@button-default-text-foreground: @pure-white;
@button-default-border-foreground: @pure-black-6;
@button-primary-background: @natural-blue-dark;
@button-primary-text-foreground: @pure-white;
@button-primary-border-foreground: @pure-black-6;

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 433


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

@button-hover-background: @hover-selection-background;
@button-hover-text-foreground: @pure-black-1;
@button-hover-border-foreground: @pure-black-6;
@button-pressed-background: @pressed-selection-background;
@button-pressed-text-foreground: @pure-black-1;
@button-pressed-border-foreground: @pure-black-6;
@link-text-foreground: @natural-blue-8;
@link-text-hover-foreground: @natural-blue-light;
@link-text-active-foreground: @natural-blue-7;
@input-default-text-foreground: @pure-white;
@input-default-background: @pure-black-2;
@input-default-border-foreground: #7e7e7e;
@input-hover-border-foreground: @natural-blue-8;
@input-focus-border-foreground: @natural-blue-10;
@input-invalid-border-foreground: @status-error;
@input-dirty-background: #00374b;
@input-readonly-background: @pure-black-4;
@warning-background: @status-caution;
@warning-text-foreground: @pure-black-1;
@title-text-foreground: @pure-white;
@logo-text-foreground: @pure-white;
@admonition-color: @functional_gray_dark;
@admonition-warning-background: #FFDCD7;
@admonition-warning-border: #C55D3F;
@admonition-note-background: #FFF1D7;
@admonition-note-border: #EC9415;
@admonition-info-background: #D7E3FF;
@admonition-info-border: #659AF7;
@admonition-tip-background: #D7FFD9;
@admonition-tip-border: #54BD51;

Legacy LESS Variables


Prior to version 2.0 of SIMATIC IT UAF, a different set of LESS variables was published. If you used those variables in
your LESS code, you can either refactor your code to use the new variables, or re-map them to the new variables, as
follows:

434 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

@button_active: @button-pressed-background;
@button_active_alternate: @button-primary-background;
@button_highlight_alternate: @button-hover-background;
@button_pressed_alternate: @button-pressed-background;
@button_face: @button-default-text-foreground;
@button_disabled: @button-inactive-background;
@button_disabled_text: @button-inactive-text-foreground;
@button_highlight: @button-hover-background;
@button_highlight_text: @button-hover-text-foreground;
@button_inactive: @button-inactive-background;
@button_inactive_text: @button-inactive-text-foreground;
@button_pressed: @button-pressed-background;
@button_pressed_text: @button-pressed-text-foreground;
@button_selected: @button-pressed-background;
@button_selected_text: @button-pressed-text-foreground;
@button_text: @button-default-text-foreground;
@control: @dialog-background;
@control_active: @dialog-header-background;
@control_background: @dialog-background;
@control_dark: @dialog-background;
@control_light: @dialog-background;
@control_text: @body-text-foreground;
@control_text_active: @body-text-foreground;
@control_text_dark: @body-text-foreground;
@control_text_light: @body-text-foreground;
@control_text_read_only: @button-inactive-text-foreground;
@dialog_background: @dialog-background;
@dialog_background_light: @dialog-background;
@dialog_border: @dialog-background;
@dialog_text: @body-text-foreground;
@login_dialog_background: @dialog-background;
@login_dialog_background_light: @dialog-background;
@login_dialog_heading_text: @body-text-foreground;
@login_dialog_information_text: @body-text-foreground;
@login_dialog_text: @body-text-foreground;
@item-tile-background: @card-background;
@tile_background: @card-background;
@tile_foreground: @body-text-foreground;
@tile_highlight: @hover-selection-background;
@toolbar_background: @toolbar-background;
@toolbar_foreground: @body-text-foreground;
@window_background: @main-background;
@window_text: @body-text-foreground;
@menu_background: @panel-background;
@menu_border: @panel-background;
@menu_foreground: @body-text-foreground;
@menu_highlight: @hover-selection-background;
@menu_highlight_text: @button-hover-text-foreground;
@menu_pressed: @pressed-selection-background;
@menu_pressed_text: @button-pressed-text-foreground;
@menu_selected: @pressed-selection-background;
@menu_selected_text: @button-pressed-text-foreground;

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 435


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

@menu_text: @body-text-foreground;
@notificationtile_shadow: @drop-shadow-background;
@sidebar_background: @toolbar-background;
@sidebar_border: @toolbar-background;
@sidebar_checked: @toolbar-background;
@sidebar_check_mark: @primary-selection-background;
@sidebar_checked_text: @body-text-foreground;
@sidebar_foreground: @body-text-foreground;
@sidebar_highlight: @button-hover-background;
@sidebar_highlight_text: @button-hover-text-foreground;
@sidebar_pressed: @pressed-selection-background;
@sidebar_pressed_text: @button-pressed-text-foreground;
@sidebar_selected: @pressed-selection-background;
@sidebar_selected_text: @button-pressed-text-foreground;
@sidebar_text: @body-text-foreground;
@grid_aggregate_text: @body-text-foreground;
@page-hyperlink: @link-text-foreground;
@page-text-highlight: @link-text-hover-foreground;
@header-border-bottom: @panel-header-background;
@code-background: @panel-background;
@code-color: @body-text-foreground;
@page-title-color: @title-text-foreground;
@common-layout-border : @main-background;

2.2.4.1.6 Invoking Commands from UIs


To retrieve data from entities or execute commands exposed on the Service Layer, you can use the
common.services.runtime.backendService Presentation Service (documented in the Opcenter Execution
Foundation UI Framework Reference) provided by the Opcenter Execution Foundation UI Framework.
Using this service provides some advantages over AngularJS $http and $resource, such as:
• authentication management (authentication is managed at framework level, and all requests after a successful
login will contain a valid authentication token, needed to access the Service Layer).
• automatic management of backend errors.
• automatic management of busy indicators.

Application command exposition on the Service Layer


Business commands exposed on the Application Service Layer are identified by the name of the App they belong to
and the name you have assigned while importing them in the Public Object Model.
Commands that are published in Extension Apps are identified by the name of the Base app they refer to and by the
name assigned in Project Studio.
Composite commands created in the Extension Apps are identified by the name of the Extension App and by the
name assigned in Project Studio.
Command invocation permissions are governed by the role configurations.
For errors returned by the Service Layer see Service Layer HTTP Error Status Codes.

Engineering command exposition on the Service Layer

436 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Engineering commands that allow you to associate users and groups with roles are also exposed on the Service
Layer and can be retrieved by a dedicated service (see common.services.runtime.backendService in the Opcenter
Execution Foundation UI Framework Reference) in order to develop UI pages that must display and handle
information related to users, groups and roles.
For more information on engineering commands and entities, start with navigating to the PublicGroup Entity in the
Engineering Model Reference Guide.
To be able to invoke these commands, a user must belong to a specific system role, and be assigned with the proper
permissions.

Example
Consider a CreateContainer command, with the following parameters:

Name Type

Name string

Location string

Product string
To execute this command based on user input, define a new state (with its own controller and template) within an
existing UI Module. Typically this state would be triggered by a button in another state (for example a state
displaying a list of containers) and opened in a side panel. In this case, the template should contain a Property Grid
and the buttons to save data or cancel:

1 <div>
2 <button ng-click="vm.cancel()" class="btn side-panel-button">Cancel</
button>
3 <button ng-click="vm.save()" class="btn side-panel-button" ng-
show="vm.validInputs">Save</button>
4 <div style="clear:both"></div>
5 <sit-property-grid sit-layout="Vertical"
6 sit-type="Fluid"
7 sit-mode="edit"
8 sit-columns="1">
9 <sit-property sit-widget="sit-text"
10 sit-value="vm.currentItem.Name"
11 sit-validation="{required: true}">Name:</sit-
property>
12 <sit-property sit-widget="sit-text"
13 sit-value="vm.currentItem.Product"
14 sit-validation="{required: true, pattern: '^P-\
\d{4}$'}">Product:</sit-property>
15 <sit-property sit-widget="sit-text"
16 sit-value="vm.currentItem.Location"
17 sit-validation="{required: true}">Location:</sit-
property>
18 </sit-property-grid>
19 </div>

In the controller, the save() method is used to execute the command and:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 437


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• return to the previous state if successful


• display an error within a message overlay in case of failure
The actual request to execute the command is sent by the invoke() method exposed by
the common.services.runtime.backendService service:

1 (function () {
2 'use strict';
3 angular.module('Siemens.DemoApp.MasterData')
4 .controller('ContainerMgtaddCtrl',
5 [ '$state',
6 '$scope',
7 'common.services.sidePanel.service',
8 'common.services.runtime.backendService',
9 function ( $state,
10 $scope,
11 sidePanelManager,
12 backendService) {
13 var self = this;
14 self.currentItem = {};
15 self.validInputs = false;
16 self.save = function () {
17 var commandModel = {};
18 commandModel.appName = "myApp";
19 commandModel.commandName = "CreateContainer";
20 commandModel.params = self.currentItem;
21 backendService.invoke(commandModel).then(function
(data) {
22 $state.go('^', {}, { reload: true });
23 }, backendService.backendError);
24 };
25 self.cancel = function () {
26 sidePanelManager.close();
27 $state.go('^');
28 };
29 $scope.$on('sit-property-grid.validity-changed', function (event,
params) {
30 self.validInputs = params.validity;
31 });
32
33 self.init = function () {
34 sidePanelManager.setTitle('Add');
35 sidePanelManager.open('e');
36 };
37 init();
38 }])
39
40 }());

 • The Save button is only displayed if valid data is entered in the form.
• The parameters on the command are collected from the view in the currentItem object.

438 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.1.7 Executing Queries from UIs


You can run queries on the business data exposed on the Service Layer, either by invoking the Reading Functions
(i.e. predefined queries modeled in Project Studio and exposed on the Service Layer) or by using the Opcenter
Execution Foundation UI Framework Presentation Services to implement oData queries (for more information, see
common.services.runtime.backendService in the Opcenter Execution Foundation UI Framework Reference.
Using this service provides some advantages over AngularJS's $http and $resource, such as:
• authentication management (authentication is managed at framework level, and all requests after a successful
login will contain a valid authentication token, needed to access the Service Layer).
• automatic management of backend errors.
• automatic management of busy indicators.

Application entity exposition on the Service Layer


Business entities exposed on the Application Service Layer are identified by the name of the App they belong to and
the name you have entered while importing them in the Public Object Model.
If you have renamed an entity with another name, the entity will be exposed with this last name.
Also entities imported from Opcenter EX FN internal views or referenced from external data sources have the name
assigned during their import in the Public Object Model.

 Before implementing queries on entities, verify that the required permissions have been given in the role
configurations. Here you can assign permissions on entities specifying artifacts that belong either to the
reading model of Functional Block domains or to the POM Models of Apps. Consequently, you must be
careful when assigning permissions to entities you want to query, since reading operations will only be
allowed on the explicitly specified data models. Keep in mind that from web applications you can only
access the POM Model entities, exposed on the Service Layer.

Engineering entity exposition on the Service Layer


Engineering entities, such as users, groups and roles are also exposed on the Service Layer and can be retrieved by a
dedicated service (see common.services.runtime.SystemDataService in the Opcenter Execution Foundation UI
Framework Reference) in order to develop UI pages that must display such information.
For more information on engineering commands and entities, start with navigating to the PublicGroup Entity in
the Engineering Model Reference Guide.
To be able to query these entities, the user must belong to a specific system role, and be assigned with the proper
permissions.

Troubleshooting
For errors returned by the Service Layer see page Service Layer HTTP Return Code Statuses.
If while executing queries, the system returns an error related either to the maximum number of allowed nodes or
expand expressions, see section Applying Custom Configurations to the Opcenter EX FN Service Layer.

Example
Consider a simple entity called Container with the following properties:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 439


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Name Type

Name string

Location string

Product string

Quantity decimal

To query this entity and display data in a grid, define a new state (with its own controller and template) within an
existing UI Module. The template in this case can simply contain an Item Collection Viewer widget:

1 <div class="content-area content-area-relative" style="height: calc(100% -


50px) !important" id="itemlist">
2 <sit-item-collection-viewer sit-data="vm.viewerData" sit-
options="vm.viewerOptions"></sit-item-collection-viewer>
3 </div>

In the controller, the code in the init() method is used to retrieve data from the Service Layer and populate the grid
using the viewerData collection:

440 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Example of data retrieval

1 (function () {
2 'use strict';
3 angular.module('Siemens.DemoApp.MasterData')
4 .controller('ContainerMgtCtrl',
5 ['$state',
6 '$rootScope',
7 'common.services.runtime.backendService',
8 function ($state,
9 $rootScope,
10 backendService) {
11 var self = this;
12
13 self.viewerOptions = {
14 selectionMode: 'single',
15 containerID: 'itemlist',
16 viewOptions: 'gml',
17 viewMode: 'g',
18 quickSearchOptions: { enabled: true, field: 'Name' },
19 sortInfo: {
20 field: 'Name',
21 direction: 'asc',
22 fields: ['Name', 'Product', 'Quantity']
23 },
24 groupFields: ['Product'],
25 gridConfig: {
26 columnDefs: [
27 { field: 'Name' },
28 { field: 'Product' },
29 { field: 'Quantity' }
30 ]
31 },
32 image: 'fa-cube',
33 tileConfig: {
34 titleField: 'Name'
35 }
36 };
37
38 self.init = function () {
39 var options =
"$select=Name,Product,Quantity&$filter=Quantity gt 0"
40 var queryModel = {};
41 queryModel.appName = "myApp";
42 queryModel.entityName = "Container";
43 queryModel.options = options;
44 backendService.findAll(queryModel).then(function (data) {
45 if ((data) && (data.succeeded)) {
46 self.viewerData = data.value;
47 } else {
48 self.viewerData = [];
49 }

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 441


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

50 }, backendService.backendError);
51 };
52 self.init();
53 }])
54 }());

In this case, the findAll() method of the common.services.runtime.backendService is used to retrieve all
containers (only their Name, Product, and Quantity fields) whose Quantity is greater than 0.

2.2.4.1.8 Executing Queries on Archived Entities


Archived entities are entities that are copied from the Opcenter EX FN database to the archiving database according
to the enabled archiving rule, and if the archiving database is properly configured.
Archived entities are exposed on the Application Archiving Service Layer and only from this Service Layer they can
be queried via OData. Indeed, the platform does not expose any reading APIs inside Command Handlers, Event
Handlers or Reading Functions.
To properly run OData queries on the archived data, you can use within the code of your UIs the
common.services.runtime.backendService findAllArchiving method documented in the Opcenter Execution
Foundation UI Framework Reference.
Using the UI Framework provides some advantages over AngularJS's $http and $resource, such as:
• authentication management (authentication is managed at framework level, and all requests that arrive after a
successful login will contain a valid authentication token, needed to access the Service Layer).
• automatic management of backend errors.
• automatic management of busy indicators.

Archived application entities' exposition on the Application Archiving Service


Layer
The archived application entities are identified by the same information that is exposed on the Application Service
Layer for the application entities.
To access the archived entities you must belong to the same role configurations that grant you access to the
corresponding application entities.
For more information on the archived entity types, see What is Maintenance.

Troubleshooting
For errors returned by the Service Layer see Opcenter EX FN Service Layer HTTP Return Code Statuses.
If while executing queries, the system returns an error related either to the maximum number of allowed nodes or
expand expressions, see Applying Custom Configurations to the Opcenter EX FN Service Layer.

Example
Consider a simple entity called Container with the following properties:

Name Type

Name string

442 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Name Type

Location string

Product string

Quantity decimal

To query this entity and display data in a grid, define a new state (with its own controller and template) within an
existing UI Module. The template in this case can simply contain an Item Collection Viewer widget:

1 <div class="content-area content-area-relative" style="height: calc(100% -


50px) !important" id="itemlist">
2 <sit-item-collection-viewer sit-data="vm.viewerData" sit-
options="vm.viewerOptions"></sit-item-collection-viewer>
3 </div>

In the controller, the code in the init() method is used to retrieve data from the Application Archiving Service
Layer and populate the grid using the viewerData collection:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 443


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Example of data retrieval

1 (function () {
2 'use strict';
3 angular.module('Siemens.DemoApp.MasterData')
4 .controller('ContainerMgtCtrl',
5 ['$state',
6 '$rootScope',
7 'common.services.runtime.backendService',
8 function ($state,
9 $rootScope,
10 backendService) {
11 var self = this;
12
13 self.viewerOptions = {
14 selectionMode: 'single',
15 containerID: 'itemlist',
16 viewOptions: 'gml',
17 viewMode: 'g',
18 quickSearchOptions: { enabled: true, field: 'Name' },
19 sortInfo: {
20 field: 'Name',
21 direction: 'asc',
22 fields: ['Name', 'Product', 'Quantity']
23 },
24 groupFields: ['Product'],
25 gridConfig: {
26 columnDefs: [
27 { field: 'Name' },
28 { field: 'Product' },
29 { field: 'Quantity' }
30 ]
31 },
32 image: 'fa-cube',
33 tileConfig: {
34 titleField: 'Name'
35 }
36 };
37
38 self.init = function () {
39 var options =
"$select=Name,Product,Quantity&$filter=Quantity gt 0"
40 var queryModel = {};
41 queryModel.appName = "myApp";
42 queryModel.entityName = "Container";
43 queryModel.options = options;
44 backendService.findAllArchiving(queryModel).then(function
(data) {
45 if ((data) && (data.succeeded)) {
46 self.viewerData = data.value;
47 } else {
48 self.viewerData = [];

444 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

49 }
50 }, backendService.backendError);
51 };
52 self.init();
53 }])
54 }());

In this case, the findAllArchiving method of the common.services.runtime.backendService is used to retrieve all
archived containers (actually, only the Name, Product, and Quantity fields of these containers) whose Quantity is
greater than 0.

2.2.4.1.9 Invoking Reading Functions from UIs


To invoke reading functions exposed on the Service Layer, you can use the
common.services.runtime.backendService Presentation Service (documented in the Opcenter Execution
Foundation UI Framework Reference) provided by the Opcenter Execution Foundation UI Framework.
Using this service provides some advantages over AngularJS's $http and $resource, such as:
• authentication management (authentication is managed at framework level, and all requests after a successful
login will contain a valid authentication token, needed to access the Service Layer).
• automatic management of backend errors.
• automatic management of busy indicators.

Application reading function exposition on the Service Layer


Reading functions exposed on the Application Service Layer are identified by the name of the App they belong to
and their name.
Reading function execution permissions are governed by the role configurations.
For errors returned by the Service Layer see Service Layer HTTP Error Status Codes.

Example
Consider a getItems reading function, belonging to the ReadFunApp App, with the following parameter:

Name Type

Category string

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 445


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
var myapp = angular.module('siemens.simaticit.common').controller('businessDataSv
cExampleController', businessDataController);;
businessDataController.$inject = ['common.services.runtime.backendService',
'$translate', 'common.widgets.busyIndicator.service',
'common.widgets.messageOverlay.service'];
function businessDataController(businessData, $translate, busyIndicatorService,
messageOverlayService) {
var bd = this;
bd.functionName = 'getItems';
bd.params = {category : "cate1"};
bd.appName = 'ReadFunApp';
bd.options = '$top1';
bd.result = '';
bd.read = function () {
busyIndicatorService.show();
bd.result = null;
var object = {
"appName": bd.appName,
"functionName": bd.functionName,
"params": bd.params,
"options": bd.options,
};
businessData.read(object).then(function (data) {
bd.result = data;
busyIndicatorService.hide();
}, function (error) {
busyIndicatorService.hide();
messageOverlayService.set({
buttons: [{
id: 'ok',
displayName: 'OK',
onClickCallback: function () {
messageOverlayService.hide();
}
}],
title: "Backend Data Error",
text: error.data.error.errorCode + ' - ' +
error.data.error.errorMessage
});
messageOverlayService.show();
});
}
// Invoke the reading function;
bd.read();
}
})();

446 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.1.10 Subscribing to a Signal


Once artifacts have been published to signals, and the solution that contains them has been deployed and started,
the Opcenter Execution Foundation infrastructure (in particular, the Signal Manager, which is hosted on the
application worker) is ready to listen to the events that arrive on the Manufacturing Service Bus and transform them
into signals, if there are clients that have subscribed to them. You can monitor the status of the Signal Manager
component in the Worker Monitor application and analyze its execution traces within Trace Viewer by using the
dedicated data provider.
To implement the subscription from your code, you must use the
common.services.runtime.backendService Presentation Service (documented in the Opcenter Execution
Foundation UI Framework Reference) exposed by the Opcenter Execution Foundation UI Framework.
When the Opcenter Execution Foundation infrastructure receives the subscription from an authorized user, it
transforms the event into a signal and sends it to the client via the websocket protocol.
You can set the subscription filters by querying on signal properties.
This page provides you with:
• an implementation example
• a troubleshooting note

Signal exposition on the Service Layer


Signals exposed on the Application Service Layer are identified by the name of the App they belong to and the same
name you have assigned during the artifact publication phase. If you have renamed the signal during this phase, the
signal will be published with this last name.

Signal subscription permissions are governed by the role configurations.

Example
Model project example
The POM of an App, called "MyApp" contains an entity (MyEntity), a signal (MySignal) and a command
(PopulateMyEntity):
• Entity: MyEntity contains
• Property1
• Property2
• Property3
• Signal: MyEntity has been promoted to MySignal. This means that each time MyEntity is modified and
a CommittedEvent is fired, the information related to the entity changes will be sent to the client.
UI project example
The UI screen contains:
• a button for connecting to the app
• a button for subscribing to the signal
• a grid which displays the entity data
• a button for unsubscribing from the signal
• a button for reconnecting to the app
• a button for disconnecting from the app
Connect button

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 447


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

This button handler calls the connectSignals method of the common.services.runtime.backendService, which
opens the web socket connection for the App.

// Function to be executed for web socket connection to the app


self.connectButtonHandler= function () {
// Input Parameter for connectSignals method
var appName = 'MyApp';
var onConnectionError = onConnectionError;
backendService.connectSignals(appName,onConnectionError).then(function () {
console.log("Connection to Signal happened successfully");
}, function (error) {
console.log("Error while connecting to the signal. \n" +
angular.toJson(error, true));
});
};

In case of errors on the connection, the onConnectionError will be called.

// callback in case of errors with connection to the web socket


function onConnectionError () {
console.log('connection to the web socket failed');
}

Subscribe button
This button handler calls the subscribe method of the common.services.runtime.backendService and subscribes
to the specified signal. If the web socket connection to the app doesn't exist then a new web socket connection is
established and then subscription to the specified signal is obtained, returning the Connection Id of the
subscription. This connection Id is used for unsubscribing the Signal.

448 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

// Function to be executed for subscribing the Signal


self.subscribeButtonHandler = function () {
// Input Parameter for subscribe method
var connectionObj = {
appName: 'MyApp',
signalName: 'MySignal',
options: '',
onMessage: onMessage,
onComplete: onComplete,
onSubscriptionError: onSubscriptionError,
onConnectionError : onConnectionError
};
backendService.subscribe(connectionObj).then(function (id) {
self.subscriptionId= id;
console.log("Subscribed to signal");
}, function (error) {
console.log("Error while subscribing to the signal. \n" + angular.toJson(error,
true));
});
};

In this example the onMessage callback receives a piece of data for each row added to the entity instance and
populates the grid accordingly. The grid must be bound to an array on which you will push the data using
this callback.

// callback to receive data from the signal


function onMessage(data) {
console.log(data);
self.viewerData.push({
Property1: data.Property1,
Property2: data.Property2,
Property3: data.Property3
});
self.viewerOptions.refresh();
}

If the signal stops sending messages, the onComplete callback will be called:

// callback on completion of messages from the signal


function onComplete() {
console.log("Signal '" + connectionObj.signalName + "' stopped sending
messages.");
}

In case of errors with subscribe, the onSubscriptionError callback will be called.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 449


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

// callback in case of errors with subscription to the signal


function onSubscriptionError(error) {
console.log("An error occurred: \n" + angular.toJson(error, true));
}

In case of errors on the connection, the onConnectionError is called. One can use reconnectSignals in case of web
socket connection failures (for example due to network disconnection).

// callback in case of errors with connection to the web socket


function onConnectionError(reason) {
console.log("Connection Error Callback: " + "Reason:" + reason);
};

Grid view template

450 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<div id="itemlist" class="content-area content-area-relative" style="height:


calc(100% - 30px) !important">
<sit-command-bar sit-type="action">
<!--Connect-->
<sit-command sit-icon="fa-link"
sit-name="connect"
sit-tooltip="Connect"
ng-click="vm.connectButtonHandler"
sit-label="Connect"
ng-show="true"></sit-command>
<!--Subscribe-->
<sit-command sit-icon="fa-exchange"
sit-name="subscribe"
sit-tooltip="Subscribe"
ng-click="vm.subscribeButtonHandler"
sit-label="Subscribe"
ng-show="true"></sit-command>
<!--Unsubscribe-->
<sit-command sit-icon="fa-eraser"
sit-name="unsubscribe"
ng-click="vm.unsubscribeButtonHandler"
sit-tooltip="Unsubscribe"
sit-label="Unsubscribe"
ng-show="true"></sit-command>
<!--Reconnect-->
<sit-command sit-icon="fa-sync"
sit-name="reconnect"
sit-tooltip="Reconnect"
ng-click="vm.reconnectButtonHandler"
sit-label="Reconnect"
ng-show="true"></sit-command>
<!--Disconnect-->
<sit-command sit-icon="fa-unlink"
sit-name="disconnect"
sit-tooltip="Disconnect"
ng-click="vm.disconnectButtonHandler"
sit-label="Disconnect"
ng-show="true"></sit-command>
</sit-command-bar>
<sit-item-collection-viewer sit-data="vm.viewerData" sit-options="vm.viewerOption
s"></sit-item-collection-viewer>
</div>

Grid view controller


The grid can be configured as follows:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 451


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

// the ICV can be configured as follows


self.viewerOptions = {
containerID: 'itemlist',
selectionMode: 'single',
viewOptions: '',
image: 'fa-cube',
gridConfig: {
columnDefs: [
{ field: 'Property1', displayName: 'Property 1' },
{ field: 'Property2', displayName: 'Property 2' },
{ field: 'Property3', displayName: 'Property 3' }
]
}
}

Unsubscribe button
This button handler calls the unsubscribe method of the common.services.runtime.backendService, which
removes the subscription to the specified signal.
The Parameter subscriptionId is the Id of the signal to be unsubscribed. closeWebSocket is a Boolean value to
indicate if the web socket connection has to be closed as well.

// Function to be called for unsubscribing the signal


self.unsubscribeButtonHandler = function () {
var closeWebSocket = false;
backendService.unsubscribe(self.subscriptionId, closeWebSocket).then(function
(id) {
self.closedConnectionId = id;
console.log('Unsubscribe callback');
}, function (error) {
console.log('Unsubscription error');
});
};

Reconnect button
This button handler calls the reconnectSignals method of the common.services.runtime.backendService, which
re-establishes web socket connection to the App and returns a hash mapping of the old subscription Ids to new
signal subscription Ids, and an error response object if there is one.

452 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

// Function to be executed for reconnecting the web socket


self.reconnectButtonHandler= function () {
// Input Parameter for reconnectSignals method
var appName = 'MyApp';
backendService.reconnectSignals(appName).then(function (reconnections) {
self.subscriptionHash = reconnections;
console.log("Reconnection to App web socket happened successfully");
}, function (error) {
console.log("Error while reconnecting to the signal. \n" +
angular.toJson(error, true));
});
};

Disconnect button
This button handler calls the disconnectSignals method of the common.services.runtime.backendService,
which closes the web socket connection for the App.

// Function to be executed for disconnecting the Signal


self.disconnectButtonHandler= function () {
// Input Parameter for disconnectSignals method
var appName = 'MyApp';
backendService.disconnectSignals(appName).then(function () {
console.log("DisConnection to App web socket happened successfully");
}, function (error) {
console.log("Error while disconnecting to the signal. \n" +
angular.toJson(error, true));
});
};

Troubleshooting notes
If the RabbitMQ service stops for any reason on the Opcenter EX FN host, Signal Manager closes all currently active
connections, it returns an error ("503 Service Unavailable") and it does not allow you to open any new connections
until the service is restarted. When the RabbitMQ service is unavailable, the involved Opcenter Execution
Foundation host is marked as running with errors in the Host Management page of Solution Studio.
For restarting the RabbitMQ service, see Troubleshooting RabbitMQ Start-Up Errors in the Opcenter Execution
Foundation Installation Guide.

2.2.4.1.11 Uploading Files from UIs


From client applications, you cannot directly upload a file to the file store. To do so, you must invoke a public
Command that executes the PutContent method and you must pass the base64-encoded contents of the file to
this Command. From client applications you can directly use only the GetContent and GetContentPayload
methods.
The UI project implementation description is based on the example of data modeling and code implementation
provided for attaching documents to entities.

UI project example

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 453


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

In order to add a defectImg to a partNumber from the user interface you can use a sit-file-uploader widget to
select the image and serialize the contents. This widget can be used within a sit-property-grid widget containing
also a sit-text widget to display the selected pnCode.

The markup of the view template can be similar to the following:

<div>
<button ng-click="vm.cancel()" class="btn side-panel-button">Cancel</button>
<button ng-click="vm.upload()" class="btn side-panel-button" ng-show="vm.validInp
uts">Save</button>
<div style="clear:both"></div>
<sit-property-grid sit-layout="Vertical"
sit-type="Fluid"
sit-mode="edit"
sit-columns="1">
<sit-property sit-id="Code" sit-widget="sit-textarea"
sit-value="vm.currentItem.code"
sit-validation="{ required: true }"
sit-read-only=" true">Code:</sit-property>
<sit-property sit-id="File" sit-widget="sit-file-uploader"
sit-value="vm.currentItem.file"
sit-validation="{ required: true }"
accept=vm.fileTypes>Image:</sit-property>
</sit-property-grid>
</div>

Note that:
• vm.currentItem.code will be set to the pnCode of the selected part number.
• vm.currentItem.file will be set to an object containing metadata and contents of the uploaded file.
• vm.fileTypes is set to comma-separated list of accepted content types, for example: 'image/jpeg,image/png'.

454 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Once the file has been selected, the sit-value attribute of the sit-file-uploader widget will be bound to an object
with the following properties:

Property Description

name The name of the file.

type The content type (mime type) of the file.

contents The contents of the file, base64-encoded.


Consequently, after a file is uploaded by the user, such information will be available in
the currentItem.file property within the controller. Note however that at this point the file contents are only
uploaded on the client side, in the browser, and must still be saved to the backend by calling (in this case)
the AssignDefectImg command.
To invoke this command on the backend, you can implement an upload method which is
called when the Save button is clicked:

self.upload = function () {
var obj = {
'pnCode': self.currentItem.code,
'createdBy': 'Author',
'imgBlob': self.currentItem.file.contents,
'imgId': self.currentItem.file.name,
'mimeType': self.currentItem.file.type
};
backendService.execute("AssignDefectImg", obj).then(function (data) {
$state.go('^', {}, { reload: true });
}, backendService.backendError);
}

In this case, the AssignDefectImg command is executed using the execute method of
the base.services.runtime.backendService service provided by the Opcenter Execution Foundation UI
Framework.

2.2.4.1.12 Exposing UI Modules and UI Components as SWAC Components


You can expose UI Modules and UI Components as SWAC Components in order to embed them in third-party user
interfaces.

SWAC Main Concepts


Concept Description

SWAC Container A SWAC Container is made up of a single web page whose SWAC
"contents" (components, services and wires) can be integrated and
collaborate with the "native" content of the hosting application.

SWAC Component A web UI (either third-party or Opcenter Execution Foundation) that


can be loaded by a SWAC Container.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 455


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Concept Description

SWAC Service The service provided by a SWAC Container for each of its
components.

SWAC Component Interface The public part of a SWAC Component that provides additional
functionalities that can be loaded inside a container if a container
wants to use them.

Exposing UI Components as SWAC Components


When you develop a UI Component from Project Studio, the system automatically creates the relative manifest in
order to expose the UI Component as a SWAC Component in the Mashup Editor in Solution Studio. Consequently,
you can load the SWAC Component within an empty page from the UI Application, simply opening the following
URL from the Runtime UI Application: <UIApplicationName>/swac.html/#/home/component/<AppName>/
<ComponentName>.
However you must manually configure the following, especially if you need to expose the components on third-
party systems:
• SWAC Component DPCs, correctly setting the DPC property within the UI Component manifest.
• SWAC descriptor, creating a .json file and then copying it into the swac folder of the <AppName>.UserInterface
project.

SWAC Descriptor Example

Exposing UI Modules as SWAC Components


When you develop a UI Module from Project Studio, the system automatically creates the relative manifest in order
to expose the UI Module as a SWAC Component. Consequently, you can load the SWAC Component within an empty
page from the UI Application, simply opening the following URL from the Single Page
Application: <UIApplicationName>/swac.html/#/home/<UIScreen>?exposedAsSwac=true. But in this case, the
SWAC Component is not provided with methods, events, types or DPCs.
To define methods, events, types or DPCs, you must inject
the common.services.component.swacComponentManager service in the controller of the UI State which
constitutes the "initial state" of the SWAC Component, calling a sequence of methods similar to the following
example:
1. create, initializes a new component object with the specified ID (typically, the UI Module name).
2. method, event, bind, dpc, interface, an so on, all methods used to populate the component public interface.
3. expose, once the public interface has been defined, this method simply initializes the component via the
SWAC.Hub and calls the SWAC.Hub's beginExpose method, to expose the SWAC Component.
In this scenario the URL to be opened from the Single Page Application is: <UIApplicationName>/swac.html/#/
home/<UIScreen>. The ?exposedAsSwac=true query string parameter must not be used as it is only necessary
when exposing UI Modules that do not expose any SWAC methods, events, etc.
The following example illustrates how to define and expose a new SWAC Component from within the controller of a
UI Module.

456 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Example

(function(){
myTestController.$inject = ['common.services.component.swacComponentManager'];

function myTestController(swacManager){
/* ... */

// Register a new SWAC Component for the UI Module


// Internally, each component is stored within the swacManager.components
object.
swacManager.create('Siemens.MyApp.MyModule')
// Add a method to an existing component.
.method('myMethod', function(param1, param2){ /* ... */});
// Add an event
.event('onSomething', /* ... */);
// Add a DPC
.dpc({key: key, value: value, type: type, flags: flags});
// Define a bind function for the DPCs.
.bind(function(root){ /* ... */});
// Alternatively, it should also be possible to access the public
interface of the SWAC Component as well
.interface.myMethod = function(param1, para2) { /* ... */ }; //
Overwrites the previous method definition.
.expose();
};
angular.module('Siemens.MyApp.MyModule').controller('MyTestController',
myTestController)
})();

In addition, you must manually configure the SWAC descriptor, creating a .json file and then copying it into
the swac folder of the <AppName>.UserInterface project.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 457


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

SWAC Descriptor Example

{
"mver": "1.2.0",
"swac": {
"identity": {
"name": "Component",
"version": "1.0.0",
"displayname": "Component 1.0.0",
"type": "http://CompanyName.intranet/
SWACComponent/MyComponent_1.2.0",
"flavor": "ui",
"source": "http://localhost:4000/chat"
},
"contracts": {
"api": {
"methods": {
"sendMessage": {
"description":
"helpstring",
"return": {

"type": "return type"


},
"parameters":
{

"text": {

"type": "text type"


}
}
},
"disconnect": {
"description":
"helpstring",
"return": {

"type": "return type"


},
"parameters":
{}
}
},
"events": {
"onMessage": {}
}
},
"interfaces": {
"sometest": {
"methods": {

458 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"method": {

"description": "helpstring",

"return": {

"type": "return type"


}
,

"parameters": {

"text": {

"type": "text type"

}
}
}
},
"events": {
"onEvent": {}
}
}
},
"dpc": {
"message": {
"type": "data type",
"description":
"helpstring",
"permission": "rw",
"node": "data"
},
"statistics": {
"children": {
"incoming": {

"type": "data type",

"description": "helpstring",

"permission": "rw",

"node": "data"
},
"outgoing": {

"type": "data type",

"description": "helpstring",

"permission": "rw",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 459


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"node": "data"
}
},
"node": "structure"
}
}
}
}
}

Embedding a third-party SWAC Component into a UI Module


You can embed any third-party SWAC Component into a UI Module, using the following directives provided by the
Mashup Editor:
• sit-component
• sit-container
For detailed information, refer to the relative reference documentation.

2.2.4.1.13 Integrating Custom Widgets


The sitPropertyGrid widget (documented in the Opcenter Execution Foundation UI Framework Reference) can be
configured to use custom widgets by specifying them in the sit-widget attribute, as follows:

<sit-property-grid sit-layout="Vertical"
sit-type="Fluid"
sit-mode="edit"
sit-columns="1">
<sit-property sit-widget="sit-text"
sit-value="vm.currentItem.Name"
sit-read-only="true">Name:</sit-property>
<sit-property sit-widget="sit-select-qty"
sit-value="vm.currentItem.pallets"
sit-widget-attributes="vm.selectQtyAttrs"
sit-validation="vm.palletValidation">Pallets:</sit-property>
</sit-property-grid>

In this case, the sit-select-qty is a custom widget that is not part of the Opcenter Execution Foundation UI
Framework.
Although virtually any directive can be rendered within a Property Grid, it is necessary to actually implement a
simple contract to make sure that data binding and input validation works as expected.

Example: sit-select-qty Widget


In the following example we are using a simple widget to specify the quantity of a specific product, for example the
number of pallets of a particular product to load in a container:

460 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

This widget can be created by combining an input value, displayed in a drop-down list, and a numeric input value to
enter a numeric quantity.

Custom Widget Template


The template of the sit-select-qty widget can be realized as follows:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 461


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<style>
.select-qty input {
max-width: 99%;
margin-left: 4px;
}
.select-qty input, .select-qty select {
border: none;
}
</style>
<div class="label label-property-grid-control-readonly" ng-if="vm.readOnly ||
vm.ngReadonly">
{{vm.displayValue()}}
</div>
<ng-form class="form-group"
ng-if="!(vm.readOnly || vm.ngReadonly)"
name='selectQtyForm'>

<div class='property-grid-input-group select-qty'


ng-class='((selectQtyForm.$invalid && selectQtyForm.$dirty) ||
(selectQtyForm.$invalid && selectQtyForm.$visited)) ? "validator-control-invalid" :
"validator-control"'>
<span class="input-group-btn">
<select ng-model='vm.selectionValue'
class="btn"
ng-options='val[vm.toDisplay] for val in vm.options track by
val[vm.toKeep]'
ng-required='vm.validation.required' />
</span>
<input type='number'
step="any"
class="form-control"
ng-model='vm.quantityValue'
ng-required='vm.validation.required'
ng-minlength='vm.validation.minlength'
ng-maxlength='vm.validation.maxlength'
ng-pattern='vm.validation.pattern'
ng-min='vm.validation.min'
ng-max='vm.validation.max' " />
<input type="hidden" ng-model="vm.value" ng-required="vm.validation.required"
sit-form-input-validator />
</div>
</ng-form>

As a best practice, the widget should be displayed as a simple textual label if set as read-only, so the first part of the
template is necessary to implement this behavior. The rest of the template is used to display the active graphic
control as the combination of a select and a numeric input.
To implement proper input validation, note that:
• The part of the template corresponding to the active control is wrapped in an ng-form directive.
• The two input elements are wrapped in a div element, and its class is set to validator-control or validator-
control-invalid depending on the validity of the data.
• A hidden input field is used solely to host the sitFormInputValidator directive, which is used to display a
warning icon that displays a validation error message when clicked. The reason why this directive is not used as

462 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

an attribute for either of the two input elements is because validation messages must be related to the widget
as a whole, rather than each separate input element. Also note that the ng-model value specified for this hidden
input field corresponds to the value of the whole widget.

Custom Widget Directive


The directive of the sit-select-qty widget can be realized as follows:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 463


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
var app = angular.module('Siemens.DemoApp');
function selectQtyController() {
var self = this;
self.init = function () {
self.quantityValue = self.value && self.value[self.quantity] ||
self.default || 0;
self.selectionValue = self.value;
self.value = {};
self.value[self.toKeep] = self.selectionValue[self.toKeep];
self.value[self.toDisplay] = self.selectionValue[self.toDisplay];
self.value[self.quantity] = self.quantityValue;
}

self.displayValue = function(){
if (self.value[self.toDisplay] && self.value[self.quantity]){
return self.value[self.toDisplay] + " - " +
self.value[self.quantity];
} else {
return "n/a";
}
}
}
app.controller('selectQtyController', selectQtyController);
app.directive('sitSelectQty', [function () {
return {
scope: {},
restrict: 'E',
bindToController: {
'readOnly': '=sitReadOnly',
'value': '=sitValue',
'validation': '=sitValidation',
'options': '=sitOptions',
'toDisplay': '=sitToDisplay',
'toKeep': '=sitToKeep',
'default': '=sitDefault',
'quantity': '=sitQuantity'
},

controller: 'selectQtyController',
controllerAs: 'vm',
templateUrl: 'Siemens.DemoApp/widgets/selectQty/selectQty.html',
link: function (scope, el, attrs, ctrl) {

scope.$watch("vm.selectionValue[vm.toKeep] + vm.quantityValue",
function () {
var value = {};
if (ctrl.selectionValue) {
value[ctrl.toKeep] = ctrl.selectionValue[ctrl.toKeep];
}
if (ctrl.quantityValue) {

464 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

value[ctrl.quantity] = ctrl.quantityValue;
}
ctrl.value = value;
}, true)
ctrl.init();
}
};
}]);
})();

Basically, the controller of the directive provides an initmethod to initialize the widget, and a displayValue method
to provide a textual representation of the value. In the directive, the following attributes at least must be specified
in the bindToController property to ensure proper integration with the property grid:
• sitValue, which stores the value of the widget and is used as an ng-model internally within the widget.
• sitValidation, an object containing all the validation rules defined within a sitProperty widget (documented in
the Opcenter Execution Foundation UI Framework Reference) .

2.2.4.1.14 Localizing Custom UI Apps and UI Framework Resources


UI Applications, containing App UI Screens and UI Framework resources are displayed by default in English, but you
can localize them into additional custom languages.
When logging on to the Runtime UI Application with the User Management Component (UMC), you can select one of
the default language (German, French, Simplified Chinese, Spanish, Italian, Russian, Korean and Japanese). If you
want to display custom localization languages, see How to Use Opcenter Execution Foundation in Multilanguage.
The required languages are then enabled in Solution Studio for each UI Application.
To localize custom UI Applications and UI Framework resources, see procedure below.

Prerequisites
You must have built the UserInterface project at least once.

 Json File Encoding


When opening or saving the .json files be sure not changing their default encoding that must be UTF-8.

Localizing UI Applications
1. In Solution Explorer right-click the user interface project of your App and select Open Folder in File Explorer.
2. Double-click the resources folder.
3. In this folder add a JSON file with the English language code for each group of translations in your App. Name
the file according to the naming convention <Prefix>.<AppName>.<ModuleName>.en-US.json.
4. In each JSON file enter a translation table with all the elements to be translated. Each row must consist of a key,
which acts as a translation ID, and value, which is the text which will then be translated. These elements can be
nested in nodes if required, according to the hierarchy used in your application and according to Angular
Translate settings. Name the key according to the naming convention <Prefix>_<AppName>_<ModuleName>.
The following is an example of JSON file.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 465


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

{
"Siemens_SimaticIT_Personnel_PersonnelGroupManagement": {
"assign": "Assign",
"title": "Assign Persons to Person Group"
}

5. Create a new file called resources.json in this folder.


6. Open the resources.json file and in this folder write a list of all the JSON files you have created, without the
language code, together with a unique name for each file (with no spaces), with the following format:

{
"Siemens_SimaticIT_Personnel_PersonnelGroupManagement" :
"Siemens.SimaticIT.Personnel.PersonnelGroupManagement",
"Siemens_SimaticIT_Material_MaterialLot" :
"Siemens.SimaticIT.Material.MaterialLot"
}

If the resource file name contains a special character (for example, umcIntégration.en-US.json), the special
character must be replaced by the corresponding unicode escape code (which you can find documented on
internet, for example at page https://en.wikipedia.org/wiki/List_of_Unicode_characters) preceded by a
backslash as shown in the following example:

{
"umcIntegration": "umcInt\u00E9gration"
}

7. Create a copy of each JSON file, with the corresponding language code, for each language translation you
require. Name each file according to the naming
convention <Prefix>.<AppName>.<ModuleName>.<Language>.json (e.g.<Prefix>.<AppName
>.<ModuleName>.it-IT.json).
8. Translate each element in the corresponding JSON files into the corresponding language.
9. If your module is model-driven, for all the translations you provided in the resource file, enter the translation
key corresponding to the provided translations, within the screen, content, action and field labels you need to
translate inside Model-driven editor (see Create a Model-Driven UI Module).

Localizing Framework Resources


1. In Solution Explorer right-click the user interface project of your App and select Open Folder in File Explorer.
2. Open the common\resources folder.
3. Copy all the resource files and paste them into the top level resources folder in the user interface project.
4. Repeat steps 5-8 of the above procedure to create the resources.json files and translations files.

Missing Translations
• If a translation is missing in an additional .json file, the system displays the relative English label in the localized
UI Application.
• If an additional .json file is missing, the UI Application displays the relative string keys, instead of the proper
translations.

466 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.1.15 Managing Locales


When the user logs on to the UI runtime application or to Solution Studio, the language settings that have been
specified in UMC for the user that is logging on, will also define some specific locale settings, such as the date and
time format.
These locale settings are saved in JS files in the common\scripts\i18n folder in the user interface project of the App
and are provided in the default localization languages (German, French, Simplified Chinese, Spanish, Italian,
Russian, Korean and Japanese).
If you want to provide your application with a language that is different from the default ones, you must download
the locale file corresponding to the code of the language you want to provide.

 Any modifications made to locale setting files will be applied for that locale in the entire UI Application
which uses any UI Module or UI Component of the App containing the modifications.

Selecting which locales are available in your App


1. In Solution Explorer right-click the user interface project of your App and select Open Folder in File Explorer.
2. Open the locales folder.
3. Open the locales.json file and add any locales you want to provide in your App. In the following example Italian
is specified as the available locale:

{
"it-IT": "it-IT",
"it": "it"
}

Adding new locale files


1. From the AngularJS repository, download the JS file for the required locale (for the required version, see
page Using Third-Party Components, while for the file download see https://github.com/angular/bower-
angular-i18n).
2. In Solution Explorer right-click the user interface project of your App and select Open Folder in File Explorer.
3. Open the locales folder and save the downloaded JS files in this folder.
4. Modify the locales.json in this folder, adding the new languages which will be available. In the following
example you will add Japanese as an available locale:

{
"ja-JP": "ja-JP",
"ja": "jp"
"it-IT": "it-IT",
"it": "it"
}

Modifying existing locale files


1. In Solution Explorer right-click the user interface project of your App and select Open Folder in File Explorer.
2. Open the common\scripts\i18n folder.
3. Copy the JS files you want to modify.
4. Paste the files in the locales folder of your user interface project.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 467


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

5. Make the required modifications to the files in the locales folder.

 If the same locale is present in the locales folder of the App and in the common/scripts/i18n folder, the
locale file in the locales folder has precedence)

2.2.4.1.16 Opcenter EX FN Service Layer HTTP Return Code Statuses


The Opcenter EX FN Service Layer manages HTTP transactions by returning the following HTTP status codes:

HTTP Reason Description


Status

200 OK The request has been correctly executed.

400 Bad Request The message is returned in the following cases:


• the content length of the request exceeded the maximum allowed,
• the payload of the request was not valid (e.g. a command parameter was
erroneously set),
• an error in the business logic was returned,
• the system cannot interpret the request.

401 Unauthorized The request not contain a valid authentication token.

404 Page Not The server could not find what was requested.
Found
The same status code is returned also if the HTTP request exceeds the request
limit.

500 Internal The message is returned if the internal infrastructure cannot manage the error.
Server Error

503 Service The message is returned if the Service Layer is stopped.


Unavailable
The same status code is returned also if there are user right problems.
There is the presence of app_offline.htm file under the root folder of website.

 For more information on possible corrective actions, you can refer to Applying Custom Configurations to
the Opcenter EX FN Service Layer in the Opcenter EX FN Installation Guide.

2.2.4.1.17 Applying Custom Configurations to the Opcenter EX FN Service


Layer
You can apply some custom values to the configuration file (web.config) of the Opcenter EX FN Application Service
Layer.
The web.config file can be found in the %SITUnifiedSystemRoot%svc-runtime folder.
Here you can modify the limits for file dimensions, query nodes, expand expressions, and query strings.

468 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 Migrating from Previous Versions


If you are migrating from a previous version, and you have modified the web.config file, the newer setup
version will install an updated file version, renamed in web.config.new, without overwriting the existing
file. You will find the renamed file in the same folder as the existing file.
You must manually merge any previously applied changes with the newer file version.

Modifying limits for uploading file


The default configuration of the Opcenter EX FN Application Service Layer site limits the file dimension to 100 MB.
If you want to set a different value, you must modify the following keys:

Service Layer Key Maximum Value (Bytes) Description

maxAllowedContentLength 524288000 This setting applies to the IIS web server.

maxRequestLength 512000 This setting applies to the .NET pipeline.

Modifying limits for query nodes and expand expressions


The default values of the MaxNodeCount and MaxExpansionDepth OData library keys are always overwritten by
custom keys specified for the Opcenter EX FN Application Service Layer.
The values of these keys can be specified in either of the following ways:
• by automatically applying a default value (documented here below), if you do not explicitly add the custom keys
to the web.config file,
• or by specifying the values you require in the Service Layer custom keys as follows:

Service Layer key Default Value Corresponding OData Description


library key

ServiceLayerMaxNode 150 MaxNodeCount Maximum number of nodes that


Count you can use in the OData query.
For more information see https://
www.asp.net/web-api/overview/
odata-support-in-aspnet-web-
api/odata-security-guidance

ServiceLayerMaxExpan 5 MaxExpansionDepth The maximum number of expand


sionDepth expressions on nested entities
that you can use in the OData
query.

The following is an example of web.config attributes:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 469


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<configuration>
...
<appSettings>
...
<add key="ServiceLayerMaxNodeCount" value="150" />
<add key="ServiceLayerMaxExpansionDepth" value="5" />
...
</appSettings>
...
</configuration>

Modifying limits for expanded OData queries


In case of expanded OData queries, the length of the URI might be longer than the maximum allowed value (i.e. by
default 2048 bytes), and you may need extra space for correctly implementing the entire query string, and its
arguments.
To increase the query string length, you can modify your web.config file (to be found in
%SITUnifiedSystemRoot%svc-runtime) by specifying the required values in the following sections:
• In the <system.web> section, by adding or modifying the maxQueryStringLength attribute of the
httpRuntime element.
• In the <requestFiltering> section, by adding or modifying the maxQueryString attribute of the requestLimits
element:

<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600" maxQueryString="50000" />
</requestFiltering>
</security>

Service Layer Key Default Value (Bytes) Maximum Value Description


(Bytes)

maxQueryStringLengt 2048 2097151 This setting applies to the IIS


h web server.

maxQueryString 2048 2097151 This setting applies to the .NET


pipeline.
When the request filtering configuration blocks an HTTP request because the HTTP request exceeds the request
limit, IIS will return an HTTP 404 error code to the client and will log one of the following HTTP statuses with a
unique sub-status dedicated to the reason for which the request was denied:

HTTP Sub-Status Description

404.13 The content length is too large.

404.14 The URL is too long.

404.15 The query string is too long.

470 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

For more information, refer to


• https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/requestfiltering/requestlimits/
• https://forums.asp.net/t/2037366.aspx?GET+with+large+query+data

2.2.4.1.18 Setting User Preferences


During the development phase of the UI Screens, you can enable some display preferences that allow users to
personalize the UI Screens.
Custom display modes are related to the instances of the sitItemCollectionViewer and the sitTable widgets
embedded in page. Widgets are documented in the Opcenter Execution Foundation UI Framework Reference.

What are user preferences


When user preferences are enabled, users can select which fields (i.e. entity properties) they want to make visible
and in which order the information will be available.
User preferences are currently available only in the UI screens that display data in a grid (sitItemCollectionViewer)
or in a table/tile list (sitTable).
If users are properly authorized via user role in Solution Studio, they can apply the following display preferences:
• hide or show a column in the grid
• set the column order in the grid
• hide or show properties in the tile.
The changes you apply at runtime will be internally persisted in the Opcenter EX FN database.
If you reset the settings for the grid visualization, you also reset settings for the tile visualization.
In particular, this information is stored in the UserPreference data structure and accessed internally via Reading
Function. The UserPreference entity is modeled inside the SITUASys system Functional Block, referenced by the
Opcenter EX FN System App.

 To be able to set and retrieve the user preferences (and, more in general, to update the Opcenter EX FN
database), you must make sure that the Opcenter EX FN System App is installed in your Manufacturing
Solution.
If this App is not installed, the user preferences configuration button will not be visible in the UI.

Enabling user preferences in the UI Screens


During the development phase of your UI Component, or UI Screen, you can decide whether you want to enable or
disable at runtime the user preferences for the sitItemCollectionViewer / sitTable widgets.
To do this, you must set the userPrefId attribute of the ICVOptions object to a string that uniquely identifies the
control within the screen.
For more information, refer to itemCollectionViewer in the Opcenter Execution Foundation UI Framework Reference.

Applying user preferences at runtime


If the userPrefId attribute is properly set, the button will be displayed in page and it will open an editor where
you can configure:
• Column visibility
• Column order

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 471


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Tile properties
Example of grid customization:

472 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Example of tile customization:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 473


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.1.19 Configuring Header Command Bar


You can configure the header command bar of your custom application. Usually, this command bar is for displaying
notifications and other counters, and also for any kind of Siemens Web Framework command.

Configuring Procedure
1. Add commands.
2. Update the Counter.

Adding Commands
A service called common.services.swac.SwacUiModuleManager by UI Framework provides a way to
communicate between your custom UI Application with Siemens Web Framework.
1. Inject common.services.swac.SwacUiModuleManager service in to your angular service/component to add
the commands.
2. Register the command bar context in the Siemens Web Framework as below:

1 if (this.swacManager.enabled) {
2 this.swacManager.contextServicePromise.promise.then(function
(contextSvc) {
3 contextSvc.registerCtx( 'notesByState', { editing: 8, locked:
2, obsolete: 0, total: 10 } );
4 });
5 }

3. Create the list of commands as per your application needs.

474 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1 var cmds = {
2 commands: {},
3 commandHandlers: {},
4 commandPlacements: {},
5 actions: {}
6 };
7 var statuses = ['editing', 'locked', 'obsolete'];
8 var icons = {
9 editing: 'cmdEdit',
10 locked: 'cmdLock',
11 obsolete: 'cmdObsolete'
12 };
13 var priority = 0;
14 statuses.forEach(function (status) {
15 var label = status;//_.capitalize( status );
16 var id = 'notepad' + label + 'NotesNotificationCommand';
17 cmds.commands[id] = {
18 iconId: icons[status],
19 title: 'Notes in ' + label + ' state',
20 isToggle: true,
21 template: '<div>{{ctx.notesByState.' + status + '}}</div>'
22 };
23 cmds.commandHandlers[id] = {
24 id: id,
25 action: 'load' + label + 'Notes',
26 activeWhen: { condition: 'conditions.true' },
27 enableWhen: { condition: 'conditions.true' },
28 visibleWhen: { condition: 'conditions.true' }
29 };
30 cmds.commandPlacements[id] = {
31 id: id,
32 uiAnchor: 'mom_headerBar',
33 priority: priority + 100
34 };
35 cmds.actions['load' + label + 'Notes'] = {
36 actionType: 'JSFunction',
37 method: 'navigateTo',
38 inputData: {
39 state: 'notes',
40 params: { status: status },
41 options: { reload: true }
42 },
43 deps: 'js/mom.swac.compatibility.service'
44 };
45 });
46 var allNotes = 'notepadAllNotesNotificationCommand';
47 cmds.commands[allNotes] = {
48 iconId: 'cmdNoteProperties',
49 title: 'All notes',
50 isToggle: true,
51 template: '<div>{{ctx.notesByState.total}}</div>'
52 };

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 475


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

53 cmds.commandHandlers[allNotes] = {
54 id: allNotes,
55 action: 'loadAllNotes',
56 activeWhen: { condition: 'conditions.true' },
57 visibleWhen: { condition: 'conditions.true' }
58 };
59 cmds.commandPlacements[allNotes] = {
60 id: allNotes,
61 uiAnchor: 'mom_headerBar',
62 priority: 10
63 };
64 cmds.actions.loadAllNotes = {
65 actionType: 'JSFunction',
66 method: 'navigateTo',
67 inputData: {
68 state: 'notes',
69 params: { status: null },
70 options: { reload: true }
71 },
72 deps: 'js/mom.swac.compatibility.service'
73 };

4. Call common.services.swac.SwacUiModuleManager service method to publish an event.

1 that.swacManager.eventBusServicePromise.promise.then(function
(eventBusSvc) {
2 eventBusSvc.publish( 'mom.commands.update', cmds );
3 });

Updating the Counter


Use the below code to update the counter for a specific command.

476 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1 if (this.swacManager.enabled) {
2 var that = this;
3 this.swacManager.eventBusServicePromise.promise.then(function
(eventBusSvc) {
4 eventBusSvc.event.subscribe(function (event) {
5 if (event.data.topic === 'appCtx.update' &&
event.data.data.name === 'updateCounters') {
6 _this.logger.logInfo("New context registered",
event.data.data);
7
that.swacManager.contextServicePromise.promise.then(function (contextSvc)
{
8 contextSvc.updateCtx('notesByState', { editing: 100,
locked: 2, obsolete: 0, total: 102 });
9 });
10 }
11 });
12 });
13 }

Example
The below code dynamically inserts commands into the Commands View Model of the Siemens Web Framework.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 477


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1 StudioService.prototype.subscribeApolloContainerEvents = function () {
2 var _this = this;
3 if (this.swacManager.enabled) {
4 var that = this;
5 this.swacManager.eventBusServicePromise.promise.then(function
(eventBusSvc) {
6
7 eventBusSvc.event.subscribe(function (event) {
8 if (event.data.topic === 'appCtx.update' &&
event.data.data.name === 'updateCounters') {
9 _this.logger.logInfo("New context registered",
event.data.data);
10
that.swacManager.contextServicePromise.promise.then(function (contextSvc)
{
11 contextSvc.updateCtx('notesByState', { editing:
100, locked: 2, obsolete: 0, total: 102 });
12 });
13 }
14 });
15 });
16 this.swacManager.contextServicePromise.promise.then(function
(contextSvc) {
17 contextSvc.registerCtx('notesByState', { editing: 8, locked:
2, obsolete: 0, total: 10 });
18 var cmds = {
19 commands: {},
20 commandHandlers: {},
21 commandPlacements: {},
22 actions: {}
23 };
24 var statuses = ['editing', 'locked', 'obsolete'];
25 var icons = {
26 editing: 'cmdEdit',
27 locked: 'cmdLock',
28 obsolete: 'cmdObsolete'
29 };
30 var priority = 0;
31 statuses.forEach(function (status) {
32 var label = status;//_.capitalize( status );
33 var id = 'notepad' + label + 'NotesNotificationCommand';
34 cmds.commands[id] = {
35 iconId: icons[status],
36 title: 'Notes in ' + label + ' state',
37 isToggle: true,
38 template: '<div>{{ctx.notesByState.' + status + '}}</
div>'
39 };
40 cmds.commandHandlers[id] = {
41 id: id,
42 action: 'load' + label + 'Notes',
43 activeWhen: { condition: 'conditions.true' },

478 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

44 enableWhen: { condition: 'conditions.true' },


45 visibleWhen: { condition: 'conditions.true' }
46 };
47 cmds.commandPlacements[id] = {
48 id: id,
49 uiAnchor: 'mom_headerBar',
50 priority: priority + 100
51 };
52 cmds.actions['load' + label + 'Notes'] = {
53 actionType: 'JSFunction',
54 method: 'navigateTo',
55 inputData: {
56 state: 'notes',
57 params: { status: status },
58 options: { reload: true }
59 },
60 deps: 'js/mom.swac.compatibility.service'
61 };
62 });
63 var allNotes = 'notepadAllNotesNotificationCommand';
64 cmds.commands[allNotes] = {
65 iconId: 'cmdNoteProperties',
66 title: 'All notes',
67 isToggle: true,
68 template: '<div>{{ctx.notesByState.total}}</div>'
69 };
70 cmds.commandHandlers[allNotes] = {
71 id: allNotes,
72 action: 'loadAllNotes',
73 activeWhen: { condition: 'conditions.true' },
74 visibleWhen: { condition: 'conditions.true' }
75 };
76 cmds.commandPlacements[allNotes] = {
77 id: allNotes,
78 uiAnchor: 'mom_headerBar',
79 priority: 10
80 };
81 cmds.actions.loadAllNotes = {
82 actionType: 'JSFunction',
83 method: 'navigateTo',
84 inputData: {
85 state: 'notes',
86 params: { status: null },
87 options: { reload: true }
88 },
89 deps: 'js/mom.swac.compatibility.service'
90 };
91 that.swacManager.eventBusServicePromise.promise.then(function
(eventBusSvc) {
92 eventBusSvc.publish('mom.commands.update', cmds);
93 });
94 });
95 }

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 479


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

96 };

The configured header bar in Siemens Web Framework is given below screenshot.

2.2.4.2 Code-Based Development of Standard UI Components and UI


Modules
In the UI Interface project, described below, you can develop the following UI standard elements:
• UI Components
• UI Modules

UI Project Structure
The project structure is the following:
• <Prefix>.<AppName> folder, dedicated to the development of project specific widgets, components and
modules.
• app.js, config.js, and index.html files.
The <Prefix>.<AppName> folders contain the following sub-folders:

Folder Contains...

components the code related to UI Components. There is a sub-folder for each


component which includes several .js and .html files for templates, and
additional folders for tests and samples.

config all configuration files (.js) relative to the service providers, and additional
folders for tests and samples.

fonts the web font files (in different formats).

images the image files.

modules the code related to UI Modules (and Model-Driven UI Modules) and


several .html files for layout templates. There is a sub-folder for each UI
Module which includes all the source files required by the UI Module (.js files
for controller, routing, etc. and .html for template files).

480 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Folder Contains...

resources the files regarding localization (one .json file for each available language).
For more information, see Localizing Custom UI Apps and UI Framework
Resources.

scripts third-party Javascript libraries.

services the code related to Presentation Services.

styles You can define custom stylesheets within your functional block by releasing
two CSS files (<AppName>-Light.css and <AppName>-Dark.css) and
placing them in the styles folder.

widgets the code related to UI Widgets.

2.2.4.2.1 Developing UI Components


UI components are complex widgets that work with a specific data source, for example a grid containing orders or a
chart displaying statistics about a piece of equipment.
They are the reusable building blocks of a UI Module and of a UI Application.
Components can be created by composing several back-end agnostic widgets and binding them to a specific data
source using the Presentation Services.
To allow interaction within Mashup UI Modules created in the Mashup Editor, they must expose specific APIs (i.e.
methods and events).
The App you have created in Project Studio includes a project called <AppName>.UserInterface, which contains
the files relative to the user interface. This project includes by default the <Prefix>.<AppName>/
components folder for the development of the UI Components.

Worflow
1. Create a UI Component.
2. Implement the logic in the <ComponentName>.js file, by also following:
• Implementing a UI Method in a UI Component
• Firing a UI Event from a UI Component
• Accessing Properties from a UI Component
3. Define the UI Component Template.

2.2.4.2.1.1 Creating a UI Component


For each Component you want to include in the App package perform the following operations to generate the
necessary files and then complete them inserting your code:
1. Right-click the <Prefix>.<AppName>/components folder and then select the Add > New Item command.
2. Select the UIComponent template (Visual C#\Web section).
3. Type a name in the Name edit box and click Add: the system automatically starts the UI Component Wizard.
4. Set the following parameters and then click Next:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 481


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Title The title of the Component. Maximum length 125 characters.

Description A user-friendly description for the component. Maximum length 255


characters.

Icon The identifier of the required icon (see Using Icons).

Image (Optional) The image that identifies the UI Component in the Mashup
Editor. To set the image, click the Browse button, navigate to the
required folder and then choose the image. SVG images are not
supported.

Default Settings The default size of the component.

Min Settings The minimum size of the UI Component in the Mashup editor,
expressed by the minimum number of rows and columns you want to
apply.

Max Settings The maximum size of the UI Component in the Mashup editor,
expressed by the maximum number of rows and columns you want
to apply.
5. If necessary, define the UI Component methods with the relative input arguments, and then click Next.
6. If necessary, define the UI Component events with the relative output arguments, and then click Next.
7. If necessary, define the UI Component properties with the relative default values, and then click Finish.

UI Component file structure and content


At the end of the UI Component Wizard, the system creates the following items within the components folder:
• <ComponentName> folder, populated with the following files:
• <ComponentName>.js, containing the logic of the UI Component and the declaration of all methods,
events and properties. Here you must add the method and the event logic, and the code required for
accessing the properties.
• <ComponentName>.html, the UI Component graphical layout.
• <Prefix><AppName><ComponentName>.json file, containing the UI Component information (i.e. the UI
Component manifest). If you right-click this file and select the UI Component command, you can modify the
information inserted during the UI Component definition phase.

482 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Each new UI Component contains by default a generic grid, which can be used as an example.

Modifying UI Components
When a UI Component is created, the <ComponentName>.js file is populated with the relevant information
automatically.
However, if you need to make some changes to the UI Component (e.g. change its general settings, add or remove
methods/events, properties), you can:
1. Right-click the <Prefix><AppName><ComponentName>.json file and select the UIComponent command. The
<Prefix><AppName><ComponentName> Update dialog box opens.
2. In the required tab, apply the needed changes by modifying the either the general settings, or adding/ removing
methods, events and so on.
Bear in mind that any information you modify will not be automatically updated in the <ComponentName>.js file,
which must subsequently be modified manually.
As the <ComponentName>.js file contains the code which is used at runtime, the system avoids any automatic
updates of runtime logic that could potentially be dangerous.

2.2.4.2.1.2 UI Component Definition


In the <ComponentName>.js file, which is automatically generated by the UI Component Wizard in
the components.<ComponentName> folder, you must write the code in order to:
• implement the logic of the declared methods,
• fire the declared events,

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 483


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• access the declared properties.


For each component, a default file is provided. This file contains an example of a UI Component that displays data
within a sitItemCollectionViewer widget (documented in the Opcenter Execution Foundation UI Framework
Reference).

Default file description


In this particular case, note that:
• The only column configured to be displayed in the grid is Id.
• No data is bound to the grid.

 The implementation of a UI Component may vary significantly depending on the specific use case. This
auto-generated code is only meant to be an example of a possible UI Component implementation.

484 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
angular.module('Siemens.MatMgt').component('siemensMatmgtMaterialdetails',
ComponentDefinition());
function ComponentDefinition() {
return {
bindings: {
name: '@'
},
templateUrl: 'Siemens.MatMgt/components/MaterialDetails/
MaterialDetails.html',
controller: ComponentController,
controllerAs: 'vm'
}
}
ComponentController.$inject = ['$rootScope', '$scope',
'common.services.logger.service', 'common.services.component.uiComponentService'];
function ComponentController($rootScope, $scope, loggerService,
uiComponentService) {
var self = this;
var logger;
activate();
function activate() {
logger = loggerService.getModuleLogger('siemensMatmgtMaterialdetails');
init();
registerEvents();
exposeApi();
//TODO: Insert Your Initialization Code Here
initGrid();
}
function init() {
logger.logDebug('Initializing component....', self.name);
self.selectedItem = null;
self.viewerData = [];
self.viewerOptions = {};
//TODO: Insert Your Variable Initialization Here
}
function exposeApi() {

}
function registerEvents() {
$scope.$on('$destroy', deregisterEvents);
//TODO: Uncomment below code if you want to listen on component resize
//For example hanlding svg elements or etc.
//uiComponentService.registerComponentResizeCallback(self.name,
onComponentResize);
//TODO: Uncomment below code if you want to listen on design mode toggled
//
uiComponentService.registerDesignModeToggleCallback(onDesignModeToggled);
}
function deregisterEvents() {
//TODO: Uncomment below code if you are enabled the registration

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 485


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

//uiComponentService.deregisterComponentResizeCallback(self.name,
onComponentResize);
//TODO: Uncomment below code if you are enabled the registration
//
uiComponentService.deregisterDesignModeToggleCallback(onDesignModeToggled);
}
function initGrid() {
self.viewerOptions = {
containerID: 'itemlist',
selectionMode: 'single',
viewOptions: 'gml',
quickSearchOptions: { enabled: true, field: 'Id' },
sortInfo: {
field: 'Id',
direction: 'asc'
},
gridConfig: {
columnDefs: [
{ field: 'Id' }
]
},
propertyFields: [
{ field: 'Id', displayName: 'Id' }
],
image: 'fa-puzzle-piece',
tileConfig: {
titleField: 'Id'
},
onSelectionChangeCallback: function (items, item) {
if (item && item.selected == true) {
self.selectedItem = item;
} else {
self.selectedItem = null;
}
}
};
}
function onComponentResize(size) {
logger.logDebug('Component resized....:' + size.width + ',' +
size.height);
//TODO: Insert code to be executed on component resize
}
function onDesignModeToggled(isEnabled) {
logger.logDebug('Design mode toggled....' + isEnabled);
//TODO: Insert code to be executed on design mode toggled
}
}
})();

486 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.2.1.3 Implementing a UI Method in a UI Component


When you create a UI Component you can add UI methods to enable communication between UI Components at
runtime.
In the <ComponentName>.js file, you can implement the logic of the methods, which have been added to the js file
during the UI Component definition.

 You can manually add new methods directly to the .js file, but these methods must then be also added to
the UI Component manifest (json file) by using the <Prefix><AppName><ComponentName> Update
dialog box.

Code example
The following method definition contains code elements that are described here below:

self.showOrders = function (operator) {


//
//Insert your method Implementation here
//
}

Element Description

self The instance of the controller.

showOrders The name of the method.

operator The name of the method parameter.

2.2.4.2.1.4 Firing a UI Event from a UI Component


When you create a UI Component in Project Studio you can specify UI events that can be fired by the UI Component
to enable communication with other Components at runtime.
In the <ComponentName>.js file, you must add the code for firing the defined events.

 You can manually add new events directly to the .js file, but these events must then be also added to the
UI Component manifest (json file) by using the <Prefix><AppName><ComponentName> Update dialog
box.

Code example
The following code represents an example of fire, containing code elements that are described here below:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 487


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

var orderSelected = function (orderid) {


var eventName1 = "siemensTestappOrderlist." + self.name +
".orderSelected";
$rootScope.$emit(eventName1, { "orderid": orderid });
}

Element Description

orderSelected The name of the event

orderid The name of the event argument

siemensTestappOrderlist The full name of the component, with prefix and App name

self.name The name of the instance of the component, which is passed as


an attribute

2.2.4.2.1.5 Accessing Properties from a UI Component


After you have defined the UI Component properties, you may now need to read their values within the code or, if
the UI Component will be exposed as a SWAC component, to set their values. You can also set property values in the
Mashup Editor.

 You can manually add new properties directly to the .js file, but these properties must then be also added
to the UI Component manifest (json file) by using the <Prefix><AppName><ComponentName> Update
dialog box.

The definition of each property, in the UI Component manifest, is characterized by the following properties:

Property Description

Name The name of the defined property.

Type This property must be set to one of the following values:


• array
• string
• number
• date
• object
• boolean
Objects only support the json syntax.

Category A logical categorization of the property, e.g. "Layout", "Data" etc. (useful
to categorize the properties in the Mashup Editor).

Description This property is optional and can be used to provide a description for the
property.

488 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Property Description

Permission This property must be set to one of the following values:


• Read, if it is a reading property,
• ReadWrite, if it is a reading/writing property
By default, the property is set to ReadWrite. If set to ReadWrite, you can
set/overwrite the default value in the Mashup Editor.

Default This property is optional and can be set to a suitable default value for the
property. By default it is set to null. If you want to modify it, the inserted
value must correspond to the selected type.

Opcenter Execution Foundation UI Framework provides you with public APIs (see UIComponent in the Opcenter
Execution Foundation UI Framework Reference) for reading and writing on the UI Component properties and for
notifying a property change.

2.2.4.2.1.6 Defining the UI Component Template


The <ComponentName>.html file contains the UI Component look and feel. This file is generated in
the components.<ComponentName> folder when you define a UI Component,
This file contains by default the instantiation of a sitItemCollectionViewer widget (documented in the Opcenter
Execution Foundation UI Framework Reference), but you must modify it according to your needs:

<style type="text/css">
/*Uncomment the below style snippet if you want the component to be displayed
above other components*/
/*div[name^="{{vm.name}}"] {
overflow: visible;
}*/
</style>
<div class="content-area content-area-relative" style="height: 100%" id="itemlist">
<sit-item-collection-viewer sit-data="vm.viewerData" sit-
options="vm.viewerOptions"></sit-item-collection-viewer>
</div>

2.2.4.2.2 Developing UI Modules and Screens


The App you have created includes a project, called <AppName>.UserInterface, which contains the files relative to
the user interface. This project includes by default the <Prefix>.<AppName>/modules folder to be used to develop
UI Modules.
It is also possible to graphically design mashup UI Modules from Solution Studio, but in some cases, as for example
when developing a set of master data pages sharing the same layout and behavior, it is preferable to perform this
operation directly from Project Studio.

2.2.4.2.2.1 Creating UI Module and UI Screens


The UI Module is the container of the UI Screens.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 489


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Prerequisites
The Service Layer is up and running.

Creating UI Module and UI Screens


For each Module you want to include in the App package perform the following operations to generate the
necessary files and then complete them inserting your code:
1. Right-click the <Prefix>.<AppName>/modules folder and then select the Add > New Item command.
2. Select the UIModule template (Visual C#\Web section).
3. Type a name in the Name edit box and click Add.
4. To add a screen (default root state) and the relative main states to the module, right-click
the <ModuleName> folder and then select the Add > New Item command.
5. Select the UI Module Screen template (Visual C#\Web section).
6. Type a name in the Name edit box and click Add.

 To make a UI Module Screen visible only to a specific user role, it must be made securable by manually
modifying its UI Module manifest.

UI Module and Screen project folder structure


Whenever you add a module to the UserInterface project, the system creates the following items within
the modules folder:
• <ModuleName> folder, populated with the module.js AngularJS file that contains the UI Module definition and
top-level routing configuration.
• <Prefix>.<AppName>.<ModuleName>.json file, the Module manifest.
Whenever you add a screen to a module, the system creates the following files in the <ModuleName> folder:
• <ScreenName>-srv.js, the screen service
• <ScreenName>-list-ctrl.js, the main controller for the screen
• <ScreenName>-list.html, the main template for the screen
• The controllers (.js) and templates (.html) for the main states:
• <ScreenName>-add-ctrl.js
• <ScreenName>-add.html
• <ScreenName>-edit-ctrl.js
• <ScreenName>-edit.html
• <ScreenName>-select-ctrl.js
• <ScreenName>-select.html
To add an additional state to the module, create the relative <ScreenName>-
<StateName>.html and <ScreenName>-<StateName>-ctrl.js files and then reference them from
the module.js (contained in the <ModuleName> folder) manually modifying it.
For detailed information on the role of each file and on how to manually modify some of them in order to complete
the UI Module development, see the relative links.

 The modules folder must contain only subfolders that correspond to actual UI Modules. If you want to use
third-party scripts, you should place them in the scripts folder instead.

UI Module Example

490 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.2.2.2 Migrating to Siemens Web Framework


This topic applies on how to configure Custom UI Screens to work seamlessly with Siemens Web Framework.

Configuring the UI Module Screen Title


1. Create a Custom UI screen in Project Studio.
2. Open the <UIModuleScreenName>-list-ctrl.js file.
3. Update the property title: with the title of the UI Module Screen as shown below.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 491


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

var state = {
name: moduleStateName + '_UIModuleScreen2',
url: '/' + moduleStateUrl + '_UIModuleScreen2',
views: {
'Canvas@': {
templateUrl: moduleFolder + '/UIModuleScreen2-list.html',
controller: ListScreenController,
controllerAs: 'vm'
}
},
data: {
title: '<The title of the UI Module Screen>'
}

Configuring the UI Module Icon


1. Create a Custom UI screen in Project Studio.
2. Open the <Prefix>.<AppName>.<ModuleName>.json file.
3. Update the property icon: with the svg icon to identify the UI Module as shown below.
Note: Make sure the svg icon is of command type (Example: cmdHome)

{
name: moduleStateName + '_UIModuleScreen2',
"type": "standard",
"title": "<ModuleName>",
"header":"",
"icon": 'The svg icon'
"functionalBlock": "<AppName>"
"dependencies": [],
"states": [
{
"id": moduleStateName + '_UIModuleScreen2',
"title": screenName,
"header":"",
"securable": true,
"roles": []
}
],
},
"manifestVersion": "<VersionId>"
}

2.2.4.2.2.3 Adopting custom UI screens to Siemens Web Framework


This page describes the page layout guidelines for custom UI screens developed in the Project Studio for an App.
There are two standard layouts which requires specific styling, as explained in detail below.

Specifications for Master screen


If a screen is configured with an ICV and a vertical command bar, apply the following style specifications:

492 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Position the vertical command bar to the extreme right.


• Set 16px padding to the top of the content.
• Set 16px padding to the right of the content.
• Set 16px padding to the left of the content.

<ScreenName>-list.html
The following default template is used to display an ICV and a toolbar with four standard buttons, but you can
customize it adding/removing buttons.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 493


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<div id="itemlistContainer" class="content-area content-area-relative" style="width:


100%; height:100%;overflow: hidden;">
<sit-command-bar sit-type="action" sit-layout="vertical" sit-vertical-
autofixed="true">
<sit-command svg-icon="common/icons/cmdEdit24.svg"
sit-name="com.siemens.customcommand.edit"
sit-tooltip="Edit"
ng-click="vm.editButtonHandler"
sit-label="Edit"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command svg-icon="common/icons/cmdInfo24.svg"
sit-name="com.siemens.customcommand.view"
sit-tooltip="View"
ng-click="vm.viewButtonHandler"
sit-label="View"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command svg-icon="common/icons/cmdTrash24.svg"
sit-name="com.siemens.customcommand.delete"
sit-tooltip="Delete"
ng-click="vm.deleteButtonHandler"
sit-label="Delete"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command svg-icon="common/icons/cmdAdd24.svg"
sit-name="com.siemens.customcommand.add"
ng-click="vm.addButtonHandler"
sit-tooltip="Add"
sit-label="Add"
sit-type="main"></sit-command>
</sit-command-bar>
<div id="itemlist" style="width:100%; height: calc(100% - 16px); padding:16px
16px 0 16px">
<sit-item-collection-viewer sit-data="vm.viewerData" sit-
options="vm.viewerOptions"></sit-item-collection-viewer>
</div>
</div>

Specifications for Master-Details Screen


If a screen is configured with a compact ICV, tabs and a vertical command bar, apply the following style
specifications:
1. Position the compact ICV to the extreme left.
2. Position the vertical command bar to the extreme right.
3. Set 16px padding to the top of the content.
4. Set 16px padding to the right of the content.
5. Set 16px padding to the left of the content.

494 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<ScreenName>-list.html
The following default template is used to display an ICV and a toolbar with four standard buttons, but you can
customize it adding/removing buttons.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 495


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<div id="itemlistContainer" class="content-area content-area-relative" style="width:


100%; height:100%;overflow: hidden;">
<sit-command-bar sit-type="action" sit-layout="vertical" sit-vertical-
autofixed="true">
<sit-command svg-icon="common/icons/cmdEdit24.svg"
sit-name="com.siemens.customcommand.edit"
sit-tooltip="Edit"
ng-click="vm.editButtonHandler"
sit-label="Edit"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command svg-icon="common/icons/cmdInfo24.svg"
sit-name="com.siemens.customcommand.view"
sit-tooltip="View"
ng-click="vm.viewButtonHandler"
sit-label="View"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command svg-icon="common/icons/cmdTrash24.svg"
sit-name="com.siemens.customcommand.delete"
sit-tooltip="Delete"
ng-click="vm.deleteButtonHandler"
sit-label="Delete"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command svg-icon="common/icons/cmdAdd24.svg"
sit-name="com.siemens.customcommand.add"
ng-click="vm.addButtonHandler"
sit-tooltip="Add"
sit-label="Add"
sit-type="main"></sit-command>
</sit-command-bar>
<div id="itemlist" style="width:100%; height: calc(100% - 16px); padding:16px
16px 0 16px">
<sit-item-collection-viewer sit-data="vm.viewerData" sit-
options="vm.viewerOptions"></sit-item-collection-viewer>
</div>
</div>

2.2.4.2.2.4 UI Module Definition


The module.js file, contained at the root level of the project (<Prefix>.<AppName> folder), is a "container" for all
the UI Modules and any other AngularJS entity developed in the App.
Consequently, you must make sure that all the AngularJS modules defined in the App are listed as dependencies for
this module, in order to be properly initialized at run time.
This file contains by default the definition of a module with the same name as the full name of the App (including
the prefix), for example Siemens.MatMgt. Then you must add the declaration of the AngularJS module
corresponding to the UI Module you are creating (for example, Siemens.MatMgt.MatDef) as a dependency:

496 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
angular.module('Siemens.MatMgt',
['Siemens.MatMgt.MatDef']);

})

2.2.4.2.2.5 UI Module Definition and Top Level Routing Configuration


The UI Module definition of each UI Module is a standard AngularJS module definition contained in the module.js
file within each module folder (<ModuleName> folder).
This file is automatically generated whenever you add a UI Module to a App.
For example:

module.js

1 (function(){
2 'use strict';
3 angular.module('Siemens.MatMgt.MatDefMgt',
[]).config(ModuleStateConfig);
4 ModuleStateConfig.$inject = ['$stateProvider'];
5 function ModuleStateConfig($stateProvider) {
6 var moduleStateName = 'home.Siemens_MatMgt.MatDefMgt';
7 var moduleFolder = 'Siemens.MatMgt/modules/MatDefMgt';
8 var moduleState = {
9 name: moduleStateName,
10 url: '/MatDefMgt',
11 abstract: true
12 };
13 $stateProvider.state(moduleState);
14 //Add new state
15 }
16 }());

In the example above, the definition creates a new AngularJS module called Siemens.MatMgt.MatDefMgt. Note
that:
• the name of the UI Module starts with the name of the App.
• if you want to organize your code in sub-modules, specify them as dependencies of the main module through
the second parameter, which is used for dependency injection. If your module does not have any dependencies,
set this parameter to an empty array when creating a module.

 The module method is used to retrieve an existing module if only the first parameter is specified. For more
information, see AngularJS documentation (https://code.angularjs.org/1.6.9/docs/api/ng/function/
angular.module).

When you define the main AngularJS module for your UI Module, you can include the routing configuration in the
same file (or split it into multiple files if it becomes too complex to manage within a single file).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 497


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

The module.js file includes the configuration of the $stateProvider, listing all additional states that are used within
the UI Module. Consequently, you must manually update this file whenever you add/delete an additional state,
while this operation is not necessary for the main states generated by the system, which are directly managed from
the corresponding .js files.
For example:

module.js

1 (function () {
2 'use strict';
3 angular.module('Siemens.MatMgt.MatDefMgt',
[]).config(ModuleStateConfig);
4 ModuleStateConfig.$inject = ['$stateProvider'];
5 function ModuleStateConfig($stateProvider) {
6 var moduleStateName = 'home.Siemens_MatMgt.MatDefMgt';
7 var moduleFolder = 'Siemens.MatMgt/modules/MatDefMgt';
8 var moduleState = {
9 name: moduleStateName,
10 url: '/MatDefMgt',
11 abstract: true
12 };
13 var matDefSave = {
14 name: moduleStateName + '.state_name',
15 url: '/state_url',
16 views: {
17 'Canvas@': {
18 templateUrl: moduleFolder + '/state_template.html',
19 controller: 'state_controller',
20 controllerAs: 'vm'
21 }
22 },
23 data: {
24 title: 'matDefSave'
25 displayBreadcrumb : false
26 },
27 params: {}
28 };
29 $stateProvider.state(matDefSave);
30 }
31 } ());

Breadcrumb visibility
The visibility of the breadcrumb in any state can be managed from routing configuration, by adding the
displayBreadcrumb property.
For example:

498 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

var item = {
name: 'rootstate',
url: '/rootstate',
views: {
'Canvas@': {
templateUrl: 'template.html',
controller: templateController,
controllerAs: 'vm'
}
},
data: {
title: 'Template Title',
help: "Managing Materials",
displayBreadcrumb: false
}
}

If the displayBreadcrumb property is not specified, its value will be inherited as follows:
• if it is not specified in any state it will be inherited from its parent state.
• if it is not present in any parent state or if the parent is not present, then the default value is true.

2.2.4.2.2.6 UI Module Manifest


Each UI Module is described by a dedicated manifest json file, which is automatically generated upon Module
creation.
The file is automatically updated when you add a new screen to the UI Module and does not need to be modified,
unless you have particular needs.
This file is named after the module name (i.e. <Prefix>.<AppName>.<ModuleName>.json file) and it is contained
at the level of the modules folder.
This file is necessary to allow the UI Module to be included in any UI Application configured with the Application
Editor, and it contains the following information:

Property Type Default Description

name string The identifier for the module.


Since it must be unique within the system,
the full AngularJS module name is used
and the naming convention is followed.

type string standard The type of the UI Module. The standard


value identifies the UI Modules created
from Project Studio and it cannot be
changed.

title string The title of the UI Module.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 499


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Property Type Default Description

header string The resource translation key used for


translating the title of the module in the UI
Application.
Note: The following special characters
should not be used anywhere in the
key -`!#%@^&*()+={}"|;\<,>?/~

icon string fa-sitemap The ID of a Font Awesone icon to be used


to identify the Module.

dependencies Array.<string> For future use.

functionalBlock string The full name of the App containing the UI


Module.

states Array.Object An array of state objects identifying all the


UI screens of the UI Module.

manifestVersion string 01.01.00 The internal version of the UI Module


Manifest format. This value is set
automatically by the system to the current
version when creating a new UI Module
Manifest.

states property Array


Each menu entry/state object has the following properties:

Property Type Default Description

id string A valid UI Application state identifier (used within


the module-specific $stateProvider
configuration).

 States must be unique within the whole


system. Consequently all states start
with a prefix corresponding to the App/
container folder ID followed by an
underscore (for example,
home.Siemens_MatMgt_MatDefMgt_M
atMgtPage)

title string The title of the state.

500 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Property Type Default Description

header string The resource translation key used for translating


the title of the screen in the UI Application.
Note: The following special characters should not
be used anywhere in the key -`!#%@^&*()+={}"|;
\<,>?/~

securable boolean Defines whether a UI screen will be visible to all


authenticated users (securable = false) or whether
it will be possible to assign its visibility as to a
specific set of users (securable = true).
The default value is true.

 If the securable node is missing, the


value will be considered false.

roles string An array of roles that will be able to view the


screen if the securable property has been set to
true.
The roles must be manually inserted.

Standard UI Module Manifest Example

1 {
2 "name": "Siemens.MatMgt.MatDefMgt",
3 "type": "standard",
4 "title": "MatDefMgt",
5 "header":"",
6 "icon": "fa-folder",
7 "functionalBlock": "Siemens.MatMgt",
8 "dependencies": [],
9 "states": [
10 {
11 "id": "home.Siemens_MatMgt.MatDefMgt.MatMgtPage",
12 "title": "MatMgtPage",
13 "header":"",
14 "securable": true,
15 "roles": []
16 }
17 ],
18 "manifestVersion": "01.01.00"
19 }

In the example above:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 501


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• The module declares a state (MatMgtPage) which will be used as an entry point for the UI Module and that will
be included in the sidebar of every UI Application containing the UoM module. The securable property is true, so
the screen can consequently only be viewed by users that have the Supervisor role assigned to them.
• The fa-folder icon ( ) will be used in the sidebar to identify the menu for this UI Module.
• The name of the App (Siemens.MatMgt) containing the UI Module is specified via the functionalBlock property.

2.2.4.2.2.7 UI Module Data Service


Opcenter Execution Foundation provides a set of AngularJS Services that can be used to communicate with the
backend. However, it is typically easier to provide one or more higher-level services that are specific to the data
manged by the UI Module.
Whenever you create a UI Module Screen the system automatically generates the <ScreenName>-srv.js file in the
<ModuleName> folder, representing the default service.
The following example shows the default service generated after adding the MatMgtPage screen to the MatDefMgt
module:

502 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
angular.module('Siemens.MatMgt.MatDefMgt')
.constant('Siemens.MatMgt.MatDefMgt.MatMgtPage.constants',
ScreenServiceConstants())
.service('Siemens.MatMgt.MatDefMgt.MatMgtPage.service', ScreenService)
.run(ScreenServiceRun);
function ScreenServiceConstants() {
return {
data: {
appName: 'MatMgt',
appPrefix: 'Siemens',
// TODO: Customize the entityName with the name of the entity defined
in the App you want to manage within the UI Module.
// Customize the command name with the name of the command
defined in the App you want to manage within the UI Module
entityName: null,
createPublicName: null,
updatePublicName: null,
deletePublicName: null
}
};
}
ScreenService.$inject = ['$q', '$state', 'common.base',
'Siemens.MatMgt.MatDefMgt.MatMgtPage.constants', 'common.services.logger.service'];
function ScreenService($q, $state, base, context, loggerService) {
var self = this;
var logger, backendService;
activate();
function activate() {
logger =
loggerService.getModuleLogger('Siemens.MatMgt.MatDefMgt.MatMgtPage.service');
backendService = base.services.runtime.backendService;
exposeApi();
}
function exposeApi() {
self.getAll = getAll;
self.create = createEntity;
self.update = updateEntity;
self.delete = deleteEntity;
}
function getAll(options) {
return execGetAll(options);
}
function createEntity(data) {
// TODO: Customize the mapping between "UI entity" and the "DB entity"
that will create
var obj = {
'Id': data.Id
};
return execCommand(context.data.createPublicName, obj);
}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 503


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

function updateEntity(data) {
// TODO: Customize the mapping between "UI entity" and the "DB entity"
that will create
var obj = {
'Id': data.Id
};
return execCommand(context.data.updatePublicName, obj);
}
function deleteEntity(data) {
// TODO: Customize the mapping between "UI entity" and the "DB entity"
that will delete
var obj = {
'Id': data.Id
};
return execCommand(context.data.deletePublicName, obj);
}
function execGetAll(options) {
return backendService.findAll({
'appName': context.data.appName,
'entityName': context.data.entityName,
'options': options
});
}
function execCommand(publicName, params) {
logger.logDebug('Executing command.......', publicName);
return backendService.invoke({
'appName': context.data.appName,
'commandName': publicName,
'params': params
});
}
}
ScreenServiceRun.$inject = ['Siemens.MatMgt.MatDefMgt.MatMgtPage.constants',
'common.base'];
function ScreenServiceRun(context, common) {
if (!context.data.entityName) {
common.services.logger.service.logWarning('Configure the entityName');
};
if (!context.data.createPublicName) {
common.services.logger.service.logWarning('Configure the
createPublicName');
};
if (!context.data.deletePublicName) {
common.services.logger.service.logWarning('Configure the
deletePublicName');
};
if (!context.data.updatePublicName) {
common.services.logger.service.logWarning('Configure the
updatePublicName');
};
}
}());

504 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

The Service depends on the following AngularJS services (provided by AngularJS, third-party libraries, or the UI
Framework):
• common.base – retrieves data from the runtime service layer, executes commands on the runtime service
layer, configures and shows a message overlay, shows/hides a busy indicator and exposes a set of commonly
used methods, such as the formatErrorMessage method, which can automatically format an error response
received from the service layer.
• $q – handles Javascript promises.
• $state – used to programmatically redirect to another application state.
• common.services.logger.service – logs diagnostic messages to the browser console.
Once created, the <ScreenName>-srv.js file must be manually modified for:
1. Constants
2. Methods

Constants
Customize the constant section of the file setting the following values otherwise an error is returned:
• entityName: the name of the entity defined in the App you want to manage within the UI Module.
• createPublicName: the name of the command to be used to create a new entity.
• updatePublicName: the name of the command to be used to modify an entity.
• deletePublicName: the name of the command to be used to delete an entity.

Example

.constant('MatMgtPage.constants', {
data: {
entityName: MaterialDefinition,
createPublicName: 'CreateMaterialDefinition',
updatePublicName: 'UpdateMaterialDefinition',
deletePublicName: 'DeleteMaterialDefinition'
}
function ScreenServiceConstants() {
return {
data: {
appName: 'MatMgt',
appPrefix: 'Siemens',
entityName: MaterialDefinition,
createPublicName: 'CreateMaterialDefinition',
updatePublicName: 'UpdateMaterialDefinition',
deletePublicName: 'DeleteMaterialDefinition'
}
};
}

Methods
The Service is realized as a factory that returns an object exposing the following high-level methods:
• getAll – retrieves all the available entities,
• create – creates a single entity,

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 505


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• update – updates a single entity,


• delete – deletes a single entity,
and consequently all relative method sections must be modified as in the following example:

function createEntity(data) {
var obj = {
'Id': data.Id,
'name' : data.name,
'description' : data.description
};
return execCommand(context.data.createPublicName, obj);
}

2.2.4.2.2.8 UI Module List Template and Controller


The following files define a simple module screen with client side data:
• <ScreenName>-list.html
• <ScreenName>-list-ctrl.js
The system automatically generates both files when you add a screen to a UI Module, but you can modify them
according to your needs.
When facet properties are to be shown along with entity properties, See Configuring Standard UI Module Screen
with Facets.

<ScreenName>-list.html
The following default template is used to display a toolbar with four standard buttons, but you can customize it
adding/removing buttons.

506 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<div id="itemlist" class="content-area content-area-relative" style="height:


calc(100% - 30px) !important">
<sit-command-bar sit-type="action">
<sit-command sit-icon="fa-edit"
sit-name="com.siemens.customcommand.edit"
sit-tooltip="Edit"
ng-click="vm.editButtonHandler"
sit-label="Edit"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command sit-icon="fa-list-alt"
sit-name="com.siemens.customcommand.select"
sit-tooltip="View"
ng-click="vm.selectButtonHandler"
sit-label="View"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command sit-icon="fa-trash"
sit-name="com.siemens.customcommand.delete"
sit-tooltip="Delete"
ng-click="vm.deleteButtonHandler"
sit-label="Delete"
ng-show="vm.isButtonVisible"></sit-command>
<sit-command sit-icon="fa-plus"
sit-name="com.siemens.customcommand.add"
ng-click="vm.addButtonHandler"
sit-tooltip="Add"
sit-label="Add"
sit-type="main"></sit-command>
</sit-command-bar>
<sit-item-collection-viewer sit-data="vm.viewerData" sit-
options="vm.viewerOptions"></sit-item-collection-viewer>
</div>

<ScreenName>-list-ctrl.js
The controller manages the visualization of the entity that has been defined in the App and allows you to use the
command bar to perform CRUD operations on this entity.
You can modify the file in order to perform additional operations, or to remove the standard ones, simply modifying
the references to the relative handlers.
For more information on the sections to be modified refer to the comments within the file generated by the system:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 507


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
ListScreenController.$inject = ['Siemens.MatMgt.MatDefMgt.MatMgtPage.service',
'$state', '$stateParams', '$rootScope', '$scope', 'common.base',
'common.services.logger.service'];
function ListScreenController(dataService, $state, $stateParams, $rootScope,
$scope, base, loggerService) {
var self = this;
var logger, rootstate, messageservice, backendService;
activate();
// Initialization function
function activate() {
logger =
loggerService.getModuleLogger('Siemens.MatMgt.MatDefMgt.MatMgtPage');
init();
initGridOptions();
initGridData();
}
function init() {
logger.logDebug('Initializing controller.......');
rootstate = 'home.Siemens_MatMgt.MatDefMgt.MatMgtPage';
messageservice = base.widgets.messageOverlay.service;
backendService = base.services.runtime.backendService;

//Initialize Model Data


self.selectedItem = null;
self.isButtonVisible = false;
self.viewerOptions = {};
self.viewerData = [];
//Expose Model Methods
self.addButtonHandler = addButtonHandler;
self.editButtonHandler = editButtonHandler;
self.selectButtonHandler = selectButtonHandler;
self.deleteButtonHandler = deleteButtonHandler;
}
function initGridOptions() {
self.viewerOptions = {
containerID: 'itemlist',
selectionMode: 'single',
viewOptions: 'gl',
// TODO: Put here the properties of the entity managed by the service
quickSearchOptions: { enabled: true, field: 'Id' },
sortInfo: {
field: 'Id',
direction: 'asc'
},
image: 'fa-cube',
tileConfig: {
titleField: 'Id'
},
gridConfig: {

508 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

// TODO: Put here the properties of the entity managed by the


service
columnDefs: [
{ field: 'Id', displayName: 'Id' }
]
},
onSelectionChangeCallback: onGridItemSelectionChanged
}
}
function initGridData() {
dataService.getAll().then(function (data) {
if ((data) && (data.succeeded)) {
self.viewerData = data.value;
} else {
self.viewerData = [];
}
}, dataService.backendError);
}
function addButtonHandler(clickedCommand) {
$state.go(rootstate + '.add');
}
function editButtonHandler(clickedCommand) {
// TODO: Put here the properties of the entity managed by the service
$state.go(rootstate + '.edit', { id: self.selectedItem.Id, selectedItem:
self.selectedItem });
}
function selectButtonHandler(clickedCommand) {
// TODO: Put here the properties of the entity managed by the service
$state.go(rootstate + '.select', { id: self.selectedItem.Id,
selectedItem: self.selectedItem });
}
function deleteButtonHandler(clickedCommand) {
var title = "Delete";
// TODO: Put here the properties of the entity managed by the service
var text = "Do you want to delete '" + self.selectedItem.Id + "'?";
backendService.confirm(text, function () {
dataService.delete(self.selectedItem).then(function () {
$state.go(rootstate, {}, { reload: true });
}, backendService.backendError);
}, title);
}
function onGridItemSelectionChanged(items, item) {
if (item && item.selected == true) {
self.selectedItem = item;
setButtonsVisibility(true);
} else {
self.selectedItem = null;
setButtonsVisibility(false);
}
}
// Internal function to make item-specific buttons visible
function setButtonsVisibility(visible) {

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 509


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

self.isButtonVisible = visible;
}
}
ListScreenRouteConfig.$inject = ['$stateProvider'];
function ListScreenRouteConfig($stateProvider) {
var moduleStateName = 'home.Siemens_MatMgt.MatDefMgt';
var moduleFolder = 'Siemens.MatMgt/modules/MatDefMgt';
var state = {
name: moduleStateName + '.MatMgtPage',
url: '/MatMgtPage',
views: {
'Canvas@': {
templateUrl: moduleFolder + '/MatMgtPage-list.html',
controller: ListScreenController,
controllerAs: 'vm'
}
},
data: {
title: 'MatMgtPage'
}
};
$stateProvider.state(state);
}
}());

 Click on Select All icon, all the rows displayed when Mode is Table are selected. While Select All checkbox
is selected, rows that are newly added and the rows that are loaded by scrolling in server side pagination
will be selected automatically.
This is the default setting. To implement the behavior, you must remove any custom settings if available
with respect to the selecting records.

 The command bar can be exposed to maximum two different button set. If you add more commands or
reduce the size of the command bar, you may miss out some of the commands.

Adding Contextual Documentation


It is possible to configure your custom screen to open a contextual help window to display custom reference
documentation related to the data model in use (e.g. entities, commands, events and so on). For more information
on the artifacts that can be documented and the procedure to be followed, see Generating the Reference
Documentation of an App.
To open the contextual help you have to add an additional help parameter to the data object of the state
configuration and set it to the title of a page already existing within the Documentation Center. The following is an
example for the Managing Materials page:

510 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1 var item = {
2 name: rootstate,
3 url: '/' + context.data.entityName,
4 views: {
5 'Canvas@': {
6 templateUrl: folder + '/MatMgtPage-list.html',
7 controller: ListScreenController,
8 controllerAs: 'vm'
9 }
10 },
11 data: {
12 title: context.data.entityName,
13 help: "Managing Materials"
14 },

If a help string has been configured in this way, the help button will be displayed in the header bar, and if clicked it
will open the documentation help window required.

2.2.4.2.2.9 UI Module Add State Template and Controller


The following files define the Add state:
• <ScreenName>-add.html
• <ScreenName>-add-ctrl.js
The system automatically generates both files when you add a screen to a UI Module.

<ScreenName>-add.html
The following default template allows you to display the standard property (Id) of the entity managed by the UI
Module. You can modify the file manually in order to display the other entity properties that have been defined in
the UI Module Data Service or to hide the Id property.

<div class="command-bar-side-panel">
<button ng-click="vm.cancel()" class="btn side-panel-button">Cancel</button>
<button ng-click="vm.save()" class="btn side-panel-button" ng-
show="vm.validInputs">Save</button>
</div>
<div class="side-panel-property-area-body">
<sit-property-grid sit-id="add_form"
sit-layout="Vertical"
sit-type="Fluid"
sit-mode="edit"
sit-columns="1">
<!-- TODO: Type here the properties of the entity managed by the service -->
<sit-property sit-widget="sit-text"
sit-value="vm.currentItem.Id"
sit-validation="{required: true}"
sit-read-only="false">ID:</sit-property>
</sit-property-grid>
</div>

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 511


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<ScreenName>-add-ctrl.js
The controller manages the creation of new entities with the properties defined in the model factory of the UI
Module Data Service.

512 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
AddScreenController.$inject = ['Siemens.MatMgt.MatDefMgt.MatMgtPage.service',
'$state', '$stateParams', 'common.base', '$filter', '$scope'];
function AddScreenController(dataService, $state, $stateParams, common, $filter,
$scope) {
var self = this;
var sidePanelManager, backendService, propertyGridHandler;

activate();
function activate() {
init();
registerEvents();
sidePanelManager.setTitle('Add');
sidePanelManager.open('e');
}
function init() {
sidePanelManager = common.services.sidePanel.service;
backendService = common.services.runtime.backendService;
//Initialize Model Data
self.currentItem = null;
self.validInputs = false;
//Expose Model Methods
self.save = save;
self.cancel = cancel;
}
function registerEvents() {
$scope.$on('sit-property-grid.validity-changed',
onPropertyGridValidityChange);
}
function save() {
dataService.create(self.currentItem).then(onSaveSuccess,
backendService.backendError);
}
function cancel() {
sidePanelManager.close();
$state.go('^');
}
function onSaveSuccess(data) {
sidePanelManager.close();
$state.go('^', {}, { reload: true });
}
function onPropertyGridValidityChange(event, params) {
self.validInputs = params.validity;
}
}
AddScreenStateConfig.$inject = ['$stateProvider'];
function AddScreenStateConfig($stateProvider) {
var screenStateName = 'home.Siemens_MatMgt.MatDefMgt.MatMgtPage';
var moduleFolder = 'Siemens.MatMgt/modules/MatDefMgt';
var state = {
name: screenStateName + '.add',

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 513


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

url: '/add',
views: {
'property-area-container@': {
templateUrl: moduleFolder + '/MatMgtPage-add.html',
controller: AddPageController,
controllerAs: 'vm'
}
},
data: {
title: 'Add'
}
};
$stateProvider.state(state);
}
}());

2.2.4.2.2.10 UI Module Edit State Template and Controller


The following files define the Edit state:
• <ScreenName>-edit.html
• <ScreenName>-edit-ctrl.js
The system automatically generates both files when you add a screen to a UI Module.

<ScreenName>-edit.html
The following default template allows you to display in edit mode the standard property (Id) of the entity managed
by the UI Module. You can modify the file manually in order to display the other entity properties that have been
defined in the UI Module Data Service or to hide the Id property.

<div class="command-bar-side-panel">
<button ng-click="vm.cancel()" class="btn side-panel-button">Cancel</button>
<button ng-click="vm.save()" class="btn side-panel-button" ng-
show="vm.validInputs">Save</button>
</div>
<div class="side-panel-property-area-body">
<sit-property-grid sit-id="edit_form"
sit-layout="Vertical"
sit-type="Fluid"
sit-mode="edit"
sit-columns="1">
<!-- TODO: Type here the properties of the entity managed by the service -->
<sit-property sit-widget="sit-text"
sit-value="vm.currentItem.Id"
sit-validation="{required: true}"
sit-read-only="false">ID:</sit-property>
</sit-property-grid>
</div>

514 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<ScreenName>-edit-ctrl.js
The controller manages the editing of entities with the properties defined in the model factory of the UI Module
Data Service.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 515


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
EditScreenController.$inject = ['Siemens.MatMgt.MatDefMgt.MatMgtPage.service',
'$state', '$stateParams', 'common.base', '$filter', '$scope'];
function EditScreenController(dataService, $state, $stateParams, common, $filter,
$scope) {
var self = this;
var sidePanelManager, backendService, propertyGridHandler;
activate();
function activate() {
init();
registerEvents();
sidePanelManager.setTitle('Edit');
sidePanelManager.open('e');
}
function init() {
sidePanelManager = common.services.sidePanel.service;
backendService = common.services.runtime.backendService;
//Initialize Model Data
// TODO: Type here the properties of the entity managed by the service
self.currentItem = angular.copy($stateParams.selectedItem);
self.validInputs = false;
//Expose Model Methods
self.save = save;
self.cancel = cancel;
}
function registerEvents() {
$scope.$on('sit-property-grid.validity-changed',
onPropertyGridValidityChange);
}
function save() {
dataService.update(self.currentItem).then(onSaveSuccess,
backendService.backendError);
}
function cancel() {
sidePanelManager.close();
$state.go('^');
}
function onSaveSuccess(data) {
sidePanelManager.close();
$state.go('^', {}, { reload: true });
}
function onPropertyGridValidityChange(event, params) {
self.validInputs = params.validity;
}
}
EditScreenStateConfig.$inject = ['$stateProvider'];
function EditScreenStateConfig($stateProvider) {
var screenStateName = 'home.Siemens_MatMgt.MatDefMgt.MatMgtPage';
var moduleFolder = 'Siemens.MatMgt/modules/MatDefMgt';
var state = {
name: screenStateName + '.edit',

516 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

url: '/edit/:id',
views: {
'property-area-container@': {
templateUrl: moduleFolder + '/MatMgtPage-edit.html',
controller: EditScreenController,
controllerAs: 'vm'
}
},
data: {
title: 'Edit'
},
params: {
selectedItem: null,
}
};
$stateProvider.state(state);
}
}());

2.2.4.2.2.11 UI Module Select State Template and Controller


The following files define the Select state:
• <ScreenName>-select.html
• <ScreenName>-select-ctrl.js
The system automatically generates both files when you add a screen to a UI Module, but you can modify them
according to your needs.

<ScreenName>-select.html
The following default template allows you to display the details of the standard property (Id) of the entity managed
by the UI Module. You can modify the file manually in order to display the other entity properties that have been
defined in the UI Module Data Service or to hide the Id property.

<div class="command-bar-side-panel">
<button ng-click="vm.cancel()" class="btn side-panel-button">Close</button>
</div>
<div class="side-panel-property-area-body">
<sit-property-grid sit-id="view_form"
sit-layout="Vertical"
sit-type="Fluid"
sit-mode="view"
sit-columns="1">
<!-- TODO: Type here the properties of the entity managed by the service -->
<sit-property sit-widget="sit-label" sit-value="vm.currentItem.Id">ID:</sit-
property>
</sit-property-grid>
</div>

<ScreenName>-select-ctrl.js
The controller allows you to define the entity property for which you want to display the details.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 517


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

By default only the details of the Id property are displayed, to add other properties, modify the init function within
the file.

518 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
ViewScreenController.$inject = ['Siemens.MatMgt.MatDefMgt.MatMgtPage.service',
'$state', '$stateParams', 'common.base', '$filter', '$scope'];
function ViewScreenController(dataService, $state, $stateParams, common, $filter,
$scope) {
var self = this;
var sidePanelManager, backendService, propertyGridHandler;
activate();
function activate() {
init();
sidePanelManager.setTitle('Select');
sidePanelManager.open('e');
}
function init() {
sidePanelManager = common.services.sidePanel.service;
backendService = common.services.runtime.backendService;
//Initialize Model Data
// TODO: Type here the properties of the entity managed by the service
self.currentItem = $stateParams.selectedItem;
//Expose Model Methods
self.cancel = cancel;
}
function save() {
dataService.update(self.currentItem).then(onSaveSuccess,
backendService.backendError);
}
function cancel() {
sidePanelManager.close();
$state.go('^');
}
function onSaveSuccess(data) {
sidePanelManager.close();
$state.go('^', {}, { reload: true });
}
function onPropertyGridValidityChange(event, params) {
self.validInputs = params.validity;
}
}
ViewScreenStateConfig.$inject = ['$stateProvider'];
function ViewScreenStateConfig($stateProvider) {
var screenStateName = 'home.Siemens_MatMgt.MatDefMgt.MatMgtPage';
var moduleFolder = 'Siemens.MatMgt/modules/MatDefMgt';
var state = {
name: screenStateName + '.select',
url: '/select/:id',
views: {
'property-area-container@': {
templateUrl: moduleFolder + '/MatMgtPage-select.html',
controller: ViewScreenController,
controllerAs: 'vm'
}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 519


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

},
data: {
title: 'Select'
},
params: {
selectedItem: null,
}
};
$stateProvider.state(state);
}
}());

2.2.4.2.2.12 Managing Deletions in UI Modules


Whenever you create a UI Module and the relative screens, Project Studio automatically manages the references
among files. On the contrary, you must perform some manual operations if you choose to remove a UI Module or
one of its screens.

Deleting a UI Module
Manually delete both of the following from Project Studio and then verify that they also have been removed from
the File System:
• <ModuleName> folder
• <Prefix>.<AppName>.<ModuleName>.json file

Deleting a Screen
1. Manually delete the following files:
• <ScreenName>-list.html
• <ScreenName>-list-ctrl.js
• <ScreenName>-srv.js
• <ScreenName>-add.html,
• <ScreenName>-add-ctrl.js
• <ScreenName>-select.html
• <ScreenName>-select-ctrl.js
• <ScreenName>-edit.html
• <ScreenName>-edit-ctrl.js
2. Open then following files and delete any reference to the removed screen:
• <Prefix>.<AppName>.<ModuleName>.json
• module.js

2.2.4.2.2.13 Configuring Standard UI Module Screen with Facets


When facet details are to be shown in a screen, we can use an item collection viewer or sit-table with required
configuration. This page explains how one can use the widgets and services in UI Framework to retrieve necessary
data for client side and server side configuration.
When configuring with server side data, we can use the enhanced configuration for widgets (ICV and sit-table) to
display properties from facets and enable capabilities like filtering, sorting and searching on the same.
The following files define a simple module screen with server side data configured with pagination:
<ServerSidePagination-Facet>-list.html

520 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<ServerSidePagination-Facet>-list-ctrl.js
findAll service has been enhanced with the capability to flatten facet information to display properties from facets
easily. The widgets ICV and sit-table internally manages the transformed data with the appropriate configuration. In
the case where your screen has to show data in client side mode involving facet information, you can
provide dataTransformInfo as an argument to the findAll service to obtain facets information flattened in the same
level as entity properties. Example for dataTransformInfo is as follows.

Example of dataTransformInfo argument passed to findAll

1 dataTransformInfo = {
2 facetKeys: {
3 <AliasNameForTheFacet_Defect>: { fullyQualifiedName:
'Siemens.MaterialFacetsTest.MaterialFacetsTest.BLPOMModel.DataModel.Readin
gModel.Defect' },
4 Location: { fullyQualifiedName: <Fully qualified name of the Facet
- Location as exposed from metadata> },
5 Status: { fullyQualifiedName:
'Siemens.MaterialFacetsTest.MaterialFacetsTest.BLPOMModel.DataModel.Readin
gModel.Status' }
6 }

When findAll is used with dataTransformInfo as an argument, original Facets array will no longer be available in the
response from findAll. Example of the response is as shown below.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 521


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Example of the response from findAll when dataTransformInfo is passed as an argument

1 succeeded: true
2 value: Array(7)
3 0: {Id: "d89eaf5a-71ac-ea11-9010-0050569f6a28", AId: "d89eaf5a-71ac-
ea11-9010-0050569f6a28", IsFrozen: false, ConcurrencyVersion: 0,
IsDeleted: 0, …}
4 1: {Id: "b67e2f80-71ac-ea11-9010-0050569f6a28", AId: "b67e2f80-71ac-
ea11-9010-0050569f6a28", IsFrozen: false, ConcurrencyVersion: 0,
IsDeleted: 0, …}
5 2: {Id: "8cf1f3d3-71ac-ea11-9010-0050569f6a28", AId: "8cf1f3d3-71ac-
ea11-9010-0050569f6a28", IsFrozen: false, ConcurrencyVersion: 0,
IsDeleted: 0, …}
6 3: {Id: "8cf1f3d3-71ac-ea11-9010-0050569f6a28", AId: "c57ea457-73ac-
ea11-9010-0050569f6a28", IsFrozen: false, ConcurrencyVersion: 0,
IsDeleted: 0, …
7 CreatedOn: "2020-06-12T06:09:58.9846043Z"
8 Defect: {@odata.type:
"#Siemens.MaterialFacetsTest.MaterialFacetsTest.VKPOMModel.DataModel.Readi
ngModel.Defect", Id: "c77ea457-73ac-ea11-9010-0050569f6a28", AId:
"c77ea457-73ac-ea11-9010-0050569f6a28", IsFrozen: false,
ConcurrencyVersion: 0, …}
9 Location: {@odata.type:
"#Siemens.MaterialFacetsTest.MaterialFacetsTest.VKPOMModel.DataModel.Readi
ngModel.Location", Id: "c87ea457-73ac-ea11-9010-0050569f6a28", AId:
"c87ea457-73ac-ea11-9010-0050569f6a28", IsFrozen: false,
ConcurrencyVersion: 0, …}
10 Status: {@odata.type:
"#Siemens.MaterialFacetsTest.MaterialFacetsTest.VKPOMModel.DataModel.Readi
ngModel.Status", Id: "c67ea457-73ac-ea11-9010-0050569f6a28", AId:
"c67ea457-73ac-ea11-9010-0050569f6a28", IsFrozen: false,
ConcurrencyVersion: 0, …}
11 Description: null
12 EntityType: "Siemens.MasterData.FacetLib_Mat.MSModel.DataModel.Material"
13 Id: "c57ea457-73ac-ea11-9010-0050569f6a28"
14 LastUpdatedOn: "2020-06-12T06:09:58.9846043Z"
15 NId: "Entity_NId"
16 Name: "Entity Name"
17 ToBeCleaned: false …}
18 4: {Id: "b028e776-a3ac-ea11-9010-0050569f6a28", AId: "b028e776-a3ac-
ea11-9010-0050569f6a28", IsFrozen: false, ConcurrencyVersion: 0,
IsDeleted: 0, …}
19 5: {Id: "0f08195e-a7ac-ea11-9010-0050569f6a28", AId: "0f08195e-a7ac-
ea11-9010-0050569f6a28", IsFrozen: false, ConcurrencyVersion: 0,
IsDeleted: 0, …}
20 6: {Id: "76b4dd67-a7ac-ea11-9010-0050569f6a28", AId: "76b4dd67-a7ac-
ea11-9010-0050569f6a28", IsFrozen: false, ConcurrencyVersion: 0,
IsDeleted: 0, …}

When you want to configure a screen with client side data, involving sorting from facet properties you can use the
findAll service by providing values for the facetInfo argument along with the dataTransformInfo as explained
earlier in this section. With the facetInfo argument provided, one can use the service to sort the entities on

522 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

properties from facet. findAll will issue two requests to the service layer to achieve sorting. Hence the queryParams
applicable for the facet query must be carefully formed, considering the required results. Example for facetInfo is as
shown below.

Example of facetInfo argument passed to findAll

1 facetInfo = {
2 name = 'Defect',
3 queryParams:
'$top=10&$skip=0&$orderby=DefectType&$select=Material&$expand=Material($ex
pand=Facets)&$count=true',
4 // prevReqState optional for client side
5 prevReqState = {
6 areMoreFacetsAvailable: true,
7 facetQueriedCount: 0,
8 entityQueriedCount: 0,
9 totalFacetCount: 0,
10 totalEntityCount: 0
11 }
12 }

The following example defines an example for the module screen with client side data. In the controller that
manages the visualization of the entity along with properties from facets that has been defined in the App. Use the
initGridData with arguments as shown below while invoking findAll.
While providing the options for entity when sorting on facet properties, we have to specify a filter condition to
exclude the entities which will be queried from the facet specific query. This must be done to eliminate duplicates.
Along with this condition specified mandatorily one can add adittional conditions to filter entities.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 523


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1 function initGridData() {
2 var clientSideFindAllArgs = {
3 'options': '$filter=not(Facets/any(f: f/
Siemens.WidgetApp.WidgetApp.WAPOMModel.DataModel.ReadingModel.Characterist
ics ne null))&$top=10&$skip=0&$expand=Facets&$count=true',
4 'appName': 'WidgetApp',
5 'entityName': 'Inspection',
6 'facetInfo': {
7 'name': 'Defect',
8 'queryParams':
'$top=10&$skip=0&$orderby=DefectType&$select=Inspection&$expand=Material($
expand=Facets)&$count=true',
9 },
10 'dataTransformInfo': {
11 'facetKeys': {
12 'Characteristics': { 'fullyQualifiedName':
'Siemens.WidgetApp.WidgetApp.WAPOMModel.DataModel.ReadingModel.Characteris
tics' },
13 }
14 }
15 }
16
17 dataService.findAll(clientSideFindAllArgs).then(function
(data) {
18 if ((data) && (data.succeeded)) {
19 self.viewerData = data.value;
20 } else {
21 self.viewerData = [];
22 }
23 }, backendService.backendError);
24 }

<ServerSidePagination-Facet>-list.html
The following template is an example that is used to display an ICV consisting of properties from entity and facets,
but you can customize it.

1 <sit-item-collection-viewer sit-data="vm.viewerData" sit-options="vm.viewe


rOptions"></sit-item-collection-viewer>

<ServerSidePagination-Facet>-list-ctrl.js
The controller manages the visualization of the entity along with properties from facets that has been defined in the
App.

524 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1 function initGridOptions() {
2 self.viewerOptions = {
3 containerID: 'inspectionDefinitionMasterDetails',
4 svgIcon: 'common/icons/typeExecGroup48.svg',
5 tileConfig: {
6 isCell: true,
7 titleField: 'NId',
8 descriptionField: 'Description',
9 propertyFields: [
10 { field: 'CharType.IsVisual', displayName:
'IsVisual',fieldSource:'Characteristics' },
11 { field: 'CharType.IsAttribute', displayName:
'IsAttribute',fieldSource:'Characteristics' },
12 { field: 'CharType.Variable', displayName:
'Variable' ,fieldSource:'Characteristics'},
13 { field: 'Facet_NId', displayName: 'Facet_NId' ,fiel
dSource:'Characteristics'}
14 ]
15 },
16 filterBarOptions: 'SQ',
17 quickSearchOptions: {
18 enabled: true,
19 field: 'Facet_NId',
20 fieldSource:'Characteristics',
21 filterText: ''
22 },
23 selectionMode: 'single',
24 serverDataOptions: {
25 dataEntity: 'Inspection',
26 optionsString: '',
27 appName: 'WidgetApp',
28 dataService: backEnd,
29 fieldSources: {
30 Characteristics: {
31 name:
'Siemens.WidgetApp.WidgetApp.WAPOMModel.DataModel.ReadingModel.Characteris
tics',
32 type: 'facet'
33 }
34 }
35 },
36 sortInfo: {
37 field: 'Name',
38 direction: 'asc',
39 fields: [
40 { field: 'Name', displayName: 'Name'},
41 { field: 'NId', displayName: 'Id'},
42 { field: 'CharType.IsVisual', displayName: 'IsVisual',
fieldSource:'Characteristics' },
43 { field: 'CharType.IsAttribute', displayName:
'IsAttribute',fieldSource:'Characteristics' },

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 525


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

44 { field: 'CharType.Variable', displayName: 'Variable'


,fieldSource:'Characteristics'},
45 { field: 'Facet_NId', displayName: 'Facet_NId' ,fieldS
ource:'Characteristics'}
46 ]},
47 userPrefId: 'InspectionMasterDetail',
48 viewMode: 'C',
49 viewOptions: 'm',
50 // TODO: Put here the properties of the entity managed by
the service
51 image: 'fa-cube',
52
53 onSelectionChangeCallback: onGridItemSelectionChanged
54 }
55 }
56
57 function initGridData() {
58 dataService.getAll().then(function (data) {
59 if ((data) && (data.succeeded)) {
60 self.viewerData = data.value;
61 } else {
62 self.viewerData = [];
63 }
64 }, backendService.backendError);
65 }

2.2.4.3 Model-Driven Development of UI Modules and UI Screens


To implement a Model-Driven UI Module with its UI Screens go through the steps described in the following
sections:
• How to Create a Model-Driven UI Module
• Examples of Model-Driven UI Modules
For an overview of the editor, see What is the Model-Driven UI Module Editor.

2.2.4.3.1 How to Create a Model-Driven UI Module


To create a UI Module in the Model-Driven UI Editor go through the following prerequisites and steps:

Prerequisites
• The App, in which you are creating the Model-Driven UI Module, references the Functional Block that contains
the Entities, the Commands or the Reading Functions you want to use in the UI Module.
• The Entities to be used in the in Model-Driven Editor must be present in the Public Object Model of the App
(Functional Block entities cannot be directly accessed).
• The Public Object Model must contain at least one entity, otherwise the Model-Driven Editor cannot start.
• The POMModel project has been built to create the required assemblies.
• If you are modifying an existing Model-Driven UI Module, each time you apply a change to the POMModel project
(for example by adding an Entity or a Command), you must recompile the POMModel project and then stop and
start the UI Model-Driven Server.

Workflow

526 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1. Create a new Model-Driven UI Module or Extend a MDUI Module From Base App.
2. Open the Model-Driven UI Editor.
3. (Optional) Modify the Model-Driven UI Module Information.
4. Create a New Model-Driven UI Screen.
5. Configure the Model-Driven UI Screen Contents . Otherwise, configure a Custom Content for a Master-Details UI
Screen.
6. Configure the Model-Driven UI Screen Actions. Otherwise, configure Custom Action Types for Execute Command
and View Actions or configure Custom Action with In-Canvas Mode for Execute Command and View Actions.

2.2.4.3.1.1 What is the Model-Driven UI Module Editor


With the Model-Driven UI Editor, UI Modules and UI Screens can be easily created starting from the reading model of
an App or and an Extension App.
Based on an entity type and on a predefined UI Screen template, the Editor creates the artifacts that make up each
UI Screen without the need of writing code.
At the end of the configuration phase, the Editor generates a manifest file, that will be used to generate UI Modules
and Screens on the fly, ready to be deployed within a the Manufacturing Solution.

Advantages of using the Model-Driven UI Editor


Although UI pages usually display data either in simple grids or in master-detail views, user interaction and
flexibility are crucial for users who often need to change the display mode of their pages (for example, switching
from a grid view to a tile list view) or the members that must be visible in a filter and so on. For such a reason, the
Editor implements the possibility to enrich the contents with additional attributes that describe how to make
members visible in the UIs, for example if they must be visible in a grid or in a tile list view, which members must be
visible in a filter and so on.
Moreover, along with the data and its display modes, UIs must also provide actions that can be executed on data.
Actions typically represent all those operations that appear in the command bar and that involve either the
invocation of your business logic or simple navigation activities between the page (such as opening a data detail or
navigating to a target screen).
In the Model-Driven Module Editor you can implement two types of user interfaces: a Master Data screen and a
Master Detail screen.
Once generated, Model-Driven UI interfaces are handled in the Manufacturing Solution in the same way as the
coded UI interfaces and the Mashup Screens (they can be assigned to user roles, they can be added to the runtime
UI Application, they can be deployed to the runtime environment).

How to create a Model-Driven UI Module


A Model-Driven UI Module is made up of one or more Model-Driven UI Screens. A Model-Driven UI Screen must have
one or more UI Contents. Each UI Content can have zero or more UI Actions. Fields are used both within UI Contents
as Entity Properties and within Actions as Command Parameters.
Each Action is characterized by a behavior that specifies what the action does (for example, it invokes a command
or it opens a page and so on).
Model-Driven UI Screens are associated to a Blueprint, which is a specialization of a View Representation.
Blueprints can be intended as a sort of template system to automatically render views at runtime, based on
common UX patterns and based on the configuration of a given UI artifact.

2.2.4.3.1.2 Creating a New Model-Driven UI Module


You can create a Model-Driven UI Module in Project Studio, in the UI Project of your App or Extension App.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 527


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

When you create a Model-Driven UI Module, the system generates a manifest with the entered project information.
You can extend a Model-Driven Module by copying it from a base App to an Extension App as described at page How
to Extend User Interfaces in an Extension App.

Procedure
1. In you App/Extension App solution, right-click the <Prefix>.<AppName>/modules folder and then select
the Add > New Item command.
2. Select the UI Model-Driven Module template (Visual C#\Web section).
3. Type the file name in the Name edit box and click Add. Under the modules project folder, the wizard creates
an .mdui extension file containing the project information (such as the module name, the module title, the icon
and so on). This information should not be modified here but rather in the module configuration page of the
Model-Driven UI Editor (as described later in the configuration process).

2.2.4.3.1.3 Opening the Model-Driven UI Module Editor


After the UI Module is created under the <Prefix>.<AppName>/modules folder you can open the Model-Driven
Editor as follows.
The UI Model-Driven service (corresponding to the node.exe process) must always be running in order to use the
editor.

Prerequisites
• The App, in which you are creating the Model-Driven UI Module, references the Functional Block that contains
the Entities, the Commands or the Reading Functions you want to use in the UI Module.
• The Entities to be used in the in Model-Driven Editor must be present in the Public Object Model of the App
(Functional Block entities cannot be directly accessed).
• The Public Object Model must contain at least one entity, otherwise the Model-Driven Editor cannot start.
• The POMModel project has been built to create the required assemblies.
• If you are modifying an existing Model-Driven UI Module, each time you apply a change to the POMModel project
(for example by adding an Entity or a Command), you must recompile the POMModel project and then stop and
start the UI Model-Driven Server.
• In the App/Extension App, right-click the <Prefix>.<AppName>UserInterface project and then select the Start
UI Model-Driven Server command.

Procedure
1. Right-click the module manifest file (<Acronym.AppName.ModelDrivenModuleName>.mdui or .ext) and then
select the Open UI Model-Driven Module Editor command. The editor opens in a Project Studio tab, with the
module configuration page open by default.

2.2.4.3.1.4 Modifying the Model-Driven UI Module Information


You can modify the default information of the generated UI Module in the Model-Driven UI Editor as follows.

Procedure
1. In the Module configuration start page, click Edit Module and enter the required information:
Parameter Description

Title Module public title that will be visible on top of the sidebar menu.

528 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Icon Module public icon. The module icon will be visible on the UI Application sidebar.
2. Click Save.
For more information on configuring the general settings for the model-driven UI module see, Configuring General
Settings for the Model-Driven UI Module.

Runtime module generation example

2.2.4.3.1.5 Creating a New Model-Driven UI Screen


A UI Screen is created in the Model-Driven UI Module Editor, inside a UI Module.
To configure a screen you will go through the definition of the following main elements:
• the layout, which specifies how you want to display the model entity, and from which data source you want to
query the entity values: either from the Live database or from the Archiving database (see Configuring Data
Sources).
• the content, which specifies the entity to display,
• the actions, which specify the operations you want to execute.

UI Screen Details
1. With the Module selected in the sidebar pane, click the plus icon, select Screen and click Add.
2. Enter the following information:

Parameter Description

ID The identifier assigned to the screen. Once the screen is created, the ID value cannot be
modified.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 529


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Title The title to be assigned to the UI Screen.

Header The resource translation key for the UI screen title. If a translation is required, enter a valid
resource translation key. The resource translation key must be present within a resource file,
which must be created as described at page Localizing Custom UI Apps and UI Framework
Resources. If present, Title will not be considered.

Icon (In Advanced Setting Enabled mode) Either of the following:


• Library: The SVG cmd icon name you want to associate to the screen, if the icon to be
inserted is selected among the pre-installed icons.
• Custom: The relative path for using your own SVG icon (added in the User Interface project
of the Functional Block Solution) must be specified as below:
Siemens.SimaticIT.Material/images/custom.svg
Here Siemens.SimaticIT.Material is the Functional Block Solution name.

Params The array of parameters that can be passed in input to the screen.

Securable The UI Screen will be defined as a securable object and will accessible only by authorized users
(via user roles).

Layout The template you want to assign to the screen (see examples below):
• Master, to display the entity record/s, which are retrieved from the Live database, on a
single pane, either in a grid view or in a tile view.
• Master-Details, to display entity records, which are retrieved from the Live database, on
two panes: the pane on the left (Master) displays the list of the records for a specified entity
type, and the pane on the right (Details) displays the details for the entity record you
selected in the Master pane.
• Custom, to insert an already developed custom screen in either of the following ways:
• (In Advanced Setting Enabled mode) By default, the Auto Generate State option
will be selected. Leave it selected and enter the following information, if you want
the model-driven runtime engine to create the UI Router State for your screen:
• Controller, the name of the controller (registered on the same module).
• Template URL, the template file path.
• (In Advanced Setting Enabled mode) Clear the selection from the Auto Generate
State option if you want to create the UI Router State for your screen by yourself. To
do so, you must assign to the custom state the same State Id which is indicated by
the model-driven editor. With this option selected, the model-driven runtime engine
will not generate the state for the screen.
• Master Archived, to display the entity records, which are retrieved from the Archiving
database, on a single pane, either in a grid view or in a tile view.
• Master-Details Archived, to display entity records, which are retrieved from the Archiving
database, on two panes: the pane on the left (Master) displays the list of the records for a
specified entity type, and the pane on the right (Details) displays the details for the entity
record you selected in the Master pane.

530 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Help (In Advanced Setting Enabled mode) The title of Documentation Center page to be linked as
contextual help.

How to Develop a Manufacturing Solution in Project Studio

Master example

Master-Details example

In the above example page, 1 indicates the Master screen and 2 indicates the Detail screen.

2.2.4.3.1.6 Configuring the Model-Driven UI Screen Contents


A Model-Driven UI Screen is made up of UI Contents and of UI Actions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 531


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

For each UI Content, you must specify an entity and, in addition, either the outcome of an OData query involving
one or more related entities, or the result of a Reading Function.
For each entity to be represented, you must specify the properties that are visible through Content Fields.
According to the layout specified in the screen configuration, you can do the following:
• For the Master screen layout, you must specify only one content.
• For the Master-Details screen layout, you must specify at least two contents (one for the Master and one for the
Details).
• Only if you have chosen a Master-Details screen layout, you can select the Audit Trail content behavior to
display audit trail information for the entity selected in the Master content.
• If you have chosen either the Master Archived or the Master-Details Archived screen layout, you can only
configure a subset of functionalities because the archiving endpoint (used to expose the Archiving data source
data) allows you to perform only reading operations.

Procedure
1. With a screen selected in the sidebar pane, click , select Content and click Add.
2. Only for Master-Details view screen types, select the content type you are configuring:
either Master or Details.
3. According to the Behavior you specify (see the reference table below), not all tabs will be available:
• For One or Many, enter the required information starting from the Details tab and then move to the
other tabs.
• For Audit Trail, enter only ID and Title as explained below.

Details tab configuration


Parameter Description

ID Content unique identifier.

Title The title that is displayed for the Details contents as tab titles (for the Master content, it will
not display any title).
If a translation is required, enter a valid resource translation key. The resource translation key
must be present within a resource file, which must be created as described at page Localizing
Custom UI Apps and UI Framework Resources.

Use Custom If selected, you can use a custom content as the Detail Content of a Master-Detail UI Screen
Behavior with the template.
See Configuring a Custom Content for a Master-Details UI Screen for reference.

 The Behavior configuration will be hidden. Also, all other tabs are disabled except for
the Details Tab.

Template The template file path.

532 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Behavior It specifies how to display data:


• One, if you want to display a grid for one entity record, with the record details on different
rows. See the example screenshot below. This option inserts a propertyGrid widget in the
content. For more information, see widgets.propertyGrid in the Opcenter Execution
Foundation UI Framework Reference.
• Many, if you want to display more entity records either in a grid or in a tile view. See the
example screenshot below. This option inserts an itemCollectionViewer widget in the
content. For more information, see widgets.itemCollectionViewer in the Opcenter Execution
Foundation UI Framework Reference.
• Audit Trail, if you want to display an audit trail record related to the entity which is
currently selected in the Master content. See the example screenshot below. This option
inserts an auditTrail widget in the content. For more information, see widgets.auditTrail in
the Opcenter Execution Foundation UI Framework Reference.
In case of Audit Trail behavior, all the configuration tabs that are described below are disabled.

 The Audit Trail behavior is not available for Master Archived and Master-Details
Archived screen layouts.

Entity If selected, it allows you to browse the entity exposed either by the Public Object Model App/
Extension App or by the archiving endpoint (see Executing Queries on Archived Entities).

 Whenever a DB view or a Third Party Entity view is selected from the Entity Picker, you
should choose a root entity to Export and Edit Segregation Tags. If root entity is not
configured you will not see the Enable Edit Tags and Enable Export check box in the
General Setting tab.

Facets (Only on Entity selected) It allows you to browse the facets associated to the selected Entity
and add them. Multiple facets can be added. Click on Add Item to add a facet and specify the
following:
• Facet, select the facet you want from the list of available Facets of the Entity.
• Alias, provide an alias name for the facet selected which will be used as reference for field
names. For example, if the Facet Alias is given as FacetAlias1 and the fields of the facets
will be represented as FacetAlais1.Field in the Fields Tab and the same field can be used
to configure in General Settings, Tile Settings and so on.
See Example for Configuring Facets in Contents.

 Facet and Facet Aliases configured has to be unique. A same facet cannot be added
more than once.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 533


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Reading If selected, it allows you to browse the Reading Function(s) exposed by the Public Object Model
Function App/Extension App.
By configuring the field Root Entity, you will select the entity to be used as reference one for
proper manage Segregation Tag and Export Data Functionalities at runtime.

 This option is not displayed for Master Archived and Master-Details Archived screen
layouts.

 When a Reading Function is selected, you should configure a root entity. If root entity
is not configured you will not see the Enable Edit Tags and Enable Export check box
in the General Setting Tab.

Params Specifies the input parameters to be passed to the Reading Function. The input parameters are
populated on Reading Function selection.

Input Parameters

{
"ConstantString":"'DefaultCounter'", // constant string
parameter
"ConstantNumber":
1000, // constant number parameter
"ConstantBool": true, // constant boolean
parameter
"CounterId":"contents.Master.selectedItem.Id" //contextual
expression
}

oDataQuery Specifies a query (via oData or via a dedicated query editor), in order to set filtering criteria.
The syntax must be specified starting from the dollar sign, as in the following example:

$filter=NId eq {{contents.WorkOrdersDetails.selectedItem.NId}}

Disable When If selected, it disables the content tab if the condition is satisfied and the condition is either an
Expression or a Function. See Contents and Expressions.
This option is available only for Detail contents of Master-Details screen.

 If a condition is configured here to disable the first Detail content, at runtime this
content will not be disabled since a first active tab of a tab set cannot be disabled.

534 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Behavior Screen

One

Many

Audit Trail

Fields tab configuration


Based on the selected entity, the entity properties will be automatically loaded into the Content as UI Content
Fields. You can decide to add, modify or delete Fields.

 A field named Id is mandatory to be present for the entity or reading function selected in Details tab
configuration. This is required for supporting drill-down and unique content item selection capabilities in
the model-driven runtime.

Parameter Description

Name Unique internal identifier, to be used when configuring an expression and you
need to retrieve the field data. If a Facet is included, then properties related to
Facet will be represented as FacetAlias.FieldName.

Property Entity or Facet property name.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 535


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Label Property display name, both for tiles and for grids.
If a translation is required, enter a valid resource translation key. The resource
translation key must be present within a resource file, which must be created
as described at page Localizing Custom UI Apps and UI Framework Resources.

Type The data type of the field.

Group (Optional and enabled only for content of multiplicity:one) The group to
which the field belongs to (see Configuring General Settings for the Model-
Driven UI Module).
The grouped fields will be rendered together in an accordion (For more
information see, Example of Configuring Groups for Content Fields).

General Settings tab configuration


Section Para Description
meter

Data Use Select the check box, if you want the data retrieval for your itemCollectionViewer to be
Settings Serve server-side. By default, it is set to client side. If the Enable Pagination option is not
r Side selected, the data is fetched from the server as you scroll down.

Enabl Select the check box, if you want to select multiple content items in the runtime. Select
e all option will be available in the runtime for View Mode of the Grid only. (See Example of
Multi Configuring Multi-Select Capabilities in Contents)
Select
ion
 This will be available only for contents of Behavior: Many and will be
unavailable for Master content of Master-Details screens.
When selecting the Enable Multi Selection, the Show When of the action buttons
must be configured by writing an expression to hide/show the button depending
on the selection of multiple items. See Contents and Expressions.
In the Grid mode, if the options Use Server Side and Enable Pagination are
enabled, only the items selected in the first page remains selected on exit of an
action.

536 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Para Description


meter

Enabl Select the check box, if you want to export data.


e
For more information, see Exporting data from the Runtime Database in Opcenter
Expor
Execution Foundation User Guide.
t

 This will be available in the following cases:


• only when the data source is an entity that belongs to the domains Master
Data, Reference Data or System Data.
• for contents of Behavior: Many (and it will be unavailable for Master
content of Master-Details screens.)
• when the Enable Multi Selection check box is selected.

 When a Reading Function is selected, you should configure a root entity. If root
entity is not configured you will not see the Enable Export check box in the
General Setting Tab.

 When a DB view or Third Party Entity is selected, you should configure a root
entity. If root entity is not configured you will not see the Enable Export check
box in the General Setting Tab.

Enabl Select the check box, if you want the pager to be available for your itemCollectionViewer.
e If this option is not selected, a scrollbar is displayed to browse the available items.
Pagin
ation

Page (Only in Advanced Settings Enabled mode) If you have selected the Enable Pagination
Size option, you must configure the page size of the itemCollectionViewer by specifying the
number of items per page (e.g. If the page size is 25, then 25 items per page is shown in
your itemCollectionViewer). This will not be available if the content is a Master of a
Master-Details screen since the itemCollectionViewer is rendered in compact mode and a
scrollbar is available to browse the other available items.

Display Mode The content display mode (Tile only, Grid only, Tile and Grid).
Settings

Defau (Only in Advanced Settings Enabled mode) Allows you to select a default view of an
lt itemCollectionViewer if the selected Mode is Tile and Grid. By default, Grid is selected.
View

Print It is a checkbox for enabling the ICV print button on runtime. If Grid only, Tile and Grid
Enabl Mode is selected this option for print capability will be displayed. Print capability is only
e available for Grid and not for Tile Mode.

File Value of this field will be prefix of the downloaded file. This field is visible only when the
Name print field is enabled.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 537


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Para Description


meter

Separ Value of this field will be used as column separator for the downloaded file. This field is
ator visible only when the print field is enabled.

Field Quick If you want to set the selected property as a search key in the Quick Search.
Settings Searc
At runtime, the Quick Search is a text box where you can enter a search string (applied
h
only to the properties defined as Quick Search relevant).

Quick (Only in Advanced Settings Enabled mode) Enter, if you want to display a custom place
Searc holder for the Quick Search text box at the runtime.
h
Place
holde
r

Data If you want to display the data segregation tags associated with the selected entity.
Segre
An example is provided to show data segregation tags.
gation
Tag

Enabl Select, If you want to enable the tags manager button for the itemCollectionViewer.
e Edit
This option is not available for Master Archived and Master-Details Archived screen
Tags
layouts.
When Reading Function is selected, you must configure a root entity. If root entity is not
configured you will not see the Enable Edit Tags check box.
When a DB view or Third Party Entity is selected, you must configure a root entity. If root
entity is not configured you will not see the Enable Edit Tags check box.

Group If you want to make the property visible in the Groupable drop down list box.
able
At runtime, the Groupable drop down list box contains the entity properties, by which
you can group the results.

Sorta If you want to make the property visible in Sortable drop down list box.
ble
At runtime, the Sortable drop down list box allows you to select the entity property, by
which you want to sort the results.

Breadcr Bread (Only in Advanced Settings Enabled mode and for Master Contents) If you select a
umb crumb content field, the value of the content field is displayed as the breadcrumb title in the
Settings Title runtime.
At runtime, the last element of the breadcrumb is displayed based on the selected object
in the master-details screen.

538 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Para Description


meter

Use Select the check box, if you want to display the screen title also in the breadcrumb.
Scree
At runtime, the configured breadcrumb title is displayed next to the screen title.
n Title

 If the breadcrumb title is not configured then, by default the screen title is
displayed as the breadcrumb.

Tile Settings tab configuration


Parameter Description

Icon The icon to be displayed on the tile.


The relative path for using your own SVG icon (added in the User Interface project of the
Functional Block Solution) must be specified as below:
Siemens.SimaticIT.Material/images/custom.svg
Here Siemens.SimaticIT.Material is the Functional Block Solution name.

Title If you select an entity property, this property is displayed as tile title.

Descriptio If you select an entity property, this property is displayed as descriptive second row of the tile.
n

Property You can add other properties to be displayed on the tile by clicking on Add Item and selecting the
Fields entity property. The tile displays maximum of four properties at a time.
The Visibility of each property can be defined by writing an Expression or a Function. See
Contents and Expressions.
It is possible to add a maximum of eight properties.

Enable Cell If set to true, all the Property Fields configured is shown irrespective of the tile size.
If set to false, the number of properties shown is dependent on the tile size.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 539


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Indicators An indicator is used to indicate few statuses of an entity instance. For example, if an entity
instance's status is made as Frozen, then indicators are used to pictorially represent that this
particular instance is frozen.
If you want to configure the indicator settings of a tile, specify the following:
• Icon
Library: The SVG icon to be displayed.
Custom: The relative path for using your own SVG icon (added in the User Interface project
of the Functional Block Solution) must be specified as below:
Siemens.SimaticIT.Material/images/custom.svg
Here Siemens.SimaticIT.Material is the Functional Block Solution name.
• Visibility, the condition on which the indicator must be visible. This property can be set to an
expression string or a function that is evaluated in the context of each tile. See Contents and
Expressions.

Visible Expression Example

tileContent.IsFrozen

Maximum only 10 indicators can be configured.

540 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Command If you want to configure the command settings of a tile, specify the following:
s
 Any changes to the commands will synchronize with Grid command configured in Grid
Settings and vice versa.
Any changes to the commands will synchronize with Drill Down Action with
Synchronize with Tile/Grid Command enabled and vice versa.
See an example for configuring data drill down capabilities.
See Example of Configuring Drill Down based on a Condition.

• Icon, the font-awesome icon or SVG icon to be displayed.


• Tooltip, the tooltip to be displayed.
• Destination Screen, select the destination screen to be navigated.
• Conditional, select if you want to add multiple destination screens based on a condition. By
Default, the first added screen will be set as default. See Example of Configuring Drill Down
based on a Condition.
• Params, lists the input parameters configured for the selected Destination Screen. Specify
the input parameters to be passed to the destination screen.
• Default, (on Conditional selected) select if you want to make the added destination screen
as default. This means that at runtime this will be considered as the screen to navigate in case
of no condition evaluates to true. It is mandatory to have one default screen configured if
Conditional is selected.
• Condition, (on Conditional selected) enter the condition on which the the destination screen
must be navigated at the runtime. This property can be set to an expression string or a
function that is evaluated in the context of each tile. This field will be hidden if Default is
selected. See Contents and Expressions.

Conditional Drill Down Expression Example

currentContentItem.Type === 'Visual'

 The Destination Screen menu lists all the screen names in the the app. You can choose
any screen across all the modules in the current app as the Destination Screen.
If more than one destination screen is configured with the same condition, then the
screen encountered at the first in the order of the screens added will be considered for
navigation.
If a single Destination Screen is configured, then in runtime the command will be hidden
in case the user is not authorized to view the screen.

To remove any selection, click Reset.

Grid/Field Settings tab configuration


To show or hide fields (i.e. columns), drag and drop the fields from Available Columns to Selected Columns. In
runtime, the field appears in the same order as in the collection of Selected Columns. You can use drag and drop
vertically to reorder the fields in Selected Columns.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 541


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

You can personalize the Field Settings preferences if the content Behavior is set to One by doing the following:

Paramete Description
r

Type Displays PropertyGrid as a list.


• Fluid: The number of columns is managed dynamically, i.e. the number is defined
automatically according to the width available.
• Fixed: The number of columns is predefined.

Columns Number of columns to be displayed for the Fixed type.


The Visibility of each field in the Available Columns can be defined, by writing an Expression or a
Function. See Contents and Expressions.

To configure indicators, select the check box on the field (i.e. columns) from Selected Columns and you can
personalize the Indicator Settings by doing the following.

 Configured column for indicators appears in Indicators section as an accordion. Any changes will
be synchronize with Grid Settings.

Indicator Settings

Paramete Description
r

displayIco Column header icon to be displayed. The icon is displayed only if indicators are configured.
n

Indicators • Icon
Library: SVG icon to be displayed.
Custom: The relative path for using your own SVG icon (added in the User Interface project
of the Functional Block Solution) must be specified as below:
Siemens.SimaticIT.Material/images/custom.svg
Here Siemens.SimaticIT.Material is the Functional Block Solution name.
• Visibility, the condition on which the indicator must be visible. This property can be set to an
expression string or a function that is evaluated in the context of each tile. See Contents and
Expressions.

Visible Expression Example

tileContent.IsFrozen

• Tooltip, the tooltip to be displayed.

542 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

You can personalize the Command Settings of a grid, if the content Behavior is set to Many by doing the following:

 The configured command will be shown in the first selected column of the grid. See an example for
configuring data drill down capabilities.
Any changes to the commands will synchronize with Tile command configured in Tile Settings and vice
versa.
Any changes to the commands will synchronize with Drill Down Action with Synchronize with Tile/Grid
Command enabled and vice versa. See Example of Configuring Drill Down based on a Condition.

Parameter Description

Icon The font-awesome icon or SVG icon to be displayed.

Tooltip Specifies the tooltip to be displayed.


If a translation is required, enter a valid resource translation key. The resource translation key
must be present within a resource file, which must be created as described at page Localizing
Custom UI Apps and UI Framework Resources.

Destinatio Select the destination screen to be navigated.


n Screen
 The Destination Screen menu lists all the screen names in the the app. You can choose
any screen across all the modules in the current app as the Destination Screen.
If a single Destination Screen is configured, then in runtime the command will be hidden
in case the user is not authorized to view the screen.

Conditiona Select if you want to configure multiple destination screens based on a condition.
l
 If more than one destination screen is configured with the same condition, then the
screen encountered at the first in the order of the screens added will be considered for
navigation.

See Example of Configuring Drill Down based on a Condition.

Params Lists the input parameters configured for the selected Destination Screen. Specify the input
parameters to be passed to the destination screen.

Default (on Conditional selected) Select if you want to make the added destination screen as default.
This means that at runtime this will be considered as the screen to navigate in case of no
condition evaluates to true. It is mandatory to have one default screen configured if Conditional
is selected.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 543


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Description

Condition (on Conditional selected) Enter the condition on which the the destination screen must be
navigated at the runtime. This property can be set to an expression string or a function that is
evaluated in the context of each grid row. This field will be hidden if Default is selected.

Conditional Drill Down Expression Example

currentContentItem.Type === 'Visual'

See Contents and Expressions.

Filter Settings tab configuration


The system retrieves the same fields that have been configured in the Fields tab. You can configure the
itemCollectionViewer's filter by doing the following :
1. To edit the page, click the Enable Filter button.
2. Select the Type to be either Filter Builder (Default) or Filter Panel.
3. (Only for Filter Builder) If necessary, configure the itemCollectionViewer's filter fields grouping, by selecting the
Enable Filter Group check box.
4. (Only for Filter Builder) Select the required logical operator from the And/Or drop down list box to define the
logical comparison to apply with the prior clause.
5. (Only for Filter Builder) If necessary, enable a case sensitive search by selecting the Enable Case Sensitive
search check box.
6. For each field, enter the following information:

Section Parameter Description

General Filterable If you want to enable this field as one of the filter fields.
Settings

Type Shows the type of the field being configured.

Default (Only for Filter Builder) If set to true, the field is by default added to the filter
dialog in an itemCollectionViewer.

Operators (Only for Filter Builder) If you want to configure different operators required for
a field.

544 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parameter Description

Value Pre-Defined If you want to configure the widget to use for the data input in
Settings Values itemCollectionViewer's filter.
• Input Text, if you want to display an input text field.
• List of Values (Manual Entry), if you want to display a drop-down list box
with a list of values. You can enter the values manually by clicking on plus
icon .
• List of Values (Query Result), if you want to display a drop-down list box
with a list of values. You can configure the entity and the following
information to fill the drop down list box with the query result.
• Use Entity Picker, If selected an entity picker will be shown instead
of a drop-down list in the runtime. This option is available only if List
of Values (Query Result) is selected in the Pre-Defined Values.
• Data Source, select the data source to be used to perform the query.
The accepted values are Entity and Reading Function. Entity is
selected by default. You can configure the following additional
parameters:
• Name, the name of the entity/reading function to be retrieved.
• Title, a title for the entity picker dialog at runtime (Available only
when Use Entity Picker is checked).
If a translation is required, enter a valid resource translation key. The
resource translation key must be present within a resource file, which
must be created as described at page Localizing Custom UI Apps and
UI Framework Resources.
• Query, the filter expression for the entity to retrieve the required
record.
• Display Property,the property whose value you want to be shown in
the drop-down list.
• Value Property, the property whose value you want to actually pass
to the action field.
• Configure Entity Picker, click to configure the additional parameters
for an entity picker. For more information on configuring entity picker
see, Entity Picker Configuration section.

 While configuring the Value Settings for a Filter Field in the Filter
Settings, properties from facets are not available for configuration if the
User Input Mode is List of Values(Query result).

Validation Required If selected, the field value cannot be empty.

Min According to the type of field, specifies the minimum number of digits accepted
Length (or for the field value, or the minimum value.
Min)

Max Length According to the type of field, specifies the maximum number of digits accepted
for the field value, or the maximum value.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 545


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parameter Description

Pattern A valid regular expression used to validate the field.


For example, the following regular expression validates a string starting with a
letter and followed by one or more letter, number, or underscore:

/^[a-z][a-z0-9_]+$/i

2.2.4.3.1.7 Configuring a Custom Content for a Master-Details UI Screen


You can configure a custom Details content in a Master-Details UI Screen by specifying the Template file path.
You can attach any controller (registered on the same module) to the template.

Procedure
If you want to interact with the model-driven runtime context from your custom template, follow the steps below:
1. Listen to the event mdui-context-refreshed inside your controller to get the Master Content's current selected
item.
2. Inject common.services.modelDriven.runtimeService service inside your controller.
3. In the place where you initialize your controller, call the initCustomContent method of the above service.
This returns an object which has the below callback functions:
• getContext, gets the complete UI Screen context
• setContext, updates the Model-Driven Runtime Context with the custom content data.
• getData, gets the data depending on the Entity or Reading Function configured.
4. Inside the controller call these callback functions (see example below).

 These steps must be performed only if you still want to use Model-Driven Runtime to make the queries to
fill the custom template data.
In this case, you can select the Entity or Reading function in the Details tab ( see Configuring the Model-
Driven UI Screen Contents).
Otherwise it is up to you to manage loading the data inside your custom template.

For example, refer to the following sample template and controller code :

546 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Sample Template

<div ng-controller="failureAttachmentsCtrl as ctrl" style="height:600px;">


<sit-document-viewer ng-if="activeContent === 'Attachments' &&
ctrl.isMasterSelectionChanged"
sit-data="ctrl.data"
sit-categories="ctrl.categories"
sit-actions="ctrl.actions"
sit-config="ctrl.config">
</sit-document-viewer>
</div>

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 547


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Sample Controller

(function () {
'use strict';
angular.module('Siemens.OpcenterEX.FN.Defect')
.controller('failureAttachmentsCtrl', ['$rootScope', '$scope', '$q',
'$timeout', 'common.services.modelDriven.runtimeService',
'common.services.runtime.backendService', function ($rootScope, $scope, $q, $timeout,
mdService, backendService) {
var vm = this;
var mdSvcApis = {};
var backend = backendService;
vm.isMasterSelectionChanged = false;
activate();
function activate() {
var contentName = 'Attachments'; //If invalid, then the apis will not
be available.
subscribeToModelDrivenRuntime(contentName);
initDocumentViewerConfig();
}

function findFormat(mimeType) {

if (mimeType == "text/plain")
return "text";
if (mimeType == "image/svg+xml")
return "svg";
if (mimeType == "application/pdf")
return "pdf";
if (mimeType.match(/^image\//))
return "image";
if (mimeType.match(/^video\//))
return "video";
}

function initDocumentViewerConfig() {
vm.data = [

];

vm.categories = [
{
"id": "1",
"label": "Attachment list",
"uploadEnabled": false,
"deleteEnabled": false
}
];

vm.selectTab = function () {
vm.config.selectCategory("1");

548 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

};

vm.actions = [

];

vm.config = {
"title": "Documents",
"showFirstDocument": false,
"mode": "display",
"fullScreenMode": "toolbar",
"plugins": [
{
"format": "svg",
"viewer": "sit-vector-viewer"
}
]
};
}

function subscribeToModelDrivenRuntime(contentName) {
//gets the model-driven runtime apis to interact with the context and
data.
mdService.initCustomContent(contentName).then(function (apiList) {
mdSvcApis = apiList; //gets the api list
}, function (error) {
//An error message will be passed in case of invalid custom
contents.
});
}

function loadFile(fileId, iconId) {


//var options = "$filter=Id eq " + fileId;
//var queryModel = {};
//queryModel.appName = "Defect";
//queryModel.entityName = "File(" + fileId + ")";
var defer = $q.defer();
var object = {
"appName": "Defect",
"functionName": "GetAttachmentFile",
"params": { FileId: fileId, IconId: iconId }
};
// queryModel.options = options;
backend.read(object).then(function (data) {
//backend.findAll(queryModel).then(function (data) {
if ((data) && (data.succeeded)) {
self.viewerData = data.value;
var len = vm.data.length;
vm.data[len] = {}
vm.data[len].name = data.value[0].File.name;
vm.data[len].category = "1";
vm.data[len].remote = "true";

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 549


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

vm.data[len].format = findFormat(data.value[0].File.type);
vm.data[len].source = data.value[0].File.data;
if (data.value[0].Icon != undefined)
vm.data[len].thumbnail = data.value[0].Icon.data;
setTimeout(function () { vm.isMasterSelectionChanged = false;
}, 50);
vm.isMasterSelectionChanged = true;
} else {
self.viewerData = [];

}
defer.resolve();

}, backend.backendError);
return defer.promise;
}
function loadFailureAttachments(data) {
var defer = $q.defer();
var promises = [];
for (var ndx = 0; ndx < data.length; ndx++) {
var fileId = data[ndx].FileAttachment_Id_Id;
var iconId = data[ndx].IconAttachment_Id_Id;
promises.push(loadFile(fileId, iconId));
}
$q.all(promises).then(function () {
defer.resolve();
});
return defer.promise;
}

function loadAttachments() {
var options = null;
vm.data = [];
options = "$filter=Failures/any(w: w/Id eq " + vm.selectedMaster.Id +
")";
mdSvcApis.getData(options).then(function (data) {
loadFailureAttachments(data).then(function () {
vm.isMasterSelectionChanged = false;
$timeout(function () { vm.isMasterSelectionChanged = true; },
100);
})
}, function (error) {
//An error message will be passed in case where entity or reading
function is not configured, but still getData api is called
});
}
//an event triggered once the model-driven context changes
var mduiContextRefreshedListener = $rootScope.$on('mdui-context-
refreshed', function (event, params) {
var eventType = params.event;

//event triggered on a master selection

550 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

if (eventType === 'onMasterSelection') {


vm.selectedMaster = params.data;
loadAttachments();
}

//event triggered on a master unselection


if (eventType === 'onMasterUnselection') {
vm.data = [];
vm.isMasterSelectionChanged = false;
vm.selectedMaster = null;
return;
}

//event triggered once a command action is complete


if (eventType === 'onActionCompletion') {
var actionOutcome = params.data //gets the outcome for selection
based on onExit configured.
loadAttachments();
}
});

function getContext() {
mdSvcApis.getContext(); //gets the complete model-driven UI Screen
runtime context
}
function selectionChanged(item) {
mdSvcApis.setContext(item); //updates the model-driven runtime
context with the current selected item
}

//destroy the event listener


$scope.$on('$destroy', function () {
mduiContextRefreshedListener();
});
}
]);
})();

Result
The custom content configured will be available in the details tab of a Master-Details UI Screen as shown in the
example below.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 551


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.3.1.8 Configuring the Model-Driven UI Screen Actions


To complete the functionality of a Model-Driven UI Screen, you can configure some UI Actions for the UI
Contents (for example to invoke a command on the selected content entity or to open another page).

Procedure
1. With a content selected in the sidebar pane, click the plus icon , select Action and click Add.
2. Enter the required information starting from the Details tab and then moving to the other tabs described below.

Details tab configuration


1. Select either of the following display modes, according to the highlighting you need (see example at the end of
this page):
• Primary button, to display a blue button with a command label,
• Default button, to display a button with only an icon on it.
2. Set the following parameters:

Paramete Description
r

ID Action identifier.

Title Button label.


If a translation is required, enter a valid resource translation key. The resource translation key
must be present within a resource file, which must be created as described at page Localizing
Custom UI Apps and UI Framework Resources.

Group Specifies the group to which the action belongs (see Configuring General Settings for the Model-
Driven UI Module for reference).

552 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Paramete Description
r

Icon Icon to be displayed on the button.


The relative path for using your own SVG icon (added in the User Interface project of the
Functional Block Solution) must be specified as below:
Siemens.SimaticIT.Material/images/custom.svg
Here Siemens.SimaticIT.Material is the Functional Block Solution name.

Tooltip (Only in Advanced Settings Enabled mode) Tooltip to be displayed.


If a translation is required, enter a valid resource translation key. The resource translation key
must be present within a resource file, which must be created as described at page Localizing
Custom UI Apps and UI Framework Resources.

Params (Only in Advanced Settings Enabled mode) A list of parameters to be passed to the action, so
that they can be referenced from expressions within action fields.
For example, if an action requires an item to be selected from the current content, the ID of this
item is typically passed as parameter to the action in order to retrieve the data of the currently-
selected item via a separate query.

Show You can configure simple expressions to show the action button if a certain condition is satisfied.
When Such conditions will be evaluated at run time within the context of the current screen and can be
expressed in either of the following ways:
• Expression, to enter a condition.
• Function, to enter the body of a javascript function.
For more information, see Contents and Expressions.

Behavior tab configuration

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 553


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description

Execute To invoke a public command, with input parameter dialog box.


command
 The Execute command action type is not available for Master Archived and Master-
Details Archived screen layouts.

For this action type you must specify:


• Command, the public command to be invoked.
• (Only in Advanced Settings Enabled mode) Disable When, the condition on which the
Submit button of the action form will be disabled. The evaluated value of this condition is
also considered along with the regular widgets.propertyGrid's form validation. For more
information on expression or function, see Contents and Expressions.
• (Only in Advanced Settings Enabled mode) Entity or Reading Function on which the query
should be made to pre-fill the matching action fields with the result.
• (Only in Advanced Settings Enabled mode) Query to specify a query for filtering for a
certain record, to be passed to the action field values.
• (Only in Advanced Settings Enabled mode) In Side Panel Behavior, select the following
configurations for your side panel.

 If a translation is required, enter a valid resource translation key. The resource


translation key must be present within a resource file, which must be created as
described at page Localizing Custom UI Apps and UI Framework Resources.

• Size, select the size of the side panel. Allowed sizes are Large and Small.
• View Mode (Only if Size is set to Small), clear the Modal check box if you want to
open the side panel without blocking the screen, otherwise you can clear this option
and the panel will be opened in a non modal view. By default, the Modal option is
selected (see examples below).
• Submit Title, the label to be displayed on the button that saves the given data in the
side panel. If the field is empty, by default Submit is displayed.
• Header Title, to display the configured side panel title. By default, the label is Action
title field if the field is empty.
• Header Title Field, to display the contextual information for the selected item.
• Cancel Title, the label to be displayed on the button that cancels or closes the side
panel without any changes. If the field is empty, by default Cancel is displayed.
• Close by clicking outside, the behavior of the side panel when a user clicks outside
the panel area. It can be one of the following options:
• Do not close.
• Close with confirmation.
• Close without confirmation.
Do not close is the option selected by default.
• (Only in Advanced Settings Enabled mode) On Exit, to specify which item you want to
automatically select and which content you want to automatically refresh after the action
completion, as follows:
• Click on Add Item to add an On Exit item.

554 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description
• Select Content Id from the drop down list that you want to refresh after the action
completion (belonging either to the Master content or to the Details content,
according to the context where the action is configured).
• In the Selection Key edit box, type the command output parameter to be used to set
the guid of the entity record that must be automatically selected (belonging either to
the Master content or to the Details content, according to the context where the
action is configured);

• Behavior - Use Custom Blueprint, if you want a custom side panel with your own input
form for your action. With this option selected, all the configurations of the Behavior tab
will be hidden and the Fields tab will be disabled. See Configuring Custom Action Types for
Execute Command and View Actions.
• Use In-Canvas Behavior, if you want a custom In-Canvas mode with your own input from
your action. This option is visible once you select the Use Custom Blueprint.
See Configuring Custom Action with In-Canvas Mode for Execute Command and View
Actions.
• Display Mode, by default the mode is selected as side panel, but you will also have an In-
Canvas option. The following option is available when you select the mode as In-Canvas:
• No of columns

 If Action is configured as Side Panel in the Base App, you will have an option
to change it as In-Canvas mode in the extension app. In such scenario if
multiple extension installed for Base App, preference is given to In-Canvas.

 When Display Mode is selected as In-Canvas, you will not see the Size, View
Mode and Close by clicking outside options.

 When In-Canvas Panel for Execute command action is open and the user
tries to navigate away using sidebar, user will view a warning pop-up. If click
Continue, user will be navigated to another screen. If user click cancel, then
everything will be retained.

 When In-Canvas Panel for Execute command action is open and the user
tries to refresh or reload the browser, user will view a confirmation pop-up.
If click Reload, user will be navigated to parent screen. If user click cancel,
then everything will be retained.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 555


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description

Execute To invoke a public command without user interaction, by displaying a confirmation message
command overlay.
with
confirmatio
 The Execute command with confirmation action type is not available for Master
n Archived and Master-Details Archived screen layouts.

For this action type you must specify:


• Command, the public command to be invoked.
• In Overlay, select the following configurations for your side panel.
• Message (required), custom message to be displayed in the confirmation window.
• (Only in Advanced Settings Enabled mode) Title, the label to be displayed in the
overlay as title. If the field is empty, by default Confirmation is displayed.
• (Only in Advanced Settings Enabled mode) Yes, the label to be displayed on the
button that validates the action. If the field is empty, by default Yes is displayed.
• (Only in Advanced Settings Enabled mode) No, the label to be displayed on the
button that invalidates the action. If the field is empty, by default No is displayed.

 If a translation is required, enter a valid resource translation key. The


resource translation key must be present within a resource file, which must
be created as described at page Localizing Custom UI Apps and UI
Framework Resources.

• (Only in Advanced Settings Enabled mode) On Exit, to specify which item you want to
automatically select and which content you want to automatically refresh after the action
completion, as follows:
• Click on Add Item to add an On Exit item.
• Select Content Id from the drop down list that you want to refresh after the action
completion (belonging either to the Master content or to the Details content,
according to the context where the action is configured).
• In the Selection Key edit box, type the command output parameter to be used to set
the guid of the entity record that must be automatically selected (belonging either to
the Master content or to the Details content, according to the context where the
action is configured);
To retrieve a property of the entity, for which you are invoking the selected command, and
display its value inside the message overlay, properly modify the following example to be used
in the Confirmation edit box:

Do you really want to delete UoM Factor


'{{contents.UoMFactor.selectedItem.TargetUoM.NId}}'?

556 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description

View To open a pane with a read-only view of the record. For this action type you must specify:
• Entity, the entity to be retrieved.
• Query, the query used to refine the retrieved data.
• (Only in Advanced Settings Enabled mode) In Side Panel Behavior, select the following
configurations for your side panel.

 If a translation is required, enter a valid resource translation key. The resource


translation key must be present within a resource file, which must be created as
described at page Localizing Custom UI Apps and UI Framework Resources.

• Size, select the size of the side panel. Allowed sizes are Large and Small.
• View Mode (Only if Size is set to Small), clear the Modal check box if you want to
open the side panel without blocking the screen, otherwise you can clear this option
and the panel will be opened in a non modal view. By default, the Modal option is
selected (see examples below).
• Header Title, to display the configured side panel title. By default, the label is Action
title field if the field is empty.
• Header Title Field, to display the contextual information for the selected item.
• Cancel Title, the label to be displayed on the button that cancels or closes the side
panel without any changes. If the field is empty, by default Cancel is displayed.
• Close by clicking outside, the behavior of the side panel when you click outside the
side panel area. Select one of the following options:
• Do not close
• Close with confirmation
• Close without confirmation
Do not close is selected by default.
• Behavior - Use Custom Blueprint, if you want a custom side panel with your own input
form for your action. With this option selected, all the configurations of the Behavior tab
will be hidden and the Fields tab will be disabled. See Configuring Custom Action Types for
Execute Command and View Actions.
• Use In-Canvas Behavior, if you want a custom In-Canvas mode with your own input from
your action. This option is visible once you select the Use Custom
Blueprint. See Configuring Custom Action with In-Canvas Mode for Execute Command and
View Actions.

 Facets are not available for configuring any Action of type View

• Display Mode, by default the mode is selected as side panel, but you will also have an In-
Canvas option. The following option is available when you select the mode as In-Canvas:
• No of columns

 You can select the number of columns between 2 to 7, and the width required for each
column is 328 pixels. The preference is given to the highest number of columns.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 557


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description

 When Display Mode is selected as In-Canvas, you will not see the Size, View Mode and
Close by clicking outside options.

Navigate To open a UI screen. For this action type you must specify:
• Destination Screen, select the destination screen to which you want to navigate.
• Params, specify the list of the input parameters configured for the selected destination
screen. These input parameters will be passed to the destination screen.

Input Parameters

{
"ConstantString":"'DefaultCounter'", // constant string
parameter
"ConstantNumber":
1000, // constant number parameter
"ConstantBool": true, // constant boolean
parameter
"CounterId":"contents.Master.selectedItem.Id" // contextual
expression
}

 • The Destination Screen menu lists all the screen names in the the app. You can
choose any screen across all the modules in the current app as the Destination
Screen.
• If the Source screen and destination screen are same, then the parameters can be
modified. These parameters can be used to filter the data.
• At runtime, if a user is not authorized to view the selected screen, the action will be
hidden.

The functionality also supports navigation among UI screens that belong to different App/
Extension Apps. In this case, Destination Screen and Params must be manually entered.

558 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description

Drill Down To perform drill down, you must specify:

 A field name Id is required for supporting drill down and unique content item selection
capabilities in the model-driven runtime. See an example for configuring data drill
down capabilities.

• Synchronize with Tile/Grid command, select in order to synchronize the current action
with the drill down commands configured for the parent content's Tile/Grid. The drill down
configuration will be in sync with Tile/Grid commands and vice versa.

 This will be available only for actions of content of multiplicity: many. In case of more
than one drill-down actions, this selection will be mutually exclusive. The action for
which synchronization enabled will be in sync with Tile/Grid commands and vice
versa.

• Destination Screen, select the destination screen to be navigated.


• Conditional, select if you want to add multiple destination screens based on a condition. By
Default, the first added screen will be set as default. See Example of Configuring Drill Down
based on a Condition.
• Params, lists the input parameters configured for the selected destination screen. Specify
the input parameters to be passed to the destination screen.

Input Parameters

{
"ConstantString":"'DefaultCounter'", // constant string
parameter
"ConstantNumber":
1000, // constant number parameter
"ConstantBool": true, // constant boolean
parameter
"CounterId":"contents.Master.selectedItem.Id" // contextual
expression
"NId":"currentContentItem.NId" // contextual
expression
}

• Default, (on Conditional selected) select if you want to make the added destination screen
as default. This means that at runtime this will be considered as the screen to navigate in
case of no condition evaluates to true. It is mandatory to have one default screen configured
if Conditional is selected.
• Condition, (on Conditional selected) enter the condition on which the the destination
screen must be navigated at the runtime. This property can be set to an expression string or
a function that is evaluated in the context of each tile/grid. This field will be hidden if
Default is selected. See Contents and Expressions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 559


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Description

Conditional Drill Down Expression Example

currentContentItem.Type === 'Visual'

 The Destination Screen menu lists all the screen names in the the app. You can choose
any screen across all the modules in the current app as the Destination Screen.
In runtime, if the single Destination Screen selected is not authorized for an user to
view, then the action will be hidden.

It also supports data drill down among UI screen belonging to different App/Extension App,
But Destination Screen, Conditional and Params has to be entered manually.

Automatic To invoke a public command without the user interaction.


command
 The Automatic command action type is not available for Master Archived and Master-
Details Archived screen layouts.

For this action type you must specify:


• Command, the public command to be invoked.
• (Only in Advanced Settings Enabled mode) On Exit, to specify which item you want to
automatically select and which content you want to automatically refresh after the action
completion, as follows:
• Click on Add Item to add an On Exit item.
• Select Content Id from the drop down list that you want to refresh after the action
completion (belonging either to the Master content or to the Details content,
according to the context where the action is configured).
• In the Selection Key edit box, type the command output parameter to be used to set
the guid of the entity record that must be automatically selected (belonging either to
the Master content or to the Details content, according to the context where the
action is configured);

Reload To refresh the page.

Fields tab configuration for UI Actions based on Commands


The system retrieves a set of Fields for the UI Command Action, based on the command you selected in the
Behavior tab and according to the Command signature that is present in the data model.
Fields can then be added, edited or removed in the same way as described for the Content Fields.
For each field, enter the required information:

560 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parame Description


ter

General Name Unique internal identifier, to be used when configuring an expression and you need to
Fields retrieve the field data.

Label Parameter label to be displayed in the input form.


If a translation is required, enter a valid resource translation key. The resource
translation key must be present within a resource file, which must be created as
described at page Localizing Custom UI Apps and UI Framework Resources.

Group Select a group from the previously defined groups (see Modifying the Model-Driven UI
Module Information) if you want the field to be part of the selected group in the side-
panel.

Default Sets the value of the field based on the condition configured and the condition is
either Expression or Function. See Contents and Expressions.
The condition will be evaluated only once and will not be evaluated after each change
in the fields inside the side panel.

 The Default field configuration will have no impact on the file uploader.

Hidden If selected, the parameter is not shown in the input form. To fill in its value, you can
specify an expression or a function.

Read- If selected, the parameter is visible in read-only mode in the input form.
Only

User Input Field Shows the type of the parameter. This will be editable only for newly added fields.
Mode Type
In the model-driven runtime, if the field of the type DateTimeOffset is not filled or is
Settings
emptied afterwards in the form opened in the side panel, the value that is sent to the
command input is null.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 561


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parame Description


ter

User To configure the widget that is displayed and used in action input form. This will be
Input automatically selected based on the Field Type (see Action Field Type Dependent User
Mode Input Modes table below).
• Input Text, if you want an input text field.
• Input Text Multiline, if you want an input text area with support of multiple lines.
If you want to populate the value of the Input Text or Input Text Multiline field
at runtime whenever an expression value changes, select Reload Data on change
and configure the following additional parameters:
• Entity, the entity type to be retrieved.
• Title, a title for the entity picker dialog at runtime (Available only
when Use Entity Picker is checked).
If a translation is required, enter a valid resource translation key. The
resource translation key must be present within a resource file, which
must be created as described at page Localizing Custom UI Apps and UI
Framework Resources.
• Query, the filter expression to retrieve the required record.
• Selection Property, the entity property from which you want to populate
the value of the field.
• List of Values (Manual entry), if you want a drop-down list with a list of values.
You can enter the values manually by clicking Add Item.
• List of Values (Query Result), if you want a drop-down list with a list of queried
values.
• Data Source, select the data source to be used to perform the query. The
accepted values are Entity and Reading Function. Entity is selected by
default. You can configure the following additional parameters:
• Name, the name of the entity/reading function to be retrieved.
• Query, the filter expression for the entity to retrieve the required record.
• Params, the input parameters for the selected reading function. The null
value validations for the input params have to be handled inside the
reading function implementation.
• Display Property, the property whose value you want to be shown in the
drop-down list. This will not be shown if the field is made as Hidden.
• Value Property, the property whose value you want to actually pass to the
action field. This will not be shown if the field is made as Hidden.
If you want to select an item of this drop-down list at runtime whenever an
expression value changes (an example is provided), based on an another
entity, then select Reload Data on change and Preselect Value and
configure the following additional parameters of Preselect Entity
Reference (this option will not be shown if the field is configured as
Hidden or if the Data Source is Reading Function):
• Entity, the entity type to be retrieved.
• Query, the filter expression to retrieve the required record.
• Base Value Property, the base entity property to be used
for selecting an item in the drop-down list.

562 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parame Description


ter
• Select Value Property, the entity property to be used for
selecting an item in the drop-down list.
If you want to use Reload Data on change on a hidden field, then a Selection
Property will be shown from which you can select the entity properties to be
used as the value of the hidden field.
• Numeric, if you want an input numeric field.
• Checkbox, if you want to display a check box.
• Date Time picker, if you want to display a datetime field.
• File Uploader, if you want to display a file upload. You can configure the
following additional parameters:
• Support All File Formats, clear this option if you want your file upload to
accept only few File Formats. This option is selected by default.
• File Formats, from the displayed list of the standard formats, choose the
required file formats to be accepted by the file upload. If you want to
select a custom file format, select Others in the drop-down list and specify
the custom file formats by clicking Add Item.
The value of a field configured with file uploader
(action.fields.FileUploaderField) will have the following attributes:
• type, the type of the file.
• name, the name of the file.
• contents, the converted base64 string of the file.
• data, the combination of type and contents. This is the suggested
way for using this value in the action command.

 While configuring an Action of type Execute command,facets are not


available for configuring the Data Source when User Input Mode is List of
Values(Query result) or when the Reload Data on change is selected
despite the User Input Mode. This is also applicable when this type of action
is extended.

Use (Only in Advanced Settings Enabled mode) If selected, an entity picker will be shown
Entity instead of a drop-down list in the runtime. This option is available only if List of
Picker Values (Query Result) is selected in the User Input Mode and you can select multiple
entity properties as Value property of the Entity Reference. Click Configure Entity
Picker to configure the additional parameters.
See Entity Picker Configuration section below.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 563


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parame Description


ter

Enable (Only in Advanced Settings Enabled mode) If selected, you will be able to select
Multi multiple items in a drop-down list in the runtime. This option is available only if List
Select of Values (Query Result) is selected in the User Input Mode.

 If Use Entity Picker is selected, Enable Multi Select check box will be
disabled and vice versa.

The selected items in the drop down will be sent as an array consisting the values of
the selected Value property of the Entity Reference to the command. (See Example
of Execute-Command Action with a Multi-Select Query Field for an example)

Format (Only in Advanced Settings Enabled mode) If you have set the Field Type to
DateTime, select the DateTime format to be displayed at runtime.
Available options are Short and Medium. By default, Medium will be selected.

Distinct (Only in Advanced Settings Enabled mode) If selected, the system will exclude from
the values that are displayed in the drop-down list any duplicated items returned by
the query response. This will not be shown if the field is made as Hidden.

Reload (Only in Advanced Settings Enabled mode) To re-execute the query when an
Data on expression value changes (for example, in a cascading drop-down list box, which
change must be refreshed according to the previous selection).

Pre (Only in Advanced Settings Enabled mode) To select an item in a drop-down list. By
Select default, first item of a drop-down list will be selected. If the Pre Select Entity
Value Reference is configured, then selection will be based on the query execution. This will
not be shown if the field is made as Hidden.

564 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parame Description


ter

Validati To configure the validation of the input field in one of the following ways:
on
• Required, if selected, the field value cannot be empty.
• Min Length (or Min), according to the User Input Mode selected, specifies the
minimum number of digits accepted for the field value, or the minimum value.
• Max Length (or Max), according to the User Input Mode selected, specifies the
maximum number of digits accepted for the field value, or the maximum value.
• Min size, for the User Input Mode as File Uploader, specifies the minimum size of
the file that can be uploaded (for example 200 KB).
• Max size, for the User Input Mode as File Uploader, specifies the maximum size
of the file that can be uploaded (for example 2 MB).
• Pattern, uses a valid regular expression to validate the field.
For example, the following regular expression validates a string starting with a letter
and followed by one or more letters, numbers, or underscore:

/^[a-z][a-z0-9_]+$/i

• Custom, to use a custom function body to validate the value of the field. In the
custom function body you can use the following parameters:
Parameter Description

forms sit-form of the propertyGrid. For more information,


see widgets.propertyGrid in the Opcenter Execution
Foundation UI Framework Reference.

validations The list of validation objects present in the manifest


for the field. It contains the required patternInfo,
minlength etc... of validation object for each field.

action The action context. For example:

action.fields.fieldName

customServices An object containing the instances of the custom


services included by the user (see Modifying the
Model-Driven UI Module Information).
The examples are provided at page Example of Custom Validation for an Action Field.
This option will not be shown if the field is configured as Hidden.

Binding Parame The name of the command parameter to which you want to pass the value.
ter

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 565


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parame Description


ter

Value Sets the value of the field based on the condition configured and the condition is
either Expression or Function. See Contents and Expressions.
The condition will be evaluated after each change in the fields inside the side panel.

Clear/ Disable If selected, disables the field if the condition is satisfied and the condition is either an
Disable When Expression or a Function. See Contents and Expressions.
When
This will not be shown if the field is made as Hidden.

Clear If selected, clears the current value of the field if the condition is satisfied and the
When condition is either Expression or Function. See Contents and Expressions.
This will not be shown if the field is made as Hidden.

Entity Picker Configuration


Tab Description

Fields Based on the selected entity/ reading function, the properties will be
automatically loaded into the Entity Picker. You can decide to add,
modify or delete Fields

General Settings • Placeholder, to configure a short hint that describes the expected
value of an entity picker.
• Searchable Field, select the property to be used as search key in
the Quick Search.
• Sortable Fields, select the properties to be visible in Sortable drop
down list box of the grid shown when the entity picker is opened.
• Use Server Side, set the data retrieval for your grid to be server-
side. By default, it will be set to client side.

 In case of server-side, the Value Property value must


include the Id field. The reason is that the Id is unique and
it is required for the selection of an appropriate item inside
the grid.

• Enable Pagination, select this check box if you want the pager to be
available for your grid. If this option is not selected, a scrollbar is
displayed to browse the available items.

Grid Settings You can customize the grid preferences by doing the following:
• showing or hiding fields (i.e. columns) by selecting the required field
and then clicking the Add to grid / Remove button.
• setting the field order in the grid, by selecting the item to be moved
and then clicking the arrow buttons on the right.

566 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Tab Description

Filter Settings Select the Enable Filter option if you want to enable the filter for the
grid that will be shown when the entity picker is opened. See Filter
Settings Configuration for an Entity Picker of an Action field section
below.

Fields tab configuration for UI Actions of type: View


The system retrieves a set of Fields for the UI Action View type, based on the entity you selected in the Behavior tab
and according to the Entity signature that is present in the data model.
It is possible to add, edit or remove the fields.
For each field, enter the required information:

Parameter Description

Property Unique internal identifier, to be used when configuring an expression and you need to retrieve
the field data.

Type Shows the type of the parameter. This is editable for fields.

Group Select one of the previously defined groups (see Modifying the Model-Driven UI Module
Information) if you want the field to be part of the selected group in the side panel.

Filter Settings Configuration for an Entity Picker of an Action field


The system retrieves the fields from the selected entity. You can configure the itemCollectionViewer's filter shown
when the entity picker is opened by doing the following: Click the Enable Filter button to edit the page.
1. If necessary configure the itemCollectionViewer's filter fields grouping, by selecting the Enable Filter
Group check box.
2. Select the required logical operator from the And/Or drop down list box to define the logical comparison.
3. If necessary enable a case sensitive search by selecting the Enable Case Sensitive search check box.
4. For each field, enter the following information:

Section Parameter Description

General Filterable If you want to enable this field as one of the filter fields.
Settings

Type Shows the type of the field being configured.

Default If set to true, the field is by default added to the filter dialog in an
itemCollectionViewer.

Operators If you want to configure different operators required for a field.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 567


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Parameter Description

Value Pre-Defined If you want to configure the widget to use for the data input in
Settings Values itemCollectionViewer's filter.
• Input Text, if you want to display an input text field.
• List of Values (Manual Entry), if you want to display a drop-down list box
with a list of values. You can enter the values manually by clicking on plus
icon .
• List of Values (Query Result), if you want to display a drop-down list box
with a list of values. You can configure the entity and the related
information to fill the drop down list box with the query result.

Validation Required If selected, the field value cannot be empty.

Min Length (or According to the type of field, specifies the minimum number of digits
Min) accepted for the field value, or the minimum value.

Max Length According to the type of field, specifies the maximum number of digits
accepted for the field value, or the maximum value.

Pattern A valid regular expression used to validate the field.


For example, the following regular expression validates a string starting with a
letter and followed by one or more letter, number, or underscore:

/^[a-z][a-z0-9_]+$/i

Custom Provision for the user to customize a validation (reserved for future use).

Action Field Type Dependent User Input Modes


For each field data type, the following table explains:
• the defaults applied
• the data input modes that are supported at runtime

Type Default Available Options

String Input Text Input Text, List of values (Manual entry), List
of Values (Query Result)

GUID Input Text Input Text, List of Values (Query Result)

Int16 Numeric Numeric, List of values (Manual entry), List of


Values (Query Result)

Int32 Numeric Numeric, List of values (Manual entry), List of


Values (Query Result)

Int Numeric Numeric, List of values (Manual entry), List of


Values (Query Result)

568 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Type Default Available Options

Int64 Numeric Numeric, List of values (Manual entry), List of


Values (Query Result)

Decimal Numeric Numeric, List of values (Manual entry), List of


Values (Query Result)

Byte Numeric Numeric, List of values (Manual entry), List of


Values (Query Result)

Boolean Checkbox Checkbox

DateTimeOffset Date Time Picker Date Time Picker, List of values (Manual
entry), List of Values (Query Result)

Parameter Value List of Values (Query Result) List of Values (Query Result)

Enum List of Values (Manual entry) List of Values (Manual entry)

Blob File Uploader File Uploader

Runtime module generation example


Side panel - Large:

Side panel - Small Non Modal View:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 569


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Side panel - Small Modal View:

Action Type - View:

570 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.3.1.9 Configuring Custom Action Types for Execute Command and View
Actions
You can configure a custom action for the Execute Command or View action types by specifying the following
information:
• Controller, the name of the controller (registered on the same module).
• Template URL, the template file path to be used.
You can only use a side panel inside this template for the Model-Driven runtime UI Module not to have
inconsistencies.
For this reason, the side panel is available only for actions of type Execute Command or View.

Prerequisites
If you want the onExit configuration to work in your custom action, follow the steps below:
1. Inject common.services.modelDriven.runtimeService service inside your controller.
2. In the place where you initialize your controller, call the initCustomAction method of the above service.
This returns an object which has onExit as callback function.
3. In the command execution response of your controller, call the callback function you received at step 2 with or
without parameters (see example below).

 These steps must be performed only if you want the onExit behavior to be supported at runtime.
Otherwise it is up to you to close the side panel and reload the state on the completion of the command
execution.

For example, refer to the following sample controller and template code:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 571


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

angular.module('Siemens.SimaticIT.Reference.StateMachine')
.controller('MyCtrl',
[ '$state',
'common.base',
'common.services.modelDriven.runtimeService',
function (
$state,
base,
mdRuntimeSvc) {
var self = this;
var sidePanelManager = base.services.sidePanel.service;
self.onCustomActionComplete = null;
self.validInputs = true;
self.save = save;
self.cancel = cancel;
var action = {
title: "My title",
shortTitle: "My short title"
}
self.sidepanelConfig = {
title: action.title,
messages: [{
type: 'warning',
text: ''
}],
actionButtons: [
{
label: action.shortTitle || "Submit",
onClick: self.save,
enabled: self.validInputs,
visible: true
},
{
label: "Cancel",
onClick: self.cancel,
enabled: true,
visible: true
}
],
closeButton: {
showClose: true,
tooltip: 'Close Sidepanel',
onClick: self.cancel
}
};
init();
function save() {
sidePanelManager.close();
var response = backendService.saveValue(self); // executes
command and returns an id as the response
if (typeof self.onCustomActionComplete === 'function') {

572 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

self.onCustomActionComplete(response.id); // callback
function received from model-driven runtime to be called on action complete
//callback function called in this format in order to refresh
and select both master and detail content on action complete
var refreshContentsId = { 'Master':response.id, 'Detail':resp
onse.detailId }
self.onCustomActionComplete(refreshContentsId);
}
}

function cancel() {
sidePanelManager.close();
$state.go('^');
}

function init() {
var initObj = mdRuntimeSvc.initCustomAction(); //gets the
callback function
self.onCustomActionComplete = initObj && initObj.onExit ?
initObj.onExit : null;
sidePanelManager.setTitle(action.title);
sidePanelManager.open({mode: 'e', size: 'small'}); //show the
small side panel in modal mode
//sidePanelManager.open({mode: 'p', size: 'small'}); //show the
small side panel in non-modal mode
//sidePanelManager.open({mode: 'e', size: 'large'}); //show the
large side panel in modal mode
}
}]);

<sit-side-panel sit-title="{{vm.sidepanelConfig.title}}" sit-messages="vm.sidepanelCo


nfig.messages" sit-actions="vm.sidepanelConfig.actionButtons"
sit-close="vm.sidepanelConfig.closeButton">
<div>
<!--My content-->
</div>
</sit-side-panel>

2.2.4.3.1.10 Configuring Custom Action with In-Canvas Mode for Execute


Command and View Actions
You can configure a custom action for the Execute Command or View action types by specifying the following
information:
• Controller, the name of the controller (registered on the same module).
• Template URL, the template file path to be used.

 The user will set the entire template.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 573


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 If the user is inside Custom In-Canvas Panel and refresh the page, then by default user will be navigated to
the parent screen.

Prerequisites
If you want the onExit configuration to work in your custom action, follow the steps below:
1. Inject common.services.modelDriven.runtimeService service inside your controller.
2. In the place where you initialize your controller, call the initCustomAction method of the above service.
This returns an object which has onExit as callback function.
3. In the command execution response of your controller, call the callback function you received at step 2 with or
without parameters (see example below)
If you want to show warning when Navigating away form the In-Canvas Action Screen configuration to work in your
custom action, follow the steps below:
1. Inject common.widget.messageOverlay.service service inside your controller.
2. In the place where you initialize your controller, call the initCustomOverlayOnStateChange method of the
above service.
3. Call setIsViewAction methodset as false (By default it will be true, it means your overlay will not be displayed).
4. Create an array of overlay button and write onClick functionality for them.
If a user wants to display a confirmation browser pop-up on refresh, then the below listed steps to be followed:
1. User has to inject $scope in the controller.
2. In the initialization of the controller, user needs to add window.onbeforeunload()
3. On destroy of the controller, user must add window.onbeforeunload = null;
If you want to configure the Title of the screen and Breadcrumb In-Canvas then refer to the example below.

 For the breadcrumb you have to inject the common.mduiBreadcrumb.breadcrumbService service,


and for the title of the screen you have to inject common.services.swac.SwacUiModuleManager.

For example, refer to the following sample controller code:

574 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

(function () {
'use strict';
var app = angular.module('Siemens.SimaticIT.Material.MaterialEngineering');

app.controller('CustomInCanvasController', ['$stateParams', '$state',


'common.base',
'common.services.modelDriven.runtimeService',
'common.services.swac.SwacUiModuleManager',
'common.mduiBreadcrumb.breadcrumbService','common.services.modelDriven.war
ningService',
function ($stateParams, $state, commonBase, mdRuntimeSvc,
SwacUiModuleManager, breadcrumbService, warningService) {
var self = this;
var backendService = commonBase.services.runtime.backendService;
var initObj = mdRuntimeSvc.initCustomAction();

function init() {

window.onbeforeunload = function (e) {


e.preventDefault();
e.returnValue = '';
};

var warning = warningService.initCustomOverlayOnStateChange();


warning.setIsViewAction(false);

// Configuring the Command bar


self.inCanvasCommandBarConfig = {
'barType': 'Action',
'bar': [
{
'name': 'Back',
'onClickCallback': closeAction,
'cmdIcon': 'Back',
'type': 'Command',
'label': 'Back'
},
{
'name': 'Save',
'onClickCallback': save,
'cmdIcon': 'Save',
'type': 'Command',
'label': "Save"
}
]
};

// buttons for display inside overlay


self.overlayButtons = [
{
id: "cancel",
displayName: $translate.instant('common.cancel'),

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 575


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

onClickCallback: function () {
//Hiding overlay on click of cancel no data will
be modify and url will be same
warning.hideOverlay();
}
},
{
id: "ok",
displayName: $translate.instant('common.ok'),
onClickCallback: okButtonclick
}
];

// Set overlay values message and buttons

warning.setOverlay($translate.instant('inCanvas.overlay.message'),
self.overlayButtons);

function okButtonclick() {
warning.hideOverlay();
//For updating breadcrumb if configured

breadcrumbService.setBreadcrumbChain(breadcrumbService.getBreadcrumbChain().pop())
;
// for updating url when you leave the canvas panel
warning.setOverlayDisplay(false);
//For new screens state and params
$state.go(warning.getState(), warning.getParam(),
{ reload: true });
}

// Configuring OnExit Behavior for the action


self.onCustomActionComplete = initObj && initObj.onExit ?
initObj.onExit : null;

// Configuring Title for the Screen


if (SwacUiModuleManager.enabled) {

SwacUiModuleManager.contextServicePromise.promise.then(function (service) {
service.updatePartialCtx('location.titles', { headerTitle:
'Dynamic Title Here' });
});
}

// Configuring Breadcrumb for the Screen


var breadcrumbTitle = breadcrumbService.getBreadcrumbChain(); //
Get the existing breadcrumb chain
breadcrumbTitle[breadcrumbTitle.length] = {
title: 'Edit Material'
}; // Appending one more chain item for the Breadcrumb as 'Edit
Material'

576 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

breadcrumbService.setBreadcrumbChain(breadcrumbTitle); // Setting
the new item to Breadcrumb chain
self.breadcrumbInCanvasOptions = {
onClick: function (breadcrumbItem) {
breadcrumbTitle.pop();
breadcrumbService.setBreadcrumbChain(breadcrumbTitle);
self.mdViewCtrl = new mdRuntimeSvc.ModelViewCtrl(stateId,
{ params: {} }, $stateParams);
self.mdViewCtrl.goToPreviousLevel(breadcrumbItem);
}
}
// Providing breadcrumb options for 'sit-mdui-breadcrumb' widget.
}

function save() {
var id = backendService.saveValue(self); // executes command and
returns an id as the response
if (typeof self.onCustomActionComplete === 'function') {
self.onCustomActionComplete(id); // callback function
received from model-driven runtime to be called on action complete
closeAction();
}
}

function closeAction() {
breadcrumbTitle.pop();
$state.go('^');
}

$scope.$on("$destroy", function () {
window.onbeforeunload = null;
});

init();
}
]);
})();

2.2.4.3.1.11 Contents and Expressions


The preconditions required across screens to show/disable/clear etc., something are defined through expressions,
which are similar to AngularJS expressions (see online documentation at page https://docs.angularjs.org/guide/
expression), and they can be used to perform simple numeric operations or comparisons, to evaluate the existence
of an object and so on.
Expressions have variables that allow you to access the Screen contents. These variables vary according to the
context in which the expression is configured.
For example, when you define the actions of a UI Screen, you may need to define some preconditions to tell the
system whether to show an action or not.
The Model-Driven UI Editor guides you to write expressions by offering an intelligent code completion functionality.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 577


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Using the Model-Driven Code Completion


In the Model-Driven editor, wherever the expression needs to be written, the moment you start writing the
expression the system gives you hints on the context variables and other fields of contents/actions. See the
screenshots below and the following paragraphs for a description of the context variables in use.

 The system displays the hints only for the context of entities, such as contents, actions or fields, for which
the related configuration screens have been created, configured and saved in the Model-Driven UI Editor.

578 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 579


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Content definition expression


The definition of a UI Content expression contains the following variables:

Variable Description

contents Allows you to access the content of the current screen.

activeConten In a Master-Details template, it specifies the Details content that is currently active among
t several contents (other than the Master content which is always active).

currentConte It specifies the fields of the current content's grid row or tile item through which the drill down
ntItem is performed.

selectedItem Allows you to access the fields of the selected content, except for the contents of Behavior
One.

selectedItems Allows you to access the list of items selected for the content of Behavior Many.

selectedItems Allows you to access the number of items selected for the content of Behavior Many.
Count

list To get a list of the values of the given property from the selectedItems list.

Use this keyword only after selectedItems

eval To evaluate the condition of each item and returns true if all the items in the selectedItems
list satisfy the condition, otherwise it returns false.

• Use this keyword only after selectedItems


• The condition should be enclosed within the brackets without any double quotes (").
• Eval will support only the list keyword, no other content expression will be supported
inside eval.

580 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Variable Description

item To access the properties of every item in the selectedItems list.

Use this keyword only in the condition of an eval function.

Examples on Expressions using Single selected content item


The following example shows an expression, if used in the oData Query of a content, then at runtime the content
items related to the NId property of the Master content will be displayed in the grid or tile.

Expression example

$filter=NId eq {{contents.Master.selectedItem.NId}}

The following example shows an expression, if assigned to a Disable When of a content, then at runtime that
content will be disabled when the Quantity property of the object, which is selected in the Master content, is lower
than 10.

Expression example

contents.Master.selectedItem.Quantity < 10

The following example shows an expression, if assigned to a Disable When of a content, then at runtime that
content will be disabled when the Quantity property of the object, which is shown in the Overview tab of
the content defined as Behavior One, is lower than 10.

Expression example

contents.Overview.Quantity < 10

The following example shows an expression, if assigned to a Disable When of a content, then at runtime that
content will be disabled when the MaterialQuantity property of an extended entity or reading function of an
extension MaterialEntityExtension of content: Overview of Behavior One, is lower than 10.

Expression example

contents.Overview.MaterialEntityExtension.MaterialQuantity < 10

The following example shows an expression, if assigned to a Show When of an action, then in runtime that action
will be shown only when the Quantity property of the object, which is selected in the Master content, is lower than
10 and active content is Overview.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 581


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Expression example

contents.Master.selectedItem.Quantity < 10 && activeContent === 'Overview'

Examples on Expressions using Multiple selected content items


The following example shows an expression, if assigned to a Show When of an action, then the action in runtime
will be shown only when the selected number of items in the Master content is 1.

Expression example

contents.Master.selectedItemsCount === 1

The following example shows an expression, if assigned to a Show When of an action, then the action in runtime
will be shown only when the selected number of items in the Master content is more than 1.

Expression example

contents.Master.selectedItemsCount > 1

The following example shows an expression, if assigned to a Show When of an action, then the action in runtime
will be shown only when the status of all the selected items in the Master content is equal to 'Ready'and the items
are not hidden.

Expression example

contents.Master.selectedItems.eval(item.status === 'Ready' && !item.IsHidden)

The following example shows an expression, if configured as a Value of an action field, then in runtime the list of
IDs of the selected items in the Master content is sent to the command payload.

Expression example

contents.Master.selectedItems.list("Id")

Example on Expressions using currentContentItem


The following example shows an expression, if configured as a Condition for a Drill Down Destination Screen,
then in the runtime the configured Destination Screen will be navigated to when the current Tile/Grid item is of
Type: Quantity

Expression example

currentContentItem.Type === "Quality"

582 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Action definition expression


The definition of a UI Action expression contains the following variables:

Variable Description

params Specifies the parameters of the current action.

action Specifies the current action to be performed.

fields Allows you to access the fields of the current action.

baseCommand Specifies the base command of an extended action.

output Specifies the output parameters of a base command used in an extended action.

queryResult Specifies the response for the query of the Entity or Reading Function. It is only applicable
for the extended fields.
The following example shows an expression, if assigned to a Disable When of an action field, then in runtime that
field will be disabled if the action field: Quantity's value is lower than "10".

Expression example

action.fields.Quantity < 10

The following example shows an expression, if assigned to a Disable When of an action field, then in runtime that
field will be disabled if the extended action field of extension: UAPI_Extension from Extension App:
UAPI_Material: Quantity's value is lower than "10".

Expression example

action.UAPI_Material_UAPI_Extension.fields.Quantity < 10

The following example shows an expression, if assigned to a Default of an action field, where the Entity or Reading
Function is queried for pre-filling, then in runtime that field has the default value set as returned from the
configured expression.

Expression example

action.UAPI_Material_UAPI.queryResult.Quantity

The following example shows an expression, if assigned to a Value of an action field, then in runtime that field will
have the value of the output parameter specified once the base command of an extended action executes.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 583


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Expression example

baseCommand.output.MaterialId

The following example shows an function body, if assigned to a Default of an action field, then in runtime that field
will have the default value set as returned from the configured function body after opening the sidepanel.

Function Body example

return contents.Master.selectedItem.NId;

The following example shows an function body, if assigned to a Default of an action field which is a
DateTimePicker, then in runtime that field will have the default value set as current date and time after opening
the sidepanel.

Function Body example

return new Date();

2.2.4.3.1.12 Extending a Model-Driven UI Module from a Base App


In order to extend a Model-Driven Module from a base App to an Extension App, follow the workflow below.

 In an extended Model-Driven UI Module, you can only add UI screens, UI contents or UI Actions. You cannot
modify or delete any of the existing base module UI screens or UI contents or UI actions.
However, you can both extend an existing Base Module UI Content of Behavior: One, by selecting
additional entities or reading functions for the content, and extend an existing Base Module UI Action of
type: Execute Command, by selecting additional commands for the Action, as described in the workflow
below.

Workflow
1. In the Solution Explorer pane, expand the User Interface project of the Extension App.
2. Right-click the <Prefix>.<AppName>/modules folder and click Extend MDUI Module from Base App. A dialog
box is displayed showing the list of the available Model-Driven UI Modules provided by the Base App.
3. Select the Model-Driven UI Module to be extended (<Prefix>.<AppName>.<ModuleName>). The system creates
a file <Prefix>.<AppName>.<ModuleName>.ext for managing the extensions to be available in your Base
App. You can select one Module at a time. Your extended Model-Driven UI Module name cannot be modified.
4. Open the Model-Driven UI Module Editor. Once it is opened, the editor will show the extended module and its
Base App module's information.
5. Do either of the following:
• Add new UI Screen to your extended module.
• Add new UI Screen Content to your extended module.
• Add new UI Screen Action to your extended module.
6. Extend a base module UI Content of Behavior: One.

584 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

7. Extend a base module UI Action of type: Execute command.


8. Build the Extension App and proceed with the deploying the App in Solution Studio.

 To update the BaseApp for an extension App of a Model driven UI module, you must manually change the
baseAppVersion key in the .ext file.
If there are major changes made to the Base App such as deletion of a page, the Extension App will not
work seamlessly after updating the Base App.

For all the existing extended modules ( .ext ) created manually, following properties must be added inside the
manifest at module level as shown below.
This is a prerequisite for Opening the Model-Driven UI Editor for such modules.

Siemens.MatExtension.MaterialEngineering.ext

{
"name": "Siemens.MatExtension.MaterialEngineering",
"type": "model-driven",
"manifestVersion": "02.01.00",
"header":"",
"title": "Material Engineering",
"icon": "sit sit-engineering-material",
"functionalBlock": "Siemens.MatExtension",
"dependencies": [],
"baseAppName": "Siemens.SimaticIT.Material", // should be added as
<Prefix.BaseAppName>
"baseAppModuleName": "Siemens.SimaticIT.Material.MaterialEngineering", //should be
added as <Prefix.BaseAppName.BaseAppModuleName>
"baseAppVersion": "03.00.00", // should be added as <BaseAppVersion>
"states": [/*{...}*/]
}

Result
The extensions for the Base App Module will be available in the runtime UI Application which includes the Base App
Module.

 The order of the new extensions merged inside the Base App Module will be based on the order of the
Extension Apps installed.

Extending a Base Model-Driven UI Module Content


In order to extend a Model-Driven Module Content of Behavior: One from a Base App to an Extension App to show
additional entity or reading function properties from a different entity or reading function along with the existing
fields in the Model-Driven Runtime , follow the procedure below.
Procedure

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 585


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

1. Select an Existing Base Module Content in the Model-Driven UI Editor.


2. Click on the Extend button to navigate to the Extension Settings tab.
3. Enter the Extension name and click on the button Add Extension for the new extension to be added.
4. For each extension added, enter the following information:
Section Para Description
meter

Entity Exten The label to be displayed if grouping is configured.


Referenc sion
If a translation is required, enter a valid resource translation key. The resource
e Title
translation key must be present within a resource file, which must be created as
described at page Localizing Custom UI Apps and UI Framework Resources.

Entity If selected, it allows you to browse the entity exposed by the Public Object Model App/
Extension App.

Facet (Only on Entity selected) It allows you to browse the facets associated to the selected
s Entity and add them. Multiple facets can be added. Click on Add Item to add a facet
and specify the following:
• Facet, select the facet you want from the list of available Facets of the
Entity.
• Alias, provide an alias name for the facet selected which will be used as
reference for field names. For example, if the Facet Alias is given as
FacetAlias1 and the fields of the facets will be represented as
FacetAlais1.Field in the Fields and the same field can be used to configure
in Fields Settings.

 Facet and Facet Aliases configured has to be unique. A same facet cannot be
added more than once.

Query The filter expression to retrieve the required record.

Readi If selected, it allows you to browse the Reading Function(s) exposed by the Public
ng Object Model App/Extension App.
Funct
ion

Para Specifies the input parameters to be passed to the Reading Function. The input
ms parameters are populated on Reading Function selection.

Input Parameters

{
"CounterId":"contents.Master.selectedItem.Id",
"StateMachine":"contents.Master.selectedItem.StateMachineNId"
}

586 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Section Para Description


meter

Fields Based on the selected entity or reading function, the properties will be automatically
loaded. You can decide to add, modify or delete Fields.

Name Unique internal identifier, to be used when configuring an expression and you need to
retrieve the field data. If a Facet is included, then properties related to Facet will be
represented as FacetAlias.FieldName.

Prope Entity or Facet property name.


rty

Label Property display name, both for tiles and for grids.
If a translation is required, enter a valid resource translation key. The resource
translation key must be present within a resource file, which must be created as
described at page Localizing Custom UI Apps and UI Framework Resources.

Type The type of the newly added property.

Field You can personalize the PropertyGrid preferences for your content of Behavior:
Settings One by doing the following:
• showing or hiding fields by selecting the required field and then
clicking Add / Remove button.
• setting the field order in the PropertyGrid, by selecting the item to be
moved and then clicking the arrow buttons on the right.
5. Build the Extension App and proceed with deploying the App in Solution Studio.

Result
The PropertyGrid fields added from the extensions for the Base App Module Content will be merged along with
other existing fields in the runtime UI Application (as shown below).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 587


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Extending a Base Model-Driven UI Module Action


In order to extend a Base Model-Driven UI Module Action by adding additional command extensions, follow the
procedure below.

 This will be available only for Actions of type: Execute Command so that you can execute additional
commands along with the base command.

Procedure
1. Select an existing Base App Module Action of the type Execute Command in the Model-Driven UI Module Editor.
2. Click on the Extend button to navigate to the Extension Settings tab.
3. Enter the Extension Name and click on the button Add Extension to add the new extension.
4. For each extension added, enter the following information:
Section Parameter Description

Command It allows you to browse the command exposed by the Public Object
Model of the App/Extension App.

Fields Based on the selected command, the editor automatically loads the
properties. You can decide to add, modify or delete Fields.
(See Fields Tab Configuration in Configuring the Model-Driven UI
Screen Actions for reference).

o Specifies a query (via oData or via a dedicated query editor), in order


DataQuer to set filtering criteria.
y

Data Entity • When you configure Entity for each extension, you will
Source view the extended field name matching with the responses
and this will be pre-filled.
• When you configure the default expression with the
respective Entity response, you will view pre-filled
configured field.
• When you configure Entity for each extension, you will
view appropriate suggestions for the default expression.

Readi • When you configure Reading Function for each extension,


ng you will view the extended field name matching with the
Functi responses and this will be pre-filled.
on • When you configure the default expression with the
respective Reading Function response, you will view pre-
filled configured field.
• When you configure Reading Function for each extension,
you will view appropriate suggestions for the default
expression.

Params Specifies the input parameters to be passed to the Reading Function.


5. Build the Extension App and proceed with deploying the App in Solution Studio.

588 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 If Action is configured as Side Panel in the Base App, you will have an option to change it as In-Canvas
mode in the extension app. In such scenario if multiple extension installed for Base App, preference is
given to In-Canvas.

 When Display Mode is selected as In-Canvas, you will not see the Size, View Mode and Close by clicking
outside options.

Result
The input fields added from the extensions for the Action will be merged along with other existing Base input fields
in the runtime UI Application.
An example is provided here Example of Extending a Base Model-Driven UI Module Action.

Manifest structure for Extended Model-Driven UI Module


The extensions to be added to the base app should be manually included in the extension app module manifest.
The following manifest shows the copy of base app module manifest
Siemens.SimaticIT.Material.MaterialEngineering.mdui:

Siemens.SimaticIT.Material.MaterialEngineering.ext

{
"name": "Siemens.SimaticIT.Material.MaterialEngineering",
"type": "model-driven",
"manifestVersion": "02.01.00",
"title": "Material Engineering",
"header": "",
"icon": "sit sit-engineering-material",
"functionalBlock": "Siemens.SimaticIT.Material_Ext",
"dependencies": [],
"states": [
{
"appName": "Material",
"appPrefix": "Siemens.SimaticIT.",
"urlPrefix": "Siemens_SimaticIT_Material_Ext_Material_Engineering_Material",
"id": "home.Siemens_SimaticIT_Material_Ext_Material_Engineering_Material",
"title": "Material",
"header": "",
"activeContent": "Master",
"layoutTemplate": "masterDetails",
"icon": "sit sit-engineering-material",
"securable": true,
"params": [],
"contents": {}
}]

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 589


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 The id of the screen which needs to be extended must be changed to the equivalent base module screen
id.
In order to extend the screen Material in the extension manifest shown above, the state id has to be
changed from
home.Siemens_SimaticIT_Material_Ext_Material_Engineering_Material
to
home.Siemens_SimaticIT_Material_Material_Engineering_Material

Extension Examples: Adding a new content to the base module screen


Add the extensions to the screen Material for adding a new content as shown below:

590 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Siemens.SimaticIT.Material.MaterialEngineering.ext

{
"name": "Siemens.SimaticIT.Material.MaterialEngineering",
"type": "model-driven",
"manifestVersion": "02.01.00",
"title": "Material Engineering",
"header": "",
"icon": "sit sit-engineering-material",
"functionalBlock": "Siemens.SimaticIT.Material_Ext",
"dependencies": [],
"states": [
{
"appName": "Material",
"appPrefix": "Siemens.SimaticIT.",
"urlPrefix": "Siemens_SimaticIT_Material_Ext_Material_Engineering_Material",
"id": "home.Siemens_SimaticIT_Material_Material_Engineering_Material",
"title": "Material",
"header": "",
"activeContent": "Master",
"layoutTemplate": "masterDetails",
"icon": "sit sit-engineering-material",
"securable": true,
"params": [],
"contents": {
"Master": {
"change":"added", //This has to be added along with other descriptors for
the content
"id": "Master",
"title": "Siemens_SimaticIT_Material.Master",
"query": "$orderby=NId asc",
"multiplicity": "many",
"master": true,
"properties": [
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "NId"
},
"name": "NId",
"label": "Siemens_SimaticIT_Material.NId",
"type": "String",
"sortable": true,
"searchable": true,
"isSelected": false,
"id": "NId"
},
{
"propertyRef": {
"entity": "Material",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 591


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"app": "Siemens.SimaticIT.Material",
"property": "Revision"
},
"name": "Revision",
"label": "Siemens_SimaticIT_Material.Revision",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "Revision"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "UId"
},
"name": "UId",
"label": "Siemens_SimaticIT_Material.UId",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "UId"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "Name"
},
"name": "Name",
"label": "Siemens_SimaticIT_Material.Name",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "Name"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "Description"
},
"name": "Description",
"label": "Siemens_SimaticIT_Material.Description",
"type": "String",
"sortable": false,
"searchable": false,
"id": "Description"
},

592 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "UoMNId"
},
"name": "UoMNId",
"label": "Siemens_SimaticIT_Material.UoM",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "UoMNId"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "TemplateNId"
},
"name": "TemplateNId",
"label": "Siemens_SimaticIT_Material.Template",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": true,
"groupable": true,
"id": "TemplateNId"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "IsCurrent"
},
"name": "IsCurrent",
"label": "Siemens_SimaticIT_Material.IsCurrent",
"type": "Boolean",
"sortable": false,
"searchable": false,
"isSelected": false,
"groupable": false,
"id": "IsCurrent"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "IsLocked"
},
"name": "IsLocked",
"label": "Siemens_SimaticIT_Material.IsLocked",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 593


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"type": "Boolean",
"sortable": true,
"searchable": false,
"isSelected": false,
"groupable": true,
"id": "IsLocked"
}
],
"blueprintSettings": {
"viewOptions": "c",
"viewMode": "c",
"tileConfig": {
"propertyFields": [
{
"field": "UId",
"displayName": "Siemens_SimaticIT_Material.UId"
},
{
"field": "Name",
"displayName": "Siemens_SimaticIT_Material.Name"
},
{
"field": "Description",
"displayName": "Siemens_SimaticIT_Material.Description"
}
],
"icon": "sit sit-engineering-material",
"titleField": "NId",
"descriptionField": "Revision"
},

"tagField": "",
"image": "sit sit-engineering-material",
"serverSidePagination": true,
"filterBarOptions": "sqgf"
},
"help": "",
"actions":[],
"entityRef": {
"entity": "Material",
"app": "Material"
}
}
}
}]

Extension Examples: Adding a new action to the base module screen's content
Add the extensions to the screen Material's content Master for adding a new action as shown below.

594 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Siemens.SimaticIT.Material.MaterialEngineering.ext

{
"name": "Siemens.SimaticIT.Material.MaterialEngineering",
"type": "model-driven",
"manifestVersion": "02.01.00",
"title": "Material Engineering",
"header": "",
"icon": "sit sit-engineering-material",
"functionalBlock": "Siemens.SimaticIT.Material_Ext",
"dependencies": [],
"states": [
{
"appName": "Material",
"appPrefix": "Siemens.SimaticIT.",
"urlPrefix": "Siemens_SimaticIT_Material_Ext_Material_Engineering_Material",
"id": "home.Siemens_SimaticIT_Material_Material_Engineering_Material",
"title": "Material",
"header": "",
"activeContent": "Master",
"layoutTemplate": "masterDetails",
"icon": "sit sit-engineering-material",
"securable": true,
"params": [],
"contents": {
"Master": {
"id": "Master",
"title": "Siemens_SimaticIT_Material.Master",
"query": "$orderby=NId asc",
"multiplicity": "many",
"master": true,
"properties": [
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "NId"
},
"name": "NId",
"label": "Siemens_SimaticIT_Material.NId",
"type": "String",
"sortable": true,
"searchable": true,
"isSelected": false,
"id": "NId"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "Revision"

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 595


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

},
"name": "Revision",
"label": "Siemens_SimaticIT_Material.Revision",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "Revision"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "UId"
},
"name": "UId",
"label": "Siemens_SimaticIT_Material.UId",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "UId"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "Name"
},
"name": "Name",
"label": "Siemens_SimaticIT_Material.Name",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "Name"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "Description"
},
"name": "Description",
"label": "Siemens_SimaticIT_Material.Description",
"type": "String",
"sortable": false,
"searchable": false,
"id": "Description"
},
{
"propertyRef": {

596 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "UoMNId"
},
"name": "UoMNId",
"label": "Siemens_SimaticIT_Material.UoM",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": false,
"id": "UoMNId"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "TemplateNId"
},
"name": "TemplateNId",
"label": "Siemens_SimaticIT_Material.Template",
"type": "String",
"sortable": true,
"searchable": false,
"isSelected": true,
"groupable": true,
"id": "TemplateNId"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "IsCurrent"
},
"name": "IsCurrent",
"label": "Siemens_SimaticIT_Material.IsCurrent",
"type": "Boolean",
"sortable": false,
"searchable": false,
"isSelected": false,
"groupable": false,
"id": "IsCurrent"
},
{
"propertyRef": {
"entity": "Material",
"app": "Siemens.SimaticIT.Material",
"property": "IsLocked"
},
"name": "IsLocked",
"label": "Siemens_SimaticIT_Material.IsLocked",
"type": "Boolean",
"sortable": true,

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 597


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"searchable": false,
"isSelected": false,
"groupable": true,
"id": "IsLocked"
}
],
"blueprintSettings": {
"viewOptions": "c",
"viewMode": "c",
"tileConfig": {
"propertyFields": [
{
"field": "UId",
"displayName": "Siemens_SimaticIT_Material.UId"
},
{
"field": "Name",
"displayName": "Siemens_SimaticIT_Material.Name"
},
{
"field": "Description",
"displayName": "Siemens_SimaticIT_Material.Description"
}
],
"icon": "sit sit-engineering-material",
"titleField": "NId",
"descriptionField": "Revision"
},

"tagField": "",
"image": "sit sit-engineering-material",
"serverSidePagination": true,
"filterBarOptions": "sqgf"
},
"help": "",
"actions":[
{
"change":"added", //This has to be added along with other descriptors
for an action
"id": "add",
"title": "Siemens_SimaticIT_Material.Add",
"tooltip": "Siemens_SimaticIT_Material_MaterialEngineering.AddMaterial",
"icon": "fa-plus",
"main": true,
"params": {},
"behavior": {
"type": "command",
"commandRef": {
"command": "CreateMaterial",
"app": "Material",
"fullName":
"Siemens.SimaticIT.Material.Material.MTPOMModel.Commands.Published.CreateMaterial"

598 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

},
"sidePanelMode": "large",
"entityRef": {
"entity": "Material",
"app": "Material"
},
"shortTitle": "Siemens_SimaticIT_Material.Save",
"fields": [
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",
"parameter": "NId"
},
"name": "NId",
"description": "",
"label": "Siemens_SimaticIT_Material.NId",
"type": "String",
"values": [],
"readOnly": false,
"hidden": false,
"validation": {
"required": true,
"maxlength": "255",
"minLength": "1",
"maxLength": "255"
}
},
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",
"parameter": "Revision"
},
"name": "Revision",
"description": "",
"label": "Siemens_SimaticIT_Material.Revision",
"type": "String",
"values": [],
"readOnly": false,
"hidden": false,
"validation": {
"required": true,
"maxlength": "128",
"minLength": "1",
"maxLength": "128"
}
},
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 599


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"parameter": "UId"
},
"name": "UId",
"description": "",
"label": "Siemens_SimaticIT_Material.UId",
"type": "String",
"values": [],
"readOnly": false,
"hidden": false,
"validation": {
"required": false,
"maxlength": "384",
"maxLength": "384"
}
},
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",
"parameter": "Name"
},
"name": "Name",
"description": "",
"label": "Siemens_SimaticIT_Material.Name",
"type": "String",
"values": [],
"readOnly": false,
"hidden": false,
"validation": {
"required": false,
"maxlength": "255",
"maxLength": "255"
}
},
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",
"parameter": "Description"
},
"name": "Description",
"description": "",
"label": "Siemens_SimaticIT_Material.Description",
"type": "String",
"values": [],
"readOnly": false,
"hidden": false,
"validation": {
"required": false,
"maxlength": "512",
"maxLength": "512"
}

600 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

},
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",
"parameter": "UoMNId"
},
"entityRef": {
"app": "Material",
"entity": "UoM"
},
"name": "UoMNId",
"description": "",
"label": "Siemens_SimaticIT_Material.UoM",
"type": {},
"values": [],
"readOnly": false,
"hidden": false,
"query": "$filter=IsHidden eq false&$orderby=NId asc",
"displayProperty": "NId",
"valueProperty": "NId",
"validation": {
"required": false
}
},
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",
"parameter": "UseDefault"
},
"name": "UseDefault",
"description": "",
"label": "Siemens_SimaticIT_Material.UseDefaultTemplate",
"type": "Boolean",
"values": [],
"readOnly": false,
"hidden": false,
"validation": {
"required": false
}
},
{
"parameterRef": {
"command": "CreateMaterial",
"app": "Material",
"parameter": "TemplateNId"
},
"entityRef": {
"app": "Material",
"entity": "MaterialTemplate"
},

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 601


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

"name": "TemplateNId",
"description": "",
"label": "Siemens_SimaticIT_Material.Template",
"type": {},
"values": [],
"readOnly": false,
"hidden": false,
"query": "$orderby=NId asc",
"clear": {
"expression": "safeVal('action.fields.UseDefault') === true"
},
"disable": {
"expression": "safeVal('action.fields.UseDefault') === true"
},
"displayProperty": "NId",
"valueProperty": "NId",
"validation": {
"required": false
}
}
],
"onExit": {
"key": "MaterialId",
"refreshAndSelectContents": [
"Master",
"Overview"
]
},
"query": ""
},
"show": {
"expression": "activeContent === 'Overview'"
}
}
],
"entityRef": {
"entity": "Material",
"app": "Material"
}
}
}
}]

 In case of duplication in the extensions of the extension apps, only the first installed extension app
changes will be merged to the base app module.

2.2.4.3.1.13 Configuring General Settings for the Model-Driven UI Module


You can configure the common settings for the generated UI Module in the Model-Driven UI Editor as follows.
Here you can define groups of actions and its fields. These groups will be used at runtime as containers of items that
the user may want to display together as sub-items of the same group (see examples below).

602 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Also you can define the custom services required for an action field custom validation.

Procedure
1. Click the in the Model-Driven UI Editor page.
2. Select the required tab to edit and enter the required information as described below.
3. Click Save.

Action Group tab configuration


For adding a group for the command bar, enter the required information described below and click on Add New
button.

Parameter Description

Name The identifier for the group (Alphanumeric).

Title The header of the command bar group.If a translation is required, enter a valid
resource translation key. The resource translation key must be present within
a resource file, which must be created as described at page Localizing Custom
UI Apps and UI Framework Resources.

Icon The icon for the command bar group.

Field Groups tab configuration


For the list of groups to be made available in the execute command action side-panel and content of Behavior:
One to group the property grid fields, enter the following and click on Add New button:

Parameter Description

Id The identifier for the group (Alphanumeric).

Heading The header of the group. If a translation is required, enter a valid resource
translation key. The resource translation key must be present within a
resource file, which must be created as described at page Localizing Custom
UI Apps and UI Framework Resources.

Collapsible Select false, if you want the group to be non-collapsible. By default all the
groups are collapsible.

Custom Services tab configuration


For adding the list of names of the custom services to be made available in the action field custom validation.

Runtime Module generation examples


Action Groups

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 603


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Action Fields Groups

2.2.4.3.2 Examples of Model-Driven UI Modules


This section shows some examples on how to create a Master-Details UI Screen and how to call some UI actions.
Any example in this section refers to the operations described in the general Model-Driven UI Module creation flow.
The following examples are available:
• Example of Master-Details UI Screen with Single Entity
• Example of Master-Details UI Screen with a Related Entity
• Example of Create Action with Parameter Type
• Example of Update Action with a List of Values
• Example of Cascade Selection in an Action Input Form
• Example of Navigation to Another UI screen
• Example of Custom Validation for an Action Field
• Example of Preselection in an Action Input Form

604 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• Example of Displaying Data Segregation Tags within Contents


• Example of Displaying Value Types within Contents
• Example of Configuring Data Drill Down Capabilities
• Example of Extending a Base Model-Driven UI Module Action
• Example of an Execute-Command Action with Multi-Select query field
• Example of Configuring Multi-Select Capabilities in Contents
• Example of Configuring Data Drill Down Capabilities for Custom UI Screens
• Example of Configuring Groups for Content Fields
• Example of Configuring Drill Down based on a Condition
• Example of Configuring Facets for a Model-Driven UI Content
• Example of Create Action with Display Mode In-Canvas

2.2.4.3.2.1 Example of Master-Details UI Screen with Single Entity


This example implements the following use cases:

Target Use Case UI Example

The UI Screen is based on a Master-Details


layout.

The Master side content displays the records


of an entity in tile mode.

The Details side content displays the details of


the selected entity.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 605


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

POM Model Artifacts


The example uses the following data model objects, which must be present in the POM Model of your App:
• MaterialTemplate
• UoM
• CreateMaterialTemplate

 If you use the corresponding entities provided by the platform Functional Blocks, you may need to import
other entities to the POM Model of your App. The description of the related entities is not provided here
and compared to the provided data model, some changes have been applied here to simplify the
examples.

The MaterialTemplate entity contains the following properties:

Property Type

NId String

Name String

Description String

IsDefault bool

UoMNId String

Properties Navigation property (composition)

The UoM entity contains the following properties:

Property Type

NId String

Name String

Description String

Master content configuration


Target Use Case Procedure

The UI Screen is a 1. In the Model-Driven UI Module, create a UI Screen by selecting


Master-Details layout screen. the Master-Details layout.

606 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

The Master side displays the 1. Add a content of Master layout type.
records of an entity in tile 2. Enter the Content ID (e.g. MaterialTemplateMaster), the title, select the
mode. entity related to the records you want to display (e.g. MaterialTemplate)
and set the Behavior to Many.
3. In the General Settings tab select the Tile View mode.
4. In the Tile Settings tab, select at least two properties to be displayed as
descriptive strings.
5. Save the content.

Details content configuration


Target Use Case Procedure

The Detail side content 1. Add a UI Content, and select the Detail option.
shows the details of the 2. Enter the Content ID, e.g. MaterialTemplateDetails.
record selected in the 3. Select the same entity as the Master entity, set
Master content. the Behavior to One and enter the following expression to display the record
related to the entity item you selected in the Master content (for more
information, see Contents and Expressions:

$filter=Id eq
{{contents.MaterialTemplateMaster.selectedItem.Id}}

where MaterialTemplateMaster is the ID of the Master Content in our


example.

2.2.4.3.2.2 Example of Master-Details UI Screen with a Related Entity


This example expands the previous example, and implements the following use cases:

Target Use Case UI Example

In a Master-Details layout screen, a tab


displays the records of an entity which is
linked to the entity that is currently selected
in the Master content.

POM Model Artifacts


The example uses the following data model objects, which must be present in the POM Model of your App:
• The MaterialTemplate entity.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 607


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• The MaterialTemplateUserField entity is linked with the MaterialTemplate entity.


• The NavigationProperty on the MaterialTemplateUserField side, which is used to link to the MaterialTemplate,
is named MaterialTemplateUserField in Project Studio (and it is transformed
into MaterialTemplateUserField_Id on the database).

 If you use the corresponding entities provided by the platform Functional Blocks, you you may need to
import other entities to the POM Model of your App. The description of the related entities is not provided
here and compared to the provided data model, some changes have been applied here to simplify the
examples.

Prerequisites
The MaterialTemplate entity is displayed in the Master side content of the screen as described in the following
example: Example of Master-Details UI Screen with Single Entity.

Content configuration to display a related Entity


Target Use Case Procedure

A tab displays the records of an 1. After the previous example is implemented, add a UI Content and
entity which is linked to the entity select the Details option.
that is selected in the Master 2. Enter the Content ID (e.g. MaterialTemplateUserField) and the title
content. for the tab.
3. Select the required entity (e.g. MaterialTemplateUserField), set
the Behavior to Many and enter an expression to display the records
of the MaterialTemplateUserField entity related to the item which
is currently selected in the Master content.
To do this, you must use the navigation property and set its value
equal to the Id of the item which is currently selected in the Master
content (e.g. if the MaterialTemplateUserField has the
MaterialTemplateUserField_Id navigation property used to
navigate to the MaterialTemplate entity, you can define the
expression as follows.

$filter=MaterialTemplateUserField_Id eq
{{contents.MaterialTemplateMaster.selectedItem.Id
}}

2.2.4.3.2.3 Example of Create Action with Parameter Type


This example implements the following use cases:

608 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

Within an existing Master-Details layout screen, an action is configured in


order to add a new record and to present a form with a set of input fields.

One of the action input fields is a complex property (Parameter Type).

A validation is set on one of the action input fields to make the field
required (and consequently the save button is disabled as long as the field
is filled in).

POM Model Artifacts


The example uses the following data model objects, which must be present in the POM Model of your App:
• MaterialTemplate
• UoM
• CreateMaterialTemplate

 If you use the corresponding entities provided by the platform Functional Blocks, you you may need to
import other entities to the POM Model of your App. The description of the related entities is not provided
here and compared to the provided data model, some changes have been applied here to simplify the
examples.

The MaterialTemplate entity and the UoM entity are described at Example of Master-Details UI Screen with Single
Entity.
The CreateMaterialTemplate command has the following parameters:

Parameter Name Type

NId (Input) String

Name (Input) String

Description (Input) String

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 609


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Name Type

UoMNId (Input) String

IsDefault (Input) bool

Properties (Input) Parameter Type ( * )

MaterialTemplateId (Output) Guid

PropertyIds (Output) Guid


( * )The Properties Parameter Type has the following properties:

Property Type

PropertyNId String

PropertyType Enum (String) composed by Name and Value

PropertyUoMNId String

PropertyValue String

Action configuration
Target Use Case Procedure

Within an existing Master- 1. With the just configured master content selected, add a UI Action.
Details Screen, an action 2. Choose the Primary button pattern and type the Action ID.
is configured in order to
add a new record and to
present a form with a set
of input fields.

The action presents a 1. Choose the Execute Command action type, and select a command that
form with a set of input creates an instance of the Master content entity
fields. (e.g. CreateMaterialTemplate).

610 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

One of the action input 1. In the Fields tab, identify the field that corresponds to the command input
fields is a complex Parameter Type (i.e. Properties in the example), set it to Hidden (because it
property (Parameter will not be passed from the UI), leave the Parameter field (in the Binding
Type). section) set to Properties.
2. For each property that makes up the structure of the Parameter Type,
manually add a UI field, leave it visible (Hidden = False) and delete the value
from the Parameter edit box in the Binding section (because the Field value
will be passed to the Properties field, and not directly to a command
parameter). For this example, add the following UI Fields:
• PropertyNIdInput (string), mapping the PropertyNId parameter type
property,
• PropertyValueInput (string), mapping the PropertyValue parameter
type property,
• PropertyTypeInput (enum, composed by a list of Name -
Value property couples, used to display the supported C# types such
as String, Datetime, Int, Decimal and so on), mapping
the PropertyType parameter type property.
• PropertyUoMNIdInput (string), mapping
the PropertyUoMNId parameter type property.
3. Expand the field that corresponds to the command input Parameter Type
(i.e. Properties field), expand the Binding section, select Function and type
the following code snippet,
where PropertyNId, PropertyValue, PropertyType and PropertyUoMNId are
the properties of the Parameter Type, whose values must be retrieved from the
just defined action fields:

return {PropertyNId:
safeVal('action.fields.PropertyNIdInput'),
PropertyType:
safeVal('action.fields.PropertyTypeInput.value'),
PropertyUoMNId: safeVal('action.fields.PropertyUoMNIdInput')
,PropertyValue: safeval ('action.fields.PropertyValueInput')
}

4. Repeat the same procedure for any other Parameter Type (e.g. Quantity, in the
current example).

A validation is set on one 1. In the Fields tab, expand the required field.
of the action input fields 2. In the User Input Mode Setting click Required and add a string length
to make the field required constraint if needed.
(the save button is
disabled).

2.2.4.3.2.4 Example of Update Action with a List of Values


This example implements the following use cases:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 611


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

In a Master-Details layout screen, a button is made visible only if the


current tab is selected and if the Master content is not empty.

The action will update the item that will be currently selected in the Master
content.

One of the action input fields displays a list of values, retrieved from
another entity. The user can select one of the displayed values.

POM Model Artifacts


The example uses the following data model objects, which must be present in the POM Model of your App:
• The MaterialTemplate entity (explained at page Example of Master-Details UI Screen with Single Entity)
• The UpdateMaterialTemplate command which accepts in input the following parameters:
Parameter Name Type

Id Guid

Name String

Description String

UoMNId String

612 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 If you use the corresponding artifacts provided by the platform Functional Blocks, you need to apply some
changes and you may need to import other entities (e.g. the entities related in composition, and so on) to
the POM Model of your App. The description of the related entities is not provided here and some changes
have been applied here to simplify the examples.

Prerequisites
The MaterialTemplate entity is displayed in the Master side content of the screen, as described in the following
example: Example of Master-Details UI Screen with Single Entity.

UI Action configuration for the Update Action


Target Use Case Procedure

In a Master-Details 1. Add a UI Action to the Details content.


View screen, a 2. Specify the following expression in the the Show When edit box:
button is added
and it is made
visible only if the contents.MaterialTemplateMaster.selectedItem &&
current tab is activeContent === 'MaterialTemplateDetails'
selected and if the
Master content is This expression makes the button visible only if the Master content
not empty. (MaterialTemplateMaster) is not empty and if the Details tab content (e.g.
MaterialTemplateDetails) is active.
3. Choose the Execute Command action type, select the command you want to invoke
(e.g. UpdateMaterialTemplate) and select the entity you want to update
(e.g. MaterialTemplate).

Action Field configuration for Hidden fields


Target Use Case Procedure

The action will 1. (In Advanced Settings enabled mode) For each field that will not be shown in the
update the item input form, select the Hidden check box and set the following expressions in the
that will be Value Expression edit box (in the Binding section):
currently selected • For the Id field, enter contents.MaterialTemplateMaster.selectedItem.Id. In this
in the Master way the form does not show the input field for the command Id, but reads it from the
content. Id of the item that is currently selected on the Master content;
• For the Name field, enter contents.MaterialTemplateMaster.selectedItem.Name.
In this way the form reads the value of the Name field from the item that is currently
selected on the Master content.

Field Configuration for displaying a List of Values

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 613


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

One of the action 1. In the Fields tab, expand the field to be displayed as a list of values, in our example
input fields displays the UoMNId.
a list of values, 2. In the User Input Mode Setting section, select List of Values (Query result).
retrieved from 3. In the Entity Reference section, in the Entity list box, select the entity from which
another entity. The you want to query (e.g. UoM, to show the list of units of measure in the list box).
user can only select 4. Set Display Property and Value Property to the required property value (e.g. NId for
one of the both values).
displayed values. 5. You can order the displayed values by entering the following snippet in the Query
edit box: $orderby=NId asc
6. Save changes.

2.2.4.3.2.5 Example of Cascade Selection in an Action Input Form


This example shows how to pass two parameters to an action and the second parameter shows a value that is
associated to the record selected in the first parameter.

Use Case
Target Use Case UI Example

A button is available to perform the required action.

A field of the input form displays the list of the records for the entity of the
Master content.

Another field of the input form displays the value related to the one of the
properties of the record selected in the previous field.

Data Model
The example uses the following artifacts:
• MaterialTemplate entity
• CreateMaterialTemplate command
These artifacts have been explained at page Example of Master-Details UI Screen with Single Entity and Example of
Create Action with Parameter Type

614 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Action configuration
Target Use Case Procedure

A button is available to 1. Add a UI Action, for example invoking a command that creates a record for
perform the action. the Master content entity (e.g. CreateMaterialTemplate).
2. Set the action Type to Execute Command.

A field of the input form Set the Name field to read the value from a list of values:
displays a list of records
1. In the User Input Mode Setting section, select List of Values (Query
retrieved by any required
result).
entity.
2. In Advanced Settings Enabled mode, in the Entity Reference section,
select MaterialTemplate from the Entity list box, and select Name both as
Display Property and as Value Property.

Another field of the input Set the UoMNId field of the command to the UoMNId value of the previously
form displays the value selected record (MaterialTemplate.Name) in cascade as follows:
related to the record
1. In Advanced Settings Enabled mode, in the Entity Reference section,
selected in another field.
select MaterialTemplate from the Entity drop down list box.
2. In the Query edit box, type $filter=Name eq
'{{action.fields.Name.Name}}' to retrieve the Name property value of the
MaterialTemplate entity, which will be passed from the Name list of
values.
3. Set the Display Property and the Value Property to UoMNId, to display the
vaue of the UoMNId property for the MaterialTemplate record that will be
passed from the Name list of values.
4. Select the Reload Data on Change check box.

2.2.4.3.2.6 Example of Navigation to Another UI Screen


This examples shows how to navigate from one screen to another screen that filters on a record selected in the first
screen. The two screens will be referred to as start screen and target screen.

Use Case
Target Use Case UI Example

A screen displays a set of records and one of these records is selected.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 615


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

When clicking on the navigation button on the command bar, a screen


opens displaying data filtered by some value related to the previous
selection.

Data Model
This example uses the MaterialTemplate entity, whose properties have been documented for previous examples.

Action configuration
Target Use Case Procedure

A record in the Master content is selected Within any already existing Details side content (for example in
and a button is added for navigating to the Details content of the first example) add an action and
another screen. configure it as follows:
• Type: Navigation
• Destination Screen: The ID of the target screen (which has
to be read from the Screen ID parameter), preceded by
"home." (with the dot and without apexes).
• Destination Screen Parameters: The parameter you want
to pass in input to the screen. For example, if you have
selected a Material Template in the Master content, you can
pass to the current screen the value of one of its properties
(e.g. UoMNId) with the following expression:
{"UoMNId":"contents.MaterialTemplateMaster.selectedI
tem.UoMNId"}

Target screen configuration

616 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

When clicking on the navigation button, a 1. Create or configure a UI Screen to be used as the target page
target screen opens displaying data filtered of your navigation as follows:
by some value related to the record
• Title: The screen title you want to display.
previously selected in the Master content.
• Params: The parameter you want to pass in input to
Here you are about to pass the UoM the screen. For example, if the navigation action
(UoMNId property) of the previously passes the UoMNId parameter, here you will enter
selected MaterialTemplate to the query of UoMNId.
the target content. 2. Create a Content (e.g. of Master type) with the following
settings:
• Entity: The entity you want to show in the content
(e.g. MaterialTemplate).
• oData Query: To retrieve the entity instances
(MaterialTemplate) that have the same Unit of
Measure (UoMNId), passed by the navigation action
parameter, set the following expression:
$filter=UoMNId eq '{{params.UoMNId}}'

2.2.4.3.2.7 Example of Custom Validation for an Action Field


This example implements the following use cases:

Target Use case UI Example

In a user input form, the user selects a type in an input field, and
according to the implemented custom validation, the system validates
the value that the user enters.

Depending the type selected, according to the confugured custom


validation, the UoM field value will be validated as required.

Data Model
The example uses the following data model objects:
• The MaterialTemplateProperty entity (which extends the MasterDataTemplate entity). This entity contains
the following properties:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 617


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Property Type

NId String

PropertyValue String

PropertyUoMNId String

PropertyType String

MaterialTemplate_Id Guid
• The CreateMaterialTemplateProperties command has been modeled to accept in input the following
parameters:

Parameter Name Type

MaterialTemplateId Guid

MaterialTemplateProperties Parameter Type

MaterialTemplatePropertyIds (Output) Array

Action field custom validation configuration


Target use case Procedure

In a user input form, the user selects a type in an input Write the following function body to validate
field, and according to the implemented custom the MaterialPropertyValue field depending on the
validation, the system validates the value that the user selected MaterialPropertyType:
enters.

if(forms && forms.properties){


if(action.fields.MaterialTemplatePr
opertyType.value === 'Bool'){

forms.properties.MaterialTemplateProp
ertyValue.$setValidity('custom',false)
;
} else{

forms.properties.MaterialTemplateProp
ertyValue.$setValidity('custom', true)
;
}
}

618 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target use case Procedure

Depending the type selected, according to the write the following function body to make the
confugured custom validation, the UoM field value will field MaterialTemplatePropertyUoMNId as
be validated as required. required only when the MaterialPropertyType is
selected as Quantity.

if(forms && forms.properties){


if(action.fields.MaterialTemplatePr
opertyType.value === 'Quantity'){

validations.MaterialTemplatePropertyU
oMNId.required = true;
} else{

validations.MaterialTemplatePropertyU
oMNId.required = false;
}
}

Example of customServices
The following example shows how to use customServices to get the reference of a custom service
validationService inside the custom function body.

if(forms && forms.properties){


if(action.fields.MaterialTemplatePropertyType.value !== undefined){
var validationSvc = customServices.validationService; //validationService is a
custom service written by the user which can be reused
var isValid =
validationSvc.validateValueByType(action.fields.MaterialTemplatePropertyValue,action.
fields.MaterialTemplatePropertyType.value);
if(!isValid){
forms.properties.MaterialTemplatePropertyValue.$setValidity('custom',false)
;
} else{
forms.properties.MaterialTemplatePropertyValue.$setValidity('custom', true)
;
}
}
}

2.2.4.3.2.8 Example of Preselection in an Action Input Form


This example shows how to populate an input text field with a value or preselect a drop-down list based on a query.

Use Case

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 619


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

An Input text field (e.g. UoM) is filled


with a value based on the selection of
other fields like Material, Material
Revision and Material Unique
Identifier.

The first value of the State Machine


drop-down list is selected as soon as
the side panel is opened.

An item in the UoM drop-down list is


selected based on the selection of
other fields like Material, Material
Revision and Material Unique
Identifier.

Data Model
The example uses the following artifacts:

620 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Entity Name Property Type

MaterialLot NId String

Name String

Description String

MaterialNId String

MaterialRevision String

MaterialUId String

TemplateNId String

Status Value Type ( * ), containing


• StateMachineNId
• StatusNId

Quantity Value Type ( * ), containing


• UoMNId
• QuantityValue

Entity Name Property Type

Material Revision String

SourceRevision String

IsCurrent Bool

UId String

NId String

Name String

Description String

UoMNId String

TemplateNId String

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 621


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Entity Name Property Type

UoM NId String

Name String

Description String

IsHidden Bool

IsSystemDefined Bool

UoMDimension_Id Guid

UoMBase_Id Guid

Command Name Parameter Name Type

CreateMaterialLot NId String

Name String

Description String

MaterialNId String

MaterialUId String

MaterialRevision String

UseDefault Bool

Quantity Parameter Type

Property Parameter Type

StateMachineNId String

TemplateNId String

UseCurrentRevision Bool

Action configuration
1. Add a UI Action, for example invoking a command that creates a record for the Master content entity
(e.g. CreateMaterialLot ).
2. Set the action Type to Execute Command.

622 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

3. In the action fields, go through the following steps in order to achieve the use cases:

Target Use case Field Procedure


Name

An Input text field UoM is filled UoM 1. Add a field with Field Name as UoM.
with a value based on the
2. Select User Input Mode as Input Text.
selection of other fields like
Material, Material Revision and 3. Enable Advanced Settings Mode.
Material Unique Identifier
4. Select Reload Data on Change check box.
5. Select Material from the Entity list.
6. Provide the Query as

$filter=NId eq
'{{action.fields.MaterialNId.NId}}' and
Revision eq
'{{action.fields.MaterialRevision.Revision}
}' and UId eq
'{{action.fields.MaterialUId.UId}}'
&$orderby=NId asc

7. Select UoMNId as Selection Property.

First value of the drop-down list State 1. Add a field with Field Name as State Machine.
State Machine is selected as soon Machi
2. Select User Input Mode as List of Values (Query Result).
as the side panel is opened ne
3. Enable Advanced Settings Mode.
4. Select Material from the Entity list.
5. Select the Preselect Value check box.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 623


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case Field Procedure


Name

An item of UoM drop-down list is UoM 1. Add a field with Field Name as UoM.
selected based on the selection of
2. Select User Input Mode as List of Values(Query Result).
other fields like Material,
Material Revision and Material 3. Enable Advanced Settings Mode.
Unique Identifier
4. Select Preselect Value and Reload on Data Change check
boxes.
5. Select the Entity as UoM.
6. Provide the Query as $orderby=NId asc
7. Select NId as Display Property and Value Property.
8. Select the Entity as Material in the Preselect Entity
Reference section.
9. Provide the preselect Query as

$filter=NId eq
'{{action.fields.MaterialNId.NId}}' and
Revision eq
'{{action.fields.MaterialRevision.Revision}
}' and UId eq
'{{action.fields.MaterialUId.UId}}'
&$orderby=NId asc

10. Select NId as Base Value Property.


11. Select UoMNId as Select Value Property.

 Refer to the explanations provided at page Example of Create Action with Parameter Type to complete
the action field configuration.
And refer to Example of Displaying Value Types within Contents to properly display the entity value
types.

2.2.4.3.2.9 Example of Displaying Data Segregation Tags within Contents


The current example implements the following use case:

624 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

The content of the screen displays the segregation tags which are
currently associated to the entity instances.

Prerequisites
• The Data Segregation tags have been assigned to the entity instances of the entity (e.g. the MaterialTemplate
entity). See Data Segregation App in the Opcenter Execution Foundation User Manual.
• A Person has been properly configured to view the required entity tags and this Person will log on at runtime.

Data Model
The same data model that is used for Example of Master-Details UI Screen with Single Entity.

Content configuration
Target Use case Procedure

The content of the screen displays the 1. In an already existing Master-Details layout screen, add a
segregation tags which are currently content of Details type.
associated with the entity instances. 2. Specify all the required information (ID, title) and set the
entity to be displayed (in our example the MaterialTemplate).
3. In the oData Query edit box, enter the following expand
syntax to retrieve the list of tags: $expand=SegregationTags
4. In the Fields tab, manually add the SegregationTags field by
setting Name, Property and Label to SegregationTags).
5. In the General Settings tab, select Grid Only and then select
SegregationTags from the Data Segregation Tag list box to
view the tags in the grid column.
6. In the Grid Settings tab, make the SegregationTags column
visible by adding it to the Selected Columns list.

2.2.4.3.2.10 Example of Displaying Value Types within Contents


The current example implements the following use case:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 625


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

When an entity contains value types,


the content shows the value type
properties on different columns, to
display all the value types.

Data Model
The example uses the data model artifacts:

Entity Name Property Type

MaterialLot NId String

Name String

Description String

MaterialNId String

MaterialRevision String

MaterialUId String

TemplateNId String

Status Value Type ( * ), containing


• StateMachineNId
• StatusNId

Quantity Value Type ( * ), containing


• UoMNId
• QuantityValue

Content configuration

626 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

When an entity contains value types, the 1. Within a Master-Details screen, add a content of Details type and
content shows the value type properties configure it to retrieve the data from the required entity (e.g.
on different columns (and not on a MaterialLot).
single column), in to display all the value 2. In the Fields tab, the new fields corresponding to the value type
types. properties you want to display will be automatically added. If
the value type is Status and it contains
StateMachineNId and StatusNId, then
Status.StateMachineNId and Status.StatusNId will be
automatically added and Status will not be added as a field.

2.2.4.3.2.11 Example of Configuring Data Drill Down Capabilities


Data Drill Down is a behavior in which you would open any entity instance and see more details of the same entity
instance in another screen.
This example illustrates the below use cases:

Target Use case UI Example

Within a Master layout screen (Material Lots),


commands with drill-down behavior should
be available from which any content item (e.g.
MaterialLot05) can be opened to a Master-
Details layout screen (Material Lot Details
MaterialLot05).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 627


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

Within a Master-Details layout screen


(Material Lot Details MaterialLot05),
depending on the content item (e.g.
MaterialLot05) on which the drill-down was
performed in the previous screen (Material
Lots), the same content item in this screen
should be selected. The last element of the
breadcrumb is displayed based on the selected
content item.
The selected content item's name also gets
appended to the screen title (e.g. Material Lot
Details MaterialLot05).

Within a Master-Details layout screen (e.g.


Material Lot Details MaterialLot05),
commands with drill-down behavior should be
available for detail (Material Tracking Unit)
content items from which any content item
(e.g. MatTrackingUnit01) can be opened to
another Master-Detail screen (Material
Tracking Unit
Management MatTrackingUnit01).

628 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

Within a Master-Detail layout screen (Material


Tracking Unit Management), depending on
the detail content item (e.g.
MatTrackingUnit01) on which the drill-down
was performed in the previous screen
(Material Lot Details), the same content item
in this Master-Detail screen should be selected.
The last element of the breadcrumb is
displayed based on the selected content
item.The selected content item's name also
gets appended to the screen title(e.g. Material
Tracking Unit Management
MatTrackingUnit01).

By clicking on the previous screen (Material


Lot Details MaterialLot05) in the breadcrumb,
the previous screen is loaded with the
appropriate Master content item (e.g.
MaterialLot05) and Detail tab (Material
Tracking Unit) and Detail content item (e.g.
MatTrackingUnit01) selection.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 629


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

Within a Master layout screen (Material Lots),


a drill down action should be available on
selection of any content item (e.g.
MaterialLot05) and can be opened to a
Master-Details layout screen (e.g Material Lot
Details MaterialLot05).

In the Material Lot Management screen,


depending on the content item
(e.g. MaterialLot05) on which the drill-down
was performed in the previous screen
(Material Lots) the same content item in this
screen should be selected.

By clicking on the previous screen (Material


Lots) in the breadcrumb, the previous screen is
loaded with the appropriate Master content
item (e.g. MaterialLot05) selected.

630 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

In the compact mode, the breadcrumbs are


displayed in this format : n objects >> selected
content item's name. n represents the number
of objects selected prior.
Click the number to view the details of the
previously selected screens. When the screen
name is selected in the breadcrumb the
respective screen is displayed with the
selected content item.

Data Model
The example uses the below data model artifacts:

Entity Name Property Type

MaterialLot NId String

Name String

Description String

MaterialNId String

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 631


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Entity Name Property Type

MaterialRevision String

MaterialUId String

TemplateNId String

Status Value Type

Quantity Value Type

MaterialTrackingUnit NId String

Name String

Description String

MaterialNId String

MaterialRevision String

MaterialUId String

MaterialLot Parameter Type

EquipmentNId String

MaterialTrackingUnitAggregate Parameter Type

TemplateNId String

Code String

CodeType Enum

Status Value Type

Quantity Value Type

Tile / Grid Command configuration

632 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

Configure a Drill-Down 1. Within a Master layout screen (Material Lot), add a master content and
command for a content. configure it to retrieve the data from the required entity (e.g. MaterialLot).
2. In the Tile Settings / Grid Settings tab, in commands section, add a
command and select the destination screen (Material Lot Management)
from the available screens.
3. By default the available params of the destination screen selected will be
updated. If you want to provide additional input parameters to be used for
the destination screen, you must execute both of the following sub-steps:
• Fill in the Params edit box as shown in the example below (See
Contents and Expressions):

Params Example

{"MasterParam":"contents.Master.selectedItem.Id"}

• Provide the same input parameter to the target screen, as described


at page Example of Navigation to Another UI Screen page. Here you
must add the just specified input parameter to the target screen
Params attribute.
4. Within a Master-Details layout screen (Material Lot Management), add a
content of Details (Material Tracking Unit) type and configure it to retrieve
the data from the required entity (e.g. MaterialLot).
5. In the Tile Settings / Grid Settings tab, in commands section, add a
command and select the destination screen (Material Tracking Unit
Management) from the available screens and provide the Params to be used
for the selected destination screen.
6. Within a Master-Details screen (Material Tracking Unit Management), add
a content of Details (Material Tracking Unit) type and configure it to retrieve
the data from the required entity (e.g. MaterialTrackingUnit).
7. Build the App Solution in Project Studio for generating the drill-down states.

Drill Down Action Configuration

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 633


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

Configure a Drill-Down 1. Within a Master layout screen (Material Lot), add a master content and
action for a screen. configure it to retrieve the data from the required entity (e.g. MaterialLot).
2. Add a Action (e.g. OpenMaterialLot) to the master content.
3. In the Details tab:
• Specify the required information (ID, Title, Icon) to be displayed.
• If required, fill in the Params edit box.
• Provide the Show When expression or function as

Drill Down Action Show When Example

contents.Master.selectedItem.Id

in order to show the drill down action only if the content item is
selected. See Contents and Expressions.
4. In the Behavior tab:
• In the Type drop down, select Drill Down.
• Select Synchronize with Tile/Grid Command, if you want to load the
configuration of the drill down commands configured in parent
content (MaterialLot). Follow the below steps if this is not selected or
if any changes needed apart from the saved content's configuration.
All the configurations saved here will be synced with Tile/Grid
commands and vice versa.
• Destination Screen, select the screen for navigation. If the required
screen is not present in the entity picker, then provide the ID of the
target Screen (Material Lot Management) in the text box of the entity
picker.

 Target State ID should be entered without including home.


For example, it should be given
as
Siemens_SimaticIT_Material_Material_Runtime_Material
Lot
instead
of
home.Siemens_SimaticIT_Material_Material_Runtime_M
aterialLot

• By default the available params of the destination screen selected will


be updated. If you want to provide additional input parameters to be
used for the destination screen, you must execute both of the
following sub-steps:
a. Fill in the Destination Screen Params edit box as shown in the
example below (See Contents and Expressions) :

634 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

Params Example

{"MasterParam":"contents.Master.selectedItem.Id"}

b. Provide the same input parameter to the target screen, as


described at page Example of Navigation to Another UI Screen page.
Here you must add the just specified input parameter to the target
screen Params attribute.
5. Click Save.
6. Build the App Solution in Project Studio for generating the drill-down states.

2.2.4.3.2.12 Example of Extending a Base Model-Driven UI Module Action


This example implements the following use cases:

Target Use Case UI Example

Within an existing UI Screen belonging to the Base App UI Module you are
extending, the Add Material action is extended with two command
extensions: UAPI_Extension belonging to the UAPI_Material Extension
App and UADM_Extension belonging to the UADM_Material Extension
App, in order to show the input parameters for the additional commands
to be executed along with the base command.
(Fields form one Extension: UAPI/UADM extension of action to execute a
different command than base command.)

After Saving, the base command: CreateMaterial will be executed.


Also, all the additional commands (CreatePIMaterial and
CreateDMMaterial) from the two command extensions for the configured
action (UAPI_Extension and UADM_Extension) will be executed in
parallel depending on the order of the command extensions.
The base command output parameters is used to fill the value of the field:
Material_Id in both the command extensions.

POM Model Artifacts


The example uses the following data model objects, which must be present in the POM Model of your Apps:
• Material
• UAPI_Material
• UADM Material
• CreateMaterial
• CreatePIMaterial
• CreateDMMaterial

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 635


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 If you use the corresponding entities provided by the platform Functional Blocks, it is required to import
other entities to the POM Model of your App. The description of the related entities is not provided here
and compared to the provided data model, some changes have been applied here to simplify the
examples.

The Material entity contains the following properties:

Property Type

UId String

NId String

Revision String

Name String

Description String

TemplateNId String

UoMNId String
The UAPI_Material entity contains the following properties:

Property Type

NId String

Name String

Material_Id Guid
The UADM_Material entity contains the following properties:

Property Type

NId String

Name String

Material_Id Guid
The commands contains the following parameters:

Command Name Parameter Name Type

CreateMaterial UId String

NId String

636 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Command Name Parameter Name Type

Revision String

Name String

Description String

TemplateNId String

UoMNId String

UseDefault Bool

Properties Parameter Type

CreatePIMaterial Material_Id Guid

UAPI_NId String

UAPI_Revision String

CreateDMMaterial Material_Id Guid

UADM_NId String

UADM_Revision String

Prerequisites
The Add Material action from Material Base App must be of type: Execute Command.

Extending a UI Action Configuration


Target Use Case Procedure

Within an existing UI Screen 1. Create an Extension App: UAPI_Material of Material App.


belonging to the Base App UI 2. Extend the Material Engineering Module and open the Model-
Module you are extending, the Add Driven UI Editor.
Material action is extended with 3. Navigate to the Add Material action of the Material Screen.
two command extensions: 4. Enter UAPI_Extension as the extension name and click on Add.
UAPI_Extension belonging to the 5. Select CreatePIMaterial command and click on Save.
UAPI_Material Extension App and
UADM_Extension belonging to the 1. Create an Extension App: UADM_Material of Material App.
UADM_Material Extension App, in 2. Extend the Material Engineering Module and open the Model-
order to show the input parameters Driven UI Editor.
for the additional commands to be 3. Navigate to the Add Material action of the Material Screen.
executed along with the base 4. Enter UADM_Extension as the extension name and click on Add.
command. 5. Select CreateDMMaterial command and click on Save.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 637


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Using the Extended Fields in the Expressions


Target Use Case Procedure

In both the extension apps, inside 1. Navigate to Extensions tab inside action Add Material of Material
the action Add Material, a field: Screen inside UAPI_Material Extension App.
NId_Hidden is created and 2. Open UAPI_Extension and create field NId_Hidden.
configured to be hidden whose 3. Open Binding section and (only on Advanced Settings mode
value is dependent on the field : enabled) specify the following expression as value of the field as
UAPI Material NId or UADM below. (See Contents and Expressions)
Material NId.

action.UAPI_Material_UAPI_Extension.fields.NId

1. Navigate to Extensions tab inside action Add Material of Material


Screen inside UADM_Material Extension App.
2. Open UADM_Extension and create field NId_Hidden.
3. Open Binding section and (only on Advanced Settings mode
enabled) specify the following expression as value of the field as
below. (See Contents and Expressions)

action.UADM_Material_UADM_Extension.fields.NId

 The names of the extensions will be maintained unique


with each Extension App by the system. Hence for all
expressions involving extended fields, Extension Name
should contain the unique extension names.

Using Base Command Output

638 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

After Saving, the base command: 1. Navigate to Extensions tab inside action Add Material of Material
CreateMaterial will be executed. Screen inside UAPI_Material Extension App.
2. Open UAPI_Extension command extension and Open field
Also, all the additional commands
Material_Id of command: CreatePIMaterial.
(CreatePIMaterial and
3. Open Binding section and (only on Advanced Settings mode
CreateDMMaterial) from the two
enabled) specify the following expression as value of the field for
command extensions for the
using the response of the base command: CreateMaterial execution.
action configured
(See Contents and Expressions)
(UAPI_Extension and
UADM_Extension) will be
executed in parallel depending on baseCommand.output.MaterialId
the order of the command
extensions. 1. Navigate to Extensions tab inside action Add Material of Material
The base command output Screen inside UADM_Material Extension App.
parameters is used to fill the value 2. Open UADM_Extension command extension and Open field
of the field: Material_Id in both Material_Id of command: CreateDMMaterial.
the command extensions. 3. Open Binding section and (only on Advanced Settings mode
enabled) specify the following expression as value of the field for
using the response of the base command: CreateMaterial execution.
(See Contents and Expressions)

baseCommand.output.MaterialId

2.2.4.3.2.13 Example of an Execute-Command Action with Multi-Select query


field
This example implements the following use cases:

Target Use Case UI Example

In a Master-Details screen (Material Group Management),


an action (Join Material Groups) should be shown once a
Master is selected and navigated to Grouped In tab.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 639


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

Clicking on the Join Material Groups action, a side panel


opens showing the list of Groups retrieved from a query. The
Group In should be a multi-select drop down list.

By clicking on Save, the selected multiple groups should be


joined to the selected Master Group.

POM Model Artifacts


The example uses the following data model objects, which must be present in the POM Model of your App:
• The MaterialGroup entity
• The AssociateParentsMaterialGroupWithMaterialGroup command which accepts in input the following
parameters:
Parameter Name Type

MaterialGroupNId String

ParentMaterialGroupIds List<String>

MaterialGroupId String

640 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 If you use the corresponding artifacts provided by the platform Functional Blocks, you need to apply some
changes and you may need to import other entities (e.g. the entities related in composition, and so on) to
the POM Model of your App. The description of the related entities is not provided here and some changes
have been applied here to simplify the examples.

UI Action configuration
Target Use Case Procedure

In a Master-Details 1. Add a UI Action (Join Material Groups) to the Details content (Grouped In).
View screen, a 2. Specify the following expression in the Show When edit box:
button is added
and it is made
visible only if the contents.MaterialGroupMaster.selectedItem &&
current tab is activeContent === 'GroupedIn'
selected and if the
Master content is This expression makes the button visible only if the Master content
not empty. (MaterialGroupMaster) is not empty and if the Details tab content (e.g. GroupedIn)
is active.
3. Choose the Execute Command action type, select the command you want to invoke
(e.g. AssociateParentsMaterialGroupWithMaterialGroup ).

UI Action Field configuration for Hidden fields


Target Use Case Procedure

The action will 1. (In Advanced Settings enabled mode) For each field that will not be shown in the
update the item input form, select the Hidden checkbox and set the following expressions in the
that will be Value Expression edit box (in the Binding section):
currently selected • For the MaterialGroupId field, enter
in the Master contents.MaterialGroupMaster.selectedItem.Id. In this way, the form does not
content. show the input field for the command Id, but reads it from the Id of the item that is
currently selected on the Master content;
• For the MaterialGroupNId field, enter
contents.MaterialGroupMaster.selectedItem.NId. In this way, the form reads the
value of the NId field from the item that is currently selected on the Master content.

Field Configuration for displaying a Multi-Select List of Values


One of the action 1. In the Fields tab, expand the field to be displayed as a list of values, in our example
input fields displays the Group In.
a multi-select list of 2. In the User Input Mode Setting section, select List of Values (Query result).
values, retrieved 3. Select Enable Multi Select check box.
from another 4. In the Entity Reference section, in the Entity list box, select the entity from which
entity. The user can you want to query (e.g. MaterialGroups, to show the list of Groups in the list box).
select multiple 5. Set Display Property and Value Property to the required property value, in our
items of the example Display property will be NId and Value property will be Id.
displayed values. 6. You can order the displayed values by entering the following snippet in the Query
edit box: $orderby=NId asc
7. Save changes.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 641


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

2.2.4.3.2.14 Example of Configuring Multi-Select Capabilities in Contents


By enabling Multi-Selection behavior you will be able to select multiple content items in the model-driven runtime,
so that you can perform the actions depending on the selected items.
This example illustrates the below use cases:

Target Use case UI Example

Certain actions (FreezeTask, UnFreeze Task


etc.) are shown in the UI screen based on the
multiple content items selected either in Tile
view mode or Grid view mode clicked.
The visibility of the action buttons is
configured by an expression or function based
on the Multiple Selected content items.

Click the Select All checkbox in the Grid view


mode to select all items in the current page.

642 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

The visibility of the Edit button is configured in


such a way that the button is hidden when
multiple items are selected by
writing an Expression or
a Function. See Contents and Expressions.

POM Model Artifacts


This example uses the following data model objects, which must be present in the POM Model of your App:
• The Task Entity.
• The ActivateTasks command which accepts in input the following parameters:

Parameter Name Type

Ids List<GUID>

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 643


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Parameter Name Type

User String

Multi-Selection Configuration
Target Use Case Procedure

In the Master content of the 1. (In the Advanced Settings Enabled mode) In a content (Master),
Master Screen (or Details content Navigate to General Settings tab.
of the Master-Details Screen), the 2. In the Data Settings section, select the Enable Multi Selection check
user can select multiple (more box.
than one) items for the content of 3. Click Save.
Behavior Many. 4. Configure the visibility of the actions (FreezeTask,UnFreezeTask etc.)
to show only when the Status of all the selected items are Ready and
not Hidden, as below:

Expression example

contents.Master.selectedItems.eval(item.Status ===
'Ready' && !item.IsHidden)

2.2.4.3.2.15 Example of Configuring Data Drill Down Capabilities for Custom


UI Screens
You can now perform drill down to or from Custom UI screen, to open and view the details of an entity instance.
This example illustrates the below use cases:

Target Use Case UI Example

Within a Custom UI screen (CustomMaterialLot), the tiles


are displayed representing the Material Lot entity items.
When clicked on the Material Lot (Lot2), a drill down is
performed to a Model-driven UI screen (Material Lot
Management).

644 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

The Material Lot item (Lot2) which was selected in the


previous Custom screen is highlighted on the Master-
Detail UI screen (Material Lot Management) and the
breadcrumb is displayed based on the configuration.

Within the Master-Detail UI screen (Material Lot


Management), a tile command is available for its detail
content (Material Tracking Unit). When clicked on the
command, a drill down is performed to a Custom screen
(Material Tracking Unit).

The Material Tracking Unit entity item (MTU2) which was


selected in the previous screen is highlighted on the
Custom UI screen (Material Tracking Unit) and the
breadcrumb is displayed based on the configuration.

Procedure
If you want the drill down command to work in your custom action, follow the steps below:
1. Inject common.services.modelDriven.runtimeService service inside your controller.
2. In the place where you initialize your controller, call the initCustomDrillDown method of the above service. The
following table describes the APIs which are exposed:
APIs Description Parameters

navigate Performs the drill down command and Input parameters


navigates to the destination screen.
• currentItem: The entity type value on
which the navigation action is
performed.
• destinationInfo: The information on the
destination screen to be navigated to.
• sourceBreadcrumbTitle: The value for
the breadcrumb title for the source
level.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 645


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

APIs Description Parameters

getInfo Gets the information from Model- Input parameters


driven runtime on the selected entity
• stateName: The state ID from which the
and the breadcrumb hierarchy.
information should be retrieved.
Output parameters
• selection: provides the selected entities
information.
• breadcrumbList: provides the
breadcrumb list information.

goToPrev Opens the clicked Model-driven UI Input parameters


iousLevel screen through a breadcrumb shown in
• clickedBreadcrumbItem: The
the custom UI screen after drill down.
information of the selected breadcrumb
entity is retrieved from breadcrumb
onClick api.

setTitle Displays the breadcrumb title for the Input parameters


destination screen of a custom layout
• breadcrumbTitle : The title to be set for
after drill down from Model-driven UI
the breadcrumb.
Screen.
3. To perform the drill down from custom screen to Model-driven UI editor screen, call the navigate api with the
required information. For more information see, Example for performing drill down from Custom screen to
Model-driven UI screen.
4. To manage the drill down from Model-driven UI screen to custom UI screen use the getinfo, goToPreviousLevel
and setTitle apis based on the requirement. For more information see, Example for managing drill down from
Model-driven UI screen to Custom screen.

Example for performing drill down from Custom screen to Model-driven UI screen

646 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Controller Code Reference

(function () {
'use strict';
angular.module('Siemens.SimaticIT.Material')
.controller('CustomMaterialLotCtrl',
[
'$translate', 'common.services.modelDriven.runtimeService', '$state','
common.base', '$q',
function ($translate, mdRuntimeSvc, $state,base, $q) {
var self = this;
var selectedItemId = '';
var backendService = base.services.runtime.backendService;
activate();

function getData() {
var defer = $q.defer();
var options = '';
var args = { appName: 'Material', entityName: 'MaterialLot',
options: options };
backendService.findAll(args).then(function (data) {
var dataToResolve = data.value || [];
defer.resolve(dataToResolve);
})
return defer.promise;
}

function initTiles(data){
self.pages = data.map(function (item) {
return {
Id: item.Id,
selected: item.Id === selectedItemId,
title: $translate.instant(item.NId),
NId: item.NId,
svgIcon: '',
onClickCallback: function (item) {
if (typeof self.performDrillDown == 'function') {
//the destination screen info to perform a
drill down.
//screenId:the id of the screen without home.
//params : the params of the screen
var destScreenInfo = { screenId:
'Siemens_SimaticIT_Material_Material_Runtime_MaterialLot', params: { } };
self.performDrillDown(item, destScreenInfo,
item.NId); //call the api to perform drill-down navigation to the destination screen
}
}
};
});
}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 647


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

function initCustomDrillDown(){
//gets the list of api to handle drill down
var apiList = mdRuntimeSvc.initCustomDrillDown();
if (apiList) {
self.performDrillDown = apiList.navigate;
self.getDrillDownInfo = apiList.getInfo;
}

if (typeof self.getDrillDownInfo === 'function') {


//call the api to get information on the item on which
the drill down navigation is performed.
var drillDownInfo = self.getDrillDownInfo($state.
$current.toString());
if (drillDownInfo && drillDownInfo.selection &&
drillDownInfo.selection.master) {
selectedItemId = drillDownInfo.selection.master.id ||
'';
}
}
}

function activate(){
getData().then(function (data) {
//initializes the custom drill-down apis
initCustomDrillDown();
initTiles(data);
})
}

}]);
}());

648 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Template Code Reference

<div class="panel panel-default">


<div class="panel-heading" data-toggle="collapse" data-target="#generalSettingsBo
dy" aria-expanded="false">
<label class="panel-title cursor-pointer tile-preview-accordion-heading">
Material Lots
</label>
</div>
<div id="generalSettingsBody" class="panel-collapse collapse tile-accordion-
body">
<div ui-view="content" class="content-area content-area-relative" style="heig
ht: calc(100% - 30px) !important">
<div style="clear:both"></div>
<div style="padding-left: 8px; padding-top: 16px">
<div style="display:inline-block; vertical-align:top;">
<sit-item-tile sit-tile-content="page" sit-tile-options="{size:'l
arge' }" ng-repeat="page in vm.pages"> </sit-item-tile>
</div>
</div>
</div>
</div>
</div>

<div class="panel panel-default">


<div class="panel-heading" data-toggle="collapse" data-target="#material" aria-
expanded="false">
<label class="panel-title cursor-pointer tile-preview-accordion-heading">
Materials
</label>
</div>
<div id="material" class="panel-collapse collapse tile-accordion-body"></div>
</div>

<div class="panel panel-default">


<div class="panel-heading" data-toggle="collapse" data-target="#mtu" aria-
expanded="false">
<label class="panel-title cursor-pointer tile-preview-accordion-heading">
Material Templates
</label>
</div>
<div id="mtu" class="panel-collapse collapse tile-accordion-body"></div>
</div>

Example for managing drill down from Model-driven UI screen to Custom screen

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 649


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Controller Code Reference

(function () {
'use strict';
angular.module('Siemens.SimaticIT.Material')
.controller('CustomMTUCtrl',
[
'$translate', 'common.services.modelDriven.runtimeService', '$state',
'common.base', '$q',
function ($translate, mdRuntimeSvc, $state, base, $q) {
var self = this;
var selectedItemId = '';
var backendService = base.services.runtime.backendService;
activate();

function getData() {
var defer = $q.defer();
var options = '';
var args = { appName: 'Material', entityName:
'MaterialTrackingUnit', options: options };
backendService.findAll(args).then(function (data) {
var dataToResolve = data.value || [];
defer.resolve(dataToResolve);
})
return defer.promise;
}

function initTiles(data){
self.pages = data.map(function (item) {
return {
Id: item.Id,
selected: item.Id === selectedItemId,
title: $translate.instant(item.NId),
NId: item.NId,
svgIcon: '',
onClickCallback: function (item) {
if (typeof self.performDrillDown == 'function') {
var destScreenInfo = { screenId:
'Siemens_SimaticIT_Material_Material_Runtime_MaterialTrackingUnit', params: { 'NId':
item.NId } };
self.performDrillDown(item, destScreenInfo,
item.NId);
}
}
};
});
}

function initCustomDrillDown(){
var apiList = mdRuntimeSvc.initCustomDrillDown();
if (apiList) {

650 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

self.performDrillDown = apiList.navigate;
self.getDrillDownInfo = apiList.getInfo;
self.goToPreviousLevel = apiList.goToPreviousLevel;
self.setTitle = apiList.setTitle;
}

if (typeof self.getDrillDownInfo === 'function') {


var drillDownInfo = self.getDrillDownInfo($state.
$current.toString());
if (drillDownInfo && drillDownInfo.selection &&
drillDownInfo.selection.master) {
selectedItemId = drillDownInfo.selection.master.id ||
'';

}
}

self.breadcrumbOptions = {
onClick: function (item) {
if (typeof self.goToPreviousLevel === 'function') {
//call the api to go to the screen clicked
through the breadcrumb
self.goToPreviousLevel(item);
}
}
}
}

function setBreadcrumbTitle(selectedItemId) {
var selectedItem = self.pages.filter(function (item) { return
item.Id === selectedItemId });
if (typeof self.setTitle === 'function' && selectedItem &&
selectedItem[0]) {
var title = selectedItem[0].NId;
self.setTitle(title);
}
}

function activate() {
getData().then(function (data) {
initCustomDrillDown();
initTiles(data);
//call the api to set the breadcrumb title for the
current custom screen
setBreadcrumbTitle(selectedItemId);
})
}

}]);
}());

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 651


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Template Code Reference

<!--Displaying the breadcrumb for the custom screen-->


<sit-mdui-breadcrumb sit-options="vm.breadcrumbOptions"></sit-mdui-breadcrumb>
<div class="panel panel-default">
<div class="panel-heading" data-toggle="collapse" data-target="#generalSettingsBo
dy" aria-expanded="false">
<label class="panel-title cursor-pointer tile-preview-accordion-heading">
Material Tracking Units
</label>
</div>
<div id="generalSettingsBody" class="panel-collapse collapse tile-accordion-
body">
<div ui-view="content" class="content-area content-area-relative" style="heig
ht: calc(100% - 30px) !important">
<div style="clear:both"></div>
<div style="padding-left: 8px; padding-top: 16px">
<div style="display:inline-block; vertical-align:top;">
<sit-item-tile sit-tile-content="page" sit-tile-options="{size:'l
arge' }" ng-repeat="page in vm.pages"> </sit-item-tile>
</div>
</div>
</div>
</div>
</div>

<div class="panel panel-default">


<div class="panel-heading" data-toggle="collapse" data-target="#material" aria-
expanded="false">
<label class="panel-title cursor-pointer tile-preview-accordion-heading">
Material Lot : Lot2
</label>
</div>
<div id="material" class="panel-collapse collapse tile-accordion-body"></div>
</div>

<div class="panel panel-default">


<div class="panel-heading" data-toggle="collapse" data-target="#mtu" aria-
expanded="false">
<label class="panel-title cursor-pointer tile-preview-accordion-heading">
Material: M1
</label>
</div>
<div id="mtu" class="panel-collapse collapse tile-accordion-body"></div>
</div>

2.2.4.3.2.16 Example of Configuring Groups for Content Fields


You can configure groups to classify items under one sub-section at the run-time.
The following example illustrates the configuration of groups for the fields of content of multiplicity : one:

652 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

When you are creating groups to associate the fields of content of multiplicity: one under one
group

Content Field Group Configuration


Target Use Case Procedure

When you are classifying content field items under


one group 1. In the Model-Driven UI Editor page, click the
icon.
2. In the Configuration Setting window, open the Field
groups tab, enter the ID (UniqueInfo) for the group,
and other details and click Save.
3. Navigate to the detail content (Overview) and open
Fields Settings and select the Field you want to
group.
4. Click on Edit and select the UniqueInfo from the
Groups list in order to group a Field inside it and click
Save.
5. In the runtime , you can view the label associated with
the field under the configured group as shown in the
above example.

2.2.4.3.2.17 Example of Configuring Drill Down based on a Condition


Data Drill Down is a behavior in which you would open any entity instance and see more details of the same entity
instance in another screen.
You can enable the condtional data drill down if you want to navigate to different destination screens based on the
entity instance opened.
This example illustrates the below use cases:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 653


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

Within a Master layout screen


(Materials), commands with drill-
down behavior should be
available from which any content
item (e.g. Water of Revision:1.0)
can be opened to a Master-
Details layout screen
(MaterialOfRevision1.0 Water).

654 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

Within a Master layout screen


(Materials), commands with drill-
down behavior should be
available from which the content
item (e.g. Egg of Revision: 2.0)
can be opened to a Master-
Details layout screen
(MaterialOfRevision2.0 Egg).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 655


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

Within a Master layout screen


(Materials), commands with drill-
down behavior should be
available from which the content
item (e.g. Other of Revision: 3.0)
can be opened to a Master-
Details layout screen
(MaterialOfAnyRevision Other).

656 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

Within a Master layout screen


(Materials), commands with drill-
down behavior should be
available from which the content
item (e.g. Ice of Revision: 4.0) can
be opened to a Master-Details
layout screen
(MaterialOfAnyRevision Cheese).

Data Model
The example uses the below data model artifacts:

Entity Name Property Type

Material NId String

Name String

Description String

Revision String

Tile / Grid Command configuration

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 657


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

Configure a 1. Within a Master layout screen (Material), add a master content and configure
Condtional Drill-Down it to retrieve the data from the required entity (e.g. Material).
command for a content. 2. In the Tile Settings / Grid Settings tab, in commands section, add a
command and select the conditional destination screen.
3. Select the screen (e.g. MaterialOfRevisionAny) from the available screens
menu and click on Add.
4. The first added screen will be automatically set as default.
5. Select the screen (e.g MaterialOfRevision1.0) from the available screens
menu and click on Add.
6. By default the available params of the destination screen selected will be
updated. If you want to provide additional input parameters to be used for
the destination screen, you must execute both of the following sub-steps:
• Fill in the Params edit box as shown in the example below (See
Contents and Expressions) :

Params Example

{"MasterParam":"currentContentItem.Id"}

• Provide the same input parameter to the target screen, as described


at page Example of Navigation to Another UI Screen page. Here you
must add the just specified input parameter to the target screen
Params attribute.
7. Enter the Condition as expression to configure the condition on which the
current destination screen should be considered for navigation. See Contents
and Expressions.

Condition Expression Example

currentContentItem.Revision === '1.0'

8. Select the screen (e.g MaterialOfRevision1.0) from the available screens


menu and click on Add.
9. Enter the Condition as function expression to configure the condition on
which the current destination screen should be considered for
navigation. See Contents and Expressions.

Condition Function Example

return safeVal('currentContentItem.Revision') === '2.0';

Drill Down Action Configuration

658 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

Configure a Conditional Within a Master layout screen (Material), add a master content and configure it
based Drill- to retrieve the data from the required entity (e.g. Material).
Down Action for a screen.
Add a Action (e.g. OpenMaterial) to the master content.
In the Details tab:
Specify the required information (ID, Title, Icon) to be displayed.
Provide the Show When expression or function as

Drill Down Action Show When Example

contents.Master.selectedItem.Id

in order to show the drill down action only if the content item is selected. See
Contents and Expressions.
In the Behavior tab:
• In the Type drop down, select Drill Down.
• Select Synchronize with Tile/Grid Command, if you want to load the
configuration of the drill down commands configured in parent content
(Material). Follow the below steps if this is not selected or if any changes
needed apart from the content's configuration. All the configurations saved
here will be synced with tile/grid commands and vice versa.
• Select the Conditional checkbox to enable the configuration of conditional
based drill down.
• Select the screen (e.g. MaterialOfRevisionAny) from the available screens
menu and click on Add.
• The first added screen will be automatically set as default.
• Select the screen (e.g MaterialOfRevision1.0) from the available screens
menu and click on Add.
• By default the available params of the Destination Screen selected will be
updated. If you want to provide any additional input parameters to be used
for the destination screen, you must execute both of the following sub-steps:
• Fill in the Params edit box as shown in the example below (See
Contents and Expressions) :

Params Example

{"MasterParam":"currentContentItem.Id"}

• Provide the same input parameter to the target screen, as described at page
Example of Navigation to Another UI Screen page. Here you must add the just
specified input parameter to the target screen Params attribute.
• Enter the Condition as expression to configure the condition on which the
current destination screen should be considered for navigation. See
Contents and Expressions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 659


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

Condition Expression Example

currentContentItem.Revision === '1.0'

• Select the screen (e.g MaterialOfRevision1.0) from the available screens


menu and click on Add.
• Enter the Condition as function expression to configure the condition on
which the current destination screen should be considered for
navigation. See Contents and Expressions.

Condition Function Example

return safeVal('currentContentItem.Revision') === '2.0';

5. Click Save.

2.2.4.3.2.18 Example of Configuring Facets for a Model-Driven UI Content


The use case relies on the following data model artifacts:

Entity Name Property Type

Material NId String

Name String

Description String

Revision String

Facet Name Property Type

Defect DefectType String

ResolvedBy String

FoundBy String

Severity Int

Facet Name Property Type

Status NId String

660 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Facet Name Property Type

Code String

Last Used Date Time

Facet Name Property Type

Location NId String

Type String

Country String

Pin Code Int

Building String

Address String

Target Use case UI Example

When an entity contains facets, the facet properties from multiple facets can
be displayed on the content grid or tile.

The facet properties can be used to perform sorting on the content grid or
tile.

The facet properties can be used for searching on the content grid or tile.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 661


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use case UI Example

The facet properties can be used for filtering on the content grid or tile.
Whenever properties from facets are used for filtering, resulting data will
only consist the entities that are related to those facets involved in filter
clauses.
For example, When the material is filtered with a condition Status_Code <>
999, dispalyed entity list will only consist the entries that has Status type of
facet associated to it. Rest of the entities without an association with Status
facet will not be part of the filtered result.

The facet properties can be used for grouping on the content grid or tile.

The facet properties can be displayed in the property grid for contents of
multiplicity: one.

Content configuration
Target Use Case Procedure

When an entity contains 1. Within a Master-Details layout screen, add a Master content of
facets, the facet properties multiplicity: many.
from multiple facets can be 2. Specify all the required information (ID, title) and set the entity to be
displayed on the content grid displayed (in our example the Material).
or tile. 3. Once the entity is selected, Open Facets accordion to add facets
associated to the entity.
4. Click on Add Item.
5. Select a facet (Defect) from the list of available Facets in the Facets Field.
6. Once a Facet is selected, Alias will be automatically filled with Facet short
name. It can be changed as per the need.
7. Select another facet (Status) from the list of available Facets and specify
the required Alias.
8. In the Fields tab, the properties from entity Material and its Facets:
Defect and Status will be shown.
9. In the General Settings tab, select the display mode as Tile and Grid.
10. In the Tile Settings tab, configure the Property Fields with the properties
from both the Facets added which should be shown on the Tile.
11. In the Grid Settings tab, configure the Selected Columns with the
properties from both the Facets added.

662 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case Procedure

The facet properties can be 1. Perform the same steps 1 -12.


used to perform sorting on the 2. In General Settings tab, open Field Settings section.
content grid or tile. 3. Select the properties from Facets for sorting by selecting the Sortable
check box.

The facet properties can be 1. Perform the same steps 1 -12.


used for grouping on the 2. In General Settings tab, open Field Settings section.
content grid or tile. 3. Select the properties from Facets for sorting by selecting the Groupable
check box.

The facet properties can be 1. Perform the same steps 1 -12.


used for searching on the 2. In General Settings tab, open Field Settings section.
content grid or tile. 3. Open Quick Search drop down to select a facet property as searchable.

The facet properties can be 1. Perform the same steps 1 -12.


used for filtering on the 2. In Filter Settings tab, click on Enable Filter.
content grid or tile. 3. Select the Facet property and select the Filterable checkbox to use it for
filtering.

The facet properties can be 1. Within a Master-Details layout screen, add a Detail content of
displayed in the property grid multiplicity: one.
for contents of multiplicity: 2. Specify all the required information (ID, title) and set the entity to be
one. displayed (in our example the Material).
3. Once the entity is selected, Open Facets accordion to add facets
associated to the entity.
4. Click on Add Item.
5. Select a facet (Defect) from the list of available Facets in the Facets Field.
6. Once a Facet is selected, Alias will be automatically filled with Facet short
name. It can be changed as per the need.
7. Select another facet (Status) from the list of available Facets and specify
the required Alias.
8. In the Fields tab, the properties from entity Material and its Facets:
Defect and Status will be shown.
9. In the Field Settings tab, configure the Selected Fields with the
properties from both the Facets added.

2.2.4.3.2.19 Example of Create Action with Display Mode In-Canvas


This example implements the following use cases:

Target Use Case UI Example

Within an existing Master-Details layout screen, you can create


execute command action with display mode as In-Canvas.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 663


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

Within an existing Master-Details layout screen, you can edit execute


command action with display mode as In-Canvas.

POM Model Artifacts


The example uses the following data model objects, which must be present in the POM Model of your App:
• Material
• UoM
• CreateMaterial

The CreateMaterial command has the following parameters:

Parameter Name Type

NId (Input) String

Revision (Input) String

Unique Identifier (Input) String

Name (Input) String

Description (Input) String

UoMNId (Input) String

IsDefault (Input) bool

Properties (Input) Parameter Type ( * )

MaterialTemplateId (Output) Guid

PropertyIds (Output) Guid


( * )The Properties Parameter Type has the following properties:

Property Type

PropertyNId String

PropertyType Enum (String) composed by Name and Value

664 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Property Type

PropertyUoMNId String

PropertyValue String

Action configuration
Target Use Case Procedure

Within an existing Master-Details Screen, an action is configured in 1. With the just configured master
order to add a new record and to present a form with a set of input content selected, add a UI
fields. Action.
2. Choose the Primary
button pattern and type the
Action ID.

The action presents a form with a set of input fields. 1. Choose the Execute
Command action type, and select
a command that creates an
instance of the Master content
entity (e.g. CreateMaterial).

Create execute command action with display mode as In-Canvas. 1. Enable the Advanced Settings.
2. Change the display mode as In-
Canvas.
3. Name the Header Title as
Localization Key.
4. Select the Header Title Field from
the drop-down list.
5. Name the Breadcrumb Title as
Localization Key.
6. Select the Breadcrumb Title Field
from the drop-down list.
7. Select the number of columns
between 2 to 7.

2.2.4.3.2.20 Example of Using File Uploader in Model-Driven UI


This example implements the following use cases:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 665


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Target Use Case UI Example

Configure the file uploader widget in action field.


In the fields tab, if you have any field with the type as blob then you can
choose file uploader as user input mode dropdown.
The value of a field configured with the file uploader
(action.fields.FileUploaderField) will have the following attributes:
• type, the type of the file.
• name, the name of the file.
• contents, the converted base64 string of the file.
• data, the combination of type and contents. This is the suggested
way for using this value in the action command.

Passing only the converted base64 string of the file to the command:
• configure a field with above mentioned use case.
• create another hidden field with its value configured as
action.fields.FileUploaderField.contents.

2.2.4.4 How To Debug UI Modules and Screens


Proceed with required procedure:
• Debugging UI Modules and Model-Driven UI Modules
• Debugging UI Modules, Model-Driven UI Modules together with the Business Logic

2.2.4.4.1 Debugging UI Modules and Model-Driven UI Modules


While developing a UI Module, or a Model-Driven UI Module, in Visual Studio, you can test it locally to make sure
that everything works as expected before using the UI Module within a UI Application.
Project Studio provides a script that automatically updates the default-debug.html file based on the current UI
Module definitions and sources.
If you are working under source control, the following files are automatically checked out when the script is run:
• app.js
• config.js
• default.html
• default-debug.html
Alternatively, this procedure can be performed manually on each individual default file, but this is not
recommended.
If you need to test the UI Modules, together with the back-end logic, see Debugging UI Modules, Model-Driven UI
Modules and Business Logic.

Limitation
If you have an environment configured in HTTPS, debugging functionalities on Business Logic and UI Modules are
not available.

666 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Prerequisites
• You must have rebuilt the <AppName>.UserInterface project to create a copy of the common folder within the
project structure, which contains the UI Framework. This folder is accessible on the file system, but it is not
visible in Solution Explorer. This operation must be performed for each project every time the UI Framework
version changes.
• The UI Model-Driven Server must have been started (by right-clicking the <AppName>.UserInterface project
and selecting the Start UI Model-Driven Server command).
• The Solution containing the entities and commands used by the UI Module has been deployed at least once.
• The Runtime Service Layer is running and it is possible to retrieve data and execute commands.

Procedure
In Project Studio,
1. Right-click the <AppName>.UserInterface project and select Generate UI Application Files to launch
the script that automatically updates the default UI Application files.
2. Right-click the <AppName>.UserInterface project and select Run UI Application in browser to open the
modules in the default browser.

 If the UI you are debugging contains widgets that make requests to any Service Layers outside your App
(e.g. the Electronic Signature sit-es-scenario-picker widget), you must manually add the required OData
endpoint to the config.js file of your UI Interface project in the applicationServiceUrls section. For
example, referring to sit-es-scenario-picker widget:
"applicationServiceUrls": {
"AuditTrail": "http://localhost/sit-svc/Application/AuditTrail/odata",
Pay attention that you need to repeat this manual operation each time you use the Generate UI
Application Files command, as the file is overwritten.

 When testing a UI Application, you should always keep your browser Developer Tools open. To open the
Developer Tools in one of the supported browsers, press F12. Keeping the Developer Tools open also
inhibits any automatic caching of web content on the client side, which can be helpful when debugging.

2.2.4.4.2 Debugging UI Modules, Model-Driven UI Modules and Business


Logic
You can directly test a UI Module or a Model-Driven UI Module during the development phase in Project Studio,
together with the implemented business logic by following the procedure below (instead of testing only the UI
Modules, as described at page Debugging UI Modules and Model-Driven UI Modules).

Preconditions
• You must have rebuilt the <AppName>.UserInterface project to create a copy of the common folder within the
project structure, which contains the UI Framework. This folder is accessible on the file system, but it is not
visible in Solution Explorer. This operation must be performed for each project every time the UI Framework
version changes.
• The UI Model-Driven Server must have been started (by right-clicking the <AppName>.UserInterface project
and selecting the Start UI Model-Driven Server command).
• The Solution containing the entities and commands used by the UI Module has been deployed at least once.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 667


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

• The Runtime Service Layer is running and it is possible to retrieve data and execute commands.
• The same preconditions described for Debugging Commands and Reading Functions via App Debugging Tool.

Procedure
In Project Studio:
1. Right-click the <AppName>.UserInterface project and select the Generate UI Application Files (Debug)
command. This command sets inside the config.js file the endpoint of the Debug Runtime Service Layer.
2. Right-click the Solution in Project Studio (App or Functional Block) and select Properties.
3. Select the Multiple startup projects option button and then set the Start action for both the User Interface
project and the Handler to be debugged (Command Handler/Composite Command Handler or Reading
Function Handler).
4. Right-click the <AppName>.UserInterface project and select Run UI Application in browser to open the
modules in the default browser.
5. In the Login page, to which you are automatically redirected, enter the credentials of an authenticated user (i.e.
a user associated with the proper role required to execute the operations invoked in the UI Screen).
6. Execute the operation you want to test. The system will automatically open the related invoked Handler and will
stop at the required breakpoint.

 If the UI you are debugging contains widgets that make requests to any Service Layers outside your App
(e.g. the Electronic Signature sit-es-scenario-picker widget), you must manually add the required OData
endpoint to the config.js file of your UI Interface project in the applicationServiceUrls section. For
example, referring to sit-es-scenario-picker widget:
"applicationServiceUrls": {
"AuditTrail": "http://localhost/sit-svc/Application/AuditTrail/odata",
Pay attention that you need to repeat this manual operation each time you use the Generate UI
Application Files command, as the file is overwritten.

 If the Debug Service Layer is not ready when you click Start, you may not be correctly redirected to the
login page. The best solution to this issue is to refresh the UI page, by pressing F5, in order to make sure
the Service Layer is running.

668 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 To avoid errors on CORS policy, make sure to set all the required headers in svc/application of IIS HTTP
Response Headers. See an example for reference.

2.2.5 How to Create and Release an App Package


After defining the artifacts required for an App and implementing the relative business logic, it is necessary to
perform some final steps in order to create an App package, which can then be browsed from Solution
Studio, properly configured and then deployed to a target scenario:
1. Add third-party files, that must be included in the Functional Block Package, to the Installer Project.
2. Compile the database initialization file.
3. Manage the application log file, if you edit it to add/remove any application messages.
4. Generate reference documentation, if required.
5. Define the build order (recommended).
6. Add automatic update function for referenced Functional Blocks, if required.
7. Generate the App package.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 669


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 If you did not use the Copy to Engineering Target Folder option during the package generation
procedure, manually copy the App package, and the packages generated while compiling the referenced
functional blocks, into the following folders in order to properly load the relative metadata in Solution
Studio:

Package Destination folder

App %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\Proj
ects

Referenced Functional Blocks %ProgramData%


\Siemens\SimaticIT\Unified\Engineering\Packages\Func
tionalBlocks

 To secure the custom package release, see Whitelisting in the Opcenter Execution Foundation Security
Concept.

2.2.5.1 Adding Third-Party Files to the App Installer Project


You can include third-party files, such as configuration files, XML or DLL, required by your App to the App package
zip.
This procedure should not be used for files which are already present on the target machine or for files which have
their own set-up. In this case the files should be installed directly on the target machine.

Limitations
• Subfolders are not supported
• There must not be two files with the same name.

Procedure
1. From the Installer project, right-click the ExternalDependenices folder and select Add > ExistingFile.
2. Browse to the files you want to include in the App package and click OK.

Result
These files will be included in the External Dependencies folder of the App package zip.

2.2.5.2 Compiling the Database Initialization File in the App


You can populate the Dbinit.xml file to initialize the database before you release the App package.
If you want to provide basic information when you create the Opcenter EX FN database, such as units of measure,
lifecycles, status transitions, you can compile the Dbinit.xml file and manually enter the default data that the
system will use to initialize the Opcenter EX FN database. The procedure for doing this is described in this page.
The first time you create your model project, an empty file is provided in the Installer project. You can manually
populate this file with an .xml representation of your data model and type in the related default values. To facilitate
this task, Project Studio provides you with a tool, which automatically generates the .xml template corresponding

670 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

to the data model defined both inside the current model project and inside the referenced Functional Blocks. You
must then manually copy the elements you need and type the required values. When you use the tool to create
the .xml template, the system does not directly overwrite the Dbinit.xml file but displays the template inside a
temporary file.
If you do not need to insert any information, leave the file empty.

 Both if you are in a Functional Block and if you are in App, the tool generates an .xml representation of the
data model present in your model project and in the referenced Functional Blocks.

 To initialize the Automation App data, you cannot use the dbinit.xml file because it does not perform data
checks
but you must follow the configuration workflow documented at How to Manage Automation Nodes in the
Opcenter Execution Foundation User Manual

Prerequisites
• The model project has been compiled and any required referenced Functional Blocks have been included.
• The entity types you want to initialize with default values must contain a logical key, otherwise they cannot be
imported inside the initialization file.
• You have used Reference Manager to manage relationships between Functional Blocks. If you have manually
added references to other Functional Blocks, the template will not be generated.

Compiling the initialization file


1. From the Solution Explorer in Project Studio, open the Installer Project.
2. In the Config folder, right-click the Dbinit.xml file and select the Generate DBInit schema command: the
generated .xml template file contains a sample entity element for each entity type. In this way, you do not have
to write the .xml file from scratch.
3. Copy and paste the elements for the entity types you want to initialize from the template to the Dbinit.xml file,
and then type in the property values.
4. Save changes.

Updating the model project and reimporting the initialization file

 You cannot update an entity instance whose logical key has the same value in the database as the one you
are specifying in the initialization file.

1. Apply the required changes to the model project.


2. Compile the model project.
3. From the Solution Explorer in Project Studio, open the Installer Project.
4. Right-click the Dbinit.xml file project and select the Generate DBInit schema command. A new representation
of the modified data models is displayed inside the temporary .xml template.
5. Copy and paste the elements for the entity types you want to initialize from the template to the Dbinit.xml file,
and type in the property values.
6. Save changes.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 671


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

 Integrity check and validation errors


During package creation, the system executes a validation task. If errors occur, the package is not created
and error details are shown in the build details pane. This check does not involve any runtime checks on
the database. It is only a formal check if the file is well formed (if entity names, entity types and related
entities are correctly compiled). Runtime checks will be executed during database update operations.
As there is no validation schema for the Dbinit.xml file, low level Information messages may be
generated when you open the file in Project Studio. However, this does not imply that the file is invalid.
You should not initialize the same entity in different Functional Blocks or App with different values
because the system cannot assign any priority to the different initialization layers. This means that it
cannot guarantee that the actually required value will be inserted.
If you manually add entities that do not have any logical key, the records will be always appended to the
database at each update operation.

Initialization file description: elements and attributes


Element Name & Element Attributes Inner elements
Description

Sections None This element can contain


multiple Section elements
Root element. Used to
(note the missing s for plural).
contain the sections.

Section • engineeringLevel, which describes the It can contain multiple Entity


abstraction level of the data model. elements.
Used to describe entities
• implementationName, which is a
belonging to a certain
custom-defined label used to identify
domain.
the specific implementation/version.
• domainName, attribute, which
specifies the name of the domain to
which the entities that are contained in
the section belong.

Entity type, which describes the type of the entity It can contain multiple
(corresponding to the Fullname displayed Property elements.
Used to describe an entity.
in the Properties pane of the entity in
Project Studio).

672 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Element Name & Element Attributes Inner elements


Description

Property • name, which describes the name of the • If the described property
property. specifies a reference to a
Used to describe a property
• kind, which specifies if the property is a parent (i.e. the kind is
of an entity.
plain property, a value type property SingleReferenceToParent)
or a reference property (see notes) the element has one inner
• value, which contains the value of the LogicalKey element
property if the property defined for indicating the referenced
kind is plain. The value representation parent entity.
follows the C# • If the described property
System.Globalization.CultureInfo.Invari specifies a many-to-many
antCulture format, except for Guid relationship (i.e. the kind is
values, which are represented in the ManyToManyReference)
following example format: the element contains
"0b0e9810-096f-4864- multiple LogicalKey
b8e0-0dca91f6ff0f". If the property is elements indicating the
enumeration type the value to be linked entities.
specified must be the enumerator • If the described
name and not its numerical value. If the property specifies a
property defined for kind is not plain, value type (i.e. the
this attribute is not present. kind is Complex),
the element should
contain the inner
properties of the
value type, which
can be either Plain
or
SingleReferenceTo
Parent.

LogicalKey entityType, which specifies the type of the It contains a Property element
Specifies the key used to link linked entity. for each property that is part of
an entity to a referenced the logical key of the referenced
entity. entity.

Notes
• The kind attribute can assume the following
values: Plain, SingleReferenceToParent, ManyToManyReference, Complex.
• Relationships among entities are always specified by the forward navigation property.
• You cannot add part entities to a composite entity when it is Frozen, Locked or Marked for Cleaning.
• Null values are indicated by specifying the NULL reserved string (upper case).
• The LogicalKey elements can be nested if the logical key of an entity type includes a navigation property.
• Blob and FileType property types cannot be initialized and should not be present in the .xml.

Example of dbinit.xml file

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 673


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

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


<Sections>
<Section engineeringLevel="LibraryFunctionalBlock"
implementationName="MyTestImplementation_v1" domainName="ReferenceData">
<Entity type="MyCompany.DataModel.MyTestEntity1">
<Property name="StringProperty" kind="Plain" value="A" />
<Property name="BoolProperty" kind="Plain" value="true" />
<Property name="DateTimeProperty" kind="Plain" value="12/31/2015
23:59:59 +02:00" />
<Property name="GuidProperty" kind="Plain" value="0b0e9810-096f-4864-
b8e0-0dca91f6ff0f" />
<Property name="BigintProperty" kind="Plain"
value="-9223372036854775808 " />
<Property name="IntProperty" kind="Plain" value="-100000" />
<Property name="SmallintProperty" kind="Plain" value="-32767" />
<Property name="TinyintProperty" kind="Plain" value="255" />
<Property name="DecimalProperty" kind="Plain" value="1.234" />
<Property name="TimeSpanProperty" kind="Plain" value="01:02:03" />
<Property name="MyNullableProperty" kind="Plain" value="NULL" />
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity2">
<Property name="MyProp1" kind="Plain" value="NULL" />
<Property name="ParentProp" kind="SingleReferenceToParent">
<LogicalKey entityType="MyCompany.DataModel.MyTestEntity3">
<Property name="Name" kind="Plain" value="TestName" />
<Property name="Version" kind="Plain" value="1" />
</LogicalKey>
</Property>
<Property name="MyValueTypeProp" kind="Complex">
<Property name="Ref" kind="SingleReferenceToParent">
<LogicalKey entityType="MyCompany.DataModel.MyTestEntity4">
<Property name="A" kind="Plain" value="NULL" />
</LogicalKey>
</Property>
</Property>
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity3">
<Property name="Name" kind="Plain" value="TestName" />
<Property name="Version" kind="Plain" value="1" />
<Property name="MyProp1" kind="Plain" value="qwerty" />
<Property name="MyValueTypeProp" kind="Complex">
<Property name="A" kind="Plain" value="zxcv" />
<Property name="B" kind="Plain" value="NULL" />
</Property>
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity4">
<Property name="Name" kind="Plain" value="A" />
<Property name="MyProp1" kind="Plain" value="qwerty" />

674 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

<Property name="Z" kind="ManyToManyReference">


<LogicalKey entityType="MyTestEntity5">
<Property name="Name" kind="Plain" value="a" />
</LogicalKey>
<LogicalKey entityType="MyTestEntity5">
<Property name="Name" kind="Plain" value="b" />
</LogicalKey>
</Property>
</Entity>
<Entity type="MyCompany.DataModel.MyTestEntity5">
<Property name="Name" kind="Plain" value="A" />
</Entity>
</Section>
</Sections>

2.2.5.3 Managing the Application Log File of an App


The Application Log file is an xml file that allows you to define the application messages for Apps / Extension Apps.
You can have an Application Log xml file for each App / Extension App.
The first time you create a new App, an empty xml file is automatically created under the Installer project. But
for an existing App, you must manually add the xml file to the Installer project. You can open this file in Project
Studio and define the application log messages.

 In both cases, the default language of xml file is English and the file name must be in the
format: <Acronym>.<AppName>.ApplicationLog.en-US.xml. You must not modify the file name, even
though the system allows you.

This way, you can have multiple Application Log xml files (1 for each App). The system manages all xml files
and stores the messages from them in the database. You can install the Application Log App in Solution Studio to
log the defined messages and view them in your UI Application at runtime.
This section describes the structure of the xml file and its restrictions.

Application Log xml File Structure

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 675


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

File Structure

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


<messages>
<message>
<id></id>
<short></short>
<long></long>
<level></level>
<params>
<param>
<key></key>
<type></type>
</param>
</params>
</message>
</messages>

The table describes the message attributes:

Attribute Name Description

ID A unique identifier for the message.

ID is a mandatory attribute.

Short A short and understandable description of the message.

Long A long description of the message that provides further verbosity


than a short message.

Level The type of message. The system accepts only Critical, Error,
Warning, Informational or Verbose value.

Level is a mandatory attribute. Any value other than the


mentioned will result in error.

Parameter Key The primary key that stores the name of the parameter that repeats
multiple times for a message.

Parameter Type The type of the parameter that repeats multiple times for a message.
Example values for the Application Log File:

676 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Id Short Message Advanced Message Level

-00001 Unable to start the operation Unable to start the operation Error
%op_name% because the work order
%wo_name% is on hold.

-00001 Unable to start the operation Unable to start the operation %op_id% Error
because the work order %wo_id% is on
hold and material lot %m_lot% is mark
to be cleaned.
The Application Log xml file requires certain restrictions that you must respect to avoid database update errors:

 XML File Restrictions


• The name and structure of xml file are system defined and must not modified.
• Length of Short and Long message must be less than 100 characters.
• Every message must have a Message ID and Level, as they are mandatory fields.
• A message ID must be Numeric only and should not be repeated within the same xml file.
• The Level defined for a message must be either Critical/Error/Warning/Informational/Verbose.
• Length of parameter key and type must be less than or equal to 100 characters.

Manually Adding xml File


1. In Project Studio select the Functional Block/App/Extension App and open the solution.
2. Expand the Installer project, right-click Config folder and select Add > New Item.
3. Select Application Log class and click Add. This will add a new xml file to the Installer project that gets the
system-defined name and structure.

 Do not modify the file name, even though the system allows you to. If you rename, the system does not
take into account the custom name and returns an error while building the Installer project.

4. Build the Installer project to package the new xml file.

 For the whole configuration procedure, see How To Manage Application Logs.

2.2.5.4 Generating the Reference Documentation of an App


In Project Studio whenever you create a new element, such as a composite command, or a new property for a
parameter type, you can provide a multi-line description using mark up.
If you have provided information from which documentation can be generated, for example descriptions of
artifacts, when your project is compiled a file is generated with these descriptions
(<Prefix>.<DomainName>.<FunctionalBlockName>.udoc) and is saved in the bin\Debug folder of your project.
This udoc file can then be imported into the Documentation Center via the Documentation Center Administrator
Tool consequently providing reference documentation for each Functional Block.

 Output files should be always generated by default when compiling the project.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 677


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

Elements you can document


This reference documentation file contains the descriptions you inserted while modeling:
• Entities
• Composite Commands
• Parameter Types
• Enumeration Types

 Sensitive data
• Access to the documentation service layer is anonymous. Consequently the documentation center
store must not include sensitive data. If this is strictly necessary, suitable security measures must be
implemented (e.g. restrict access to the network where the documentation service layer is deployed).
• HTTPS communication is recommended.

Inserting comments
The following procedure is the same described for Functional Blocks, but related to the App solution environment:
1. In Project Studio, in the Object Model (or Public Object Model for Apps), double-click the artifact for which you
want to enter comments.
2. In the Model Details pane, in the General tab, type the required description in the Description edit box.

3. In the Properties window, enter the required descriptions for each artifact parameter or property.

Generating output files


The custom documentation .udoc file should be generated by default when you compile your project. If this does
not happen perform the following steps to check your configuration options, which are valid both for Functional
Blocks, Apps or Extension Apps:
1. In Solution Explorer right-click the Model project (or POMModel project) and select the Properties command.
2. Click the Compiler tab.
3. Make sure the Enable Documentation Compiler check box is enabled.
4. If you want to optimize the compilation process, select the Enable Parallel Compiler check box.
5. Build the Model project.
6. Check that the <Prefix>.<DomainName>.<FunctionalBlockName>.<DomainAcronym>.Model.udoc file (or
<Prefix>.<DomainName>.<AppName>.<Acronym>.POMModel.udoc) is saved under the
currently configured output folder (by default, the bin folder) of the Model (or POMModel) project. If you are

678 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

compiling the Installer project, the file will be placed under the output folder which is currently set for the
solution configuration you are using (e.g. bin\Debug or bin\Release or any other output folder).

2.2.5.5 Defining the Build Order of an App


The order in which projects are built in Project Studio is important to ensure errors do not occur.
For example, the model project should be compiled before the command handler project.
The alternative procedure provides a more complex solution, used in previous versions of Visual Studio, but still
valid if preferred.

Procedure
1. In the Solution Explorer pane, right-click your Command Handler project and select Build Dependencies >
Project Dependencies.
2. Click on the Dependencies tab.
3. Select your Command Handler project from the Projects drop down list.
4. In the Depends on pane select your model project and click OK.
5. Select your Event Handler project from the Projects drop down list.
6. In the Depends on pane select your model project and click OK.

 If build errors persist when building from the command line, open .sln file from the solution folder, and
make sure the model project (.pmproj) is the first project in the list.

Alternative Procedure
To set the build order perform the following procedure, first for the command handler project and then for the
event handler and Installer project:
1. Create a reference to the model project from the command handler project by right-clicking
the CommandHandler project node in Solution Explorer and clicking Add > Reference.
2. In Reference Manager select Solution > Projects in the left hand pane, select the model project and click OK.
3. Right-click the CommandHandler project and select Build.
4. Right-click the CommandHandler project node in Solution Explorer and select Open Folder in File Explorer.
5. Open the file <AppName>.CommandHandler.csproj with a text editor.
6. In the <ProjectReference> node you created in step 2 enter <ReferenceOutputAssembly>false</
ReferenceOutputAssembly>.

<ProjectReference Include="..\FBAppxx.UPPOMModel\FBAppxx.UPPOMModel.pmproj">
<Project>{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}</Project>
<Name>FBAppxx.UPPOMModel</Name>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>

7. Click Save.
8. Repeat the whole procedure for the event handler and installer project.

2.2.5.6 Automatically Updating Referenced Functional Blocks in an App


You can automatically update referenced Functional Blocks every time you build your solution.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 679


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

The RestoreSimaticITUAFPackage target replaces the necessity to perform a Restore operation from Reference
Manager.

Prerequisites
The build order must have been defined.

Procedure
The RestoreSimaticITUAFPackage target can be added to your solution as follows:
1. Right-click the model project node in Solution Explorer and select Open Folder in File Explorer.
2. Open the file <AppName>_<Acronym>POMModel.pmproj with a text editor.
3. At the end of the file add the following nodes:

<Target Name="RestorePKG" DependsOnTargets="BeforeBuild">


<CallTarget Targets="RestoreSimaticITUAFPackage"/>
</Target>

<Import Project="$(SITUnifiedVSToolingPlatformBin)
\Siemens.SimaticIt.ReferenceManager.targets" />

4. Click File > Save.

2.2.5.7 Generating an App Package


This page describes how to generate the App package. You can determine whether this App can be extended or not.

Prerequisites
• If the App contains the definition of composite commands, reading functions or new event handlers, you must
also have imported the related command, or reading functions, or event C# classes (these classes must not
necessarily contain implemented code, but they must be present in the App).
• If you want to enter default values for the initialization of the Opcenter EX FN database, the Dbinit.xml file has
been compiled.
• If you want to add/edit the application log messages for the App, Application Log file has been managed.
• If you want to use the Copy to Engineering Target Folder (see explanation below), the user that is currently
running MS Visual Studio must have write permissions on the target folder (either the user himself or by means
of a dedicated Windows group).

 If your App contains references to Functional Blocks, Reference Manager will ensure that these Functional
Blocks will also be referenced by the App Package. However, if you added references manually, without
using Reference Manager, you must modify the <Prefix>.<App>.References.xml file contained in
the Installer project > Config folder, as described for the Functional Block package.

Generating the Package


To generate the App output package, to be configured to define runtime behavior:
1. Right-click the Installer project and select Properties.
2. Select the Copy to Engineering Target folder check box to automatically copy the generated zip file to the
Engineering target folder (%SITUnifiedSystemData%\Engineering\Packages\Projects) .

680 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an App for a Manufacturing Use Case

3. If you want be able to extend this App through an Extension App, set the Can be Extended option to True.
4. Build the Installer Project in either of the following ways:
• by building the entire Solution
• by building the Installer project.

 The output files are saved in the bin\Debug folder of the Installer project (for example,
MyApp\MyApp.Installer\bin\Debug). You define where the project will be saved as its Location when you
create the solution in MS Visual Studio. If you do not select the Copy to Engineering Target folder check
box, you will have to manually copy the output zip file, which is placed in the Installer project local output
folder, to the Engineering target folder.

App Package Structure


The system assigns by default the name <Prefix>.<AppName>V<AppVersion>.zip to the App output package. The
package has a fixed folder structure and contains:
The package has a fixed folder structure:
• config folder, with the configuration file and log files
• ExternalDependencies folder, with the files required by third-parties
• handlers folder, with the assembly files (.dlls) produced by command, reading function and event handler
projects.
• model folder, which in turn contains:
• bin folder, with the .dlls for entities, reading functions, types and the definition of the public commands
(i.e. either Composite commands or referenced Commands that have been published to the POM Model);
• manifacturingmodel folder, with the .um and .umd files;
• signals folder, which contains:
• descriptors folder, containing signal descriptions (for future implementations)
• diagrams folder, containing the signal diagrams;
• metadata folder, which contains the metadata of the App.
• ui folder, with the files required by the user interface
• manifest.xml, which includes:
• the metadata created in the Functional Block (relative to the model and the business logic)
• any referenced library Functional Blocks.
• udoc file, present if custom documentation has been generated from descriptions provided in the App.

Model project assemblies


The package contains the following model assemblies:

Assembly name Description

<Prefix>.<DomainName>.<AppName>.< It contains the definitions of the commands.


Acronym>Model.Commands.dll

<Prefix>.<DomainName>.<AppName>.< It contains the definition of the entity classes that are required to
Acronym>Model.PublicModel.dll execute reading operations on the public object model.

<Prefix>.<DomainName>.<AppName>.< It contains the definitions of the reading functions.


Acronym>Model.ReadingFunctions.dll

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 681


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

Assembly name Description

<Prefix>.<DomainName>.<AppName>.< It contains the definitions of the classes for the types (parameter
Acronym>Model.Types.dll types, enumeration types) that are required to handle the events,
commands and reading functions.

2.3 How to Develop an Extension App


You can extend an existing App, through an Extension App, which references the base App you want to extend.
The Extension App includes the Public Object Model of the base App, along with its roles and subscriptions.
Starting from this inherited model you can further extend the App by:
• referencing new Functional Blocks and extending the Public Object Model,
• creating new Composite Commands and Reading Functions
• delivering new Predefined Roles and Event subscriptions
• releasing new UI screens or components.

Workflow
1. Create an Extension App.
2. Extend the Public Object Model.
3. Create new Artifacts and Business Logic.
4. Extend User Interfaces.
5. Generate the Extension App Package.

2.3.1 How to Create an Extension App


You create Extension Apps through a specific Visual Studio solution wizard.
Once you have created your Extension App, selecting the App on which it is based, you may want to reference
additional Functional Blocks, or you may need to update existing references.
These operations are performed in Reference Manager in Project Studio

682 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

Workflow
1. Create an Extension App.
2. Reference other Functional Blocks from an Extension App.
3. Load Base App changes from an Extension App.

2.3.1.1 Creating an Extension App


Extension Apps are created in a specific Visual Studio solution wizard.
There are some significant differences between the wizard used to create standard Apps, and the wizard used to
create Extension Apps:
• you must specify the App you want to extend.
• as Extension Apps inherit the domain of the base App, you do not need to specify an App domain.
• you must specify a Public Object Model acronym. This acronym will be used to identify the name of the
extended Public Object Model (while the base App Public Object Model remains unchanged).

 Once you have selected the base App which your Extension App will extend, you cannot remove this base
App, or any of the Functional Blocks it references, from the Extension App solution.

Prerequisites
• The base App to be referenced must have been compiled with the required extension option (Can Be
Extended option) (see Generating an App Package).
• The output zip file of the App you want to reference, created during the App generation, must be saved in the
folder %ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\Projects and the zip files of any
referenced Functional Blocks must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

Procedure
1. In Project Studio select the File > New > Project command.
2. In the left pane, click Installed and then expand the Simatic IT node.
3. Select FunctionalBlock.EApp.
4. Enter a name for the Extension App, which will then be used in the solution. The name can contain only
alphanumeric characters (20 characters maximum), and it cannot be modified once inserted.

 The name of the Extension App must be different from the name of the base App it will reference, and
the names of the Functional Blocks referenced by the base App. It must also be different from the name
of the artifact types (e.g. "event", "commands" etc) and must not contain C# reserved keywords.

5. Enter the location where the Extension App will be created. The location name cannot contain the following
special characters: < (less than), > (greater than), : (colon), " (double quote), / (forward slash), \ (backslash), |
(vertical bar or pipe), ? (question mark), * (asterisk), & (ampersand), # (hashtag), % (percentage), , (comma).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 683


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

6. Click OK: the creation process is simplified by an integrated wizard which guides you through the
necessary steps.

7. Click Next.

8. Select the base App you want to extend and the specific version you require.

 Once selected you cannot uninstall the referenced base App, or install a different App.

684 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

9. Enter a prefix for the Extension App (see constraints below). The prefix is then appended to the Extension App
name in order to easily identify it within the development and configuration process.

 Prefix naming constraints


• The prefix cannot start with a number.
• The prefix cannot contain:
• special characters (< (less than), > (greater than), : (colon), " (double quote), / (forward
slash), \ (backslash), | (vertical bar or pipe), ? (question mark), * (asterisk), ! (exclamation
mark)
• underscore (_) or hyphens (-)
• C# keywords
• accented characters (for example à, ò, é, ù and so on)
• dots (.) as the first or last characters
• commas
• spaces
• non-latin characters (for example, 新浪网 or ‫)ﻣﺆﺳﺴﺔ‬.

10. Modify the Extension App version if the default value (01.00.00) does not correspond to your requirements.
11. Insert a description providing other users with additional and exhaustive information on the functionality
provided by the Extension App.
Note During the modeling phase, it will be possible to modify the description of the Extension App at any time,
right-clicking the Installer project and selecting the Properties command.
12. Enter a two-character acronym for the Public Object Model (POM), which must be different from the acronyms
assigned to the standard domains (i.e. not RF, OP, MS) and from the acronym assigned to the base App Public
Object Model. The acronym must not start with a number.
13. Click Next.
14. Select which elements (called projects in the Solution Explorer in Project Studio) your Extension App will
contain:
• Public Object Model (POM) Project (always selected by default) which contains the public reading data
model.
• Reading Function Project: from which you can implement the query expression for reading functions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 685


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

• Command Handler Project: from which you can implement the business logic for composite
commands.
• Event Handler Project: from which you can implement the business logic for referenced events.
• UI Project: from which you can develop a user interface for your Extension App.
• Installer Project (always selected by default): where the files required to create the Extension App
package are contained.

Result
If you have selected all available projects the structure displayed in the Solution Explorer pane is the following:

686 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

The <Prefix>_<Acronym>_<AppName>.dm file, which will contain the graphical representation of the data model
(in the Diagrams sub-folder), is created within the model project folder.

Additional operations
• To remove a project, right-click it and then select the Remove command.
• To add a new project, right-click the App root, select the Add > New Project command, select
the Installed\Templates\Simatic IT node and then select the required option. The following restrictions apply
when adding a new project:
• there can be only one POMModel Project
• there can be only one UserInterface Project
• there can be only one Installer Project
• it is not possible to add a Model Project to an Extension App solution
• it is not possible to add an External Data Source Project to an Extension App solution.
There can be several Reading Function Projects, Command Handler Projects, Event Handler Projects.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 687


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

2.3.1.2 Creating a New Version of an Extension App


As for any Apps, if you modify an Extension App after its deployment you must create a new version to properly
apply semantic versioning (see Creating a New Version of an App).

2.3.1.3 Referencing Other Functional Blocks from an Extension App


Extension Apps include any Functional Blocks that were referenced by the base App.
However, you can reference additional Functional Blocks you may require to populate the Public Object Model
(POM).

Referenced and imported artifacts


You can automatically access all the referenced entities, types, events and protected commands of the Functional
Blocks from the Extension App.
Events and types (e.g. parameter types, enumerations) are automatically imported in the Public Object Model
(POM), whilst you must select which entities and protected commands you want to import.
Referenced artifacts cannot be modified or deleted, however, a number of operations can be performed from the
Public Object Model on imported artifacts:
• Imported entities:
• Import and rename referenced entities
• Hide properties and relationships of imported entities
• Unpublish entities, removing them from the Public Object Model
• Create relationships from imported entities to referenced entities
• Imported protected commands:
• Import and rename a referenced protected command, consequently exposing them on the Service Layer.
• Unpublish protected commands, removing them from the Public Object Model

 Although events cannot be modified, you can create new handlers for referenced events.

Available operations
• Installing a Functional Block from an Extension App
• Updating the Version of a Functional Block from an Extension App
• Restoring the Files of a Functional Block from an Extension App

2.3.1.3.1 Installing a Functional Block from an Extension App


You can install additional Functional Blocks in an Extension App to enrich its Public Object Model (POM).
When you install a new Functional Block with Reference Manager you are creating a new reference to a Functional
Block.

Prerequisites and constraints


• The output zip file of the Functional Block you want to reference, created during the Functional Block
generation, must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
• Functional Blocks referenced by the base App cannot be removed from the solution. Additional Functional
Blocks successively added to the Extension App can however be removed by selecting them and clicking
Uninstall.

688 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

• The Functional Block packages must have been created in at least version 2.0 of SIMATIC IT UAF or migrated to
this version. If you try to install a Functional Block from a prior product version an error message will be
displayed.

 If two referenced Functional Blocks themselves reference the same Functional Block (i.e. A and B both
reference C) Reference Manager checks to see whether they reference the same version.
If they differ by patch or minor version the highest version is loaded.
For example:
• A references version 01.00.01 of Functional Block C
• B references version 01.00.02 of Functional Block C
Reference Manager will load version 01.00.02 as this should not cause compatibility issues.
If they differ by major version an error is returned and the operation will not be possible.

Procedure
1. In the Solution Explorer pane, double-click the packages.reference file in the Solution Items folder.
2. Click on the Browse tab and select the Functional Block you want to reference. If it can be installed, its details
will be displayed in the pane on the right, otherwise an error message will be displayed.
3. Click Install. If the Functional Block contains references to other Functional Blocks, these will be displayed
under Dependencies and will automatically be installed if their .zip files are available in the folder,
otherwise you will receive an error message.

Result
• The packages you have installed will be displayed in the Installed tab and will have a green tick icon next to
them.
• The Solution Explorer tree view will contain the .um, .umd and .dlls of the referenced Functional Block. A new
folder, SimaticITPackages, if it doesn't already exist, will be created in the folder where your project files are
saved. A subfolder will be created for each referenced Functional Block, its name is comprised of the name and
version of the referenced Functional Block. The files contained in the .zip file are saved in this folder, with the
following structure:
• config folder, with the Dbinit.xml file for initializing the database
• handlers folder, with the command and event handlers
• model folder, with the data model files and assemblies
• ExternalDependencies folder, with third-party files required by the Functional Block you are referencing
• manifest file

2.3.1.3.2 Updating the Version of a Functional Block from an Extension App


The references you can update depend on the version you are working on:
• Patch version - you can update your reference to a new Patch version. For example, if you referenced version
01.00.00. of Functional Block x, and 01.00.01 is available in Reference manager you can update the reference.
You could not update to version 01.01.00 as this would imply a new minor version.
• Minor version - you can update your reference to a new Patch or Minor version. For example, if you referenced
version 01.00.00. of Functional Block x, and 01.01.00 is available in Reference manager you can update the
reference. You could not update to version 02.00.00 as this would imply a new major version.
• Major version - you can updates all references to any version. Bear in mind that Major versions could contain
cancellations in the referenced Functional Block, which could lead to incompatibilities within the Extension
App, which will then require manual alignment in Project Studio.

Prerequisites

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 689


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

• The output zip file of the Functional Block you want to reference, created during the Functional Block
generation, must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
• The Base App you want to reference is updated.

Procedure
1. In the Solution Explorer pane, double-click the packages.reference file in the Solution Items folder.
2. Click on the Installed tab and select the Functional Block you want to update. If it can be updated, its details
will be displayed in the pane on the right, otherwise an error message will be displayed.
3. Click Update. If the Functional Block contains references to other Functional Blocks, they will be automatically
installed if their .zip files are available in the folder, otherwise you will receive an error message.

 If two referenced Functional Blocks themselves reference the same Functional Block (i.e. A and B both
reference C) Reference Manager checks to see whether they reference the same version.
If they differ by patch or minor version the highest version is loaded.
For example:
• A references version 01.00.01 of Functional Block C
• B references version 01.00.02 of Functional Block C
Reference Manager will load version 01.00.02 as this should not cause compatibility issues.
If they differ by major version an error is returned and the operation will not be possible.

2.3.1.3.3 Restoring the Files of a Functional Block from an Extension App


If you need to replace the files of the same version of a previously referenced Functional Blocks you can restore your
reference.
This may be necessary if:
• you have accidentally deleted some of the files, or
• if your solution configuration is under source control, and another user has created a reference to which you
must align your solution, or
• if you are creating a new machine.
The Restore operation simply unzips the folder of the referenced Functional Block in the local folder without adding
references (e.g. .um, .dll files) and can be performed whether you are working in a Patch, Minor or Major version.
This procedure can also be performed automatically.

Prerequisites
The output zip file of the Functional Block you want to reference, created during the Functional Block generation,
must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

Procedure
1. Copy the new .zip file of the modified Functional Block in folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.
2. Double-click the packages.reference file in the Solution Items folder of the Solution Explorer.
3. Click Restore packages. If the zips of the referenced Functional Blocks have been saved in the correct folder the
referenced Functional Blocks will be installed on the user's machine, otherwise an error message will be
displayed.

690 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

2.3.1.4 Loading Base App changes from an Extension App


The Extension App can reference only a Base App and this reference is automatically created during the generation
of the Extension App.
If you change the Base App and you want view these changes in the Extension App, you must do one of the
following:
• Restoring a Base App from an Extension App
• Updating a Base App from an Extension App

2.3.1.4.1 Restoring a Base App from an Extension App


If you need to replace the files of the same version of the referenced Base App you can restore your reference.
This may be necessary if:
• you have accidentally deleted some of the files, or
• if your solution configuration is under source control, and another user has created a reference to which you
must align your solution, or
• if you are creating a new machine.
The Restore operation simply unzips the folder of the referenced Apps and Functional Blocks in the local folder
without adding references (e.g. .um, .dll files) and can be performed whether you are working in a Patch, Minor or
Major version.

Prerequisites
The output zip file of the App you want to reference, created during the App generation, must be saved in the
folder %ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\Projects and the zip files of any
referenced Functional Blocks must be saved in the folder %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

Procedure
1. Double-click the packages.reference file in the Solution Items folder of the Solution Explorer.
2. Click Restore packages. If the zips of the referenced base App and Functional Blocks have been saved in the
correct folder they will be installed on the user's machine, otherwise an error message will be displayed.

2.3.1.4.2 Updating a Base App from an Extension App


The Base App you can update depends on the version of Extension App you are working on:
• Patch version - you can update your Extension App to a new Patch version. For example, if you referenced
version 01.00.00. of Base App x, and 01.00.01 is available in Reference manager you can update the reference.
You could not update to version 01.01.00 as this would imply a new minor version.
• Minor version - you can update your Extension App to a new Patch or Minor version. For example, if you
referenced version 01.00.00. of Base App x, and 01.01.00 is available in Reference manager you can update the
reference. You could not update to version 02.00.00 as this would imply a new major version.
• Major version - you can update all references to any version. Bear in mind that Major versions could contain
cancellations in the Public Object Model of the Base App, which would lead to incompatibilities within the
Extension App, which will then require manual alignment in Project Studio.

Prerequisites
The output zip file of the App you want to reference, created during the App generation, must be saved in the
folder %ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\Projects and the zip files of any

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 691


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

referenced Functional Blocks must be saved in the folder %ProgramData%


\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks.

Procedure
1. In the Solution Explorer pane, double-click the packages.reference file in the Solution Items folder.
2. Click on the Installed tab and select the App you want to update.
3. Select the required version from the Version drop down list and click Update.
• Any Functional Blocks referenced by the App will be automatically installed if their .zip files are available in the
folder, otherwise you will receive an error message.
• The version of the Base App in an extended Model-driven UI module gets updated automatically for an
extension app.

2.3.2 How to Extend the POM of an Extension App


Once you have created the Extension App and added any additional references, you can extend the Public Object
Model (POM).
The POM can be extended by importing additional artifacts from the referenced Base App or Functional Blocks,
such as entities or commands. However, whilst you can import new artifacts you cannot remove any of the artifacts
belonging to the Base App.
It is also possible to import new views from the Opcenter EX FN repository.

Naming Conventions
The name of any artifact imported in the POM is automatically composed by the short name of the Extension
App and the artifact name separated by underscore (_).
Note that the Extension App prefix cannot be removed.
Example: (<ExtAppShortName>_<ArtifactName>).

Possible operations
The following procedures refer to standard App operations, as they are identical to those required to extend the
POM of the Extension App:
• Import new entities to the Public Object Model (entities from the newly referenced Functional Blocks or from
the Base App)
• Import commands to the Public Object Model
• Import views from the Opcenter EX FN repository to the Public Object Model
• Promoting new Signals from referenced entities or business events
• Creating new subscriptions on referenced events (events that are either referenced from Functional Blocks or
Base App). Existing subscriptions cannot be modified.
• Modeling Post-Actions for Composite Commands (both Referenced and not Referenced, as described for the
Functional Blocks).

692 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

 Working with Signals in Extension Apps


As for all referenced artifacts, you cannot modify referenced Signals.
If you create a Signal for a referenced artifact in the Extension App and then you create another Signal for
the same artifact in the Base App, after you restore or update the referenced packages you will see two
Signals on the same referenced artifact. The referenced Signal will be identified by a lock icon and cannot
be modified or deleted, while the Signal created in the Extension App can still be modified or deleted.
Both Signals can be configured and used in the Signal App and they will use the same source artifact.

 You can also deprecate artifacts. Note that artifacts deprecated in the Functional Block are automatically
set as deprecated in the referenced App as well, where they are displayed as read-only.

2.3.3 How to Create new Artifacts and Business Logic in an Extension


App
In the Extension App you can create new artifacts in the Public Object Model, and you can then implement the
related business logic in the same way as you did in the Base App. Post-Actions and Pre-Checks can be created in
the same way as in the Functional Blocks.
Here you can find an overview of the available operations.

Naming Conventions
The name of any created artifact is automatically composed by the short name of the Extension App and the
artifact name separated by underscore (_).
Note that the Extension App prefix cannot be removed.
Example: (<ExtAppShortName>_<ArtifactName>).

Working in the Public Object Model


• Creating new Types (Parameter Types and Enumeration Types)
• Creating new Composite Commands
• Modeling Pre-Checks for referenced Composite Commands (as described for the Functional Blocks).
• Modeling Post-Actions for Composite Commands (both Referenced and not Referenced, as described for the
Functional Blocks).
• Creating new Reading Functions
• Defining and developing custom Event Handlers
• Creating new Roles
• Creating new Event subscriptions

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 693


How to Develop a Manufacturing Solution in Project Studio

How to Develop an Extension App

 Copying artifacts
You can copy the following artifacts: Parameter Types, Enumeration Types, Public Commands, Composite
Commands, Reading Functions and Roles. If you copy a Public Command, the artifact you actually create
is a Composite Command, because the only commands that you can create inside Apps and Extension
Apps are Composite Commands.

Implementing Business Logic


• Implementing the code of Composite Commands
• Implementing the code of Reading Functions
• Implementing the code of Pre-Checks
• Implementing the code of Post-Actions
• Implementing remote calls

2.3.4 How to Extend User Interfaces in an Extension App


With the Model-Driven UI Module Editor, UI Modules can be easily created starting from the reading model of an App
or an Extension App.
Once implemented, Model-Driven UI Modules provided by the Base App can be extended either by copying them in
an Extension App in Project Studio as described below or by following Extending a Model-Driven UI Module from a
Base App.

 If you have configured Model-Driven UI screen actions by using a custom Blueprint in order to have a
custom side panel with your own input form for your action, pay attention that all files required for a
correct action functioning (controller, template file and any related file) will not be copied in the Extension
App. For this reason, you need to copy these files in your extended UI manually, in order for the custom
panel to work correctly.

Prerequisites
• You have previously created a Model-Driven UI Module in Project Studio. As result, the wizard has created
a .mdui extension file containing the project information, such as the module name, the module title, the icon
and so on (<Prefix>.<AppName>.<ModuleName>.mdui file).
• You have created the .json resource files required to localize the UI Applications according to the suggested
naming convention.

Copying a Model-Driven UI Module from a Base App to an Extension App


1. In the Solution Explorer pane, expand the User Interface project of the Extension App.
2. Right-click the <Prefix>.<AppName>/modules folder and click Create MDUI Module from Base App. A dialog
box is displayed showing the list of the available Model-Driven UI Modules provided by the Base App.
3. Select the Model-Driven UI Module to be extended (<Prefix>.<AppName>.<ModuleName>). You can select one
Module at a time.
4. Enter the new name of the Model-Driven UI Module, according to the following constraints:
• The name must begin with a letter.
• The length of the name must be between 3 and 255 characters long.
• The name can contain letters, numbers and the underscore character (_).
If the constraints are satisfied, then the system validates the new name.
5. Click OK.

694 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

 Resource files' management


When copying the selected Model-Driven UI Module from the Base App to the Extension App, the system
also copies the .json resource files required to localize the UI Applications, replacing the information on
the Base App with that about the Extension App (both the file name and the information within the files).

Extending a Model-Driven UI Module from a Base App to an Extension App


1. In the Solution Explorer pane, expand the User Interface project of the Extension App.
2. Right-click the <Prefix>.<AppName>/modules folder and click Extend MDUI Module from Base App. A dialog
box is displayed showing the list of the available Model-Driven UI Modules provided by the Base App.
3. Select the Model-Driven UI Module to be extended (<Prefix>.<AppName>.<ModuleName>). You can select one
Module at a time.
4. The file will be created as <Prefix>.<AppName>.<ModuleName> by the system and cannot be modified.
5. Click OK.

 For any operations on the Model-Driven UI Module, refer to chapter How to Create a Model-Driven UI
Module.

2.3.5 How to Generate an Extension App Package


Extension Apps cannot be extended (and consequently they do not have the Can Be Extended option in
the Installer project settings).
After you build the Extension App solution (as for the Base App Package), the output zip containing the Extension
App files is deployed in %ProgramData%\Siemens\Engineering\Packages\ExtendedProject.

 To make your changes effective at runtime, add the Extension App to your solution, associate the new UI
modules and deploy the solution.

2.4 How to Manage Projects under Source Control


Opcenter Execution Foundation supports the following source control systems in order to manage Project Studio
solutions:
• TFS
• Git
• Subversion

Supported operations
The following operations can be performed for Project Studio files:
• Create an automated build process
• Merge modifications
• Configure the .gitignore file

 We recommend that you version in a source control system only the files which are displayed in the
solution (i.e. you should not add hidden files under the model project or the SimaticITPackages folder).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 695


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

2.4.1 Creating an Automatic Build Process for Project Studio Files


When two or more people work simultaneously on the same model, these differences will need to be merged into
your model.
Project Studio generate a .ul file for each category of artifact (e.g. entities, commands, events, etc), which contains
all required information on that category.
These files can then be versioned and merged in a source control system.

Prerequisites
• The source control system is correctly configured to manage the required projects.
• Opcenter Execution Foundation has been installed.
• The build order of the projects within each Opcenter Execution Foundation solution (i.e. Functional Blocks and
Apps) has been set (see Defining the Build Order of a Functional Block and Defining the Build Order of an App);
• Functional Block references have been automatically updated for each compiled solution
• The Copy To Engineering Target Folder option has been selected in the Build Options properties of the
installer project to avoid needing to manually copy the output zip file, which is placed in the local output folder
of the Installer project, to the Engineering target folder.

Process
1. Set the solutions under source control and check-in all the solution files.
2. Create a build definition by setting the following:
• multiple solution management;
• the build order of the solutions according to the solution dependencies;
• a distinct output folder for each solution;

Detailed procedure for TFS


1. Put all Functional Blocks and Apps under source control on TFS.
2. Check-in all the solution files, with the exception of the UI files in the Common folder.
3. Create a .proj XML file, which defines the build order of the solution, with the following characteristics:
- each Functional Block/App must be inserted a solution node, in the order in which they will be built, starting
with the Functional Block with no dependencies, followed by the Functional Block that references it, and
building in dependency complexity up to the App.
- a separate output folder (OutDir) must be defined for each node so separate zips are created for each solution.

696 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

<ItemGroup>
<Solution Include="$(SourcePath)FB1\FB1.sln">
<Properties>
Configuration=$(Configuration);
Platform=Any CPU;
OutDir=$(OutDir)\FB1
</Properties>
</Solution>
<Solution Include="$(SourcePath)FB2\FB2.sln">
<Properties>
Configuration=$(Configuration);
Platform=Any CPU;
OutDir=$(OutDir)\FB2
</Properties>
</Solution>
<Solution Include="$(SourcePath)FBApp1\FBApp1.sln">
<Properties>
Configuration=$(Configuration);
Platform=Any CPU;
OutDir=$(OutDir)\FBApp1
</Properties>
</Solution>
</ItemGroup>

4. Add a build node to the .proj XML file, which specifies the order to be used when building, as follows:

<Target Name="Build">
<MSBuild Targets="Build"
Projects="@(Solution)"
StopOnFirstFailure="true" />
</Target>

5. In Visual Studio, in the Builds tab, click New Build Definition.


6. Enter a name for the build definition and configure any required variables.
7. In the tab Process > Required click the browse button and select the .proj XML file you created.

2.4.2 Importing and Merging a Project Studio Model


When more than one person is working on the same model it may be useful to be able to import the modifications
performed by others and merge these differences into your model.
In this way two or more people can work simultaneously on the same model, although in some specific cases you
must necessarily check-out files in exclusive mode.
Project Studio provides a UL file in the Model folder for each category of artifact, for example entities, commands,
events, reading functions and so on, which contains all required information on that category.
These UL files can be versioned in a source control system and can be merged.
During the model merge operation, some errors might occur and manual changes to the files might be required, as
described in the following sections.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 697


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

 DM files, where graphical representations of the model are saved, can be saved and versioned in source
control systems, but cannot be merged.

Aligning UL files in Project Studio


Whenever you make a change to your model in Project Studio, the model document will be marked as "modified"
and "unsaved" (by means of a "dirty" indicator asterisk * in the project name), indicating that the UL are not saved.
You must save your model to align these files. Unaligned UL files are updated also when you close or build your
model.
Every time you click Save the UL files are updated, whether there is an asterisk or not.

 UL files cannot be opened in Project Studio and should not in any case be used as a shortcut to make
modifications to the model for the following reasons:
• The major/minor/patch version compliancy checks in Project Studio cannot be applied to the manual
modification of UL files.
• Manual modifications can also result in data loss due to misalignment.

Checking-in the model project

698 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

When you check-in your changes in your source control system, if there is a merge conflict because there is a more
recent version of your UL files, you must follow this procedure:
1. Close your model in Project Studio.
2. In your source control system launch the Get Latest Version command. This is particularly important to
perform before checking in if you are using a gated check-in rule, which includes a build action.
3. Manually resolve conflicts in the UL files if they are not managed automatically by the source control system.
4. (Optional) In Project Studio, double click the dm model project file in the Model Explorer: the new changes will
be automatically applied.
5. Check-in all your UL files in your source control system.

 Troubleshooting notes
If import errors occur, a message will inform you and the error details will be displayed in the Visual Studio
output window. Make the appropriate modifications to your model in Project Studio wherever possible,
for example by removing the property of an entity that has been deleted.
Only if it is not possible to directly solve the errors in Project Studio, you can modify the UL files in Visual
Studio (as long as the Functional Block is closed), or in another instance of Visual Studio or with any text
editor program. Use the error details displayed in the Visual Studio output window as guidelines. Although
the Open, Open with, View code and Run custom tool commands are enabled in Project Studio, they
cannot be used because UL files must not be edited in this work environment to avoid inconsistencies.
Should an error concerning a Mandatory attribute appear (such as Model has to be aligned from UL files,
alignment operation in progress ... ERROR! [...] Semantic error at (0, 0): invalid usage of token
'[LogicalKey]' (#0). Details: LogicalKey attribute requires that Mandatory attribute is defined at the same
time), manually open the DataModel.ul, browse to the line indicated in the error message and add the
[Mandatory] tag to the wrongly configured property. This error should only occur in cases of migration
from older product versions such as 1.3 Update 3. More recent versions correctly support the functionality
of setting a navigation property to logical key.

Checking out files in exclusive mode


To avoid inconsistencies in the model during merge operations, you should check out in exclusive mode the
following project files in specific situations:

If you are about to... You must check-out the following files:

Create a new version of a Functional Block • All the files in the model project
• The .iproj file in the Installer project
• The .csproj files in the CommandHandler and
EventHandler projects

Add changes to Reference Manager • All the files in the model project
• The .csproj files in the CommandHandler and
(e.g. to add a reference to a Functional Block)
EventHandler projects

 Troubleshooting notes
If you have added changes to Reference Manager checking out the related files not in exclusive mode, a
misalignment between data in the Project.config file and data displayed in Reference Manager can occur.
In this case, we suggest that you resolve it manually, by modifying the Project.config file according to the
information displayed in Reference Manager.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 699


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

2.4.2.1 UL File Examples


UL files are written in a specific Manufacturing Modeling Language, which is an internal proprietary language
used by Project Studio to generate the assemblies corresponding to the model projects.
These UL files must not be manually modified unless you have to solve conflicts during merge operations.
The model project of each Functional Block or App contains the following UL files:
• DataModel
• Command
• Event
• Security
• Type
• Alias
• ReadingFunction (only in the App)

 Each file must contain the version number only once.

An additional file is present in the model project and contains the project properties (name, domain, version etc...).
The file must not be manually modified unless you have to merge conflicts. The file structure must respect the
following format:

<DSL Version='1.7'>
<Project>
<Name>FBApp1.FRPOMModel</Name>
<Version>01.00.00</Version>
<Prefix>Myprefix</Prefix>
<Domain>FBApp1</Domain>
<Guid>9b1c0689-4d4c-4640-b4e9-cc078dfa4ef2</Guid>
<ProjectKind>Pom</ProjectKind>
</Project>
<References>
<Project>
<Name>FBLibrary2.MSModel</Name>
<Version>01.00.00</Version>
<Prefix>bbb</Prefix>
<Domain>MasterData</Domain>
<Guid>25c49d93-fcc2-41a0-9dd6-7d7656b18917</Guid>
</Project>
</References>
</DSL>

2.4.2.1.1 DataModel File Examples


DataModel example of a Functional Block
This example contains the following elements:
• a standard base entity
• a derived entity
• an entity with relationships
• a facet

700 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

• an index on entity
Each entity contains comments, annotations, properties with annotations.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 701


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

///sec = true
///modified
[Sealed]
[@Guid(714d2ba9-b17b-47ea-a7a6-64d4067d5766)]
[@GuidId(4786f70a-ab79-4f9a-b718-ac16c5624eec)]
[#tag entity]
[#securable]
[Securable]
ENTITY ent_1_sec
WITH
[Length = 255]
[@Guid(c13af04a-f3e5-405e-8f0b-daf90ef8f498)]
ent_1_sec_NewProperty AS string
[Length = 255]
[@Guid(7bc892c0-bc54-4d26-8935-22372e7e5296)]
ent_1_sec_NewProperty1 AS string
[Length = 255]
[@Guid(f2175b7a-ad69-4466-8f0d-00ae34a97752)]
ent_1_sec_NewProperty2 AS string

///sec = False
[@Guid(accc5235-1c1b-49aa-af17-56b425706bc3)]
[@GuidId(cb5418f3-c6de-4017-b6c6-88952a502af6)]
[#tag entity]
[#no securable]
ENTITY ent_1_NoSec
WITH
[Length = 255]
[@Guid(16cefb18-a5cc-49a6-bae7-b14555c16d57)]
ent_1_NoSec_NewProperty AS string
[Length = 255]
[@Guid(63fa8265-51b2-4576-a7ef-0680545eb80b)]
ent_1_NoSec_NewProperty1 AS string

[@Guid(f8b50fca-1143-4c75-ac2c-db76b55d551f)]
INDEX CLUSTERED ON ent_1_NoSec
[@Guid(2c8858dc-e9af-4db6-abae-7360f4d4770d)]
ent_1_NoSec_NewProperty

[@Guid(718b7fc5-6665-46b9-9672-ecd7a4426984)]
[@GuidId(69e7c4fc-e942-47b4-8901-e95bb0af3f5b)]
[#tag entity]
[#no securable]
ENTITY ent_1_NoSec_1 EXTENDS ent_1_NoSec
WITH
[Length = 255]
[@Guid(6d5bd334-6eae-401d-8295-8b26bcca1270)]
ent_1_NoSec_1_NewProperty AS string
[Length = 255]
[@Guid(8b93941e-b01b-4144-ad96-7f249099a30c)]
ent_1_NoSec_1_NewProperty1 AS string

702 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

///modified
[@Guid(83634c94-edf6-472a-acb3-78e92de29132)]
[@GuidId(9bd77402-5431-4eb2-a67a-e7a0a9885087)]
[#tag entity]
[Securable]
ENTITY ent_sealed_sec
WITH
[Length = 255]
[@Guid(f165a75f-e46c-498c-9a10-871f7553cc9f)]
ent_sealed_sec_NewProperty AS string
[Length = 255]
[@Guid(c043d2a7-1b53-4bf5-bd69-96274ec22975)]
ent_sealed_sec_NewProperty1 AS string

[@Guid(2b116c10-dbfe-46a2-bc4e-b8b0224d8bea)]
[@GuidId(44e63cb5-5657-46b5-aed3-724ccc964907)]
FACET ent_seal_fac1 EXTENDS ent_sealed_sec
WITH
[Length = 255]
[@Guid(2a56a8cf-0246-4823-8a16-a6268580d978)]
ent_seal_fac1_NewProperty AS string

DataModel example of an App


This file contains:
• the list of the entities imported by Opcenter EX FN database views, identified by the ENTITY keyword and the
name of the view
• the list of the imported entities, identified by the namespace and the linked entity

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 703


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

VERSION '01.07'
[Sealed]
[Securable]
[@Guid(afe67022-5a54-45ec-b194-51cda63146c8)]
[@GuidId(e0868d1f-b1d3-4b09-a6e0-dd8f1aa7ffbc)]
ENTITY vw_MOM_SHCVUN_BREAK
WITH
[Mandatory]
[@Guid(e0868d1f-b1d3-4b09-a6e0-dd8f1aa7ffbc)]
id AS int
[Mandatory]
[@Guid(ebff8cd2-c9ee-4933-a367-f71d18995701)]
myGuid AS Guid
[Mandatory]
[@Guid(52832268-16a5-466f-8d25-c7691dda17db)]
bias AS smallint
[Mandatory]
[@Guid(0be75205-6c8a-4257-aaf7-52ee0319f565)]
break_end_bias AS smallint
[Mandatory]
[@Guid(1701c5c4-4373-4e51-850b-511f0480f103)]
break_start_bias AS smallint
[Mandatory]
[Length = 50]
[@Guid(a56dfe9e-1c78-455f-98a8-612a16663daa)]
label AS string
[Mandatory]
[@Guid(c5645585-fa65-4292-ab81-c1feb54241a0)]
colour AS int
[Mandatory]
[Length = 50]
[@Guid(4b2b7fac-65b8-4111-8954-dfcb54d03e11)]
last_user AS string
[Mandatory]
[Length = 1]
[@Guid(a49fbb7a-a296-4222-b27d-5c739dbbd948)]
type AS string
[@Guid(c4f5eafe-a8f7-4580-92d2-b3129cd94433)]
myTinyint AS tinyint
[Mandatory]
[@Guid(a8921947-b0a2-4a0b-9cb8-9f1bf37ce721)]
myGuid_1 AS Guid
[Mandatory]
[@Guid(901a19af-8540-4ce4-a4e6-e4cfdbcd3d8d)]
myGuid_2 AS Guid

///description
[@Guid(fcb6f1bd-fcae-4883-8b9b-2f39594c25d5)]
ENTITYLINK e1 TO aaaaa.AppTerzePa.AppTerzePa.AAPOMModel.DataModel.e1
[@Guid(24c42161-5cdb-42f9-8290-ba26d8c45d5e)]
ENTITYLINK Ent1 TO bbb.MasterData.FBLibrary2.MSModel.DataModel.Ent1

704 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

[@Guid(e0de9e0f-0324-4ceb-8382-b10c7eab1f2b)]
ENTITYLINK Ent2 TO bbb.MasterData.FBLibrary2.MSModel.DataModel.Ent2

2.4.2.1.2 Command File Examples


Command example of a Functional Block
This file contains:
• a command with a set of annotations (e.g. protected, private, securable)
• a command with an input parameter defined as a Parameter Type and an output parameter of property
reference type.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 705


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

VERSION '01.07'
///securable = true
///protected
[Protected]
[@Guid(31946744-9b74-4634-94b7-6aec4f9be091)]
COMMAND cmd_1_sec
WITH
[Length = 255]
cmd_1_sec_NewParameter AS string
RESPONSE
[Optional]
[Length = 255]
cmd_1_sec_NewParameter AS string

///securable = false
///protected
[Protected]
[NotSecurable]
[@Guid(cec060b6-a444-4fef-baa6-94a26770b79d)]
COMMAND cmd_1_noSec
WITH
[Length = 255]
cmd_1_noSec_NewParameter AS string
RESPONSE
[Optional]
[Length = 255]
cmd_1_noSec_NewParameter AS string

///private
[Private]
[@Guid(4c726a82-ef3b-43c6-8516-71d78fe47f7d)]
[NotSecurable]
[@Guid(d4777a0c-3cc6-48c8-857b-68078bd4917c)]
COMMAND C3Priv
WITH
[Length = 255]
C3Priv_NewParameter AS string

///Protected and Securable


[Protected]
[@Guid(6bbfd66e-abfd-4420-8124-9b10d72c7ef4)]
COMMAND C1
WITH
[Length = 255]
C1_NewParameter AS string
C1_NewParameter1 AS int
RESPONSE
[Optional]
C1_NewParameter AS Guid

[Protected]

706 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

[@Guid(28ec8c92-f0e7-4f8c-99d1-fc11f17ede44)]
COMMAND C2
WITH
C2_NewParameter AS aaaaaa.MasterData.FbTest2.MSModel.Types.Pt2
RESPONSE
[Optional]
[Length = 255]
C2_NewParameter AS aaaaaa.MasterData.FbLibTest.MSModel.DataModel.Ent01.PropA

Command example of an App


This file only contains the Composite Commands, identified by the Composite annotation.

VERSION '01.07'
[Composite]
[Protected]
[@Guid(82526211-a95c-42cf-889a-6940d5e53d37)]
COMMAND Composite1
WITH
[Length = 255]
Name AS string
Height AS int
RESPONSE
[Optional]
C1_NewParameter AS Guid

2.4.2.1.3 Event File Examples


Event example of a Functional Block
This example contains:
• an event without parameters
• an event with parameters
• an event with parameters, where the first parameter is a property reference while the second is a Parameter
Type, with the annotations for properties and descriptions
The file also contains the list of the Event Handlers associated with each event (which might also be a referenced
event).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 707


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

VERSION '01.07'
[@Guid(a3afe955-9ce6-4483-b241-5d63037d8b08)]
EVENT evt_1_sec

[NotSecurable]
[@Guid(b43d5632-1903-4e7f-ba99-ae43fae873c8)]
EVENT Evt1
WITH
[Length = 255]
Evt1_NewParameter AS string
Evt1_NewParameter1 AS Guid
Evt1_NewParameter2 AS DateTime
[@Guid(7b531a08-ed74-4175-afe1-b0ba1b1c18b9)]
EVENT Evt2
WITH
[Length = 255]
Evt2_PropRef AS Myprefix.MasterData.FbLibTest.MSModel.DataModel.Ent01.PropA
Evt2_ParamType AS Myprefix.MasterData.FbTest2.MSModel.Types.Pt2

[@Guid(63a38930-b938-48a9-9ec9-81ce65e09bf8)]
EVENTHANDLER EvtHandler1 LINKED TO Myprefix.MasterData.FbTest2.MSModel.Events.Evt2

[@Guid(50467d47-0c34-464d-95c2-7ca7c1ca0c2c)]
EVENTHANDLER Evthandler2 LINKED TO Myprefix.MasterData.FbTest2.MSModel.Events.Evt2

[@Guid(aef3b15d-46fb-42c0-9ca2-e0868d01b66f)]
EVENTHANDLER Evthandler1 LINKED TO Myprefix.MasterData.FbTest2.MSModel.Events.Evt1

Event example of an App


This file contains:
• the Event Handlers defined within the App for the referenced events
• the list of the signals published for each referenced event

VERSION '01.07'
[@Guid(e0d3923b-ca07-4349-8c35-76dcd7c096fa)]
EVENTHANDLER MyHandler LINKED TO Myprefix.MasterData.FbTest2.MSModel.Events.EvtNoSec
[@Guid(e46251a8-dbb7-4645-9357-dedd01056e2b)]
SIGNAL SignalEnt2 ON Myprefix.FBApp1.FBApp1.FRPOMModel.DataModel.Ent2

[@Guid(92812d86-ac01-48a6-9915-dfa6da786fac)]
SIGNAL SignalEnt1 ON Myprefix.FBApp1.FBApp1.FRPOMModel.DataModel.Ent1

2.4.2.1.4 Security File Examples


Security example of an App
This file contains the list of the roles, and for each role, the list of the associated artifacts and permitted actions.

708 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

VERSION '01.07'
[@Guid(667ac4f5-2975-4b2e-b3c6-7bd2307581e7)]
USERROLE UR
GRANT
[@Guid(24c42161-5cdb-42f9-8290-ba26d8c45d5e)]
Myprefix.FBApp1.FBApp1.FRPOMModel.DataModel.Ent1 AS Read
[@Guid(e0de9e0f-0324-4ceb-8382-b10c7eab1f2b)]
Myprefix.FBApp1.FBApp1.FRPOMModel.DataModel.Ent2 AS Read

[@Guid(05449674-d48b-4b0b-87b3-5e0639b37928)]
USERROLE UR2
GRANT
[@Guid(e46251a8-dbb7-4645-9357-dedd01056e2b)]
Myprefix.FBApp1.FBApp1.FRPOMModel.Events.Signals.SignalEnt2 AS Subscribe
[@Guid(92812d86-ac01-48a6-9915-dfa6da786fac)]
Myprefix.FBApp1.FBApp1.FRPOMModel.Events.Signals.SignalEnt1 AS Subscribe
[@Guid(24c42161-5cdb-42f9-8290-ba26d8c45d5e)]
Myprefix.FBApp1.FBApp1.FRPOMModel.DataModel.Ent1 AS Read

2.4.2.1.5 Type File Examples


Type file example of a Functional Block
This example contains:
• a Type Alias
• a Value Type containing a property of property reference type
• a Parameter Type containing another Parameter Type
• an Enumeration Type

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 709


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

VERSION '01.07'
[Length = 255]
[@Guid(8b5f4cf3-e68c-46f1-b347-af0529a4bee8)]
[#tag type]
TYPE ta1 AS string

[@Guid(ccac6430-4345-4e4c-ae31-12d150917611)]
VALUETYPE VTWithPropRef
WITH
[Length = 255]
[Reference]
[@Guid(1488c6fa-5537-4bcb-a05e-f866c341b4fd)]
VTWithPropRef_NewProperty AS
Myprefix.MasterData.FbLibTest.MSModel.DataModel.Ent01.PropA

[@Guid(f841c0ed-68ac-41ca-a51c-a563a3c75b0d)]
[#tag type]
PARAMETERTYPE pt1
WITH
[Length = 255]
[@Guid(01d9becf-9f51-4d47-871b-2751db686fa9)]
pt1_NewProperty AS string
[Length = 255]
[@Guid(7d7164ad-d4e3-4203-b794-bd888ed9c94b)]
pt1_NewProperty1 AS string
[Length = 255]
[@Guid(d479a087-d326-49fc-86df-d23a33a695a7)]
pt1_NewProperty2 AS string
[@Guid(a0fc3486-8eaa-41aa-a600-cc9f9d223ba0)]
PARAMETERTYPE Pt
WITH
[Length = 255]
[@Guid(22a17a7a-a3d5-4d3d-828f-41b5059929ac)]
Pt_NewProperty AS Myprefix.MasterData.FbLibTest.MSModel.DataModel.Ent01.PropA
[@Guid(ef4fe891-18bb-4e4e-9feb-183a8532f78f)]
Pt_NewProperty1 AS bool
[Optional]
[@Guid(721361e3-8d44-4395-82e5-da732503c6ef)]
Pt_NewProperty2 AS Myprefix.MasterData.FbTest2.MSModel.Types.pt1
[@Guid(57687c46-0483-4176-9209-510ce93511d1)]
[#tag type]
ENUM Colors
WITH
[@Guid(406375df-bc26-45df-866f-1118a80139b5)]
Blue AS 1
[@Guid(52a37281-ecf7-469d-b4da-c81bd6329c93)]
Red AS 2
[@Guid(c5bf4e3d-fc2d-46ce-900d-ce2ec9bd1963)]
Yellow AS 3

710 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

Type file example of an App


This file can only contain Parameter types and Enumeration types.

[@Guid(a0fc3486-8eaa-41aa-a600-ce9f9d223ba0)]
PARAMETERTYPE PtApp
WITH
[@Guid(ef4fe891-18bb-4e4e-9feb-182a8532f78f)]
Pt_NewProperty1 AS bool

[@Guid(57687c46-0483-4176-9209-410ce93511d1)]
[#tag type]
ENUM Enum1
WITH
[@Guid(406375df-bc26-45df-866f-0118a80139b5)]
Prop1 AS 1
[@Guid(52a37281-ecf7-469d-b4da-f81bd6329c93)]
Prop2 AS 2
[@Guid(c5bf4e3d-fc2d-46ce-900d-ee2ec9bd1963)]
Prop3 AS 3

2.4.2.1.6 Alias File Examples


Alias example of an App
This file contains the list of the public commands.

VERSION '01.07'

PUBLISH COMMAND Myprefix.MasterData.FBLibrary2.MSModel.Commands.Command1 AS Command1

PUBLISH COMMAND Myprefix.MasterData.FBLibrary2.MSModel.Commands.Command2 AS Command2

2.4.2.1.7 ReadingFunction File Examples


ReadingFunction example of an App
This file contains the Reading Functions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 711


How to Develop a Manufacturing Solution in Project Studio

How to Manage Projects under Source Control

VERSION '01.10'
[@Guid(82123211-a95c-42cf-143a-6940d5e53d37)]
READING FUNCTION MyReadingFunction
INPUT
[Length = 255]
LotId AS string
Quantity AS int
OUTPUT
[Mandatory]
RowCount AS int

2.4.3 Configuring the .gitignore File


When you use Git as source control system you create files and code that must be excluded to correctly use Project
Studio. The .gitignore file allows you to set which files will be excluded in order to:
• improve performance
• correctly perform Reference Manager operations
• avoid merge conflicts on Model Project

Prerequisites
• Opcenter Execution Foundation has been installed.
• The .gitignore file is installed in Team Explorer. If not, follow the procedure described in: https://
docs.microsoft.com/en-us/azure/devops/repos/git/ignore-files?view=azure-devops&tabs=visual-studio.

Procedure
1. In Team Explorer, edit the .gitignore file located in the Ignore & Attributes Files section.
2. Add the section below at the end of the file to exclude the unnecessary files:

# OpCenter EX Foundation
**/SimaticITPackages/*
**/*UserInterface/common/*
*.um
*.umd

712 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Projects under Source Control

3 How to Manage a Manufacturing Solution in Solution Studio


Solution Studio is a full web configuration client from which any authorized user can manage Apps, and Extension
Apps, developed in Project Studio, in order to configure the Manufacturing Solution and deploy it on a target
scenario.
If translated resources are available, you can display Solution Studio in the required language as described in How
to Use Opcenter Execution Foundation in Multilanguage.

Solution management workflow


To create and configure the Solution, go through the following main steps:
1. Create a Manufacturing Solution.
2. Add Apps.
3. Configure Apps (commands and event subscriptions).
4. Configure accounts (roles and associated users/groups).
5. Configure user interfaces (Mashups and UI Applications).
6. Configure maintenance (if required).
7. Configure deployment settings (data sources and worker roles).
8. Deploy the Manufacturing Solution.

Available Operations
The Solution Studio home page contains cards and icons which allow you to perform the following operations:

Card Description

Create Solution Allows you to create a new solution or open the currently indicated solution and perform
all the required configurations.
If the solution is already created, the solution name will be displayed as card title.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 713


How to Manage a Manufacturing Solution in Solution Studio

How to Access Solution Studio

Card Description

Create Solution Allows you to create a solution from an existing backup file.
from Backup

Documentation Allows you to access all official documentation and custom reference
Center documentation (Documentation Center).

Host Allows you to deploy a solution package on the environment hosts (Host Management)
Management and monitor the environment host status.

Icon Title Description

About Allows you to view the current Opcenter Execution Foundation version.

Help Allows you to open the context-sensitive help.

Settings Allows you to customize the Solution Studio Settings.

Avatar Icon Allows you to change the view of the Solution Studio.
• Sign out option to sign out the current signed in user from Opcenter Execution
Foundation.
• Settings
• Full Screen Mode option to view the Solution Studio in full screen.
• Command Labels option to display the name of the command icons in
Solution Studio.

(n/a) Allows you to move back to the previous screen.

User session expiration


The user session is active as long as you are performing operations in Solution Studio pages, and the login is not
required.
If you do not perform any operations for approximately 30 minutes (which corresponds to the default session
duration in the User Management Component), at the end of this time range a message is displayed warning you
that the session is about to expire. If you do not actively acknowledge this message the session could expire and
you may be redirected to the interactive login page.

3.1 How to Access Solution Studio


You access Solution Studio home page as shown below.

Procedure

714 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Authenticate in Solution Studio

1. Do either of following to open Solution Studio:


• if you are directly on the Engineering host, from the Start menu go to Opcenter Execution
Foundation category and choose the Solution Studio link.
• if you are on a client workstation or on a Runtime host, manually compose the Solution Studio URL as
follows: https://<HostName>/sit-ui/system/studio/index.html where HostName represents the FQDN
of either the ARR server name or the Engineering host name in a distributed scenario.
2. Log-in with the proper credentials (user name and password).

 To correctly connect from the web clients to Opcenter EX FN hosts check that you have correctly executed
the following procedures:
• Configuring Microsoft ARR Load Balancer in the Opcenter Execution Foundation Installation Guide.
• Configuring the Web Endpoint settings. See one of the following sections in the Opcenter Execution
Foundation Installation Guide, depending on the configured scenario:
• Web Endpoints Parameters
• Web Endpoints Parameters for StandAlone Separate Database
• Web Endpoints Parameters for Distributed Scenario.
Should login problems occur, see also Troubleshooting Login Errors in the Opcenter Execution
Foundation Installation Guide.
Be also aware that some web browser versions need to use an FQDN name or an IP address (i.e. they must
contain a dot character in the URL).

3.2 How to Authenticate in Solution Studio


The user that logs on to Solution Studio must belong to the SIT_UAF_SYSADMIN UMC predefined group.
This group is associated to the Opcenter EX FN SysAdmin engineering role, you defined while configuring the
environment (as described in How to Configure the Environment with the Opcenter Execution Foundation
Configuration Tool of the Opcenter Execution Foundation Installation Manual).
By default, to log on to Solution Studio or to the UI Application, you must enter user and password in an interactive
dialog box.
By means of User Management Component, you can enable different login modes such as for example the
Integrated Windows Authentication (also called Autologin in UMC), PKI and so on.
To properly configure these authentication modes, you must refer to the UMC Web UI User Manual.
If the autologin is enabled, you will be automatically redirected to the required UI page and you will be able to
change the language or log on to the application with another user after you have manually logged out.

3.3 How to Configure Solution Studio Settings


Solution Studio allows you to customize your work environment, such as the log levels and themes. This operation
is performed in the General screen.
In the Advanced screen, you can choose to enable the visualization of Functional Block elements that have not
necessarily been published in the Public Object Model:
• protected commands are displayed in a separate tile in the App Management page, where they can be
associated to worker roles.
• entities are displayed in the Roles page, with their original Functional Block name, where they can be assigned
to roles.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 715


How to Manage a Manufacturing Solution in Solution Studio

How to Create a New Solution

Additionally, you can enable the minification procedure for your UI Application. Minification allows you to compress
the javascript files that are part of your UI Application by minifying them and generating a unique bundled file. This
process helps in improving the performance of the runtime application as multiple resource files are processed as
one file thus saving time and results in fast processing of the application. The minification applies to any UI
Application that is part of the Solution.
The minification procedure takes place during the Build process. If you modify this setting on an already deployed
Solution (and consequently the Minification column value in the Package Management page is not aligned with
the Enable Minification check box in the Advanced screen) you must perform a Force Build procedure to apply the
global configuration.

Customizing the work environment


1. In the Solution Studio home page click on the Settings icon and then select General.
2. Select the required log level.
3. Select the theme you want to apply to Solution Studio pages.
4. Click Save Changes.

Enabling the advanced configuration


1. In the Solution Studio home page click on the Settings icon and then select Advanced.
2. Select the Enable Advanced Configuration check box.
3. Click Save Changes.

Enabling the Minification of the UI Application


1. In the Solution Studio home page click on the Settings icon and then select Advanced.
2. Select the Enable Minification check box to enable minification of the UI Application. The option is selected by
default.
3. Click Save Changes.

3.4 How to Create a New Solution


The solution provides the working environment where Apps and their referenced Functional Blocks can be
added and configured.
A solution is considered valid only if the Apps it contains, and the referenced Functional Blocks, belong to
compatible versions.
If the solution is considered invalid, you will be able to navigate pages in order to check the configuration status,
but you can only execute operations involving App management.
Only one solution can be created at a time.
A solution can be created either from scratch or from a previously created backup file. Backup copies can be
made in order to revert to previous versions or to recreate the solution on a different machine.

Available Operations
In the Solution Studio home page, you can do either of the following:
• Create a solution from scratch
• Create a solution from a previously backed-up solution
If the solution is already created, go to How to Manage the Solution.

716 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Create a New Solution

3.4.1 Creating a Solution from Scratch


You can create a new solution from scratch in Solution Studio if you do not want to use a previously backed-up
solution.

Prerequisites
• Engineering Services are up and running.
• The user that logs in must belong to the SIT_UAF_SYSADMIN UMC predefined group, as described in the
Opcenter Execution Foundation Installation Guide.
• There are no solutions present. Any existing solutions must be deleted in order to create a new one.

Procedure
1. From Solution Studio home page click Create Solution.
2. In the Create Solution pane, insert the name you want to assign to the solution and, if required, a description
with additional information. The description can be modified later.
3. Click Create. The new solution is displayed in the Solution Administration page. You can now add Apps to your
solution by navigating to the App Management page.

3.4.2 How to Create a Solution from a Backup


You can use a backup copy of a previously created solution rather than creating your solution from scratch.
You can use backups created either in the current product version or in earlier product versions, except for 1.2. Bear
in mind that:
• Backups created in SIMATIC IT UAF 1.3 could contain Apps compiled in SIMATIC IT UAF 1.2. Since this use case is
not supported, the restore operation of this backup version will be blocked returning an error message.
• You will not be able to reload Apps that belong to version 1.3 (including all successive 1.3 updates) of SIMATIC IT
UAF backed-up solutions.
• Mashup modules from previous versions will not be included in the backup. They can be restored separately.

Workflow
1. Restore the backup.
2. Only for earlier versions, update the solution apps to the current platform version.

Prerequisites
• There are no solutions currently loaded. If there is one, it must be deleted. If required you can make a backup
copy of the solution.
• If you want to restore the MOM Solution database on a new database machine, restore its backup file as usual
but remember to also configure the database ownership if you are on a SQL Server instance.
• You have saved the backup files of the solution you want to restore in %SITUnifiedSystemData%
\Engineering\Packages\Solutions.
• If the backed-up solution references other Apps/Functional Blocks, copy the App/Functional Block packages
(including the System App and the SITUASys Functional Block, if referenced) to the required destination
folders.
• If you want to be able to further develop code, also copy the project model files (.um, .umd and .dll) from the
ExtensionApps/Apps/Functional Blocks to the required destination folders.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 717


How to Manage a Manufacturing Solution in Solution Studio

How to Create a New Solution

Files Destination folder

App packages %SITUnifiedSystemData%


\Engineering\Packages\Projects

Extension App packages %SITUnifiedSystemData%


\Engineering\Packages\ExtensionProjects

Referenced Functional Block packages %SITUnifiedSystemData%


\Engineering\Packages\FunctionalBlocks

*.um and *.umd %SITUnifiedSystemData%


\Engineering\Dev\ModelSource

*.dll %SITUnifiedSystemData%
\Engineering\Dev\ModelBin

Restoring the solution backup


1. From Solution Studio home page click Create Solution from Backup.
2. In the Create Solution From Backup pane, if required select the following check boxes:
Check box Description

Restore Role Associations to Users/ To maintain the previously defined UMC configurations
Groups concerning associations between roles and users/groups. This
option is useful if you are creating the solution in the same
environment where you created the solution backup file. In this
way you can manage more than one solution in the same
environment. If the package is restored in a different
environment with a different UMC domain (i.e. different from the
one where it was first created) and you select the Restore Role
Associations to Users/Groups option, some user or user group
IDs may correspond to different users/groups. Consequently, to
avoid misalignment, do not select the Restore role associations
to users/groups check box if you want to restore the package in
a different environment.

Restore Database Connection To restore all the previously defined database connections.
Information This option is useful if you are creating the solution in the same
environment where you created the solution backup file. In this
way you can manage more than one solution in the same
environment.
3. Select the backup file you want to restore.
4. Click Create.

Updating the solution apps to the current version


1. In the App Management page,
• Update (with the button) or reload (with the button) the Foundation Apps that are present in
your Solution (e.g. Automation App, Personnel App, Signal App and so on) according to the following

718 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Create a New Solution

behavior: the Apps that require an update are marked with the indicator, while all the other Apps
that do not show this indicator require a reload ( ).
• If you have updated any custom Apps in Project Studio, either reload them ( ) or update them (
) according to the versioning logic you have used (see Creating a New Version of Functional Block or
App and Reloading Apps and Extension Apps in a Solution).
2. If you come from version SIMATIC IT UAF 1.3 Update 4, in the Mashup page you have to open each Mashup
module, check that the wiring page is well formatted and then generate the Mashup.
3. In the UI Applications page, open any UI Applications to verify the following:
• Ensure they do not contain UI Modules that are no longer used in the updated solution. If you find any UI
Modules whose status is deleted, select them and click Unassign deleted modules. If you fail to do this,
the UI Application will be invalid.
• Add/delete the required UI Modules; for example, you can add new UI Modules in order to display any
newly provided screens.
4. Run the scripts for upgraded Apps, if you have Apps that reference the
Siemens.SimanticIT.EQU_MS 05.00.00, Siemens.SimaticIT.EQ_OP 05.00.00, Siemens.SimaticIT.TSK_MS
06.00.00, Siemens.SimaticIT.TSK_OP 08.00.00 and Siemens.SimaticIT.UDM_RF 04.00.00 Functional Blocks.

 When you restore a Solution, you can choose whether to restore or not the configuration of the data
source and the configuration of the roles. If you do not restore this configuration now, remember that you
need to perform these configurations (see database connections and associations between roles and
users/groups) before deploying your Solution in Solution Studio.

3.4.2.1 Restoring SQL Server Databases


In order to correctly restore and access a database coming from another instance of SQL Server, you must ensure
that the new instance is properly configured. Then you must assign the ownership of the restored database to the
user that belongs to the SIT_UNIFIED_MEDIUM_H group. This can be done in the following ways that are described
in this topic:
• automatically, by executing a script on the restored database.
• manually, by using SQL Server Management Studio interface.

Prerequisites
You can restore the Opcenter EX FN database only on an instance that has already been properly configured. See
Moving Databases to a Different Database Instance in the Opcenter Execution Foundation Installation Guide.

Restoring the database backup


Restore the database by following the standard SQL Server procedure.

Applying ownership with script


The following script applies the required ownership to the UnifiedSrv user. Before you run it, set the name to the
correct user.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 719


How to Manage a Manufacturing Solution in Solution Studio

How to Create a New Solution

DECLARE @DbName SYSNAME


DECLARE @MachineName NVARCHAR(50)
DECLARE @machinenamesrv NVARCHAR(50)
DECLARE @mandatoryDomain NVARCHAR(50)
DECLARE @optionalDomain NVARCHAR(50)
DECLARE @sqltoexec NVARCHAR(MAX)
DECLARE @SQL NVARCHAR(MAX)
DECLARE @Domain NVARCHAR(1000)
DECLARE @key NVARCHAR(1000)
SELECT @DbName = DB_NAME()
SELECT @machinenamesrv = CAST (SERVERPROPERTY('MACHINENAME') AS NVARCHAR(50))
SELECT @machinename = CAST (SERVERPROPERTY('ComputerNamePhysicalNetBios') AS
NVARCHAR(50))
IF NOT EXISTS(select 1 from sys.database_principals ss
inner join sys.syslogins logs on ss.sid = logs.sid where logs.name = @machinename +
'\SIT_UNIFIED_MEDIUM_H')
BEGIN
SET @sqltoexec = N'ALTER AUTHORIZATION ON DATABASE::[' + @DbName + '] TO [' +
@machinename + '\UnifiedSrv]'
EXEC sp_executesql @sqltoexec
END
SET @key = 'SYSTEM\ControlSet001\Services\Tcpip\Parameters\'
EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key=@key, @value_name='Domain'
, @value=@Domain OUTPUT

SET @optionalDomain = NULL


IF (@machinenamesrv <> @machinename)
BEGIN
SET @mandatoryDomain = DEFAULT_DOMAIN()
SET @optionalDomain = @machinename
END
ELSE
BEGIN
SET @mandatoryDomain = @machinename
IF @Domain IS NOT NULL SET @optionalDomain = DEFAULT_DOMAIN()
END
SET @SQL =
N'
/* THE USER MUST BE LINKED WITH ITS LOGIN */
IF EXISTS (SELECT 1 FROM dbo.sysusers INNER JOIN master.dbo.syslogins
ON ( (dbo.sysusers.name = master.dbo.syslogins.loginname COLLATE
database_default)
and master.dbo.syslogins.sid <> dbo.sysusers.sid ) WHERE dbo.sysusers.name = N''@
LOGIN'')
BEGIN
ALTER USER [@LOGIN] WITH LOGIN = [@LOGIN], DEFAULT_SCHEMA = [dbo]
END'
BEGIN TRAN
SELECT @sqltoexec = REPLACE(@SQL,'@LOGIN',@mandatoryDomain + '\SIT_UNIFIED_LOW')
EXECUTE(@sqltoexec)
SELECT @sqltoexec = REPLACE(@SQL,'@LOGIN',@mandatoryDomain +
'\SIT_UNIFIED_MEDIUM_L')

720 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage the Solution

EXECUTE(@sqltoexec)
SELECT @sqltoexec = REPLACE(@SQL,'@LOGIN',@mandatoryDomain +
'\SIT_UNIFIED_MEDIUM_H')
EXECUTE(@sqltoexec)
COMMIT TRAN;
BEGIN TRAN
IF @optionalDomain IS NOT NULL
BEGIN TRY
SELECT @sqltoexec = REPLACE(@SQL,'@LOGIN',@optionalDomain + '\SIT_UNIFIED_LOW'
)
EXECUTE(@sqltoexec)
SELECT @sqltoexec = REPLACE(@SQL,'@LOGIN',@optionalDomain +
'\SIT_UNIFIED_MEDIUM_L')
EXECUTE(@sqltoexec)
SELECT @sqltoexec = REPLACE(@SQL,'@LOGIN',@optionalDomain +
'\SIT_UNIFIED_MEDIUM_H')
EXECUTE(@sqltoexec)
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRAN;

Applying ownership manually


1. In SQL Server Management Studio, right-click the restored database and select Properties.
2. In the Database Properties page, click Files and enter the name of the user.

3.5 How to Manage the Solution


Once you have created a solution you can perform operations to customize its data and layout, view its current
configuration status and create solution backups.

Accessing the Solution Administration Page

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 721


How to Manage a Manufacturing Solution in Solution Studio

How to Manage the Solution

To access this page select either of the following:


• the card with your solution in the Solution Studio home page.
• the Administration icon in the sidebar if you are navigating from other Solution Studio pages.

Available Operations
• Checking the current solution status
• Creating a backup of the solution
• Navigating to the App installation
• Checking the status of the Audit Trail App and redirecting you to the required target page.
• Checking the Maintenance Configuration status.
• Editing the solution description (by clicking Edit).
• Deleting the solution (by clicking Delete).

 The Audit Trail configuration pages are visible only if you install the Audit Trail app. For more information,
see Audit Trail App in the Opcenter Execution Foundation User Manual.

3.5.1 Checking Solution Status


The Solution Administration page displays the current status of your solution.
If the solution is not valid a warning message is displayed indicating the problem, which could be one of the
following:
• the solution is empty, because it does not contain any Apps
• the solution is inconsistent, because the Apps it contains reference incompatible Functional Blocks.
Along with the name of the solution and a description, there are summaries of the elements contained in each
configuration area that make up the final solution:

722 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage the Solution

Possible operations
The operations that can be performed in this area depend on the status of the solution:

Operations Description Empty Inconsistent Valid

To modify the description of the


Edit
solution.

To delete an existing solution.


Delete

To create a backup of your


Backup
solution.

3.5.2 Creating a Backup of a Solution


To configure a new manufacturing solution in the same environment where another solution is currently managed,
it is necessary to make a backup copy of the current one before deleting it from Solution Studio, otherwise all
existing configurations will be lost.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 723


How to Manage a Manufacturing Solution in Solution Studio

How to Add Apps

A backup copy can be used afterwards to restore the previous solution in the same environment as the current
solution or to move the solution from one engineering environment to another.
The backup package does not contain Functional Block or App files or any MOM solution database backup
files. Consequently, if you archive the solution backup package in a dedicated folder or other storage media, make
sure you archive also all the Functional Block and App packages referenced by the solution.
This page describes how to create a backup of the current solution.

Prerequisites
A solution has been created.

Procedure
1. In the Solution Administration page, click Backup > Create Backup.
2. Enter the name you want to assign to the backup package, a description of its content and then click
Save. A default name for the backup package is proposed with the following format:
<SolutionName>_<date>_<time>, but you can change the proposed name.
3. Manually create a backup of the following folders, if you want to restore the solution on a different engineering
machine:
• %SITUnifiedSystemData%\Engineering\Packages\FunctionalBlocks folder to copy all referenced
Functional Block packages.
• %SITUnifiedSystemData%\Engineering\Packages\Projects folder to copy the Apps.
• %SITUnifiedSystemData%\Engineering\Packages\ExtensionProjects folder to copy the Extension
Apps.

Result
To see the newly created backup, as well as any other previously created backups, click Backup > Show
Backups.
Solution backup packages are listed in the Backups pane and the related files are located in the
%SITUnifiedSystemData%\Engineering\Packages\Solutions folder, containing:
• all the engineering configurations (i.e. Manufacturing Solution repository data, including User Roles).
• the content of the UI configurations, including Mashup UI Modules and the UI Applications (with the whole
folder content, if existing, contained in %SITUnifiedSystemData%\Engineering\Solutions\<SolutionName>).

3.6 How to Add Apps


After creating your solution, you can add Apps to your solution.
Apps implement manufacturing use cases. The metadata contained in the Apps, and in their referenced Functional
Blocks, is loaded into the Opcenter Execution Foundation administration and engineering environments.
This metadata will be stored in the Engineering repository.

 When creating a new solution or migrating an existing one, the latest version of the System App is
automatically installed.
For more information, see System App in the Opcenter Execution Foundation User Manual.

Accessing the App Management Page

724 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Add Apps

To access this page, click the card with your solution in the Solution Studio home page, and click App
Management in the sidebar.

Available operations
• Adding an App
• Removing an App

3.6.1 Adding a New App to a Solution


After creating a Manufacturing Solution you can start adding Apps.
You can add as many Apps as required to your solution, but they must be added one at a time.

Constraints
• A solution has been created.
• The required App packages (.zip file) must have been copied to %SITUnifiedSystemData%
\Engineering\Packages\Projects.
• The referenced Functional Block packages (.zip files) must have been copied to %SITUnifiedSystemData%
\Engineering\Packages\FunctionalBlocks.
• Apps cannot have the same App Name and different Prefix.

Supported Versions
Product Version Supported

App created with a version prior to 2.0 (*)

Referenced FB created with a version prior to 2.0 (*)

App created after 2.0

Referenced Functional Blocks created after 2.0

• (*): This means that the App/Referenced Functional Block version is supported only if it has been migrated to
a 2.x/3.x version in Project Studio first.
• : This means that the App/Referenced Functional Block is fully supported.

Functional Block reference conflicts


If you add an App to a solution, and both Apps reference the same Functional Block, conflicts may occur if the
version of the commonly referenced Functional Block is different.
The conflict depends on whether the difference is between the patch, minor or major version.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 725


How to Manage a Manufacturing Solution in Solution Studio

How to Add Apps

Conflict Description

Different patch versions The Functional Block with the highest patch version number will
always be used in the solution.

 Whenever a solution is created, or an App is added, updated


or reloaded, Solution Studio checks in the
%SITUnifiedSystemData%
\Engineering\Packages\FunctionalBlocks folder whether
there is a new patch available for the minor/major version in
question, and applies the latest patch version it finds.
If the patch version of the current version = 0, and you are in
the initial development phase, the behavior is different. See
Reloading Apps in development phase.

Different minor versions The referenced Functional Block with the highest minor number is
used in the solution. For example, if App1 references FB_A version
02.02.00 and the user adds App2, which references FB_A 02.03.00, the
Functional Block FB_A 02.03.00 will be used in the Solution.
If there is a higher minor version of FB_A (02.04.00), but this version is
not referenced by any of the Apps in the solution, it will not be used.

Different major versions The user will be warned that there are conflicts. If the user performs
the add operation anyway, the solution will be marked as invalid, no
engineering operations are allowed and the higher version cannot
consequently be removed from the solution. The Apps must be
aligned to the higher version in one of the following ways to resolve
the conflicting Functional Block references:
• removing the App which references the lower major version of the
commonly referenced Functional Block.
• aligning the Functional Blocks references of the Apps in Project
Studio so that all Apps reference the same higher Major Functional
Block version. This operation may also require modifying the Apps
themselves in order to align them with the new Functional Block
version.
If neither of the previous operations are possible, you can recover the
last valid Solution status by restoring a previously backed up solution.

Procedure
1. In the App Management page click the Available tab.

2. Click Show all Version if you want to see all the versions of available Apps. Click Show latest
Version if you only want to see the recent version of available Apps.
3. Should a previous version of the System App be in use (example by restoring a 2.3 backup), always update it to
the most recent version.
4. Select the tile of the App you want to add, and click Install. You can now configure your Apps.

726 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Apps and Extension Apps

3.6.2 Removing an App from a Solution


You can remove Apps from a previously created solution, as long as the Solution contains at least one App.
Bear in mind that removing an App from a solution could imply the removal of artifacts, and consequently it may be
necessary to enable potentially destructive operations when updating the database.

Constraints
• The App cannot be removed if any of its UI Components are used within a UI Mashup Module or if any of its UI
Modules are used within a UI Application.
• You cannot remove an App that references a higher major version of a Functional Block, if the other Apps in the
solution do not also reference the higher version, and the solution is consequently in invalid status. Once all the
Apps have been aligned to the higher major version of the common Functional Block the App can be removed.
• If two Apps reference different minor versions of the same Functional Block, and one of these Apps is removed,
the minor version of the Functional Block loaded in the solution will correspond to the version referenced by the
remaining App. For example, if a solution contains App1, which references FB_A 01.02.00 and contains App2,
which references FB_A 01.03.00, FB_A 01.03.00 will be used in the solution. If App1 is removed, FB_A 01.02.00
will then be used in the solution.
• You cannot remove an App if any of its App Extensions have been installed.
• Do not remove the System App as it is a prerequisite for building the solution.

Procedure
1. In the App Management page, select the App you want to remove.
2. Click .

3.7 How to Manage Apps and Extension Apps


Once you have added an App to a solution you can perform various operations to make sure you are always using
the latest versions and to keep an eye on its contents, and where it is used.
You can also add Extension Apps related to the installed Base App.

Accessing the App Management Page


To access this page, click the card with your solution in the Solution Studio home page, and click App
Management in the sidebar.

Available operations
• Adding Extension Apps
• Viewing App and App Extension Details
• Reloading Apps and Extension Apps
• Updating Apps and Extension Apps

3.7.1 Adding Extension Apps to a Solution


An Extension App is a customized extension of a base standard App.
A base App can have multiple Extension Apps, but each Extension App references only one base App.
While adding an Extension App, all UI Applications associated with the base module will be updated with new
screens added to extended modules if any.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 727


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Apps and Extension Apps

 Extension Apps cannot be removed from the solution if any of their artifacts are used by a UI Application or
UI Module.
You can check this in the Where Used tab of the App Extension details.

Prerequisites
• The Extension App packages (.zip file) must be present in %SITUnifiedSystemData%
\Engineering\Packages\ExtensionProjects.
• All packages required for the Base App must be present in the required directories.
• The Base App has been compiled with the required extension option (Can Be Extended option), otherwise the
Extensions tab is not displayed.
• The Base App is installed.

Procedure
1. Click on the Installed tab in the App Management page.
2. Select the tile of the base App whose Extension App you want to add.
3. Click to open the App.
4. Click on the Extensions tab.
5. Click to load the most recent version of each Extension App.
6. Then do either of the following to add the most recent version of the Extension App:
• Select the tile of the Extension App you want to add and click .
• Click Alternative Versions , select a specific version of an Extension App and then click on the
corresponding row.

The installed Extension Apps have the indicator icon within their tile.

3.7.2 Viewing App and Extension App Details


The App Management page provides information on the contents of each App and Extension App added to the
solution (see How to Add Apps).

Viewing App details


1. In the App Management page, click on the Installed tab.
2. Click the App tile and click to open a details side pane with the name, prefix, version, description and
platform version of the App you have installed.
3. Do either of the following:
• Click on the Dependencies tab to display the Functional Blocks referenced by the App.
• Click on the Where Used tab to display in which UI Components and Modules the App is used.

Viewing Extension App information


1. In the App Management page, click on the Installed tab.
2. Click the App tile whose Extension App you want to show and click to open it.
3. Click on the Extensions tab.
4. Click to load the most recent version of each Extension App.
5. Select the tile of the Extension App whose information you want to view.
6. At the bottom of the page you can:

728 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Apps and Extension Apps

• Click on the Alternative Versions tab to see which other versions exist of the Extension App.
• Click on the Dependencies tab to display the Functional Blocks referenced by the Extension App and
ones referenced by the Base App.
• Click on the Where Used tab to display in which UI Components and Modules the Extension App is used.

3.7.3 Reloading Apps and Extension Apps in a Solution


You can reload an App or an Extension App if the App/Extension App (or one of the Functional Blocks it references)
has been compiled in Project Studio in one of the following ways:
• with an increased patch number (e.g. 01.01.01)
• without increasing any version number (pure development phase)
Unlike the update operation which always requires an explicit choice of the required package, in the reload
operation, Solution Studio automatically loads the latest patch version it finds in the engineering project folders
(see below) for the installed package.

 Note about Pre-Checks


The reload operation of Apps and Extension Apps preserves the configurations you have applied in
Solution Studio for the Pre-Checks.

 Note about Post-Actions


• In case of mandatory Post-Actions, the reload operation of Apps and Extension Apps does not affect
the current Post-Action configuration because no further configuration can be applied in Solution
Studio for the Post-Actions.
• In case of optional Post-Actions, the reload operation preserves the configurations you have applied in
Solution Studio, except when the Post-Actions become mandatory. In this case, the reload operation
applies the new configuration, overwriting the configuration you have applied in Solution Studio.
• If mandatory Post-Actions become optional, the reload operation applies the new configuration by
enabling the Post-Action execution in Solution Studio by default. If needed, you can modify the Post-
Action configuration in Solution Studio disabling the Post-Action execution.
For more information, see Modeling Post-Actions and Configuring Command Settings.

Apps with increased patch number


Patch versions contain only changes to the business logic or code of the App, and not to the model and its manifest.
Whenever an App/Extension App that is present in a manufacturing solution, is reloaded or updated, Solution
Studio checks in the following folders whether there is a new patch available for the minor/major version in
question, and applies the latest patch version it finds:
• %SITUnifiedSystemData%\Engineering\Packages\FunctionalBlocks
• %SITUnifiedSystemData%\Engineering\Packages\Projects
• %SITUnifiedSystemData%\Engineering\Packages\ExtensionProjects
If the Copy To Engineering Target Folder option has been selected in the Build Options properties of
the Installer project (see Generating an App Package), the zip files are automatically copied to the folders.
This is applicable both to the Apps/Extension Apps in the solution and the Functional Blocks they reference.
When you reload an App/Extension App in the solution, all the UI Applications dependent on the App/Extension App
are updated with the changes. If you have customized your UI Application in the sidebar configuration, your
changes made to icon, title, display will be preserved, otherwise the latest update from the reloaded App/Extension

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 729


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Apps and Extension Apps

App is applied. It is not required to reset the UI Application to get the latest update. The changes to other properties
such as custom folder, home state, order of folder and screens are also preserved.

Apps in development phase (without patch number)


When your solution is in its initial development phase, the Apps/Extension Apps and Functional Blocks may be
frequently modified without changing versions. To identify these initial packages, their patch number is left to 00 or
even not modified with respect to the previous one.
Consequently there could be new package zips in the engineering folders, with the same minor and major version
as the loaded App/Extension App, and where the patch number is either 00 or the same as the previous one.
In this scenario, the new packages are loaded into the solution, and a warning message is generated, as the zips
could contain modifications that might cause inconsistencies. For example, a UI Application may use a UI
Component that is no longer present, or a command may call another command which is no longer present.

Procedure
1. In the App Management page click the Installed tab.
2. Select the required App.
3. To reload the App, click .
4. To reload also the related Extension App, click on the selected App tile and then click the Extensions tab.
5. Click to load the most recent version of each Extension App. The installed Extension Apps have the
indicator icon within their tile.
6. Select the tile of the installed Extension App you want to reload and click .

3.7.4 Updating Apps and Extension Apps in a Solution


You can update an App or an Extension App by choosing the required upgraded package if the App/Extension App
(or one of the Functional Blocks it references) has been compiled in Project Studio in one of the following ways:
• With an increased minor version (e.g. 01.02.00), if the App/Extension App contains additional elements, such as
new entities, or new UI components or UI modules. As it only adds new elements, the update operation does not
create compatibility issues.
• With an increased major version (e.g. 02.01.01), if the App/Extension App can contain modifications that break
compatibility. New major versions can be loaded into the solution, but a warning message will inform you that
problems may occur. For example, if the new version of the App does not contain a UI Component that has been
used within a Mashup UI Module the Mashup UI Module will be moved to Invalid status.
Since minor and major versions introduce consistent changes to your solution, you must always explicitly choose
the exact version you need.

 Note about Pre-Checks


The update operation of Apps and Extension Apps preserves the configurations you have applied in
Solution Studio for the Pre-Checks.

730 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Apps and Extension Apps

 Note about Post-Actions


• In case of Mandatory Post-Actions, the update operation of Apps and Extension Apps does not affect
the current Post-Action configuration because no further configuration can be applied in Solution
Studio for the Post-Actions.
• In case of optional Post-Actions, the update operation preserves the configurations you have applied in
Solution Studio, except when the Post-Actions become mandatory. In this case, the update operation
applies the new configuration, overwriting the configuration you have applied in Solution Studio.
• If mandatory Post-Actions become optional, the update operation applies the new configuration by
enabling the Post-Action execution in Solution Studio by default. If needed, you can modify the Post-
Action configuration in Solution Studio disabling the Post-Action execution.
For more information, see Modeling Post-Actions and Configuring Command Settings.

Constraints
You cannot update an App/Extension App with an inferior version (major or minor).

Functional Block reference conflicts


If you have a solution with two Apps/Extension Apps that reference the same Functional Block, and one the these is
updated, conflicts may occur if the version of the commonly referenced Functional Block is different.
The conflict depends on whether the difference is between the patch, minor or major version.

Conflict Description

Different patch versions The Functional Block with the highest patch version number will always
be used in the solution.

 Whenever a solution is created, or an App/Extension App is


added, updated or reloaded, Solution Studio checks in the
%SITUnifiedSystemData%
\Engineering\Engineering\Packages\FunctionalBlocks
folder whether there is a new patch available for the minor/
major version in question, and applies the latest patch version
it finds.
If the patch version of the current version = 0, and you are in
the initial development phase, the behavior is different. See
Reloading Apps and Extension Apps in development phase.

Different minor versions The referenced Functional Block with the highest minor number is used
in the solution. For example, if App1 and App2 reference FB_A version
02.02.00 and the user updates App2, which now references FB_A
02.03.00, the Functional Block FB_A 02.03.00 will be used in the Solution.
If there is a higher minor version of FB_A (02.04.00), but this version is
not referenced by any of the Apps/Extension Apps in the solution, it will
not be used.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 731


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Apps and Extension Apps

Conflict Description

Different major versions The user will be warned that there are conflicts. If the user performs the
update operation anyway, the solution will be marked as invalid, no
engineering operations are allowed and the higher version cannot
consequently be removed from the solution. The Apps/Extension Apps
must be aligned to the higher version in one of the following ways to
resolve the conflicting Functional Block references:
• removing the App/Extension App which references the lower major
version of the commonly referenced Functional Block
• aligning the Functional Blocks references of the App/Extension App
in Project Studio so that all App/Extension App reference the same
higher Major Functional Block version. This operation may also
require modifying the App/Extension App themselves in order to
align them with the new Functional Block version.
If neither of the previous operations are possible, you can recover the
last valid Solution status by restoring a previously backed up solution.

Prerequisites
It is recommended to save a backup copy of your solution before performing update operations as you cannot
subsequently revert to a previous version.

Procedure
1. In the App Management page click the Installed tab.
2. Select the required App and to update it, click . All the more recent versions for the selected App are
displayed in the Available Versions pane on the right. Apps which have a more recent version available have
the indicator icon within their tile.
3. To update also the related Extension App, click on the selected App tile and then click the Extensions tab.
4. Click to load the most recent version of each Extension App. Extension Apps which have a more recent
version available have the indicator icon within their tile.
5. Select the tile of the Extension App you want to update.
6. Click the Alternative Versions tab. The highest patch version for each major/minor version is displayed.
7. Select a specific version of an Extension App then click .

Result
When you update a minor version of an App/Extension App the following operations will also be performed:
• all new items are loaded
• new UI Module screens are added
• any new commands and event subscriptions are associated with the default worker role.
• all UI Applications dependent on the App/Extension App are updated with changes.
• If you have customized your UI Application in the sidebar configuration, your changes made to icon, title,
display will be retained, otherwise the latest update from the reloaded App/Extension App is applied.
• It is not required to reset the UI Application to get the latest update. The changes to other properties such
as custom folder, home state, order of folder and screens are also retained.
• any newly added screens will be added as they are.
When you update a major version of an App/Extension App the following operations will also be performed:

732 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

• all items contained in the previous version and not present in the current version are removed
• associations between deleted commands and existing worker roles are removed
• subscriptions relative to deleted events and associations between these subscriptions and the existing worker
roles are removed
• the status of UI Modules referencing deleted UI Components is set to Invalid.
• the status of UI Applications referencing invalidated UI Modules is set to Invalid.
• deleted Modules or Screens will be removed from the UI Application.
• all UI Applications dependent on the App/Extension App are updated with changes.
• If you have customized your UI Application in the sidebar configuration, your changes made to icon, title,
display will be retained, otherwise the latest update from the reloaded App/Extension App is applied.
• It is not required to reset the UI Application to get the latest update. The changes to other properties such
as custom folder, home state, order of folder and screens are also retained.
• any newly added screens will be added as they are.

3.8 How to Configure Apps


The published commands and predefined event subscriptions of the Apps you have added to your solution are
automatically assigned to the default worker role.
A default worker role is created in the solution for each CPU type. The default worker role cannot be removed from
the solution.
However, you can create alternate worker roles and assign commands or event subscriptions to these roles, to
customize the way in which the business logic that makes up your project is distributed.
You can also create and configure new event subscriptions.

Accessing the App Management Page


To access this page, click the card with your solution in the Solution Studio home page, and click App
Management in the sidebar.

Viewing the Default Worker Roles


1. From the App Management page, click the App tile and click Open.
2. In the App Configuration page click on the Default Configuration tab.

Available operations
• Configure command settings
• Configure protected command settings
• Manage App Extensions
• Configure event subscriptions

3.8.1 Configuring Command Settings


When an App is added to a solution, all its commands are automatically assigned to the default worker role created
along with the solution. A command that is associated with a worker role is called a published in role command. A
published in role command can be invoked outside transaction from the code of an event handler, or from the code
of a project using the IUnifiedSdkLean or by any other client using the Opcenter Execution Foundation Service
Layer. Commands that are not associated with a worker role can only be invoked inside the transaction from the
code of the command handlers.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 733


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

However, it is possible to create new worker roles, and assign commands to this worker role and modify
the command execution timeout for individual commands, overriding the default settings of its worker role.
When an App is reloaded or updated, these modifications are maintained, except in specific cases described in
Reloading Apps and Extension Apps in a Solution and Updating Apps and Extension Apps in a Solution, and any new
commands are added to the default worker role.
If you enable the Advanced Configuration option in the Solution Studio settings, you can also see protected
commands, that have not been published in the Public Object Model, and you can modify their command execution
timeout value and worker role.
You can also enable or disable Pre-Checks previously defined in Project Studio for Public and Composite
Commands belonging to Base or Extension Apps.
These Pre-Checks can be used to implement conditions that determine the execution, or the non execution, of a
command. This additional code is executed at the beginning of the command logic, performing required checks
before the command execution.
Depending on the Pre-Check behavior you have configured, at the first Pre-Check failure:
• the Pre-Check execution stops, according to the stop and fail behavior (default).
• all Pre-Checks are executed anyway, according to the fail and proceed behavior.
The command will be executed after the success of all Pre-Checks.
This functionality allows you to reuse existing commands by simply enabling or disabling the Pre-Checks, without
rewriting business logic.
You can also enable or disable Post-Actions previously defined in Project Studio for Public and Composite
Commands belonging to Base or Extension Apps. Post-Actions belonging to Protected Commands can be only
configured via script (for more information about the configuration, see How to Manage Post-Actions via Scripts in
Opcenter Execution Foundation Installation Guide) .

Constraints
A command cannot be associated with two worker roles at the same time. However, when you import a protected
command in the POM Model, the published command and the original protected command of the Functional Block
are two distinct artifacts although they trigger the same business logic. Consequently they can be associated with
different worker roles as well as with the same worker role.

Modifying the Command Execution Timeout


1. In the Installed tab of the App Management page, click the App tile whose commands you want to modify and
click .
2. In the App Configuration page, click on the Commands tab.
3. Select the commands whose configuration you want to modify, click and then choose Edit
Command Timeout from the command menu.
4. Modify the command execution timeout value, overriding the value set for the worker role, if required. The
minimum value is 10 seconds, the maximum is 3 hours (10800 seconds) and the default value for the default
worker role and all new worker roles is 30 seconds.
5. Click Save. The override column of the commands whose timeout value has been changed will be flagged. To
return to the default time out value click to reset the timeout.

Changing the Worker Role


1. In the Installed tab of the App Management page, click the App tile whose worker role you want to modify and
click .

734 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

2. In the App Configuration page, click on the Commands tab: the commands that are already associated with
the current worker role are displayed.
3. Select the commands whose association you want to modify, proceed in either of the following ways and when
finished click Save to apply the changes:
• click > Move Commands To An Existing Worker Role to select an existing worker role and then
select the required worker role from the list box.
• click > Move Commands To A New Worker Role to create a new target worker role for the selected
commands and enter the following information:
Parameter Description

Name Enter a meaningful name that allows other users to easily identify the
worker role.

Description Enter a useful description for the worker role.

Execution Mode Set the Execution Mode either to Parallel or Sequential, according to
the required execution logic (see Parallel vs. Sequential Command and
Event Handler Execution). If Sequential mode is selected, some other
configuration options are automatically set by the system and cannot
be modified (i.e. the retry number will be set to 0, and the number of
instances will be set to 1).
For more information, see Command Retry Management.

Deployable Select the Deployable check box to include the worker role in the
deployment package and make it ready for execution on the Runtime
hosts. If no commands or event subscriptions are assigned to the
worker role, it will not be included in the deployment package even if it
has been flagged as deployable.

Number of Instances Specify the number of instances to be created for each worker role, if
the worker role has been flagged as deployable.

Target CPU (Only if you are creating the Worker Role from the Worker Roles page)
Select the Target CPU architecture type for the worker role from the
drop down list.

 This option is not available if you are creating the Worker Role
either from the App Configuration page or from the Protected
Commands Configuration page. In these use cases, if you
select a command, the target CPU of its Command Handler will
drive the Target CPU of the created Worker Role (in particular,
if the selected commands have either anyCPU or x64, the
created Worker role will be x64, on the contrary if the selected
commands have either anyCPU or x86, the Worker Role will be
x86). Be aware that if you select commands with x86 and x64
CPU, it will not be to possible create any Worker Roles for
moving the commands.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 735


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

Parameter Description

Retry Number Enter a retry number to specify the maximum number of times the
execution of a command will be retried before failing. Possible values
range from 0 to 5, the default value is 3. This behavior is then applied to
all commands assigned to the worker role, but this can be overridden
for specific commands in the commands tab.

Command Timeout Enter a command execution timeout value in seconds. Possible values
range from 10 seconds to 3 hours (10800 seconds), the default value is
30 seconds. This behavior is then applied to all commands assigned to
the worker role, but this can be overridden for specific commands in the
commands tab.

Modifying the Pre-Check Configuration


1. In the Installed tab of the App Management page, click the App tile for which Pre-Checks you want to define
and click .
2. In the App Configuration page, click on the Commands tab.
3. Click the icon next to the Public/Composite Command for which Pre-Check configuration you want to
modify. This icon is displayed only if a Pre-Check (or a Post-Action) has been defined for the command. The
system displays the related list of Pre-Checks (as well as the list of Post-Actions) according to the order of
execution, showing both the Pre-Checks that have been enabled in Project Studio (with the check box selected)
and the disabled ones (with the check box cleared).
4. Click Configure.
5. In the Pre and post execution configuration pane, open the Pre-Checks tab.
6. Leave the Pre-Checks you require as selected to enable their execution: otherwise, deselect those you do not
require to disable them.
7. If needed, modify the order in which the Pre-Checks will be executed by moving them within the Pre-
Checks area. If a Pre-Checks panel has this icon it means that it has still the default order ( i.e. -1 value in
Order Execution field ).
8. If needed, modify the Pre-Check behavior previously configured in Project Studio by selecting or removing the
selection from the Stop at first fail option: if this option is set, the Pre-Check execution stops at the first Pre-
Check failure. Otherwise, all Pre-Checks will be executed anyway for the specified Command, according to the
fail and proceed behavior. The command will be executed only after the success of all Pre-Checks.
9. Click Save. The Pre-Check configuration is persisted in the system.

Modifying the Post-Action Configuration


1. In the Installed tab of the App Management page, click the App tile for which Post-Actions you want to define

and click .
2. In the App Configuration page, click on the Commands tab.
3. Click the icon next to the Public/Composite Command for which Post-Actions configuration you want to
modify. This icon is displayed only if a Post-Action (or a Pre-Check) has been defined for the command. The
system displays the related list of Post-Actions (as well as the list of Pre-Checks) according to the order of
execution.
4. Click Configure.
5. In the Pre and post execution configuration pane, open the Post-Actions tab.
6. If you have set Post-Actions as optional in Project Studio, enable or disable the Post-Action execution within the
Post-Actions area according to your needs.

736 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

 Post-Actions which have not been set as optional in Project Studio are mandatory by default. So, they
cannot be edited and will be always executed.

7. If needed, modify the order in which the Post-Actions will be executed by moving them within the Post-
Actions area. If a Post-Actions panel has this icon it means that it has still the default order ( i.e. -1 value in
Order Execution field ).
8. Click Save. The Post-Action configuration is persisted in the system, including the Post-Actions which you have
not changed.

3.8.2 Configuring Protected Command Settings


Protected commands are commands that have not been published in the POM model in the App.
Protected commands are automatically added to the default worker role when the App is loaded in the
solution. Assigned protected commands can be invoked outside transaction from the code of an event handler, or
by an application that uses the IUnifiedSdkLean interface. If you need to call protected commands, you can switch
to Advanced Configuration mode and configure the protected commands as required.
Protected commands can be assigned to a different worker role or a new worker role can be created, and their
command execution timeout can be modified, overriding the default settings of the worker role. Protected
commands that are not associated with a worker role can only be invoked inside the transaction from the code of
the command handlers.
When an App is reloaded or updated, these modifications are maintained.

Constraints
• A command cannot be associated with two worker roles at the same time. However, when you import a
protected command in the POM Model, the published command and the original protected command of the
Functional Block are two distinct artifacts although they trigger the same business logic. Consequently they can
be associated with different worker roles as well as with the same worker role.
• You can associate with a worker role only protected commands that have been compiled in MS Visual Studio to
run on the same, or on any, target platform. For example, if you have selected the x86 option as worker role
architecture type, you can associate with it only commands compiled to run on a 32 bit, or on any, target
platform.

Prerequisite
Protected commands are visible in Solution Studio only if the Advanced Configuration mode has been enabled in
the How to Configure Solution Studio Settings page.

Modifying the command execution timeout


1. In the Installed tab of the App Management page, click the Protected Commands tile and click .
2. In the Protected Commands Configuration page, click on the Assigned to worker role tab.
3. Select the commands whose configuration you want to modify, click and then choose Edit
Command Timeout from the command menu.
4. Modify the command execution timeout value, overriding the value set for the worker role, if required. The
minimum value is 10 seconds, the maximum is 3 hours (10800 seconds).
5. Click Save. The override column of the commands whose timeout value has been changed will be flagged. To
return to the default time out value click to reset the timeout.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 737


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

Changing the worker role


1. In the Installed tab of the App Management page, click the Protected Commands tile and click .
2. In the Protected Commands Configuration page, click on the Assigned to worker role tab.
3. Select the commands whose association you want to modify, proceed in either of the following ways and when
finished click Save to apply the changes:
• click > Move Commands To An Existing Worker Role to select an existing worker role and then
select the required worker role from the list box.
• click > Move Commands To A New Worker Role to create a new target worker role for the selected
commands and enter the following information:
Parameter Description

Name Enter a meaningful name that allows other users to easily identify the
worker role.

Description Enter a useful description for the worker role.

Execution Mode Set the Execution Mode either to Parallel or Sequential, according to
the required execution logic (see Parallel vs. Sequential Command and
Event Handler Execution). If Sequential mode is selected, some other
configuration options are automatically set by the system and cannot
be modified (i.e. the retry number will be set to 0, and the number of
instances will be set to 1).
For more information, see Command Retry Management.

Deployable Select the Deployable check box to include the worker role in the
deployment package and make it ready for execution on the Runtime
hosts. If no commands or event subscriptions are assigned to the
worker role, it will not be included in the deployment package even if it
has been flagged as deployable.

Number of Instances Specify the number of instances to be created for each worker role, if
the worker role has been flagged as deployable.

738 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

Parameter Description

Target CPU (Only if you are creating the Worker Role from the Worker Roles page)
Select the Target CPU architecture type for the worker role from the
drop down list.

 This option is not available if you are creating the Worker Role
either from the App Configuration page or from the Protected
Commands Configuration page. In these use cases, if you
select a command, the target CPU of its Command Handler will
drive the Target CPU of the created Worker Role (in particular,
if the selected commands have either anyCPU or x64, the
created Worker role will be x64, on the contrary if the selected
commands have either anyCPU or x86, the Worker Role will be
x86). Be aware that if you select commands with x86 and x64
CPU, it will not be to possible create any Worker Roles for
moving the commands.

Retry Number Enter a retry number to specify the maximum number of times the
execution of a command will be retried before failing. Possible values
range from 0 to 5, the default value is 3. This behavior is then applied to
all commands assigned to the worker role, but this can be overridden
for specific commands in the commands tab.

Command Timeout Enter a command execution timeout value in seconds. Possible values
range from 10 seconds to 3 hours (10800 seconds), the default value is
30 seconds. This behavior is then applied to all commands assigned to
the worker role, but this can be overridden for specific commands in the
commands tab.

Removing protected commands from a worker role


1. In the Installed tab of the App Management page, click the Protected Commands tile and click .
2. In the Protected Commands Configuration page, click on the Assigned to worker role tab.
3. Select the commands you want to remove from their worker roles and click : the unassigned protected
commands will be displayed in the Unassigned tab.

3.8.3 Configuring Event Subscriptions


During the configuration of the Manufacturing Solution, you can establish an association between events and event
handlers: each event to be monitored must be associated with one or more event handlers in order to execute a
specific logic when the event is raised.
The association between an event and an event handler is defined in the event subscription.
Each event subscription establishes a one-to-one relationship between an event and an event handler.
The same event can be associated to different event handlers in different event subscriptions (i.e. you can have
several event subscriptions for the same event).
For each subscription you can set a filter on the received event.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 739


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

Event subscriptions can be configured either in Solution Studio by directly associating events with event handlers
or within the Apps in Project Studio, in the predefined event subscriptions.
Once configured in either of the two ways, event subscriptions must be assigned to one or more worker roles.
Predefined subscriptions are loaded together with the App in Solution Studio, and are directly associated to the
default worker role and are read-only. These subscriptions can be assigned to different or even no worker roles, but
they cannot be modified or deleted.
The association between event subscriptions and worker roles is not unique: different worker roles can receive the
same event and execute the same logic.
You can also implement event subscriptions inside a third-party application through
the IUnifiedSdkLean interface.

Configuration workflow

Filters on received Events


Inside the subscription you can restrict the events you want to receive for a certain event handler by defining a sub-
group of event instances with specific properties.
If you have fired an event defining the envelope optional input parameter, you can configure the system in order to
execute the business logic associated with the specified event handler only if certain conditions are satisfied. In
particular, you can execute an event handler only if the received event contains the properties that you defined in
the envelope parameter of the fire event call.
For example, you may subscribe to the OnLotMoved event fired with the following envelope: the module property
set to MyWarehouseModule, and the category property set to information and so on. This means that the event
handler you are subscribing will not receive all the OnLotMoved events, but only the OnLotMoved events that have
been fired with the specified envelope (module = MyWarehouseModule, and category = information).
To implement this behavior, it is necessary to configure one or more filters on the envelope fields in the Filter tab
when creating or editing an event subscription. Each item of the subscription filter is used as a filter condition with
an AND clause.
The Filter Envelope flag is checked for event subscriptions characterized by specific conditions in the Events page.

Procedure
1. In the App Management page, click the App tile whose configuration you want to modify and click .
2. In the App Configuration page, click on the Event Subscriptions tab: the predefined event subscriptions that
are already associated with the current worker role are displayed, but cannot be modified.
3. Click Add Event Subscription Here (or click if an item is already present in the page).
4. In the New Subscription pane, in the Properties tab enter a name and description that identify the
subscription.
5. Select Show valid events only if you want to display only the events that are already associated to a handler
and that can be consequently assigned to the worker role as valid event subscriptions. If you clear the check
box, you will also display the events that are not associated to any handler (and that cannot be used in an event
subscription because there is no business logic to be triggered).
6. Click on the Event browse button to view available events in the Select Item dialog box, where you can filter
and sort results.

740 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Apps

7. Click on the required event and click Select.


8. Select Show unassigned handlers only if you want to see only event handlers that have not yet been assigned
to any event yet.
9. Select an event handler from the Event Handler drop down list that identifies the logic that must be executed
when the event is raised.
10. To set a filter on received events, click the Filter (envelope) tab and specify a value for the envelope fields.
11. The event subscription is automatically assigned to the default worker role. To modify the worker role click the
Worker Role tab and select Move to another worker role and either:
• Click Select existing and select a worker role from the drop down list.
• Click Create New and enter the following information:
Parameter Description

Name Enter a meaningful name that allows other users to easily identify
the worker role.

Description Enter a useful description for the worker role.

Execution Mode Set the Execution Mode either


to Parallel or Sequential, according to the required execution
logic (see Parallel vs. Sequential Command and Event Handler
Execution). If Sequential mode is selected, some other
configuration options are automatically set by the system and
cannot be modified (i.e. the retry number will be set to 0, and the
number of instances will be set to 1).
For more information, see Command Retry Management.

Deployable Select the Deployable check box to include the worker role in the
deployment package and make it ready for execution on the
Runtime hosts. If no commands or event subscriptions are
assigned to the worker role, it will not be included in the
deployment package even if it has been flagged as deployable.

Number of Instances Specify the number of instances to be created for each worker role,
if the worker role has been flagged as deployable.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 741


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Accounts

Parameter Description

Target CPU (Only if you are creating the Worker Role from the Worker
Roles page) Select the Target CPU architecture type for the worker
role from the drop down list.

 This option is not available if you are creating the Worker


Role either from the App Configuration page or from the
Protected Commands Configuration page. In these use
cases, if you select a command, the target CPU of its
Command Handler will drive the Target CPU of the
created Worker Role (in particular, if the selected
commands have either anyCPU or x64, the created Worker
role will be x64, on the contrary if the selected commands
have either anyCPU or x86, the Worker Role will be x86).
Be aware that if you select commands with x86 and x64
CPU, it will not be to possible create any Worker Roles for
moving the commands.

Retry Number Enter a retry number to specify the maximum number of times the
execution of a command will be retried before failing.
Possible values range from 0 to 5, the default value is 3. This
behavior is then applied to all commands assigned to the worker
role, but this can be overridden for specific commands in the
commands tab.

Command Timeout Enter a command execution timeout value in seconds. Possible


values range from 10 seconds to 3 hours (10800 seconds), the
default value is 30 seconds. This behavior is then applied to all
commands assigned to the worker role, but this can be overridden
for specific commands in the commands tab.
12. Click Save to apply the changes.

Modifying an event subscription


Once you have created a new event subscription, in the Event Subscriptions tab you can

• modify its description, filter and worker role by selecting the event subscription and clicking .
• unassign the event subscription from the worker role, by selecting the event subscription and clicking .

3.9 How to Configure Accounts


During the configuration of the Manufacturing Solution, it is necessary to configure the user accounts in order to
correctly execute runtime operations.
Interactive users must have a valid account and a valid authorization role.
To have a valid account, users or groups must be properly created in the User Management Component.

742 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Accounts

To be authorized, users must be associated to roles. Roles represent groupings of permissions used to set
constraints on the operations that users are allowed to perform within the Manufacturing Solution. For the list of
object types and operations you can associate to roles, see Modeling Roles.
This authorization method is valid for Web Applications that access the Opcenter EX FN Service Layer by means of
the UI Framework infrastructure, which is made available by Project Studio.
Alternatively, Web Applications that interact with the Opcenter EX FN Service Layer but that do not use the UI
Framework infrastructure, can be authorized through a valid access token.

Opcenter Execution Foundation roles


Different role types must be associated to user accounts in order to access either the application data model (i.e.
the data model you have defined in Project Studio) or some of the information contained in the engineering data
model (i.e. information related to user accounts and roles) from the deployed UI Applications.

Role Description

AccessControlAdmin A system-defined role which groups permissions required to invoke the


commands of the engineering data model (in particular, commands that
associate roles with users or groups). This role is created by the setup and
you can only assign users or groups to it.
Accounts associated with this role can access UI screens containing
account-related data from any deployed UI Applications, and can also
invoke commands that associate roles with users or groups.
This role does not allow access to Solution Studio.

AccessControlViewer A system-defined role which groups permissions required to retrieve


information from the engineering data model (in particular, from users,
groups, roles and role associations). This role is created by the setup and
you can only assign users or groups to it.
Accounts associated with this role can access UI screens containing
account-related data from any deployed UI Applications, but cannot
invoke commands.
This role does not allow access to Solution Studio.

SignalRulesAdmin This role is associated to the management of Signal Rules in the Signals
App.
Account associated to this role can view, create, modify, import, export,
approve and deploy Signal Rules.

SignalRulesEngineer This role is associated to the management of Signal Rules in the Signals
App.
Account associated to this role can view, create, modify, import and
export Signal Rules.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 743


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Accounts

Role Description

SignalRulesViewer This role is associated to the management of Signal Rules in the Signals
App.
Account associated to this role can view Signal Rules.

SysAdmin A system-defined role, which cannot be configured or displayed in


Solution Studio, which groups permissions required to access Solution
Studio and to configure the Manufacturing Solution.
This role is more powerful of the other roles, as it also grants all the
permissions described for all the other roles.
You can only assign accounts to this role in the Opcenter EX
FN Configuration tool or by running scripts (see Assigning or Removing the
SysAdmin Role in the Opcenter Execution Foundation Installation Guide).

SystemMonitoring A system-defined role which groups permissions required to retrieve


information about the platform environment from the monitoring
endpoint.
This role is created by the setup and you can only assign users or groups to
it.
This role does not allow you to access Solution Studio.

User-defined Roles User-defined roles which group permissions required to access the
application data model (read entities, invoke commands, subscribe to
events or signals, display UI screens). These roles are created either in the
Apps or in Solution Studio, and are always applied to the solution you are
configuring. If you load an App containing one or more predefined roles
that match the authorization requirements of your Solution, you do not
have to create and configure other roles in this page.
This role does not allow access to Solution Studio.
Pre-defined user roles, created in Project Studio, cannot be modified in
Solution Studio.

RemoteSystemCall This role is associated with the system certificate required to invoke
remote artifacts and it is created by the Opcenter Execution
Foundation Configuration tool, both in fresh installation and when
migrating from a previous product version.
Account associated with this role can access the remote App backend and
invoke commands and read entities. You don't need to assign users or
groups to this role. You cannot delete the role but you can only modify it
by assigning additional function rights or unassigning the existing ones.

UserPreferences This role is associated to the management of the user preferences and, in
particular, to the possibility of saving the changes applied to the view of
tables, grids or columns within UI screens.

744 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Accounts

For more information regarding the following roles:


• SystemMonitoring, see Monitoring Worker and Host Status from Web Clients.
• User-defined roles, see Creating and configuring Roles (predefined roles in Apps), or Configuring roles (Solution
Studio),
• UserPreferences see Setting user preferences

Accessing the Account pages


To access the following screens, click the card of your solution in the Solution Studio home page, click
Account in the sidebar and then select one of the following:
• Users
• Groups
• Roles

Available operations
• View users and groups
• Configure roles

3.9.1 Viewing Users and Groups


The users and groups, which can be assigned to roles in the Role Configuration page, can only be created in the
User Management Component, and cannot be modified in Solution Studio.
However they are displayed in read-only mode in order to easily view which roles have been assigned to them.

 For more information on creating users and groups, refer to the UMC documentation (i.e. UMC Web UI User
Manual and UMX User Manual).

Procedure
1. Click Account in the sidebar and then select either Users or Groups.
2. Select the user/group whose details you want to view.
3. Click Details: the name and assigned roles are displayed.

3.9.2 Configuring Roles


To configure roles, you must first create the roles, then configure the operation permissions and then associate
roles to users or groups.

Workflow
1. Create user-defined roles from scratch, by copying existing roles or by using predefined roles (i.e. roles
configured in Apps).
2. Assign rights to roles according to their category (entities, reading functions, commands, events, signals,
screens).
3. Assign users/groups to roles.
4. Apply changes to runtime hosts.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 745


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Accounts

System roles, identified by a lock icon, cannot be edited, configured or deleted, but only assigned to users/
groups.

3.9.2.1 Creating Roles


The Roles page allows you to view predefined roles configured in Apps, or create new role either by:
• creating a role from scratch, or
• copying an existing role. This functionality is very useful if you want to adapt a predefined role to your specific
requirements.

Prerequisites
The artifacts displayed on this page must have been flagged as securable during the development phase in Project
Studio (or Solution Studio for Mashup Module screens).

Creating a role from scratch


1. Click Account in the sidebar and then select Roles.
2. In the Roles page click .
3. In the Create New Role pane, enter a name and a description for the new role. The role will be identified by a
full name, which is automatically filled in during its creation, and it will be displayed in the Role Details panel.
4. If you want to assign all available rights to the role for any categories (such as commands, entities, signals,
reading functions), select the required categories in the GrantFull Permission to area.
5. Click either:
• Save to save and close the role and return to the Roles page: the new role is displayed in the list, along
with any user roles that were pre-defined in Project Studio or provided by default.
• Save and Config to save the role and open the Roles pane where you can specify rights for specific
entities, commands, events, signals or UI screens (as described at page Assigning Rights to Roles).

Copying an existing role


1. Click Account in the sidebar and then select Roles.
2. In the Roles page select the role you want to copy and click . Predefined roles can also be copied.
3. In the Copy Role pane enter a new name and description for the copied role, if required.
4. Select the Associate users and groups check box to maintain the association with any users or groups assigned
to the original role.
5. Click the Associate certificates check box to maintain any certificates associated to the original role.
6. Click Save.

3.9.2.2 Assigning Rights to Roles


Once you have created roles in the Roles page, you can assign rights to these roles in order to manage artifacts such
as commands, screens, and reading functions.

746 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Accounts

By default only commands and entities that have been imported into the POM model of the App they belong to are
displayed. However, if the Advanced Settings option has been enabled, protected commands and entities of
referenced Functional Blocks are also listed and can be configured for compatibility purposes.

 If the referenced entities and commands have been also imported to the POM Model (and the Advanced
Settings option is enabled), protected commands and entities imported to the POM Model appear in the
list both with the name used in the Functional Block and with the name assigned in the POM Model. These
objects are handled within role configurations as autonomous, distinct securable objects and you can
consequently configure them separately.

Procedure
1. Click Account in the sidebar and then select Roles.
2. Click the role tile for the role you want to assign rights to and click .
3. In the Roles pane, select the category tab of the artifacts you want to assign to the role.
4. In the desired tab, do one of the following:
• If no rights are assigned, click Assign Entities / Assign Commands / .... Assign <Artifact type> (the name
of the button depends on the type of rights you are associating) and select the artifacts from the list.
• If any rights are already present, click to add any new right or select a right and click to remove
the association.
• If all rights for a certain artifact type have been assigned during the role creation, by means of the Grant
Full permission option, and you now want to override the configuration, click Assign Rights and select
the single permissions you want to assign. In this way, the previous list will be completely removed and
only the newly selected permissions will be displayed. For this reason, a warning message is displayed,
advising you are about to change the configuration.
5. Click Assign.

3.9.2.3 Assigning Users and Groups to Roles


Once you have created roles in the Roles page, and assigned rights to these roles, they can be assigned to users
and/or groups.

Procedure
1. Click Account in the side bar and then select Roles.
2. Click the role tile for the role you want to assign users or groups.
3. Click to assign users/groups: a pane opens with the list of users/groups configured in User Management
Component (for more information, refer to User Management Component documentation).
4. Click on either of the following tabs:
• Users
• Groups
5. Click Assign Users / Assign Groups and select the required user or group. You can select multiple users or
groups simultaneously.
6. To confirm the association, click Assign at the bottom of the pane.

3.9.2.4 Applying Changes to Hosts


Once you have configured your roles, you can directly apply the changes you have made to the runtime
environment, without stopping the services, if the following prerequisites are satisfied.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 747


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

If one of these prerequisites is not satisfied you must redeploy the solution.

Prerequisites
• The solution has already been deployed on a target environment and at least one of its hosts has been run once.
• There are no running hosts in errors.
• The Apps or the Extension Apps inside the Solution have not been reloaded, updated or deleted (this is required
because the commands, events and signals must be the same as the previously deployed ones).

Procedure
1. In the Roles page, click to deploy the new configuration on all running hosts.
2. Verify that no error messages are displayed in the host tiles in the Host Management page, to make sure that
your changes have been applied successfully.

3.10 How to Configure User Interfaces


The UI configuration process begins in Project Studio in the code development phase, in which the developer who
is implementing a given manufacturing functionality, combines the provided widgets (or custom ones) with the
Service Layer in order to develop custom UI Components and complex UI Modules to be used within the pages.
These operations require good programming skills.
This process then continues in Solution Studio in the development of the graphic aspect of the UI.

Accessing the User Interface Pages


To access this page, click the card with your solution in the Solution Studio home page, click User Interface in
the side bar and then select one of the following:
• SWAC Components
• Mashups

748 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

• UI Applications

Available operations
1. Managing SWAC components and their manifests.
2. Designing Mashup UI Modules.
3. Configuring the final UI Application by combining the Mashup UI modules (and the UI Modules created in MS
Visual Studio).

3.10.1 Managing SWAC Components


SWAC (Siemens Web Application Collaboration) components are a way to aggregate remotely-hosted UIs into
specific application views, and define a communication system among potentially very heterogeneous UIs.
The SWAC Components page in Solution Studio allows you to import the SWAC components you want to add to
your UI Module, and manage SWAC Component Manifest modifications.

Accessing the SWAC Component page


To access this page, click the card with your solution in the Solution Studio home page, click User Interface in
the side bar and then select SWAC Components.

Available operations on SWAC Components


• Importing SWAC Components into your solution
• Migrating the SWAC Compoment Manifest to the current version
• Reloading modified SWAC Component Manifests
• Updating the target URL of SWAC Components

3.10.1.1 Importing SWAC Components


You can import SWAC Components into your solution so they can consequently be added to a UI Module.

Procedure
1. In the SWAC Components page click New.
2. Select the .json descriptor of the SWAC component from the drop down list by browsing to the proper file. Its
name is displayed read-only in the Name field.
3. Enter a title for the SWAC Component, which will be displayed in the toolbox.
4. Enter the ID of the icon, which will graphically identify the SWAC component. Start typing the icon type (e.g. svg)
to browse the available list.
5. Define the height of the SWAC Component by specifying the default number of rows.
6. Define the width of the SWAC Component by specifying the default number of columns.
7. Click Save. The imported SWAC Component is displayed as a tile, with the following information:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 749


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Tab Item Description

Properties Icon The icon defined by the user when a SWAC


component is imported.

Name The name of the SWAC component.

Migration flag If the SWAC component manifest must be


migrated a message is displayed.

Title The title of the SWAC component.

Status Possible statuses are:


• In use: the SWAC component is used in a
Mashup UI screen and cannot be deleted.
• Not in use: the SWAC component is not
used in a Mashup UI screen and can be
deleted.

Where Used Mashup UI Screen The Mashup UI Screen where the SWAC
component has been used.

Title The title of the Mashup UI Screen where the


SWAC component has been used.

Status The status of the Mashup UI Screen where


the SWAC component has been used.

Parent UI Module The name of the module which contains the


Mashup UI Screen where the SWAC
component has been used.

 View SWAC Component details by clicking , or modify the SWAC Component by clicking Edit.

3.10.1.2 Migrating the SWAC Component Manifest


When the SWAC Manifest is modified due to a SWAC component upgrade (see Using Third-Party Components), it
may happen that previously created SWAC components use a previous version of the manifest.
At runtime both manifest versions are managed, and SWAC components with previous manifest versions can be
used in modules and deployed.
However, it is advisable to migrate the manifest to avoid problems occurring in the future.
In the SWAC Components page, each SWAC tile displays a specific to be migrated message if the manifest needs to
be updated.

Procedure
1. In the SWAC Components page, select the tile of the SWAC component whose manifest needs to be migrated.

750 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

2. Click to migrate the manifest.

3.10.1.3 Reloading the SWAC Component Manifest


If the SWAC Component manifest has changed, it can be reloaded in the following situations:

Changes made Can be reloaded

The name of the manifest has been changed.

New methods, events and properties have been added to the


manifest.

Methods, events and properties have been removed from the


manifest.

Prerequisites
The SWAC Component manifest must have been migrated to the current version.

Procedure
1. In the SWAC Components page, select the tile of the SWAC component whose manifest needs to be reloaded.
2. Click Reload.
3. Select the required manifest from the SWAC Manifest drop down list.
4. Click Save.

3.10.1.4 Updating SWAC Components


You can update the target URL of a SWAC Component that has already been added.

Prerequisites
The SWAC Component manifest must have been migrated to the current version.

Procedure
1. In the SWAC Components page, select the tile of the SWAC component whose URL needs to be modified.
2. Click : the name of the component and its current URL are displayed.
3. Enter a new URL.
4. Click Save. The SWAC manifest, available in the Engineering repository, is updated, along with the Mashup
manifest, if the component has been used within a module.

3.10.2 Designing Mashup UI Modules


Solution Studio includes a Mashup Editor where you can create Mashup UI Modules, which then make up UI
Applications.
In this editor you can design simple and non-repetitive UI Screens (for example, dashboards).
Alternatively, it is possible to programmatically create UI Modules in Project Studio.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 751


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Accessing the Mashup page


To access this page, click the card with your solution in the Solution Studio home page, click User Interface in
the side bar and then select Mashups.

Workflow
1. Create a Mashup UI Module
2. Design UI Screens
3. Test and generate the Mashup UI Module

Mashup UI Module Lifecycle

Status Description

Editing The initial status of the UI Module.


If you modify a module in Generated status, its status reverts to Editing as
soon as you save your changes.

Generated The UI Module is complete and has been generated.


Only modules in Generated status can be used to configure a UI Application.

Invalid A new major version of an App has been reloaded, and one of its UI
Components used in the UI Module has consequently been modified or
deleted.

3.10.2.1 Creating a Mashup UI Module


The Mashup page is the Mashup Editor main page and displays the list of Mashup UI modules created for the
current solution.
Each Mashup UI Module contains a default UI Screen, and additional screens can be added.
You can create a Mashup UI Module in various ways:

752 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Creation mode Description

From scratch To create a totally new additional Mashup UI Module.

Copy To copy an existing Mashup UI Module.

Restore To restore a Mashup UI Module created in a previous version.

Import To import a previously exported Mashup UI Module.


UI Mashup Modules can be imported/exported in the form of a JSON file,
which contains all the information required to use the UI Module.
This JSON file must not be manually edited.
When a UI Module is exported, if it contains more than one UI Screen, you
can select which of these will be exported together with the module.

Creating a Mashup UI Module from scratch


1. In the Mashups page, click the Create New button.
2. In the Create New Mashup UI Module pane, enter a name and title to identify the module.
3. In the Mashup Screen Settings area, click either:
• Autogenerate UI Screen name and title, to use default settings to create the initial UI Screen.
• Customize, to specify the name and title you want to give the initial UI Screen.
4. Enter the name of the icon to be displayed in the application sidebar at runtime. This icon will allow the user to
access the module. As soon as you start typing the icon name or type, the drop down list box is populated with
matching items. For more information on the supported types, see Using Icons.
5. Clear Securable if you want to make this module globally visible, without assigning it to any specific roles.
6. Click Save: the new Module tile is displayed in the Mashups page.

Copying a Mashup UI Module


You can copy a UI Module, by selecting the module to be copied in the Mashups page and clicking . You can
provide a new name, title and icon for the new module, and decide whether it will be securable or not.

Restoring a Mashup UI Module from a previous version


If you want to restore Mashup UI Module created in a previous version perform the following procedure for each
module:
1. In the Mashups page, select the module you want to restore.
2. Click to change its status to editing.
3. Click Save.
4. Click .

Importing a Mashup UI Module


1. In the Mashups page, click Import.
2. Browse for the JSON file of the module you want to import under UI Module Manifest.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 753


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

3. If required, you can provide a new name, title and icon for the new module, and decide whether it will be
securable or not.
4. Click Save.

 To export a UI Module simply select it in the Mashups page, click Export and select which screens you
want to export together with the UI Module.

3.10.2.2 Designing UI Screens


Mashup UI Modules can contain multiple UI Screens.
A default UI Screen is created when the Mashup UI Module itself is created.
UI screens are configurable screens that contain UI and SWAC Components, which can be connected in a wiring
screen.
A Mashup system component is provided to facilitate the configuration of navigation between screens, as well as
the definition of the position, size and visibility of components within a screen.

Workflow
1. Create additional UI Screens.
2. Manage the layout.
3. Add UI and SWAC Components.
4. Connect the Components.
5. Set parameters and contexts.

3.10.2.2.1 Creating Additional UI Screens


Mashup UI Modules can contain multiple UI Screens.
A default UI Screen is created when the Mashup UI Module itself is created.
There are two main ways to create additional UI Screens:

Creation mode Description

From scratch To create a completely new UI screen.

Copy To copy an existing UI Screen and then modify it.


If a UI Screen is added to or removed from a UI Module that has already been associated to a UI Application, you
must reset the UI Application before deploying the solution.

 If a Mashup UI Module has only one screen, this screen can be modified by clicking on the icon in the
tile.

If it contains more than one screen, the pencil icon is not visible, and you must click on the icon to
open the UI Screen page, where you can create, modify, copy, or delete the UI Screens in the module.

Creating additional UI Screens from scratch


1. In the Mashups page, click the module tile where you want to create a new screen and click .

754 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

2. In the UI Screen page of your selected module, click New.


3. In the New Screen pane enter a name and title for your screen.
4. Optionally insert an icon to identify the screen, which will be associated to the screen, but will be displayed in
future versions only.
5. Specify whether the screen will be visible to all authenticated users or only to assigned users by selecting
the Securable flag.
6. Click Create.

Copying an existing UI Screen


You can create a new screen by copying an existing screen.

1. In the Mashups page, click the module tile which contains the screen you want to copy and click .
2. In the UI Screen page of your selected module, click .
3. If required, modify the following fields:
Field Value provided

name <source screen name>_copy

title <source screen title>_copy

icon the source screen icon

securable flag the source screen securable flag


4. Click Save.

3.10.2.2.2 Customizing the Layout of a Mashup Screen


Once you have created your UI Mashup Module you can modify the layout of its screens to correspond to the
behavior you require, such as automatically placing the components at the top of the grid or showing lines between
the rows and columns of the grid.

Procedure
1. In the Mashups page, click the Mashup UI Module tile containing the required screen and click .
2. In the UI Screen page click the screen row you want to modify and click .
3. Click on the Layout Design tab.
4. Use the following command bar buttons to customize your layout:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 755


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Icon Action Description

Configure Layout Design Displays the Configure Layout Design Properties side
Properties panel. The available settings are:
• Number of Columns: the number of columns displayed
in the working area. Default: 12 columns.
If you change the number of columns in a populated UI
Screen, the Mashup Editor will attempt to scale
components accordingly. In some cases this may lead to
the incorrect placement of the components on the
working area, and therefore manual rearrangement may
be required.
• Vertical Margin: the distance (in pixels) between each
component (y axis), when displayed at runtime.
• Horizontal Margin: the distance (in pixels) between
each component (x axis), when displayed at runtime.
• Allow components to be moved and resized at
runtime: if enabled, it will be possible to rearrange and
resize components at runtime but the Pushing, Floating
and Swapping toggles will be disabled.
• Outer Margin: if enabled, the values previously set for
the vertical and horizontal margins around each
component, will also be applied to the whole Mashup
canvas at runtime.
• Enable responsive mode: if enabled
• For small devices: it identifies the threshold
below which the components will be stacked in a
single column.
Default width: 768 pixels, minimum value: 320
pixels.
• For medium devices: the layout of the
components will depend on the user's
configuration of the selected components and
screen size. For example, if the width of a
component is set to less than half of the screen
width value, then two components will be
viewed alongside each other in one row. If the
width is set to more than half of the screen width
value, then only one component will be viewed
on the row.
Default width: 1024 pixels, minimum value: 769
pixels.

Toggle Pushing Pushes components out of the way when dragging or


resizing a component.

Toggle Floating Automatically places the components at the top of the grid if
there is space available.

756 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Icon Action Description

Toggle Swapping Swaps over the components when dragging a component of


the same size (overrides the Pushing behavior).

Toggle Gridlines Shows the lines between rows and columns in the grid.

3.10.2.2.3 Adding UI and SWAC Components to a UI Screen


Mashup UI Modules are created together with a default screen, which is initially empty. However, you can create
new empty screens for your Mashup UI Module.
You can add the following components to the screen, by dragging them onto the working area from the side panel:
• UI Components, developed in Project Studio, and displayed in the Mashups page, grouped by the related
available Apps. These Components are complex widgets that work with a specific data source, for example a
grid containing orders or a chart displaying statistics.
• SWAC (Siemens Web Application Collaboration) Components. These Components are not developed in Project
Studio, and must be imported into the Solution from the SWAC Management page.
You can pin a maximum of five Components for your session to make it easier to work with them. There is no limit to
the number of components you can add to a UI Module, but if you add more than 10 you may encounter
visualization issues during the design phase.

Prerequisite
SWAC Components are available for UI screens if they have been previously imported to Solution Studio
(see Importing SWAC Components).

Procedure
1. In the Mashups page click the required module tile and click .
2. In the UI Screen page, click the screen you want to configure and click .
3. Click on the UI Components tab in the toolbox on the right-hand side, and drag and drop the required UI
Components onto the working area.
4. Click on the SWAC Components tab in the toolbox on the right-hand side, and drag and drop the required SWAC
Components onto the working area.
5. Locate and resize the Components in the available space according to project requirements.
6. Set the default properties for UI Components by selecting the UI Component in the working pane, clicking on
the UI Component Properties tab in the side bar and defining default values for the properties contained in the
Component in the Model area. Any category properties defined for the UI component can be viewed.

 The properties for SWAC Components are not displayed in this tab. However, if you need to set default
values you can manually modify the SWAC Component Manifest, and reload it.

7. Connect the components.

3.10.2.2.4 Setting Parameters and Contexts for UI Screens


Parameters and contexts can be set when connecting components in UI Screens in order to pass data when
navigating between screens.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 757


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

• Parameters are used to define inbound data, when navigating to a Mashup Screen.
• Contexts are used to define outbound data, when navigating from a Mashup Screen. Contexts are automatically
transformed into parameters when you are connecting to a new screen, as they then become inbound
parameters.

Procedure
1. In the Mashups page click the required module tile and click .
2. In the UI Screen page, click the screen row (whose parameters and contexts you want to configure) and click
.
3. Click the Wiring tab.
4. Click to configure Mashup Module parameters.
5. To define new parameters:
• Click the Parameters tab.
• Click Add New Parameter.
• Define the name, type and default value for the inbound parameter from the screen you are navigating
from.
• Click Save.
6. To define new contexts:
• Click the Context tab.
• Click Add New Context.
• Define the name, type and default value for the outbound parameter for the screen you are navigating
to.
• Click Save.
7. Click .

3.10.2.2.5 Connecting Components in a UI Screen


Once you have selected the UI and SWAC Components that will make up your UI Screens, you must connect these
components in order to define how they will communicate.
For each UI Screen, you can specify a set of parameters to be bound to the components you selected, and a context,
consisting of a set of properties, that will be used to trigger transitions to other screens defined in a UI Application.

Procedure
1. In the Mashups page click the required module tile and click .
2. In the UI Screen page, click the screen row and click .
3. Click the Wiring tab.
4. To configure the UI Screen parameters and properties, click the button and set the following parameters
for each new item:
Parameter Description

Name It must be unique within the UI Module.

Type The supported types are:


• String
• Number (both integer and floating point)
• DateTime (includes dates)
• Boolean

758 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Parameter Description

Default (Optional parameter) The parameter default value.

5. Click the button to define a new wiring among the selected components: the system prompts you to enter
both a name and a description that, once inserted, cannot be modified.

 You change change the order in which wires are displayed by dragging and dropping them.

6. The system automatically groups and displays the selected components in the Components tab within the
sidebar according to their possible role:
• only input (components raising events).
• only output (components exposing methods).
• both input and output (components raising events and exposing methods).
Move the components to the working area, the system helps you locate them correctly by highlighting
the proper column (or columns).
If you have configured at least one parameter or context for the UI Screen, a system UI Component
(called Mashup System Component) is also displayed in the Input-Output Components list. Move it to
the working area if you want to use it to define your navigation logic.

7. Select the output component relative to each connection you want to configure.
8. In the Configuration tab, configure the module behavior, establishing a mapping between the events exposed
by the input component (Source Event parameter) and the methods exposed by the output component
(Destination Method parameter).
9. If the type of the event and the command parameters are different, or if you want to customize the conversion
mode, type the relative code in the Code tab.

 Since the system does not perform any checks on the Javascript code, entering incorrect code could
break:
• wiring
• Mashup UI Module
• any UI Application using the Mashup UI Module containing incorrect code

Example - Wire Connection

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 759


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

The following image displays the wire configuration of a Mashup UI Module containing a button as input
component and a grid as output component: whenever the user clicks the button, the grid content is updated
through the refresh command.

If necessary, the system prompts you to configure the parameters required by the selected event and/or command,
displaying them in the Standard tab.
If, in the example above, you select the sortOrders command instead of the refresh one, you must select the field
to be used to sort data (in this case, Id).

3.10.2.2.6 Mashup System Component


The Mashup System Component is a component with no graphical representation, principally used to navigate
between screens, and set the position, size and visibility of components.
To make it easier to use the following information is provided:
• Mashup System Component Methods
• Mashup System Component Events
• Example - Configuring Screen Navigation

3.10.2.2.6.1 Mashup System Component Methods


The Mashup System Component exposes the following methods.

setContext
This method can be called to change the value of one or more contexts defined for the screen.
Its parameters are dynamic, as they depend on the screen whose context you want to change.

760 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Parameter Name Type Description

contexts object An object exposing one property for each context.

navigateTo
This method can be called to navigate to another screen in a UI Application.
It contains the following parameters:

Parameter Name Type Description

screen string The ID of the screen to navigate to.


When navigating to the specified screen, all the contexts
defined above for the screen will be passed as parameters
when performing the state transition.

display
This method can be called to show/hide specific instances of components included in the screen.
It contains the following parameters:

Parameter Name Type Description

UIComponentId string The ID of the component you want to show/hide.


To find out the ID of the component hover over the
required component in the wiring tab.

toggle boolean Defines whether the component is visible or not. If


true the component is displayed.

setPosition
This method can be called to define the physical position and size of a component in a screen.

 Ensure your configuration maintains the component within the grid and doesn't overlap other
components.

It contains the following parameters:

Parameter Name Type Description

UIComponentId string The ID of the component whose position you want


to define.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 761


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Parameter Name Type Description

position object An object with two properties:


row, the number of the row where the
component will be positioned
col, the number of the column where the
component will be positioned

size object An object with two properties:


• x, the number of the columns the component
will occupy
• y, the number of the rows the component will
occupy.

3.10.2.2.6.2 Mashup System Component Events


The Mashup System Component exposes the following methods.

onLoaded
This event is triggered when you navigate to the screen corresponding to the Mashup UI Module.
It contains the following parameters:

Parameter Name Type Description

parameters object An object containing one property for each


parameter defined in the screen.

onContextChanged
This event is triggered when any of the screen contexts changes.
It contains the following parameters:

Parameter Name Type Description

contexts object An object exposing one property for each context.

3.10.2.2.6.3 Example - Configuring Screen Navigation


This example describes how to use the Mashup Editor to implement a simple custom navigation between the
screens of a UI Application, using the Mashup System Component.
This example, shows how to define an external parameter for the screen, and how to configure a component to:
1. retrieve this parameter when the screen is loaded.
2. use this parameter internally.
In our example the following Mashup System Component methods and events are used:
• onLoaded event
• onContextChanged event
• setContext method

762 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

• navigateTo method

 See Mashup System Component Methods and Mashup System Component Events for details.

Prerequisites
You have created a UI Module which includes the following UI Components:
• materialFilter, a list box displaying material data, that is used to provide a filter for the orderGrid component.
• orderGrid, a grid suitable to display order data, optionally filtered by material.
• navButtons, a set of buttons.

Configuration Procedure
1. In the Mashups page click the required module tile and click Open.
2. In the UI Screen page, click the screen row and click Open.
3. Click the Wiring tab.
4. Click the button, and:
• in the Parameters tab, define the MaterialId parameter with number type.
• in the Context tab, define the OrderId with string type and the MaterialId with number type, leaving
the default values empty.
5. Wire the components as follows:
Wiring Result

When the mashup UI Component is loaded, the


value of the MaterialId parameter is passed to the
materialFilter UI Component, and it is selected in
the grid.
The mashup UI Component has been automatically
created by the system when you have defined the
Module parameter and properties. This component is
not displayed in the Mashup Editor but it is displayed in
the Wiring environment.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 763


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Wiring Result

When a material is selected in the materialFilter


component:
• the orders filtered by the specified
material are loaded in the orderGrid
component.
• the value of the Materiald parameter
is saved in the mashup component.

When an order is selected in the orderGrid


component:
• a set of buttons is displayed through
the navButtons component.
• the OrderId of the selected order is
saved in the mashup component.

When a button is clicked, another screen is


displayed according to custom user logic which
includes the name of the target UI State.

Runtime Behavior
At runtime the configured wirings are activated as follows:
1. When the user navigates to the UI State through the relative url (for example, <server>/myscreen1?
MaterialId=73), the onLoad event is triggered passing the value of the MaterialId parameter in input to the
materialFilter list box.
2. When the value of the MaterialId parameter changes to 73, the onMaterialChanged event is fired and then,
consequently to the configured wiring, the following methods are called:
• setContext, setting the value of the UI Module MaterialId property to 73.
• loadOrdersByMaterial, loading the orders filtered by the specified material ID in the orderGrid grid.
3. When the user selects an order in the orderGrid grid (for example A0042), the onOrderChanged event is fired
and then, consequently to the configured wiring, the following methods are called:
• setContext, setting the value of the UI Module OrderId property to A0042.
• displayOrderButtons, displaying a set of buttons dedicated to perform operations on orders.
4. When the user clicks a button, the onButtonClicked event is fired thus calling the navigateTo method, as
configured in the wiring. This method, displays another UI State of the UI Application, passing a url that contains
the values of the properties saved in the UI Module context (for example, <server>/myscreen2?
MaterialId=73&OrderId='A0042').

3.10.2.3 Testing and Generating a Mashup UI Module


Once you have created your UI Module and designed its UI Screens it can be generated in order to use it in a UI
Application.
Before generating the module it is recommended to test its validity.

764 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Constraints
• The Test Run operation will attempt to deploy a test UI Application on the current host, and it will work only if
the engineering service layer is running on the current host.
• In some circumstances the Test Run may fail if access to some files on the web server are blocked by a process
or by IIS itself. If this should happen try executing the Test Run again.

Procedure
1. In the Mashups page select the module you want to test.
2. Click : the system creates and deploys a test UI Application containing the UI Module you have configured
and prompts you to open it in order to verify the UI Module before deploying the whole solution.
3. Once you are ready to generate the Mashup UI Module, select it again in the Mashups page.
4. Click : the system displays a message informing you that the operation has been completed successfully
and sets its status to Generated.

3.10.3 Configuring UI Applications


Solution Studio includes a UI Application editor that allows you to configure project-specific Single Page
Applications, which are containers of UI Modules aimed to fulfill a specific manufacturing need (for example, a
Single Page Application for Master Data Management).
The UI Modules you can use to configure an Application are those included in the imported Apps or are designed
directly in Solution Studio in the Mashup Editor.

Accessing the UI Applications page


To access this page, click the card with your solution in the Solution Studio home page, and click User
Interface in the side bar and then select UI Applications.

Workflow
1. Create a UI Application. For more information on the home page and the Navigation menu visualization, see
Home Cards and Navigation in the Opcenter Execution Foundation User Manual.
2. If required, modify any UI Application properties (for example, to apply Multilanguage).
3. Select the UI Modules.
4. If required, configure the UI Application menu.
5. Test the UI Application.
6. If required, reset the UI Application. This discards all the user configurations and reverts all apps to their original
configuration.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 765


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

UI Application Lifecycle

Status Description

Editing The initial status of the UI Application.


As long as at least one of the assigned Mashup Modules is in Editing status the
UI Application status will also be Editing.

766 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Status Description

Ready All the UI Modules in the UI Application are in Generated status and the
application can be deployed.
If one of the UI Modules reverts back to Editing status, the application will
also revert back to Editing status.

Deployed You have deployed the Application on a specific host.


If you choose to reconfigure a deployed Application, the system resets its
status to Editing as soon as you save your changes.

Invalid A new major version of an App has been reloaded, and one of the UI
Components used in the UI Application has consequently been modified or
deleted.

3.10.3.1 Creating a UI Application


UI Applications are managed in the UI Application editor page in Solution Studio, which displays the list of
applications created for the current solution.
You can create a UI Application in one of the three following ways:
• from scratch
• by copying an existing UI Application
• by importing an existing UI Application.
Once flagged as Deployable the UI Application will be included in the deployment package.

 Localization
In case of localization, it is mandatory to set the proper languages as described below, and modify the UI
Application properties in order to define the UI Framework Localization Master app (see Modifying UI
Application Properties).
In case of localization of system apps, see How to Use Opcenter Execution Foundation in Multilanguage.
In case of localization of custom apps, the resources must have been translated and saved in the App
project files (see Localizing Custom UI Apps and UI Framework Resources).

Creating a UI Application from scratch


1. In the UI Applications page click .
2. In the Create UI Application pane enter a name and title for your application.
3. If necessary, modify the default options for Theme, Logo and Log Level of warnings.
4. If required, you can specify additional languages (Languages edit box) in which your application can be
translated. English is provided by default, and must not be removed, but you can add additional languages, for
example en-US,it-IT,fr-FR, with no spaces between the languages.

 The required language is selected at login from the User Management Component (UMC). For detailed
information on how to perform this operation, see the relative documentation.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 767


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

5. Select Deployable if you want the UI Application to be included in the final deployment package. Only UI
Applications in Ready or Deployed status can be effectively deployed.
6. Select DataSegregation to display the data segregation tags assigned to the user in the runtime application.

 This option is available only if the Data Segregation App is installed in the solution (for more
information see Data Segregation App in the Opcenter Execution Foundation User Manual). If the option
is selected, and the Data Segregation App is then removed from the solution, the option will be reset.

7. If necessary, change Home Page Type by choosing one of the following options:
• Single Page with Quick Search (selected by default): The Home page contains the Home Cards on the
top and the Home Tiles below. The Search filter is available on top of the page to filter by the Home Tiles.
• Multi Page: The Home Page contains the Home Cards only. When the user clicks on a Home Card, a new
page is shown with the Home Tiles of the associated UI Screens.
• Custom: A UI Screen is set as Home page. In this case no Home Cards or Home Tiles are present.
8. If necessary, change settings for Home Page Configuration, not applicable to the Custom Home page. You can
choose either of the following:
• Configuration per Top Menu (selected by default): In the Home page, the configured categories are
displayed as Home Cards and the associated screens are displayed as Home Tiles. You can view the
configured categories in the sidebar menu. The side bar will also have the same menu structure as the
home page (categories > associated screens).
• Configuration per Menu Item: In the Home page, the categories that are associated with a screen are
displayed as Home Cards and its corresponding screens are displayed as Home Tiles. The side bar
displays the associated modules and corresponding screens.

 For more information on the home page configuration types, see Home Cards and Navigation in
the Opcenter Execution Foundation User Manual.

9. If necessary, choose a different Home Card in the Default Home Card category list. This setting can be applied
only if Home Page Type is either set to Single Page with Quick Search or to Multi Page.
10. Click Create.

Copying a UI Application
1. In the UI Applications page click .
2. Modify the values proposed for the new Application as required, such as the title or languages.
3. Click Save. It will be saved in the UI Applications page, together with all its copied modules.

Importing a UI Application
Previously exported UI Applications can be imported into the solution. UI Applications are exported by selecting
them in the UI Applications page, and clicking .

1. In the UI Applications page click .


2. Browse for the JSON file of the application you want to import from the UI Application Manifest.
3. Modify the values proposed for the new UI Application as required, such as the title or languages. Note that the
JSON file must not be manually modified.
4. Click Save.

3.10.3.2 Modifying UI Application Properties


You can modify the UI Application properties such as title, logo, log level, languages, deployable, enable home card
property and the UI Framework Localization Master app.

768 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Procedure
1. In the UI Applications page select the required UI Application.
2. To modify the UI Application properties, click .
3. Modify the needed information for Title, Theme, Logo, Log Level, Languages, UI Framework Localization
Master, Deployable, Home Page Type, Home Page Configuration, Default Home Card. See Creating a UI
Application for the description of the UI Application properties while for UI Framework Localization Master
see below.
4. Click Save.

UI Framework Localization Master App - Deprecated


The UI Framework Localization Master app property can be set only during the edit phase (and not during the UI
Application creation phase). Master App list box is optional, since it is a deprecated functionality. if you select the
Master App that includes the common UI Framework files you have previously copied, the resource file available in
the UIFramework zip will not be considered and the Locale file in Locales folder will not be considered.
In case of localization, to localize the UI Framework file see Copying the localized UI Framework Resources instead
of translating via Master app.
After adding UI Modules to the UI Application, the UI Application may contain modules that derive from different
Apps. UI Framework resources may have been defined for each App and each App may have been used inside
different UI Applications. Consequently, at UI Application level, it is necessary to specify which App contains the
common resources that must be applied to the whole UI Application, by specifying the correct App name from the
UI Framework Localization Master list.

3.10.3.3 Selecting UI Modules


Once you have created the UI Application, it is effectively an empty container, which must be populated with UI
Modules.
When you have selected and added the required UI Modules, you can subsequently configure how these UI Modules
and their screens will be displayed in the menu.

Prerequisites
• The UI Module ExportImportAdmin must be associated to the selected UI Application in order to import and
export the related entities and instances.
• Only UI Modules in generated status can be added to a UI Application.

Procedure
1. In the UI Applications page, click the UI Application tile and click .
2. Click Associate UI Modules (if no modules are associated yet) or click .
3. In the Associate UI Modules pane select the required UI Modules, from among those included in the entire
Solution, and click Associate.
4. Click Save.

You can remove associated modules by selecting them and clicking .

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 769


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

3.10.3.4 Configuring the UI Application Menu


Once you have selected which UI Modules will be part of the UI Application, you can see the screens arranged in a
tree structure based on the home page configuration selected, i.e. Per Top menu or Per menu item.
If Per Menu item or custom configuration is selected, each UI Module acts as a folder for its screens, and you can
also add additional new folders to group screens as appropriate, and drag and drop screens between folders.
For Per menu item mode, it is possible to assign screens from different UI Modules to the same category.
If Per Top menu mode is selected, the default category set during creation acts as a folder for all the screens, and
you can also add additional categories/Home cards from the set of 14 available home cards, to group screens as
appropriate, and drag and drop screens between categories. Home cards are predefined and cannot be
customized.
Additionally, irrespective of the mode selected, you can choose the screen icons that will be displayed in the
sidebar menu.
At runtime the home cards are displayed within the home page, providing access to the associated UI Module
screens.
When you install/reload an extended App that affects the previously created UI Application, the changes will be
reflected automatically to the sidebar menu with the extended UI screens.

Procedure
1. In the UI Applications page, click the UI Application tile whose menu you want to configure and click .
2. If modules are present, click to configure the sidebar menu.
3. In the Sidebar Configuration pane, select the folder or screen you want to modify and set the following
parameters:
Parameter Description

Title Enter a title for the folder or screen as required. (The title for the
categories in case of per top menu configuration cannot be
modified).
Note: If the title is edited by the user, the runtime application
displays the edited title in the Navigation sidebar and the home
page. The title will not be translated in such a scenario.
Note: If you have chosen the Custom Home Page Configuration, in
order to have the Custom Folder and Screens properly translated,
you need to provide here a valid resource key.

Header (Read-only) Translation key for the screen title. The key must be
present, together with the required translation, in the application
translation file.
If there is no key provided in this parameter, the Runtime
application displays the value defined in the Title parameter.
Note: This parameter is not available if you have chosen a Custom
Home Page Configuration and you have selected a Custom Folder
or you have chosen Per Top Menu and you have selected a
Category.

770 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure User Interfaces

Parameter Description

Icon Choose an icon from the provided list. Only svg icons are visible in
the UI Application sidebar.
• A Category or a Folder must have cmd icon.
• A Screen must have type icon.

Show in Home Page Select whether or not to display the category, folder or screen in
the runtime UI Application Home page and sidebar. Hidden
elements are displayed in grey in the menu, with a hidden icon
displayed next to them. Screens inherit the visibility
properties of their parent folder, so if the parent folder is hidden,
all its screens are hidden too and cannot be made visible.

Home (Valid only if you have set the Home Page Type to Custom while
Creating the UI Application or Updating the UI Application). Select
whether or not the screen will be used as the runtime application
home page. Home page screens cannot be hidden. Home screens
have a home icon displayed next to them.

Picture for the Home Page (Enabled if a Screen is selected in the Configuration per Menu
Item or a category is selected in the Configuration per Top menu,
while Creating the UI Application or Updating the UI Application
configuration). Select a Home card from the list of pre-defined
home cards.

 The ProcessEngineeringFlow module is for internal use only. For this reason, we recommend that you
do not display the Process Engineering Flow element in the UI Application sidebar and do not use the
related screen as the run-time application home page.

4. In the Sidebar Configuration pane, click to create a new container folder to group screens in the navigation
menu. You can delete a Category only if it does not contain any screen. If you delete any folder, the screens they
contain will be displayed at the top of the menu at the root level, and can be reorganized under different folders.
5. Drag and drop folders and screens to change their position in the menu. Screens can also be moved into
different folders/categories.
6. Click to expand all nodes in menu configuration and click to collapse all nodes in menu configuration.

7. To reinstate the initial configuration, click on group button. Reset All will reinstate all the configurations
done by user. Reset Titles And Icons will reinstate changes in Title and Icon only.
8. Click to reinstate changes of Title and Icon in selected item.
9. Click Save when you are satisfied with your configuration.
10. Click Save and close when you are sure of the configuration and want to close the Sidebar Configuration pane.

3.10.3.5 Testing a UI Application


Once you have created your UI Application and added the required UI Modules it can be deployed with the solution.
It is recommended, but not mandatory, to test the application before deployment.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 771


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

Prerequisite
You can test the UI Application only if you are running Solution Studio directly on the Engineering host.

Procedure
1. In the UI Applications page select the UI Application you want to test.
2. Click . The system creates and deploys a test UI Application containing all UI Modules you have inserted and
prompts you to open it in order to verify the UI Application before deploying the whole solution.

 During the test procedure the system deploys a test UI Application (called __TEST__) on IIS. This
application must be removed before moving to the production environment, by deleting the relative folder
from File Explorer. Client side caching of static files is not enabled for the test run.

3.10.3.6 Resetting UI Applications


The (Reset) button is enabled by default for all UI Applications that are in Ready or Deployed state. It can be
used to reset the UI Application Manifest to its original state. Any changes made by the user in the sidebar
configuration such as icon, title, display, custom folder, home state, order of folder and screens will be lost.

Procedure
1. In the UI Applications page select the required UI Application.
2. Click .
3. Click Ok.

3.11 How to Configure Maintenance


In order to preserve system performance and make long-term data available for querying you can configure a
maintenance registry (containing cleaning conditions and/or cleaning schedules) and a maintenance configuration
(containing the cleaning rules and the archiving rules).
For a general overview of the functionality, see What is Maintenance.

Accessing the Maintenance pages


To access these pages, click the card with your solution in the Solution Studio home page, click
Maintenance in the sidebar and then select one of the following:
• Registry
• Configuration

Available operations
• How to Execute Maintenance on the Live (runtime) Database
• How To Execute Maintenance on the Archiving Database

772 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

 • If you are interested in rebuilding database indexes, see Managing Indexes in Opcenter Execution
Foundation.
• Refer to How to Manually Align the Live Database and the Archiving Database in case of Maintenance
configuration problems.

3.11.1 What is Maintenance


Opcenter Execution Foundation allows you to keep long-term data available for querying, while not affecting the
performance of the live activities and preventing the live (runtime) database from growing uncontrollably.
For this purpose you can define a Maintenance Configuration to:
• Archive production data from the live (runtime) database to an Archiving database
• Clean the live (runtime) database from the entities that are not needed for production anymore
Moreover, you can perform maintenance on the Archiving database to clean data that was previously logically
deleted.

 Opcenter Execution Foundation does not delete data from third-party databases and does not copy it to
the Opcenter EX FN Archiving database. Thus if you autonomously set up your own cleaning mechanism
for third-party databases, you should also set up your own mechanism to preserve this data.
The Maintenance Configuration becomes active only after you build and deploy the Solution.

How to archive data (from the Live database to the Archiving database)
A Maintenance Configuration can contain a Maintenance Archiving Rule, defining how often data will be copied to
the archiving database.
After your application creates, modifies or deletes an entity instance, the system replays the transaction on the
archiving database.
Besides the production data, the Archiving rule also copies the Audit Trail records and the Data Segregation Logs.
For more information, see AuditTrailRecord Entity and AuditTrailRecordCreated Event and Displaying Segregation
Tag Logs in the Opcenter Execution Foundation User Manual.

 Remember that data marked as ToBeCleaned and IsDeleted is differently handled in the Runtime and
Archiving databases:
• IsDeleted: any data that has been logically deleted from the Runtime database (IsDeleted attribute)
will be also logically deleted in the Archiving database. You can physically remove this data from the
Archiving database by means of the PurgeLogicallyDeletedItems Stored Procedure (see below).
• ToBeCleaned: any data that has been marked as ToBeCleaned will be physically removed from the
Runtime database (according the defined scheduling) but will be preserved in the Archiving
database. The value of the ToBeCleaned entity attribute is not copied to the Archiving database.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 773


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

How to clean data from the Live (runtime) database


A Maintenance Configuration can contain a set of Maintenance Cleaning Rules, each referencing:
• an Entity Type referring to the Opcenter Execution Foundation entity type to clean.
• a Cleaning Condition specifying the entity instance to clean.
• a Schedule defining how often the rule will be run.
For each Maintenance Schedule used in at least one Maintenance Cleaning Rule, a periodic Timer will be created to
trigger the cleaning procedure at runtime.
For each Maintenance Schedule, the cleaning procedure will physically remove entities that have been selected by
Maintenance Cleaning Rules and that are no more in use.
The cleaning procedure will find the selected entities and group them into clusters, including all related entities.
A whole cluster will be cleaned if it entirely consists of selected instances that can be cleaned according to the
following table, otherwise no action will be performed.

Entity Model Can be Behavior during cleaning procedure


cleaned

Entities in In Maintenance Cleaning Rules you may select composite entities and not
composition composition parts.
A composite will be cleaned with all its parts, when all the following conditions
apply:
• the Cleaning Conditions apply to the composite and to the parts or the parts
are logically deleted
• neither the composite nor any part is locked/frozen
• neither the composite nor any part is at the One end of relationships with
other locked/frozen instances or instances not selected by rules

774 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

Entity Model Can be Behavior during cleaning procedure


cleaned

Facets (logical In Maintenance Cleaning Rules you may select main entities and not facets.
extension)
An entity will be cleaned with all its facets, when all the following conditions
apply:
• the Cleaning Conditions apply to the composite and to the facets or the
facets are logically deleted
• the owner entity is not locked/frozen
• the owner entity is not at the One end of relationships with other locked/
frozen instances or instances not selected by rules

Derived entities You must explicitly specify derived entities in Maintenance Cleaning Rules.
(physical
A Maintenance Cleaning Rule will just apply to the instances of the selected type,
extension)
with no impact on instances of derived entity types.
The existence of instances of other types that cannot be cleaned will not prevent
the specified entities from being cleaned.

Entities at the Selected instances at the One end of a relationship will be cleaned only after all
One end of instances at the Many end have been cleaned.
relationships

Entities at the Selected instances at the Many end of a relationship will be cleaned.
Many end of
relationships

Locked entities Locked entities cannot be cleaned and they will be ignored during the cleaning
(IsLocked) procedure, together with their parts and facets, if any.
If a locked entity is at the Many end of a relationship, the instance at the One end
will be ignored as well.

Frozen entities Frozen entities cannot be cleaned and they will be ignored during the cleaning
(IsFrozen) procedure, together with their parts and facets, unless they were logically
deleted.
If a frozen entity is at the Many end of a relationship, the instance at the One end
will be ignored as well.

Logically If you define Cleaning Conditions on logically deleted entities, they will be
deleted entities cleaned even if they had been frozen before being deleted.
(IsDeleted > 0)

 Instances cannot be cleaned and will be ignored during the cleaning procedure.
Instances selected in Maintenance Cleaning Rules will be cleaned during the cleaning procedure, if no
other rows in this table prevent it.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 775


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

 The cleaning procedure defined within the Maintenance Configuration affects only the Runtime database.

How to execute Maintenance on the Archiving database


To perform maintenance on the Archiving database, the systems provides you with a stored procedure,
named [dbo].[PurgeLogicallyDeletedItems], which removes all the logically deleted items from the Archive
database. See How To Execute Maintenance on the Archiving Database.

3.11.2 How to Execute Maintenance on the Live (Runtime) Database


To set up data cleaning, you must first define Maintenance Cleaning Conditions (or use the
"All_ToBeCleaned_Entities" built-in Cleaning Condition), Maintenance Schedules and then associate them with
runtime model entities.

Workflow
1. Configure the Maintenance Cleaning Conditions.
2. Configure the Maintenance Schedules.
3. Define the Maintenance Configuration.
4. Associate Entities to Cleaning Conditions and Schedules.
5. Configure the Maintenance Archiving Rule.
6. Enable the Maintenance Configuration, if it is not yet enabled.
7. Build and Deploy the Solution.
In particular, if no custom conditions are needed, an alternative basic workflow based on the built-in condition can
be followed:

Alternative Workflow using the Built-in condition


1. Develop a custom business logic to mark entities to be cleaned.
2. Configure the Maintenance Schedules.
3. Configure the Maintenance Configuration.
4. Associate Entities to the Built-in Cleaning Condition and to Schedules.
5. Configure the Maintenance Archiving Rule.
6. Enable the Maintenance Configuration, if it is not yet enabled.
7. Build and Deploy the Solution.
The default cleaning condition can also be used mixed with custom cleaning conditions.
Marking entities to be cleaned in the custom business logic
Whether you are using the built-in condition ("All_ToBeCleaned_Entities") or your custom conditions based on the
ToBeCleaned attribute, you may want to mark entities for cleaning programmatically.
In cases where the business condition which triggers the cleaning does not depend on standard Entity attributes,
e.g. you want to physically delete a Work Order that has reached a certain Status recorded in one of its attributes,
you can:
1. Develop a command and command handler, where you use the MarkForCleaning method to mark the entity
(or entities) you wish to physically delete.
2. Define an event triggered when the relevant change has been committed (e.g. a business event named
OnStatusChanged).
3. Develop an event handler for the event, where you call the command described at step 1.
4. Subscribe the event handler to the event.

776 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

The maintenance rules defined for the entities you have marked will remove them physically according to their
schedules.
The value of the ToBeCleaned attribute is not copied to the Archiving database.

3.11.2.1 Configuring Maintenance Registry


In this page you can define custom Cleaning Conditions and Schedules which can later be associated to entity
types through Maintenance Rules and will determine which entities will be physically removed from the live
database at runtime.

Accessing the Maintenance Registry page


To access this page, click the card with your solution in the Solution Studio home page, click Maintenance in
the side bar and then select Registry.

Accessing the Registry Panes


From the registry page you can define Maintenance Cleaning Conditions and Maintenance Schedules to be used in
Maintenance Rules.

Tab title Description

Maintenance Cleaning Conditions To create, modify or delete custom Maintenance Cleaning


Conditions.

Maintenance Schedules To create, modify or delete Maintenance Schedules.

3.11.2.1.1 Configuring Maintenance Cleaning Conditions


In this pane you can define custom Cleaning Conditions which can later be associated to entity types and
schedules and will determine which entities will be physically removed from the live (Runtime) database.
Frozen and Locked entities are automatically excluded from cleaning.

Available Operations
• Creating a new cleaning condition from scratch
• Modifying a cleaning condition
• Deleting a cleaning condition

Creating a new cleaning condition from scratch


1. In the Maintenance Registry page, click the Cleaning Conditions tab. A default Cleaning
Condition (All_ToBeCleaned_Entities) is always available by default.
2. In the Cleaning Conditions pane, click .
3. In the Create New Cleaning Condition pane, enter a name to identify the cleaning condition and a description.
4. Define a condition expression as a combination of clauses.
5. Save changes.

Modifying a condition
1. In the Maintenance Registry page, click the Cleaning Conditions tab.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 777


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

2. In the Cleaning Conditions pane, select the row you want to edit and click .
3. Modify name or description if needed.
4. Change the condition expression, if needed.
5. Save changes.

 The built-in Cleaning Condition ("All_ToBeCleaned_Entities") cannot be modified.

Deleting a cleaning condition


1. In the Maintenance Registry page, click the Cleaning Conditions tab.
2. In the Cleaning Conditions pane, click .

 You cannot delete:


• The built-in Cleaning Condition ("All_ToBeCleaned_Entities").
• A Maintenance Cleaning Condition that is used by a Maintenance Rule.

Defining or changing a cleaning condition expression


In the lower part of Create New Cleaning Condition or Edit Cleaning Condition pane, it is possible to define the
cleaning expression.
Every row in the lower part of the page represents a clause, i.e. an elementary true/false comparison between a
system field of an entity and a set value.
Clauses can be grouped together to define their operator precedence.
The whole expression will be used at runtime to remove entities from the live database.
1. Select the field filter you want to use from the Field drop-down list:
• The To Be Cleaned field corresponds to the ToBeCleaned field of entities and, if selected, it must equal
true.
• The Is Logically Deleted field corresponds to the IsDeleted field of entities and, if selected, it must
equal true.
• The Unchanged For field is related to the time passed after the value of the LastUpdatedOn field
of entities.
2. Insert the required value for the clause, either by clicking and manually entering a value, or by clicking
and selecting the value from a list of possible values.
3. If you want to group clauses, click for each filter clause you want to group, and then select And or Or for the
first clause in the group.

 To add new clauses click , and select whether the new clause is additional or in alternative to the
first clause by selecting And or Or. To remove existing clauses, click .
You can define up to ten clauses for each cleaning condition.

3.11.2.1.2 Configuring Maintenance Schedules


In this pane you can define maintenance schedules which can later be associated to entity types and cleaning
conditions and will determine when entities will be physically removed from the live database at runtime.

778 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

Available Operations
• Creating a new maintenance schedule from scratch
• Modifying a maintenance schedule
• Deleting a maintenance schedule

Creating a new schedule from scratch


1. In the Maintenance Registry page, click the Schedules tab.
2. In the Schedules pane, click Create New.
3. In the Create New Schedule pane, enter a name to identify the maintenance schedule.
4. Enter a start date and, if the schedule must expire at a fixed date, an end date.
5. Enter the time of the day when the maintenance occurs and the time zone.
6. Set the Schedule Mode value by selecting either of the following options:
• Daily schedule, if the maintenance will be triggered every X number of days.
• Weekly schedule, if the maintenance will be triggered every week, at the specified day/s.
7. Specify the recurrence value according to the chosen schedule mode: either as a number of days or as specific
week days (for example, to trigger the maintenance either every 4 days or every Monday and Thursday).
8. Save changes.

 Daylight Saving Time


When the time zone of a maintenance schedule is set, DST settings will apply. Please consider the
following edge cases:
• during spring forward transition to Daylight Saving Time, schedules that are configured to trigger at a
time of the day that does not exist due to the shift will be skipped completely
• during fall back transition, schedules that are configured to trigger at a time of the day that exists twice
will be fired only the first time

Modifying a schedule
1. In the Maintenance Registry page, click the Schedules tab.
2. In the schedules pane, select the row you want to edit and click .
3. In the Edit Schedules pane, modify name if needed.
4. Modify start date, time of the day and time zone, end date, schedule mode and recurrence according to the
selected schedule mode, if needed.
5. Save changes.

Deleting a schedule
1. In the Maintenance Registry page, click the Schedules tab.
2. In the schedules pane, select the row you want to delete and click .

 You cannot delete a Maintenance Schedule that is used by a Maintenance Rule.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 779


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

3.11.2.2 Defining a Maintenance Configuration


You can define a Maintenance Configuration (create, update, delete, enable/disable) and the Maintenance Rules:
the Cleaning Rules, on which cleaning will be based at runtime, and the Archiving Rule, which is used to schedule
the copy of the data to the Archiving database.
The Maintenance Configuration is saved in the Engineering Repository and there can only be one configuration for
the Solution.

Accessing the Maintenance Configuration page


To access this page, click the card with your solution in the Solution Studio home page, click Maintenance in
the sidebar and then select Configuration.

Available operations
In the Maintenance Configuration page:
1. Click the Overview tab to manage the Maintenance Configuration name, description and the enabled/disabled
flag.
2. Click the Rules tab to configure the following rules contained in the Maintenance Configuration:
• Cleaning Rules
• Archiving Rule

3.11.2.2.1 Managing a Maintenance Configuration


To manage your Maintenance Configuration you can execute the following operations in the Maintenance
Configuration page:

Available Operations
• Create a new configuration from scratch
• Modify a configuration
• Delete a configuration
• Enable or disable the configuration

Creating a new configuration from scratch


1. In the Maintenance Configuration page, click Create New.
2. In the Create New Maintenance Configuration pane, enter a name and description to identify the
configuration. Special characters cannot be used.
3. If you want to make this configuration ready to be enabled, select the Enabled check box (see also Enabling the
Configuration at Runtime).
4. Save changes.

Modifying a configuration
1. In the Maintenance Configuration page, in the Overview tab, click .
2. Modify name or description if needed.
3. Save changes.
4. If you want to enable (or disable) the configuration, see Enabling the Configuration at Runtime.

Deleting a configuration

780 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

In the Maintenance Configuration page, in the Overview tab, click .


If your Maintenance Configuration is running and you only want to temporarily stop it, you can use the disable
functionality (see Enabling the Configuration at Runtime).
If your Maintenance Configuration is running and you delete it, the system follows the current maintenance until
you deploy the solution.

3.11.2.2.2 Configuring Maintenance Cleaning Rules


In the Maintenance Configuration you can associate entity types with cleaning conditions and schedules to
determine which entities will be physically removed from the live (Runtime) database.
The entity types you can choose belong to the data models (writing models) of the Master Data and Operational
Data that are referenced by the Apps of your Solution.
According to the selected entity types and their relationships within the data model, the system will automatically
apply the maintenance to some related model objects, as described below in the Maintenance Behavior for Related
Entity Types section.

Prerequisites
• The maintenance configuration to contain the rules has been defined.
• Some custom maintenance cleaning conditions have been defined, if you do not want to use the built-in
maintenance cleaning condition.
• Some maintenance schedules have been defined.

Available operations on Maintenance Cleaning Rules


To manage your Maintenance Cleaning Rules you can execute the following operations in the Rules pane:

Operation Description

Create a new Maintenance Cleaning Rule from To create a new Maintenance Cleaning Rule.
scratch

Modify a Maintenance Cleaning Rule To modify Maintenance Cleaning Rules by changing the
associations of entities with conditions and schedules.

Delete a Maintenance Cleaning Rule To delete a Maintenance Cleaning Rule.

Click on the arrow icon to expand the details of an entity (e.g. in case of parts of composite entities or facets).

Creating a new rule from scratch


1. In the Maintenance Configuration page, click the Rules tab.
2. In the Cleaning Rule panel, click Create New to open the Create New Cleaning Rule pane, where you must
expand all the available panels and enter the required configuration.
3. Expand the Entities panel and select the required entity types, optionally filtering by functional block and entity
name.
4. Expand the Cleaning Conditions panel and select the cleaning condition to apply to the entity instances.
5. Expand the Schedules panel and select the schedule to apply to the entity instances.
6. Save changes.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 781


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

 If you select more than one entity type, one rule will be created for each selected entity type, combined
with the selected condition and schedule.

Modifying a rule
1. In the Maintenance Configuration page, click the Rules tab.
2. In the Cleaning Rule panel, select the rule you want to edit and click .
3. In the Edit Cleaning Rule pane, expand the Cleaning Conditions panel and select a different the cleaning
condition, if needed.
4. Expand the Schedules panel and select a different schedule, if needed.
5. Save changes.

 You can modify multiple rules at once only if they have the same condition and the same schedule.

Deleting a rule
1. In the Maintenance Configuration page, click the Rules tab.
2. In Cleaning Rule panel, select the rule you want to delete and click .

Maintenance behavior for related entity types


When you select an entity type, the system applies the Maintenance Cleaning Rule depending on the entity model
as follows:

Entity Model Maintenance attribute propagation

Entities in composition A Maintenance Cleaning Rule configured for a composite entity


type applies to instances of the composite entity type and to
their part instances. Part entity types cannot be cleaned
independently.

Derived entities (physical extension) A Maintenance Cleaning Rule configured for entity types
participating in physical extension applies to the specified
entity type only. Each entity type must be independently
selected.

Facets (logical extension) A Maintenance Cleaning Rule configured for entity types with
facets applies to instances of the parent entity type and to their
facets.

Entities in relationships A Maintenance Cleaning Rule configured for entity types


participating in relationships applies to the specified entity
type only. Each entity type must be independently selected.

 See How Maintenance Works At Runtime paragraph at section What is Maintenance.

782 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

3.11.2.2.3 Configuring the Maintenance Archiving Rule


In the Maintenance Configuration you can schedule an Archiving Rule to copy data from the live (Runtime) database
to the Archiving database.
The copy operation will start at the time interval specified in the copy rule. Once the rule is activated, you can
suspend it and resume it.

Activating the Maintenance Archiving rule


1. In the Maintenance Configuration page, click the Rules tab and then expand the Archiving Rule section.
2. Click to start archiving.
3. In the Create Archiving Rule pane, specify the required interval (Between 1 minute and 24 hours) and choose if
it is in minutes or hours.
4. Click Save.
The changes will be effective after deploying the solution.

Once the rule is activated, you can either suspend it, or stop it.

 If you stop and start the archiving, you must manually align the database (see How to Manually Align the
Live Database and the Archiving Database), while if you suspend it and resume it, the live (Runtime) and
the Archiving databases are automatically aligned.

Modifying the Maintenance Archiving rule


1. In the Maintenance Configuration page, click the Rules tab and then expand the Archiving Rule section.
2. Click .
3. In the Edit Archiving Rule pane, update the required interval (Between 1 minute and 24 hours) and choose if it
is in minutes or hours.
4. Click Save.
The changes will be effective after deploying the solution.

Suspending and resuming the Maintenance Archiving rule


1. In the Maintenance Configuration page, click the Rules tab and then expand the Archiving Rule section.
2. Do either of the following:
• If the rule has been previously activated and you want to suspend it, click Suspend.
• If the rule has been suspended and you want to reactivate it, click Resume.
While the rule is suspended, the changes are internally stored and when the rule is resumed, the changes will be
copied to the Archiving database. From now on, the synchronization between the live (Runtime) and the Archiving
database is active again.
As for the rule activation or deactivation, also the operations of suspending and resuming an Archiving rule
are effective after redeploying the solution.

Disabling the Maintenance Archiving rule


1. In the Maintenance Configuration page, click the Rules tab and then expand the Archiving Rule section.
2. Click to stop archiving.
3. Click OK to confirm disable the Maintenance Archiving rule.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 783


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

The changes will be effective after deploying the solution.

 If you stop and start the archiving, you must manually align the database (see How to Manually Align the
Live Database and the Archiving Database), while if you suspend it and resume it, the live (Runtime) and
the Archiving databases are automatically aligned.

3.11.2.3 Enabling a Maintenance Configuration at Runtime


To start (or stop) maintenance at runtime, you must enable (or disable) the Maintenance Configuration as follows:
• if you are creating a new maintenance configuration, open the Maintenance Configuration page, follow steps
described at Defining a Maintenance Configuration and enable the configuration in the New Maintenance
Configuration side pane by selecting the Enabled check box.
• if you are modifying an already existing configuration, open the Maintenance Configuration page and click

to enable/disable the configuration status on the command bar.


In both cases, if you want to apply the maintenance at runtime, you must build and deploy the Solution.

 See How to Manually Align the Live Database and the Archiving Database to check the use cases that
require a manual alignment of the databases.

 Interaction between Cleaning and Archiving rules


• When maintenance is enabled, the system will clean the entities from the live database as specified in
the Maintenance Cleaning Rules and it will copy data from the live database to the archiving database
as specified in the Maintenance Archiving Rule.
• If you configure the Cleaning Rules, it is strongly recommended to also configure the archiving
database and the Archiving Rule to always make cleaned data available for querying.
• If both the Maintenance Archiving Rule and the Cleaning Rules (Maintenance Configuration) are
enabled, the system will clean entities only if they have been copied to the archiving database. If only
the Cleaning Rules are enabled, entities are directly cleaned and no warning is generated.
• If the Archiving Rule is suspended, entities are not archived and consequently the Cleaning Rules do
not clean them. When the Archiving Rule is resumed again, a database alignment is automatically
performed, the entities are archived and the Cleaning Rules will clean them as required.

 Interaction between Cleaning rules and Audit Trail


• If both the Audit Trail and the Cleaning Rules (Maintenance Configuration) are enabled, the system will
clean Audit Trail relevant entities only if the corresponding Audit Trail records have been generated. If
only the Cleaning Rules are enabled, entities are directly cleaned and no warning is generated.

 Interaction between Purge and Archiving rules


• The Purge method does not check whether the Maintenance Archiving Rules have been configured or
not. The data will be removed regardless of whether it have already been archived or not.

784 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

3.11.3 How To Execute Maintenance on the Archiving Database


Opcenter Execution Foundation provides you with a stored procedure, named PurgeLogicallyDeletedItems, which
performs maintenance on the Archiving database by removing all logically deleted items from it. The stored
procedure is provided only inside the Archiving database.

Stored procedure input parameter


You can execute it by specifying the following parameter:

Parameter Description
Name

CorrelationId A Guid that uniquely identifies the current stored procedure execution.

Stored procedure call examples


The following examples show how to call the stored procedure on SQL Server and Oracle.

SQL Server example

EXECUTE dbo.PurgeLogicallyDeletedItems @CorrelationId = '78A93853-D46C-4E6F-


AE47-5AE29CB69FE3'

Oracle example

DECLARE
CORRELATIONID RAW(200);
BEGIN
CORRELATIONID := '46456D5AA83849308B68DDAA543A0A15';

"MyMaintenanceDBArch"."PurgeLogicallyDeletedItems"(
CORRELATIONID => CORRELATIONID
);
END;

 The stored procedure should be executed either by a SQL Server/Oracle Job or by a DBA.

3.11.4 How to Manually Align the Live Database and the Archiving
Database
If you have not configured and enabled Maintenance properly in your Manufacturing Solution, you must perform a
manual database alignment as described in order to ensure the system will correctly archive all the data that will be
permanently removed.
You must manually align the live and the Archiving database in the following use cases:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 785


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Maintenance

• if you have enabled an Archiving Rule after you have already populated the live database,
• if you have disabled the Archiving Rule and the production has proceeded in the meantime,
• if you have disabled/deleted the Maintenance Configuration containing an Archiving Rule and the production
has proceeded in the meantime.

 If you need to temporarily stop the Archiving Rule, we suggest you suspend the Archive Rule and resume it
when needed, instead of disabling or deleting it. In this case, the manual alignment must not be
performed.

The described procedure is provider-specific.

Provider Procedure

SQL Server 1. In Solution Studio, stop the runtime hosts.


2. In Solution Studio, in the Maintenance pages, enable Archiving (both the
Maintenance Configuration and the Archiving Rule must be enabled).
3. In Solution Studio, in the Data Sources page, configure the Archiving tile:
set it to a catalog that does not exist yet.
4. Make a backup of the live (runtime) database as described in the SQL
Server documentation.
5. Move the backup file where needed. For example, to another database
server.
6. Restore the backup file, with the catalog name previously configured in
Solution Studio as Archiving database (step 3).
7. In Solution Studio, build the Solution Package, deploy to the hosts,
update the database by using the procedure described at page Deploying
the Solution Package to Hosts. This will set the restored catalog as the
Archiving database for this specific live database.
8. Start the runtime hosts.

786 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

Provider Procedure

Oracle 1. In Solution Studio, stop the runtime hosts.


2. In Solution Studio, in the Maintenance section, enable Archiving (both the
Maintenance Configuration and the Archiving Rule must be enabled).
3. In Solution Studio, in the Data Sources page, configure the Archiving tile:
set it to a schema that does not exist yet.
4. In Solution Studio, build the Solution Package, deploy to the hosts,
update the database by using the procedure described at page Deploying
the Solution Package to Hosts. This will create the Archiving schema on
Oracle (with no data) for this specific live database. Do not start the
runtime hosts yet.
5. Use the Oracle Data Pump to export the Manufacturing Solution data
from the live database. System tables must be excluded from the export
operation, as shown in the following example: expdp system/<system
password>@<database name> schemas='\"<live schema>\"'
directory=DIRECTORY_NAME dumpfile=exporteddata.dmp
logfile=exporteddata.log EXCLUDE=TABLE:\"LIKE N'__%' ESCAPE
N'_'\".
6. Move the exported file where needed. For example, to the Archiving
database server.
7. Use the Oracle Data Pump to import data from the exported file to the
Archiving schema. Use the CONTENT=DATA_ONLY option to import only
data, and specify the remap_schema option with the live and Archiving
schema names (step 3). See the following snippet as general example:
impdp system/<system password>@<database name>
schemas='\"<live schema>\"' remap_schema='\"<live schema>\":
\"<archiving schema>\"' DIRECTORY=DIRECTORY_NAME
CONTENT=DATA_ONLY DUMPFILE=exporteddata.dmp.
8. Start the runtime hosts.

3.12 How to Configure Deployment Settings


Once you have performed all App configuration steps, you must check how your configurations will be deployed in
the runtime environment, making any necessary modifications to worker roles and the default configuration for the
Opcenter EX FN database and, if necessary, adding third-party data sources.
As a result of this operation, a unique data model (including entities from both the Opcenter EX FN reading model
and from the third-party reading model, if available) is exposed on the Service Layer, allowing you to run queries
involving all these entities.
The system merges and publishes on the OData Service (Opcenter EX FN Service Layer) the entities of Opcenter EX
FN read data model together with the entities of any additional third-party data model, by means of the assemblies
you previously generated.
The assemblies of the Public Object Model are created at the end of the App modeling phase. The assemblies of the
third-party data model are created once the model project of the Functional Block (specific for User domain) is
built.

Accessing the Settings pages


To access these pages, click the card with your solution in the Solution Studio home page, click Settings in the
sidebar and then select one of the following:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 787


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

• Data Sources
• Worker Roles

Available Operations
Solution settings cover two main areas:
• Configuring data sources
• Configuring worker roles

3.12.1 Configuring Data Sources


Before deploying the solution, you must configure the default Opcenter Execution Foundation database in order to
create database objects either inside a MSSQL repository or inside an Oracle database.
Depending on the data provider type, you have to set the appropriate configuration.
You can configure the data sources that you want to use as your live or archiving data source by entering the
parameters or by selecting one of the Opcenter EX FN data sources you defined using the Opcenter Execution
Foundation Configuration tool and changing the parameter values as needed.
The database type for the live and for the archiving database must be the same and they cannot be mixed (i.e. you
cannot have the Opcenter Execution Foundation database on SQL Server and the archiving database on Oracle). If
you want to change an existing configuration (e.g. from SQL Server to Oracle, or vice versa), you must change first
the live database configuration otherwise an error will block you.
If you have imported views from an external data source by means of dedicated Functional Blocks, you must
configure the external data source here by typing in the required parameters or by selecting one of the third party
data sources you defined using the Opcenter Execution Foundation Configuration tool and changing the parameter
values as needed.

 If you have deployed Signal Rules in the Signals App, and subsequently change the data source, alignment
problems will occur.
Consequently, before changing the data source you must delete all the deployed Signal Rules (see How to
Manage Signals Rules in the Opcenter Execution Foundation User Manual. First ensure that you have
backed-up all the Signal Rules by exporting them, and, if you want to continue working on the same
solution configuration, re-import them after changing the data source.

Configuring Opcenter Execution Foundation data sources


1. In the Data Sources page, select the Runtime DB tile and click .
2. Select the data provider type (either MSSQL or Oracle).
3. According to the just selected data provider, type in or select the required value either from the Database
Server Instance or from Server Name list box.
4. Configure the live database by entering the following parameters:
Parameter Description

Descriptio A description of the data source.


n

788 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

Parameter Description

Data (MSSQL only) The SQL Server instance name (i.e. <SQL Server machine name>\<SQL Server
Engine instance>). If you are in SQL Server Cluster, the SQL Server instance is preceded by the virtual
Instance node.
You can create the database on a remote SQL Server instance (if this has been properly
configured) or in SQL Server Cluster (for the required procedures see the Opcenter Execution
Foundation Installation Guide). If you do not enable the SQL Server Browser service (as
described in Opcenter Execution Foundation Installation Guide), also specify the port of the
instance as follows: <SQL Server machine name>\<SQL Server instance>,<PortNumber>.

Initial (MSSQL only) The name that will be assigned to the database. It is set by default to the
Catalog Solution name.

Server (Oracle only) The Oracle server name. You can create the database on a remote Oracle
Name server (if this has been properly configured).

Database (Oracle only) The name of an existing database.

Schema (Oracle only) The name that will be assigned to the schema. The schema will contain all model
objects as a collection of tables/views.
It cannot contain dots (.) or begin with the letters "sys".

Connectio The timeout for the database connection (in seconds). The minimum value that this timeout
n Timeout can assume is 0, where 0 on SQL Server/Oracle means that the Connection timeout is infinite.
Consequently, if you set this timeout to 0, it means that you do not apply any timeout here
and the value of the worker role Command timeout is applied. The default value is 15
(seconds).

Command The execution timeout (in seconds) of any database statement (such as for example a Submit
Timeout or a Delete operation). This timeout must not be confused with the timeout of the worker role
Command. The timeout applied to a worker role Command refers to the entire Commands'
chain (i.e. the chain of Commands invoked by a root Command) and cannot be exceeded by
the database statement timeout. Consequently, the maximum value that you can set here for
the database statement is 3 hours (10800 seconds), which corresponds to the maximum value
of the worker role Command timeout. The minimum value that this timeout can assume is 0,
where 0 means that the Command timeout is infinite. Consequently, if you set this timeout to
0, you actually do not apply any timeout here, and the timeout of the worker role Command
will be applied. The default value is 30 (seconds).
5. Click Save.

Configuring Opcenter Execution Foundation Archiving data sources


1. In the Data Sources page, select the Archiving DB tile and then click .
2. Select the same data provider type you selected for the Opcenter EX FN data source (either MSSQL or Oracle).
3. According to the just selected data provider, type in or select the required value either from the Database
Server Instance or from Server Name list box.
4. Configure the archiving database by entering the required parameters (for the description, refer to the
parameters described above for the Opcenter EX FN data source).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 789


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

 See How to Manually Align the Live Database and the Archiving Database to check the use cases that
require a manual alignment of the databases.

 Constraints:
• The archiving database is created/updated together with the Opcenter EX FN database during the
deploy procedure (see Deploying the Solution Package to Hosts), only if all these conditions are met:
• both the Opcenter EX FN database and the archiving database are configured
• the Maintenance Configuration has been enabled
• an Archiving Rule has been activated
• The archiving and the Opcenter EX FN database (live database) cannot be the same database.
• The archiving and the Opcenter EX FN (live database) must have the same data structure and the same
collation.
• Once you have configured and updated an archiving database for a live database, the archiving
database cannot be chosen as archiving database for any other live database.
• Once you have configured and updated an archiving database, this database cannot be reused as live
database.

Configuring external data sources


Execute this procedure if you have imported views from external data sources through dedicated functional blocks.
1. In the Data Sources page, click the tile of the required data source in the Third-Party Repositories area.

 You must define the connection string for all the external data sources from which you have imported
views during the development phase and related to the Functional Blocks specific for external data
sources you have referenced inside your Apps.

2. Click .
3. Set the following parameters by typing or selecting the required value:
Parameter Description

Server Name The data source server instance.


(Oracle only) /
Database Engine
Instance (MSSQL
only)

Initial Catalog The name of the SQL Server data source.


(MSSQL only)

Database Name The name of the Oracle data source.


(Oracle only)

Schema The name of the Oracle schema.


(Oracle only)

790 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

3.12.2 Configuring Worker Roles


The Worker Roles page displays all the worker roles that have been created for your solution, together with details
such as whether they are in use (with commands and event subscriptions) and whether they are deployable.
A worker role contains the list of the commands that each worker will receive from the Manufacturing Service Bus.
These commands are also called root commands, because they represent the starting point of the command
execution chain. Different worker roles cannot execute the same root command, but they can handle the same
event through different subscriptions.
All the sub-commands that are invoked by a root command are all executed by the same worker.

Possible operations
The operations that can be performed in the Worker Roles page are:
• Viewing and editing an existing worker role (to modify some of the worker role configurations).
• Creating a new worker role.

 Here you cannot associate events subscriptions or commands to worker roles (or remove them from
worker roles) as this operation can only be performed in the App Management environment.

Deleting Worker Roles


You can delete Worker Roles as long as they are not "in use". A worker role is "in use" when it contains at least one
published command or an event subscription:

If the Worker Role contains... Delete operation

Published commands or subscriptions

Only protected commands

No published commands, no event subscriptions, no protected


commands

Automation Worker Role


An additional Worker Role, named Automation Group, is displayed if you have installed the Automation Gateway
App. This Worker Role hosts the commands that download and activate the Automation Node configuration to the
Automation Gateway Server.
A lock icon is displayed within the tile to indicate that the set of commands, which are already assigned to this
Worker Role, cannot be changed (i.e. you cannot assign any new commands/event subscriptions or unassign
existing commands).
For this Worker Role, you can only modify the command execution timeout and the command retry number. No
parallel instances of Automation Workers can be run as this Worker Role is set to sequential execution mode by
default. Consequently, you cannot modify the number of Worker instances.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 791


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

3.12.2.1 Parallel vs. Sequential Command and Event Handler Execution


While configuring a runtime worker role you can specify if the instantiated worker will process event and command
handlers in parallel or sequentially.

Parallel worker runtime process


In case of a parallel worker role, each worker can be replicated in order to execute in parallel the flow of command
requests which can increase significantly and create a long queue on the Bus. In this way, you can have a number of
additional identical processes that run the handlers which are needed to execute the incoming requests.
Parallel configuration is designed to optimize performances.
Each worker configured in the Worker Role tries to process up to 10 parallel command requests for each Core that is
present on the machine. Additionally, in a distributed environment, the worker role configuration is replicated on
each runtime node and each node can instantiate the required workers, thus granting load balancing and high
availability (for more information, see Configuring Opcenter EX FN in High Availability in the Opcenter Execution
Foundation Installation Guide). In case of a fatal error impacting any of the parallel Worker Role instances on any
host, the impacted instance is automatically restarted.
As for commands, the worker is also configured to listen to the events that are queued on the Manufacturing Service
Bus.
The same limit configured for the command execution (10 * Number of Cores) applies to the maximum number of
events (with the related single or multiple event handlers) that each worker can handle at the same time (i.e. on a
system with 4 processors, the system will try to handle 40 events, processed at the same time, per worker).
If a worker role is associated with one or more event subscriptions, the worker will execute all the event handlers
that are defined within the subscriptions. If there are more subscriptions for the same event, the worker executes all
the required event handlers in parallel. Multiple event handlers, associated to the same incoming event type, are
executed using different threads as if the were handled as different events; the maximum number of events is
limited by the same amount previously stated and comprehends the number of handlers that are executed at the
same time.
In a parallel configuration, command handlers and events handlers can be executed in parallel between each
other.

Sequential worker runtime process


If you need to execute your business logic sequentially you should use sequential worker roles.
Sequential worker roles handle both commands and events.
As opposed to parallel worker roles, where command handlers and event handlers are executed in parallel
between each others, sequential worker roles guarantee the sequential execution of commands and events
separately (i.e. commands towards commands, and events towards events).
The system ensures that each command handler, as well as each event handler, is executed after the previous
command handler (or event handler, respectively) has returned its response (sequencing) and following a First In
First Out pattern (ordering) to unqueue requests from the Manufacturing Service Bus.
In case of multiple handlers subscribed to the same incoming event, the worker executes the associated event
handlers sequentially but with an indeterminate sequence ordering.
Only one worker process configured in the sequential worker role dequeues one event (or command) at a time,
scheduling each event handler as 'reliable' (overriding the original configuration). This single worker instance is
automatically managed by the runtime infrastructure and you cannot choose on which host it will run.

792 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

To grant high availability for this process, the system implements an active-passive hot-standby mechanism
whereby the worker instance that is executing the handlers is the active instance and the workers on the other
hosts are the passive instances (i.e. they are running but do not execute handlers). Should the active instance fail,
the infrastructure will activate one of the passive workers which starts executing the command and event
requests. During the switch-over there is the possibility that some command requests, or events, are lost. This
happens if they are queued and they go in timeout because the system was not able to unqueue them in time.
In a Stand-Alone environment, in case of a fatal error impacting the only worker role instance connected and
listening to the Manufacturing Service Bus queues, the system tries to restart the worker process anyway.
If a command handler returns a transactional error, an immediate retry is performed (see Command Retry
Management) but in case of system errors or timeouts, no delayed retry will be performed and the successive
command is directly executed.

 This sequential and synchronous behavior is not optimal in terms of performance and system scalability
because sequential long running logics could act as bottlenecks.
Performance slowdown occurs also when you subscribe handlers to the CommittedEvent, because the
worker role applies logics to grant the ordering of the CommittedEvents.
Consequently, you should always carefully evaluate the logic you are planning to execute sequentially.
Moreover, bear in mind that if a command is queued in a sequential worker role, and this command waits
for the completion of another (long-running) command before it, it might go in timeout if the time in the
queue exceeds the timeout limit specified for the worker role.
To grant sequential execution of your business logic, ensure that the commands associated to a sequential
worker role are not at the same time sub-commands of other root commands, possibly associated to
parallel worker roles. In such configuration scenarios, the sequential execution will not be applied as the
same commands will be executed by different processes.

Acknowledgement management and failure management


Commands and Events stay in the Manufacturing Service Bus queue until Workers return an acknowledgement
message.
Workers send acknowledgement messages only if the execution of the Command Handler has completed
successfully, whilst for Events the acknowledgment message is sent according to the configuration of the IsReliable
option in the Event Handler (see Configuring Reliable Event Handlers). If this option is disabled, the
acknowledgement is sent as soon as the subscribed Event Handler (or Handlers) have started (without waiting for
their successful completion). If this option is enabled, the acknowledgement is sent after the related code execution
has finished successfully.
If a worker crashes before completing the execution of the Command Handler, the Command stays in the
Manufacturing Service Bus queue and can be executed by other Workers. Consequently, for Command Handlers
there is never the risk of data loss.
In case of non-reliable Event Handlers, if a Worker crashes before completing the execution of the Event Handler,
the Manufacturing Service Bus removes the Event from its queue and the Event is lost. This risk is averted by
implementing reliable Event Handlers, because if a Worker crashes, another Worker takes over the event execution
in High-Availability.
Sequential workers always execute event handlers as if they were all reliable.
As far as failure management is concerned, we distinguish between an internal failure of the event handler (which
provides a response anyway, and a consequent acknowledgment) and an infrastructural failure (for which the event
acknowledgement is provided as described before).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 793


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

Consequently, according to the worker execution type, event subscriptions are handled as follows.
• Failure management for event subscriptions in parallel workers:
• If an event handler fails during its execution, the event is considered handled and it will not be recovered
by any retry mechanism.
• If an event handler, which is subscribed to an event together with other event handlers, fails, the other
event handlers are executed regardless of the one that failed.
• If the worker process fails while executing one or more event handlers, the pending event handlers that
are marked as IsReliable are recovered and they will be executed again, the event handlers already
completed are not re-executed, the event handlers that are not yet executed will be executed later, and
the event handlers that were in progress during the failure will be re-executed again from the beginning.
• Failure management for event subscriptions in sequential workers:
• If an event handler fails during its execution, the event is considered handled and it will not be recovered
by any retry mechanism.
• If one out of more event handlers, which are subscribed to the same event type (multiple event handlers)
fails, the other event handlers are always executed in a 'reliable' way regardless of the one that failed,
always one at a time.
• If the worker process fails while executing an event handler, the pending (partially executed) event is
recovered and it will be executed again.
• If the worker process fails while executing an event handler belonging to a multiple handler subscription,
only the pending event handlers will be recovered and executed again, the event handlers that are
already completed will not be re-executed, the event handlers that are not yet executed will be executed
later and only the event handler that was in progress during the failure will be re-executed again from
the beginning.

3.12.2.2 Viewing and Editing an Existing Worker Role


In the Worker Roles page you can perform the following operations on existing worker roles:
• view in read-only mode the commands and events that have been assigned to an existing worker role.
• modify the worker role configuration, such as its description, the retry and the timeout values for its commands,
the execution mode.

Viewing existing worker role details


1. In the Worker Roles page select the worker role you want to view and click . The information inserted when
the worker role was created is displayed in read-only mode in the Properties tab.
2. Click Assigned Commands for a read-only display of commands. You can search for specific commands by
name using the quick search function, or by filtering and sorting the command list.
3. Click Assigned Event Subscriptions for a read-only display of assigned event subscriptions, along with the
name of the event and handler that form the subscription. You can search for specific event subscriptions by
name using the quick search function, or by filtering and sorting the event subscription list.
4. Click Assigned Protected Commands for a read-only display of protected commands. You can search for
specific protected commands by name using the quick search function, or by filtering and sorting the command
list.
5. Click Close.

Editing existing worker role configuration


1. In the Worker Roles page select the worker role you want to modify and click .
2. Modify the details you provided when creating the worker role. The name and the target CPU cannot be
modified once a worker role has been created and saved.
3. Click Save.

794 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Configure Deployment Settings

3.12.2.3 Creating a New Worker Role


New worker roles can be created when performing other operations:
• In the App Management page when modifying command configurations or configuring event subscriptions.
• In the Worker Roles page while configuring Worker Roles.
The basic procedure is the same in all cases, except for the target worker role CPU which cannot be freely chosen
when you are assigning commands to a new worker role.

Procedure
1. Click Create New.
2. Enter the following parameters and then click Save:

Parameter Description

Name Enter a meaningful name that allows other users to easily identify the
worker role.

Description Enter a useful description for the worker role.

Execution Mode Set the Execution Mode either to Parallel or Sequential, according to the
required execution logic (see Parallel vs. Sequential Command and Event
Handler Execution). If Sequential mode is selected, some other
configuration options are automatically set by the system and cannot be
modified (i.e. the retry number will be set to 0, and the number of
instances will be set to 1).
For more information, see Command Retry Management.

Deployable Select the Deployable check box to include the worker role in the
deployment package and make it ready for execution on the Runtime
hosts. If no commands or event subscriptions are assigned to the worker
role, it will not be included in the deployment package even if it has been
flagged as deployable.

Number of Instances Specify the number of instances to be created for each worker role, if the
worker role has been flagged as deployable.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 795


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

Parameter Description

Target CPU (Only if you are creating the Worker Role from the Worker Roles page)
Select the Target CPU architecture type for the worker role from the drop
down list.

 This option is not available if you are creating the Worker Role
either from the App Configuration page or from the Protected
Commands Configuration page. In these use cases, if you select
a command, the target CPU of its Command Handler will
drive the Target CPU of the created Worker Role (in particular,
if the selected commands have either anyCPU or x64, the created
Worker role will be x64, on the contrary if the selected commands
have either anyCPU or x86, the Worker Role will be x86). Be aware
that if you select commands with x86 and x64 CPU, it will not
be to possible create any Worker Roles for moving the
commands.

Retry Number Enter a retry number to specify the maximum number of times the
execution of a command will be retried before failing. Possible values
range from 0 to 5, the default value is 3. This behavior is then applied to all
commands assigned to the worker role, but this can be overridden for
specific commands in the commands tab.

Command Timeout Enter a command execution timeout value in seconds. Possible values
range from 10 seconds to 3 hours (10800 seconds), the default value is 30
seconds. This behavior is then applied to all commands assigned to the
worker role, but this can be overridden for specific commands in the
commands tab.

3.13 How to Deploy a Manufacturing Solution


To make all changes available at runtime, you have to build and deploy the solution.

Accessing the Deployment pages


To access these pages click the card with your solution in the Solution Studio home page, click Deployment in
the sidebar and then select one of the following:
• Package Management
• Host Management
• Host Monitoring

Workflow
1. Create the deployment package.
2. (Optional) View deployment package details.
3. Deploy the solution package.
4. (Optional) Check Troubleshooting Deployment Operations.
5. Access the UI Application or, if needed, debug Runtime UI Applications.

796 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

6. (Optional) Monitor Hosts with Host Monitoring.

3.13.1 Creating the Deployment Package


When the App configuration phase is completed, it is necessary to build the solution package, in order to correctly
deploy it on the required hosts.
Similarly to the Functional Block/App/Extension App packages, the solution package applies semantic versioning to
indicate significant changes applied to its sub-packages by increasing either the major or the patch version.
Solution versioning affects the deploy procedure, as described at Deploying the Solution Package to Hosts.
The solution package consists of the following sub-packages:
• Access control configuration
• Application Log
• Audit Trail
• App Name, a package containing the artifacts related to business logic and versions of each installed App in the
package.
• Data Source Configuration
• UI Application Name, a sub package for each UI Application flagged as deployable.
• Maintenance
• Solution runtime configuration

Procedure
1. Click Deployment in the sidebar and then select Package Management, a grid containing the solution
sub-packages is displayed.

 The Build Number column displays the number associated with the last generated package. If no
packages have been generated, the column is empty. The Minification column displays whether
minification is applied or not. For more information on minification, see How to Configure Solution
Studio Settings.

2. Click .

Result
The system updates only the packages containing new or modified data and performs the following operations:
• increases the related version (Build Number column),
• sets the status to Updated,
• performs the minification of the UI Application package based on the Advanced settings configuration,
• increases the Solution semantic versioning depending on which sub-packages have been modified as described
below:
Modified Sub-Package Increased Solution Semantic Versioning

Runtime Application Package patch

Access control configuration patch

Apps major

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 797


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

Modified Sub-Package Increased Solution Semantic Versioning

Runtime Configuration major

Maintenance major

AuditTrail major

AppLog major

 Warning Message:
When specifying a list of supported languages for your UI Application, it is necessary to provide the
respective resource files in the following path:
<setup drive>:\ProgramData\Siemens\SimaticIT\Unified\Engineering\Packages\Resources.
If the resource file is not present in the above path, then the system will display a warning message
reporting the list of missing resource files. Example, if you configure the UI Application to support German
and French languages and the same resource files are missing in the above location, then the following
warning message is displayed: “The <your UI Application name> ui application resource files for de-DE, fr-
FR are not available.”
For more information see, How to Use Opcenter Execution Foundation in Multilanguage.

Available Operations
Operation Description

To force the build (available as a main command grouped under Build,


when all the sub-packages are in Updated status) can be used to trigger a
build when the package has no new or modified sub-packages. For
example, a force build operation is required:
• when all the sub packages are in Updated status and you need to add
new resource packages for the Application Log messages,
• if you have modified the Minification Advanced settings.

To reload the UI localization packages and set the UI applications


to ToBeUpdated (see Building and Deploying Localization Packages ).

3.13.2 Viewing Deployment Package Details


The Host Management page displays:
• a tile for each configured host in the solution and, inside the tile, brief information about the latest deployed
package
• more detailed information about the last deployed package on a selected host
• detailed information about the package that has been built and not deployed yet (deployment package)

798 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

Procedure
1. Click Deployment in the sidebar and then select Host Management.
2. To see the details of the deployment package, click , which is visible if there is at least one package. The
following information is provided on the latest package that has been built:
• solution build name, version and solution build number
• last package update
• detailed information on all the sub-packages (such as App packages and data source configuration) that
make up the solution package.
3. To see the details of the host, select the host tile and then click . The following information is provided:
• the host name
• the host status
• the solution name
• the version number of the last deployed package
• the date/time of the last deployment operation
• the license type in use

3.13.3 Deploying the Solution Package to Hosts


After building a package that contains all solution data and configurations, you must deploy it to the hosts (or to a
subset of them) connected to the target runtime environment.

 Only if you are deploying changes regarding either UI Applications or Role management (i.e. Solution
'patch' version, described at Creating the Deployment Package), you can deploy your solution without
stopping the runtime services.
All the other changes, which correspond to the Solution 'major' version changes, require you to stop the
runtime services (i.e. stop the hosts).
As a general rule, be aware that within the same environment there cannot be hosts that run a different
build number

Consequently, the following deployment order is permitted to minimize downtime in a multi host environment: if
you have host 1, 2 and 3, you can deploy the solution on host 1 and 2 firstly and leave the 3rd host running but host
1 and 2 can be restarted only after host 3 is also aligned.

Preliminary operations
In case of database update, we suggest that you create a backup of the Opcenter EX FN database before
proceeding.

Procedure
1. If you are not deploying the solution package for the first time, make a backup copy of the Opcenter EX
FN database.
2. Click Deployment in the sidebar and then select Host Management.
3. Only in case of Major solution versions, select the runtime host(s) on which you want to deploy the solution and,
if these hosts are running, click to stop any runtime service.
4. With the host(s) selected, click . The system automatically performs on each host the following operations:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 799


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

• copies all .dll files related to commands, command handlers, events, event handlers and related
endpoints into the bin folder of the deployment root directory (%ProgramData%
\Siemens\SimaticIT\Unified\Deploy\bin).
• copies the files related to signals into the Signals folder of the deployment root directory
(%ProgramData%\Siemens\SimaticIT\Unified\Deploy\Signals).
• copies all .dll files related to the data models (Opcenter EX FN and any added third-party data model)
and updates the Information Layer governance in the governance registry.
• copies the configuration of the workers and the related commands and event subscriptions.
• if the package includes at least one UI Application:
• adds the new deployment location to the IIS Configuration.
• copies the generated UI application folder structure from the UI Applications engineering location
to the UI Applications deployment location.
• sets the UI Application status to Deployed.
• if the UI Application had been previously deployed, all its files are replaced.
5. Verify that no errors are displayed in the previously selected host tiles and then click : the system creates
(or updates) the data structures in the Opcenter EX FN database (with any available default initialization values)
and, only if properly configured, it also creates and updates the archiving database.
6. After verifying that no errors are displayed in the previously selected host tiles, select them and then click
to start runtime services.

What to do next
• Proceed with either Debugging Runtime UI Applications or Accessing the UI Application.
• In case of deployment errors, see Troubleshooting Deployment Operations.
• To monitor Commands, post-actions, signals and event subscriptions that have been assigned to the worker
roles, see Monitoring Worker Runtime Instances.
• To monitor the host status, see Monitoring Hosts with Host Monitoring

Available operations
Operation Description

To stop any runtime services on the required host.

To exclude the selected host from the runtime scenario: the host status is
set to Offline. This operation is possible only on stopped hosts.

To enable any previously disabled hosts, select the required hosts and
click .

To view the details of the deployment package. See Viewing Deployment


Package Details.

To view the details of the selected host. See Viewing Deployment Package
Details.

Deployment notes
Take note of the following solution deployment details:

800 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

• Business Logic: The business logic is deployed through the Application Service Layer (for the available Service
Layers, see Configuring the Opcenter EX FN Service Layer Securely in the Opcenter Execution
Foundation Installation Guide).
• SWAC components: If your App includes a UI Module and/or UI Component which has been exposed as a SWAC
Component, the related files are saved after deployment in each UI Application within the
folder %SITUnifiedSystemData%\Deploy\UI\Apps\<UIApplicationName>\<Prefix.Appname>\swac. On each
host modify the source attribute within these files as follows:
• <UIApplicationName>/swac.html/#/home/component/<AppName>/<ComponentName> for UI
Components.
• <UIApplicationName>/swac.html/#/home/<UIModuleName>/<UIScreen> for UI Modules.
• Custom index management: If you have generated custom indexes directly on the database ('custom' indexes
are indexes that have not been created in Project Studio) and the columns affected by the custom indexes must
be modified during a database update operation (i.e. by means of drop and/or alter column operations),
Opcenter Execution Foundation temporarily removes the custom indexes to correctly perform the update
database operation and then recreates them, after columns have been modified.

3.13.4 Accessing the UI Application


At the end of the deploy process, the UI Application is deployed in Internet Information Services and you can access
it the required URL by taking the following steps.

Workflow
1. Open the UI Application in one of the following ways:
• from Solution Studio
• from IIS
• by typing the URL in browser
2. Logon to the UI Application.

Opening the UI Application from Solution Studio


1. Click Deployment in the sidebar and then select Host Management.
2. Click the required host tile.
3. In the UI Applications tab below, you can find the list of the deployed UI applications: click in the extreme
right of the list to directly open, in a new browser tab, the corresponding UI Application.

Opening the UI Application from IIS or browser


Alternatively, you can open the UI Application as follows:
1. Open Internet Information Services (IIS).
2. Expand Default Web Site > sit-ui > runtime node.
3. Right-click<UI Application Name> and select Manage Folder > Browse to open the UI Application main page.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 801


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

Opening the UI Application from a browser


Alternatively, you can open the UI Application as follows:
1. Open a supported browser.
2. Type the following URL: http://<WebServerName>/sit-ui/runtime/<Your Solution Name>.<Your UI Application
Name>.

Logging on to the UI Application


By default, to log on to Solution Studio or to the UI Application, you must enter user and password in an interactive
dialog box.
By means of User Management Component, you can enable different login modes such as for example the
Integrated Windows Authentication (also called Autologin in UMC), PKI and so on.
To properly configure these authentication modes, you must refer to the UMC Web UI User Manual.

Client side caching of static files


Client side caching of static files has been enabled for all the UI Applications. The .svg, .js, .json, .css
and .png extensions are added to the profiles. The default time is set as 30 days.

 Any customizations made on the maximum age for client cache will be reset to the default value every
time a Solution is deployed. See How To Manage Time To Live for Client Cache in the Opcenter Execution
Foundation User Manual.

3.13.5 Debugging Runtime UI Applications


You can debug all the deployed UI Applications by following the steps described below.

Procedure
1. Navigate to the home page of the deployed UI Application (Ex.: "http://.../sit-ui/runtime/(name of the solution)/
index.html#/home/").

802 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

2. In the URL, include the property "?momSwacScreens=swac-debug" (Ex.: "http://.../sit-ui/runtime/(name of the


solution)/index.html?momSwacScreens=swac-debug#/home/").
3. Load the page of interest to debug it.

3.13.6 Monitoring Hosts with Host Monitoring


In the Host Monitoring screen of Solution Studio you can have an overview of the status of all the environment
hosts and the related components.
Information is organized in a grid view: the property types to be analyzed are listed vertically and the scenario hosts
to be compared, with the related statuses, are organized horizontally. The status values are accompanied by status
indicators (such as Running, Pause, Failed and so on...).
In the first three rows directly under the host icons, you can find the names of the hosts belonging to the scenario,
their status, and which host is the Engineering host.
Then, moving downward in the grid, you can find the Availability Group table section, with the information related
to the running Availability Groups: Signal Rules, Timers, the RabbitMQ active instance if RabbitMQ is configured in
Active/Standby, the Sequential Worker Roles. For more information on Availability Groups see High Availability of
Opcenter EX FN Components in the Opcenter Execution Foundation Installation Guide.
On the bottom of the grid, you can find the subsystem information, conveying the status of the connection to the
related servers: the connection to the UMC Ring Server (either the primary or the secondary), the connection to the
Automation Gateway running instance, the connection to the RabbitMQ active instance, the connection to the
system databases.

When clicking on the icon, the systems displays on a side-pane the details about the selected host or
subsystem.

Procedure
1. Click Deployment in the sidebar and then select Host Monitoring.
2. If needed, click the information details icon to view the subsystem detail properties.
3. If needed, click the column you want to highlight to perform comparative analysis operations.

Information details
The following information is available:
• Environment details, such as the environment name, the environment configuration mode (Stand-Alone or
Distributed) and the RabbitMQ configuration mode (Cluster or Active/Standby).
• Host details, such as host name and host status with the related details, host time, and a flag indicating whether
the host is the Engineering host.
• Availability Groups, such as active Signal Manager - Rules and Timers, Sequential Worker Roles and RabbitMQ
leader instance (only if RabbitMQ was configured in Active/Standby).
• Subsystem details related to the configurations returned from the scenario subsystems (see Retrieving
Information from Scenario Subsystems).

 The time differences between the environment hosts (Host Time parameter) must not be greater than 5
seconds, otherwise you may encounter system malfunctioning.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 803


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

 See Functional Limitations in the Opcenter Execution Foundation Release Notes for the Host Monitoring
functional limitations.

3.13.7 Troubleshooting Deployment Operations


For each environment host, the host tile displays the host status, along with the host license information.
If the status is different from Stopped, the system returns the license type in use.
If you click the Details button, if the status is Running, you can also retrieve:
• the number of logical cores of the selected host (this number is strictly related with the required license)
• the license expiration date
• the license type
• or any details concerning possible errors. See Troubleshooting_deployment_operations.

 If one of the following cases occur, runtime host can be run anyway:
• the License Server is not up and running; so, licenses cannot be verified because the License Server is
not responding
• no license has been activated
• the maximum number of seats has been reached
• the license validity has expired.
In these cases, the system will return you:
• a warning message traced with both Event Tracing for Windows and Windows Event Viewer every 20
minutes; in case of Event Tracing for Windows in verbose mode, the system displays the expiration
date
• a warning pop-up in any connected UI.

Troubleshooting Deployment Operations


Failed operation Description of failure Cause of failure Possible corrective
action

Deployment A failure occurred when Connection to the file store is 1. Restore the
uploading the solution interrupted or the database connection.
package server is down 2. Repeat the deploy
operation.

Deployment A failure occurred when Access to the database is 1. Check the security
uploading the solution denied configuration of the
package from the file store system database.
2. Repeat the deploy
operation.

Deployment A failure occurred when The solution package is 1. Recreate the solution
uploading the solution not consistent package.
package from the file store 2. Repeat the deploy
operation.

804 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

Failed operation Description of failure Cause of failure Possible corrective


action

Deployment A failure occurred when Some files (dlls, UI files) are 1. Stop the SIMATIC IT
copying the files to the blocked UAF Service.
deploy folder 2. Restart the SIMATIC
IT UAF Service.
3. Repeat the deploy
operation.

Deployment A failure occurred when System error (full disk, ..) 1. Disable the host.
copying the files to the 2. Analyze the error in
deploy folder the tracer and try to
solve the problem
according to its cause.
3. Repeat the deploy
operation.

Deployment of A failure occurred when Different possible causes: 1. Stop the runtime
Signal Rules deploying the signal rules services on the host
• The system cannot
and the host returns one of that returns the error.
retrieve the files from the
the following errors: 2. Start the runtime
file store or it cannot
services on the host
• Deployment of the correctly write the files on
again.
Signal Rules on the host the target host (perhaps,
failed due to problems with the
• Signal Rules package is access rights).
not aligned • The system encountered
a network disconnection
while deploying signal
rules and one or more
hosts are misaligned after
the connection is
restored.

Database The database is not If you are deploying a solution • For more information
creation/update created/updated that has already been on the destructive
previously deployed, and that changes and the
contains procedure to
potentially destructive chang temporarily allow
es within the data model, the them, see:
system will return errors. • Modifying a
Deployed
Functional
Block.
• Enabling
Potentially
Destructive
Operations

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 805


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

Failed operation Description of failure Cause of failure Possible corrective


action

Database The database is not The connection between the 1. Disable the host
creation/update created/updated host performing the operation 2. Restore the
and the database server is connection to
interrupted or the database the database server.
server is down. 3. Enable the host
4. Repeat the database
creation/update
operation.

Database The database is not The operation is not allowed 1. Disable the host
creation/update created/updated 2. Check the security
configuration of
the database server.
3. Enable the host
4. Repeat the database
creation/update
operation.

Services start During the Start operation, Several issues can cause this Stop runtime services and
one or more workers error then:
encountered a serious
• If this operation
problem, which prevented
completes
the process from starting.
successfully, restart
runtime services.
• If the problem
persists or the host
does not stop,
analyze the log for
more details.

806 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Deploy a Manufacturing Solution

Failed operation Description of failure Cause of failure Possible corrective


action

Services start The solution correctly Several issues may cause this 1. Stop runtime services
started on the host but later error and if the operation
one or more workers then completes
encountered a serious successfully, restart
problem which caused the runtime services.
operation to terminate. 2. If the problem
persists or the host
does not stop,
analyze the log for
more details (see
Persisting System,
Security and
Application Messages
on Microsoft Event
Viewer), then stop the
SIMATIC IT UAF
Service and verify
that no other product
processes (e.g.
workers, Service
Layers) are running.

Any runtime The system returns The This error is returned if a 1. Stop runtime services
operation High Availability Group High-Availability group fails and if the operation
has been terminated on all repeatedly and rapidly within then completes
host because it has been a system-defined time frame. successfully, restart
reached the maximum runtime services.
number of failures in the 2. If the problem
allotted time. persists or the host
does not stop,
analyze the product
logs for more details
(see Persisting
System, Security and
Application Messages
on Microsoft Event
Viewer).
For more information on the applied licensing schema, see What Is the Opcenter Execution Foundation Licensing
Schema in the Opcenter Execution Foundation Product Overview.

Warning Messages on License Acquiring

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 807


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Documentation

Operation Description of the Cause of the warning Possible corrective action


warning

Services start The system returns The The PLM License Server is for 1. Check the syntax used to
host is currently not some reason unavailable while specify the License Server
connected to the PLM the host is starting up and connection string by
License Server if the host cannot be reached. opening the Opcenter
is being automatically Execution
restarted after it was Foundation Configuratio
already running (typically, n tool in edit mode, and
after you have stopped apply the criteria
the SIMATIC IT UAF described in License
Service or you have Server Connection
shutdown the machine). Configuration of the
Opcenter Execution
Foundation Installation
Guide.
2. Check that the Siemens
PLM Licence Server can
be reached on the
network.
3. Check that the Siemens
PLM Licence Server is
running (for example,
from Task Manager >
Services tab).
4. If the previous checks are
successful, restart the
host.

Services start The system This warning occurs if the 1. Check that the license file
returns Unable to acquire system cannot acquire a valid is valid (e.g. the validity is
license for SIMATIC IT license (e.g. if the license validity not expired, the
UAF. is expired, the maximum maximum number of
number of seats has been seats has not been
reached, the license type is not reached, or the license
valid for the server type and so type is valid for the server
on) or if is being manually type and so on).
restarted and it encounters one 2. Repeat all steps
of the connection problems described above for The
described above (see The host host is currently not
is currently not connected to connected to the PLM
the PLM License Server). License Server error.
For more information on the applied licensing schema, see What is the Opcenter Execution Foundation licensing
schema in the Opcenter Execution Foundation Product Overview.

3.14 How to Manage Documentation


Solution Studio includes the Documentation Center, a UI Application from which you can browse and search
Opcenter Execution Foundation documentation.

808 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Documentation

Accessing the Documentation Page


You can access the Documentation Center in either of the following ways:
• Click the Documentation Center card in Solution Studio home page.
• From Windows Apps, select Opcenter Execution Foundation > Documentation Center.
While performing the post-installation procedures, you are prompted to populate the Documentation Center with
the documents released with the product (see Configuring the Documentation Center in the Opcenter Execution
Foundation Installation Guide), or with a subset of them, according to your needs, but you can modify the content of
the Documentation Center at any time by selecting the documents to be displayed (both released with the product
and generated during the development phase).

Available operations
• Load product and custom documentation into the Documentation Center
• Manage documentation releases.
• Search for information in documentation.

3.14.1 Loading Product and Custom Documentation into the


Documentation Center
You can choose which documents you want to be able to access in the Documentation Center (both released with
the product and generated during the development phase).

Prerequisites
You must be a member of the Administrators group on the Documentation Center machine.

Procedure
1. Select Opcenter Execution Foundation > Documentation Center Administration from Windows Apps to open
the Documentation Center Administrator Tool window.

2. Select the Tools > Load Documents command.


3. Click either of the following radio buttons:
• Upload from folder, to upload all the documents in a specific folder.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 809


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Documentation

• Upload files, to upload a single document.

4. Browse to the required file:


• for product documents, go to C:\Program Files\Siemens\SimaticIT\Unified\Documentation\UDOC.
• the path configured in Project Studio for the output file for the custom reference documentation
(e.g. bin\Debug folder of the Model project, for
example Projects\MyFBLibrary\MyFBLibrary\MYFBLibrary.RF.Model\bin\Debug).
5. Click the Load Documents button: the selected documents will be automatically saved in the correct release
folder.
6. To remove previously loaded documents, firstly select the release from the Documents in drop-down list
box, then select the documents from the displayed list and finally select Remove documents.

 Only documents with the Published check box selected will be visible in the Documentation Center.

Deleting the Documentation Data Store


To remove all the imported documents and repository that contains them:
1. In the Documentation Center Administrator Tool, select the Tools > Delete Documentation Data
Store command: you must recreate the data store before repopulating the Documentation Center.
2. To recreate the Documentation Data Store, do either of the following:
• select the Tools > Create Documentation Data Store command.
• reopen the Opcenter Execution Foundation Configuration tool from the Windows Apps > Opcenter
Execution Foundation > Opcenter EX FN Configuration. In this case the Documentation Data
Store will be recreated automatically.

 Error log
If an error occurs you can obtain further information from the log available in the following folder:
%SITUnifiedSystemData%\Documentation.

3.14.2 Managing Documentation Releases


Documents in the Documentation Center are grouped into product releases. You can choose to perform certain
operations on a release as opposed to a single document.

810 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Manage Documentation

Prerequisites
You must be a member of the Administrators group on the Documentation Center machine.

Procedure
1. Select Opcenter Execution Foundation > Documentation Center Administration from Windows Apps to open
the Documentation Center Administrator Tool window.
2. From the Documents in drop-down list box select the release of interest.
3. Select one of the following commands:
• Tools > Publish Release, to publish all the documents in the selected release. If you want to publish only
specific documents within a release, firstly select the release and then select the required document in
the Published column.
• Tools > Unpublish Release, to unpublish all the documents in the selected release. If you want to
unpublish only specific documents within a release, firstly select the release and then unselect the
required document in the Published column.
• Tools > Remove Release, to remove a selected release.

3.14.3 Searching for Information in Documentation


Once imported into the Documentation Center, documents are grouped according to dynamic factors such as
whether you have loaded different products and/or different versions.
If you have loaded more than one version you can choose whether to display the latest versions or all versions by

clicking on .

To access the available documents, click the tile of interest and then click the icon within the tile of the
document you want to read. The document is displayed together with the following sections:
• Contents

• Related Links (Only if you click on )

• Page Information (Only if you click on )

Security Information

Click on to view the Security Information.

Available search functions


The Search function in the Documentation Center is contextualized according to the environment you are in. For
example, within all documents from the Home page, or within a specific version or document according to what
you select in the Documentation Center before searching.
There are two different search functions available from the Search edit box:
• A quick search function suggests pages of interest as you type.
• A full search function when you type the words you want to search by and click enter. The results are displayed
together with a short extract of the document containing the term you are searching by, along with its Release

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 811


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

(version number) etc. You can further narrow down your search results by clicking the and selecting
whether to filter by Release, Document, Category, Audience and Type.

Releases and Categories view


It is possible to view the documents by Releases or Categories.
• Click the Releases tab to view the latest documentation releases.
• Click the Categories tab and select the category of interest to see the documents of interest.

Changing the Documentation Center view


It is possible to change the view of the documentation center.

• Click on the sidebar, select the Settings option and then:


• select the Full Screen Mode option to view Documentation Center in full screen.
• select the Command Labels option to display the name of the command icons in Documentation
Center.

• Click on the sidebar, select the Change Theme option and then select the required theme.

3.15 How to Use Opcenter Execution Foundation in Multilanguage


You can localize Solution Studio and UI Applications in any language.
English is the default language. To localize Opcenter Execution Foundation, choose the proper procedure:
1. Check whether the translation package is available on Support Center at https://support.sw.siemens.com/en-
US/ and:
• if the translation package is available, go to Display Solution Studio and UI Applications in a Default
Language
• if the package is not available, go to Display Solution Studio and UI Applications in a Custom Language
2. If you need to localize Application Log Messages, go to Localizing Application Log Messages.
3. If you also need to localize User Management Component, see Configuring Languages in the UMC Web User
Interface Manual.

3.15.1 How to Display Solution Studio and UI Applications in a Default


Language
You must perform the steps below to display Solution Studio and UI Applications in one of the platform default
languages that you can find on Support Center.

Workflow
1. Download the resources from Support Center. If the required package is not present, go to Generate custom
localization packages.
2. Localize the UI Application.

812 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

3. Localize Solution Studio.


4. Set the runtime language.
5. Configure languages for Login page.

3.15.1.1 Downloading Resources from Support Center


Download one of the available zips as described below.

Procedure
1. Access the product download center at link https://support.sw.siemens.com/en-US/
2. Browse for Opcenter Execution Foundation within the My Products tile list and click the required tile.
3. Click the Downloads tile.
4. Click the Additional Downloads tab and select Opcenter Execution Foundation Localization Resources.
Here, in the left-hand pane, you can select the product major version number and the required language.
5. Download the required zip file.
6. Unzip the localization package in a temporary folder. The zip contains the following files:
• a localization zip for each App or Extension App (e.g.
Siemens.SimaticIT.<AppName>.Resources.<Language>.<VersionNumber>.zip or Siemens.Opcenter
EXFN.<AppName>.Resources.<Language>.<VersionNumber>.zip)
• a localization zip for Solution Studio (SolutionStudio.Resources.<Language>.zip)
• a localization zip for UI Framework
(UIFramework.Resources.<Language>.<ProductVersionNumber>.zip), containing the common files
required for Solution Studio and the UI Applications.
7. Extract the localization zip for Solution Studio and UI Framework.

3.15.1.2 How to Localize the UI Application


You can localize the runtime UI Application into one of the default languages by going through the steps below.
Bear in mind that the procedure on how to copy common UI Framework translations has changed.

Workflow
1. Do one of the following
• use case a) If you are localizing the Solution from scratch, copy the localized UI Framework Resources.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 813


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

• use case b) If you are migrating from a previous version, and if you want to still use the old Master App
procedure (now deprecated), prepare the UI Framework Localization Master App Zip.
• use case c) if you are migrating from a previous version and you do not want to use the Master App
deprecated procedure, copy the localized UI Framework Resources.
2. Set the UI Application to a Default Language.

 If you are passing from the Master App deprecated procedure to the new one (use case c), you must
remove the Master App from the UI Application configuration, otherwise the system will not all display
all translations correctly.

3. Build and Deploy Localization Packages.

3.15.1.2.1 Copying the localized UI Framework Resources


To properly localize the UI Application common elements, you must include the translated UI Framework resources
in the localization zip and then copy it to the required folder.
UI Framework localization package contains the following files
• common.<language>.json
• entitypicker.<language>.json

 Bear in mind the following use cases:


• use case a) If you are localizing the Manufacturing Solution from scratch, take steps below.
• use case b) If you are migrating from a previous version, and if you want to still use the old Master App
procedure (now deprecated), skip the steps below and go to prepare the UI Framework Localization
Master App Zip.
• use case c) if you are migrating from a previous version and you want to pass from the deprecated
Master App procedure to the new simplified one, take steps below but remember to remove the
Master App from the UI Application configuration at step Setting the UI Application to a Default
Language, otherwise the system will not display all translations correctly.

Procedure
1. Copy the UI Framework resource zip file into %SITUnifiedSystemData%\Engineering\Packages\Resources.
The UI Framework zip name must respect the following naming convention
UIFramework.Resources.<language>.V<product version>.

3.15.1.2.2 (Deprecated) Preparing the UI Framework Localization Master App


Zip
This procedure is deprecated and maintained only for compatibility reasons.

814 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

 • If you are localizing the Solution for the first time, you must not follow this procedure as it will be
removed in future versions and it is substituted by the new Copying the localized UI Framework
Resources.
• If you are migrating from previous versions, you can still use it although we suggest that you perform
the new Copying the localized UI Framework Resources.

 App localization packages contain the following folder hierarchy: UI folder > resources sub-folder.
This hierarchy is relevant for the localization procedure and UI resources must always be contained in
the resources sub-folder.

Procedure
1. Decide which App will be set as UI Framework Localization Master inside your UI Application.
2. Locate the files you have previously extracted from the UI Framework zip (or custom generated).
3. Extract files from the localization zip of the UI Framework Localization Master App.
4. Expand the UI folder and then the resources sub-folder.
5. Copy the UI Framework files to the resources sub-folder of the Localization Master App.

6. Zip the UI folder of the Localization Master App and name it exactly with the same name as the original
localization zip file.
7. Verify that the app zip contains the UI > resources folder structure with the just copied common files.

3.15.1.2.3 Setting the UI Application to a Default Language


After you have copied the UI Framework resources, you must set the UI Application language.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 815


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

 • Only if you are still following the deprecated UI Framework localization procedure, you must keep the
UI Framework Master Localization app below.
• If you are passing to the new UI Framework localization procedure, remove the selection from the
Master App.

The procedure applies only if the resource files are localized in one of the platform default languages:
German, French, Simplified Chinese, Spanish, Italian, Russian, Korean and Japanese.

Procedure
1. For each App (or Extension App) that is present in your UI Application, copy the localized zip package
to %ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\Resources.
2. In Solution Studio, in the current manufacturing solution, click User Interface in the side bar and then
select UI Applications.
3. Select the required UI Application tile and click .
4. In the Languages edit box, type the required language code by adding it to the list of the available languages,
without removing en-US.

 When mentioning the language code, we refer to the four-letter code (or two-letter code) used to
represent languages in the ISO 639 standard. E.g. zh-CN, fr-FR, de-DE, it-IT and so on.
Do not remove any language code and always leave at least en-US not to compromise the application
functionalities.
You must use the comma separator, without blank spaces. For example, to display Italian resources, the
string must be en-US,it-IT.

5. (Deprecated step) For compatibility reasons, you can still use the Master App list box to select the App that
includes the common UI Framework files. Note If the UI Framework Master App is selected, any files copied in
the UI Framework zip will be ignored (step Copying the localized UI Framework Resources).
6. Save changes.

3.15.1.2.4 Building and Deploying Localization Packages


After you have properly set the UI Application language and you have manually copied the localization packages to
the required folders, build or reload files and deploy the solution.
In case of UI application resource updates, you can reload the packages and then build and deploy the solution.

Procedure
1. Click Deployment in the sidebar and then select Package Management.
2. If you have only changed the UI localization packages click , the UI applications will be set to ToBeUpdated.
3. Click to build solution packages according to the latest modifications (for details see Creating the
Deployment Package).
4. Deploy the solution packages to the solution hosts as described in Deploying the Solution Package to Hosts.

3.15.1.3 Localizing Solution Studio in a Default Language


Copy the UI Framework common files and the Solution Studio resources to a specific application folder, in order to
change the Solution Studio language to one of the platform default languages (German, French, Simplified Chinese,
Spanish, Italian, Russian, Korean and Japanese).

816 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

Procedure
1. Locate the Solution Studio localization files you have previously downloaded (or custom generated).
2. Copy the Solution Studio localization files to %ProgramFiles%
\Siemens\SimaticIT\Unified\UI\Apps\studio\studio\resources.
3. Copy UI Framework (loose) resource files to %ProgramFiles%
\Siemens\SimaticIT\Unified\UI\Apps\studio\common\resources.

4. Logon to Solution Studio as described at Setting the Runtime Language.

3.15.1.4 Setting the Runtime Language


To display Solution Studio and the UI Application in the required language, you must run the application with an
authenticated user and set the language.
The User Login dialog box of Solution Studio and UI Application supports the selection of a default language.
Nevertheless you may want to configure the language for each UMC user (and skip the selection in the User Login
dialog box) or even avoid any UMC user configuration and use the browser language settings (thus skipping the
selection in the User Login dialog box as well).
The system applies the language settings by checking them in the following order:
1. UMC settings
2. User Login dialog box settings
3. Browser language settings
First the system checks the UMC language settings. If no user language is defined in UMC, then the system applies
the language you choose in the application User Login dialog box. If the language in the login dialog box is left to
Default, the system applies the language defined in the browser settings.
A point to consider regarding the default language setting is that, whenever the system fails to find the default
language, it will switch to the closely matched language available in the application supported languages.
For instance, the application supported languages are: [en-US, en-IN, it-IT].
If the default language is English (United Kingdom) en-UK, and if the system fails to identify it, the application will
automatically use en-US as it is a first closely matched supported language.
In other case, where the default browser language is Italian it, the system will use it-IT.
By default, to log on to Solution Studio or to the UI Application, you must enter user and password in an interactive
dialog box.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 817


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

By means of User Management Component, you can enable different login modes such as for example the
Integrated Windows Authentication (also called Autologin in UMC), PKI and so on.
To properly configure these authentication modes, you must refer to the UMC Web UI User Manual.

Preliminary operation
Do one of the following to set the default language:
• (a) in the UMC user settings, enter the language code in the Language and Data Language edit boxes, as
documented at How to Manage Users in the UMC Web User Interface Manual (e.g. add de-DE for German),
• (b) in the browser settings, choose the required default language (in this way you can avoid to configure each
user language),
• (c) none of these options: you will use the User Login dialog box.

Procedure
1. Open Solution Studio or the UI Application.
2. In the User Login dialog box, enter a properly authenticated UMC user.
3. Do one of the following according to the chosen preliminary operation:
• for option (a), leave the Default value and click Sign In.
• for option (b), leave the Default value and click Sign In.
• for option (c), select the language and click Sign In.

3.15.1.5 Configuring Languages for Login Page


UMC is providing English, French, Spanish, German, Italian and Chinese as Built-in languages.
For additional Languages like Japanese, Russian and Korean you need to provide the translation files (they can be
found on the installation media) in the UMC installation path and then update UMC IDP Configuration so that the
Login page will be properly rendered in the requested language.

Workflow
1. Create and provide resource files with translations.
2. Add new languages.

3.15.1.5.1 Creating and providing resource files with translations


Before configuring a new language, you have to install the resource files that contain the translations for the new
languages.
Copy the resource files to %ProgramFiles%\UserManagement\WEB\IPSimatic-Logon\IDPAuthSite\locales for
the login page of the Identity Provider application. For languages such as Japanese, Russian and Korean the
resource files are available in Instdata\UMC64\resources\loginpage.

3.15.1.5.2 Adding new languages


1. Open UMC web UI interface (for more information, see Quick Start to Using the User Management Component
Web User Interface in the UMC Web UI User Manual).
2. Navigate to IDP Configuration.
3. Select the Language Configuration tab.
4. In the Custom languages area, click Add language.
5. Insert a language identifier and a name with which the language will be displayed in the system. The language
identifier must be compliant with RFC 5645.
6. Click Apply.

818 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

7. Click Save all changes.

3.15.2 How to Display Solution Studio and UI Applications in a Custom


Language
Perform the steps below to display Solution Studio and UI Applications in a custom language, i.e. in any language
that is not available on the Support Center.

Workflow
1. Generate custom localization packages.
2. Localize the UI Application into a custom language.
3. Localize Solution Studio into a custom language.
4. Set the runtime language.
5. Configure custom languages for Login page.

3.15.2.1 Generating Custom Localization Packages


This procedure must be used to:
• localize Solution Studio and Foundation Apps or Extension Apps into a language that is not available on the
Support Center,
• localize custom Apps or Extension Apps

Procedure
1. Choose either of the following:
• In case of custom Apps or Extension Apps, localize the English resource files for Solution Studio, UI
Framework and Apps by referring to How to localize UI App and UI framework resources.
• In case of Solution Studio and Foundation Apps, translate the UI master English files into the required
language. Master English files can be found in the same Support Center section that contains the
translated UI resources, described at Downloading Resources from Support Center.
2. For each App to be localized, create a new empty folder and name it UI.
3. Inside the UI folder, create another empty folder and name it resources.
4. Copy the App localized resources to the resources folder.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 819


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

5. Zip the newly created UI folder, maintaining the sub-folder hierarchy, and name it as follows:

<prefix>.<app name>.Resources.<language code>.V<major version.minor version>.<patch


version for the resource package>.zip

where
• <prefix>, <app name>, <major version.minor version> must contain exactly the same values as the app
package. The <app name> used in the resource zip file name must be always the same as the app name used in
the app zip name. For example, if the app zip is Siemens.OpcenterEX.FN.DefectV01.00.00.zip, the related
resource zip file must be Siemens.OpcenterEX.FN.Defect.Resources.zh-CN.V01.00.00 (and not
Siemens.SimaticIT[...].zip as for the other Foundation Apps).

In case of Extension Apps, translation packages must be created separately. The convention is the same as the
one described for the app, but the the values must be congruent to the Extension app zip file name
(i.e.. <prefix>, <extension app name>, <major version.minor version> must be the same as the ones of the
Extension App).

• the patch version, the version for the resource package which is indicated in the app zip (e.g. V01.01.00). This
value can be different (greater , smaller or equal) in order to permit resource changes (or app changes) without
reloading the corresponding app (or resource) package.
For example, for app version V01.01.00 you can have the following resource versions:
V01.01.00, V01.01.01, V01.01.02 and so on.

If multiple resource packages for the same app are available in %SITUnifiedSystemData%
\Engineering\Packages\Resources with different patch version numbers, the package with the highest patch
version will be automatically used.

• the Resources.<language code> string must be manually added to the resource zip name. The language code
must be a four-letter code based on ISO 639 (e.g. ko-KR) and it must be the same everywhere: in locale files, in
the UI Application settings, in UMC, in browser options (if used) and so on. If you use the two-letter code system,
e.g. ko, the same code must be applied everywhere accordingly (and only if you are not using Foundation Apps).

 If a resource package zip from Application Log localization already exists, then copy the UI folder to the
existing zip.

Examples
App Name Localization Zip Name

Siemens.OpcenterEX.FN.Def Siemens.OpcenterEX.FN.Defect.Resources.ko-KR.V01.01.00.zip
ectV01.01.00.zip

Siemens.SimaticIT.AuditTrail Siemens.SimaticIT.AuditTrail.Resources.ko-KR.V02.01.00.zip
V02.01.01.zip

Next Steps
Proceed in either of the following ways:

820 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

• If the localization language is one of the platform default languages, you must continue with step 2 at How to
Display Solution Studio and UI Applications in a Default Language.
• If the localization language is a custom language, proceed with step 2 at How to Display Solution Studio and UI
Applications in a Custom Language.

3.15.2.2 How to Localize the UI Application into a Custom Language


To localize the runtime UI Application to a custom language, you must go through the steps below.

Workflow
1. Do one of the following
• use case a) If you are configuring the Solution from scratch, copy the Custom Translations for UI
Framework Resources.
• use case b) If you are migrating from a previous version, and if you want to still use the old Master App
procedure (now deprecated), prepare the UI Framework Localization Master app zip.
• use case c) if you are migrating from a previous version and you do not want to use the Master App
deprecated procedure, copy the Custom Translations for UI Framework Resources.
2. Set the UI Application to a custom Language.

 If you are passing from the Master App deprecated procedure to the new one (use case c), you must
remove the Master App from the UI Application configuration, otherwise the system will not display all
translations correctly.

3. Build and deploy localization packages.

3.15.2.2.1 Copying the Custom Translations for UI Framework Resources


To properly localize the UI Application common elements, you must include the translated UI Framework resources
in the localization zip and then copy it to the required folder.
UI Framework localization package contains the following files
• common.<language>.json
• entitypicker.<language>.json

 Bear in mind the following use cases:


• use case a) If you are localizing the Manufacturing Solution from scratch, take steps below.
• use case b) If you are migrating from a previous version, and if you want to still use the old Master App
procedure (now deprecated), skip the steps below and go to prepare the UI Framework Localization
Master App Zip.
• use case c) if you are migrating from a previous version and you want to pass from the deprecated
Master App procedure to the new simplified one, take steps below but remember to remove the
Master App from the UI Application configuration at step Setting the UI Application to a Default
Language, otherwise the system will not display all translations correctly.

Procedure
1. Copy the UI Framework resource zip file into %SITUnifiedSystemData%\Engineering\Packages\Resources.
The UI Framework zip name must respect the following naming convention
UIFramework.Resources.<language>.V<product version>.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 821


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

3.15.2.2.2 (Deprecated) Preparing the UI Framework Localization Master App


Zip
This procedure is deprecated and maintained only for compatibility reasons.

 • If you are localizing the Solution for the first time, you must not follow this procedure as it will be
removed in future versions and it is substituted by the new Copying the Custom Translations for UI
Framework Resources.
• If you are migrating from previous versions, you can still use it although we suggest that you perform
the new Copying the Custom Translations for UI Framework Resources.

 App localization packages contain the following folder hierarchy: UI folder > resources sub-folder.
This hierarchy is relevant for the localization procedure and UI resources must always be contained in
the resources sub-folder.

Procedure
1. Decide which App will be set as UI Framework Localization Master inside your UI Application.
2. Locate the files you have previously extracted from the UI Framework zip (or custom generated).
3. Extract files from the localization zip of the UI Framework Localization Master App.
4. Expand the UI folder and then the resources sub-folder.
5. Copy the UI Framework files to the resources sub-folder of the Localization Master App.

6. Zip the UI folder of the Localization Master App and name it exactly with the same name as the original
localization zip file.
7. Verify that the app zip contains the UI > resources folder structure with the just copied common files.

822 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

3.15.2.2.3 Setting the UI Application to a Custom Language


After you have copied the UI Framework resources, you must set the UI Application language and download the
required locales.
The system provides you with a set of locale files that correspond to the languages that are by default enabled in
Solution Studio (German, French, Simplified Chinese, Spanish, Italian, Russian, Korean and Japanese).

 • Only if you are still following the deprecated UI Framework localization procedure, you must keep the
UI Framework Master Localization app below.
• If you are passing to the new UI Framework localization procedure, remove the selection from the
Master App.

Procedure
1. Download the locale files for the required languages from https://github.com/angular/bower-angular-i18n. For
each language, you have to download two files. For example, if you want to use Dutch, the following files are
required: angular-locale_nl.js, angular-locale_nl-nl.js.
2. Do either of the following:
• If you are planning to elect the Master Localization app, copy the just downloaded locale files to
%ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\Locales.
• If you are not using the deprecated path, copy the downloaded locale files to %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\UIFramework\common\scripts\i18n.
3. For each App that is present in your UI Application, copy the localized zip package to %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\Resources.
4. In Solution Studio, in the current manufacturing solution, click User Interface in the side bar and then
select UI Applications.

5. Select the required UI Application tile and click .


6. In the Languages edit box, type the required language code by adding it to the list of the available languages,
without removing en-US.

 When mentioning the language code, we refer to the four-letter code (or two-letter code) used to
represent languages in the ISO 639 standard. E.g. zh-CN, fr-FR, de-DE, it-IT and so on.
Do not remove any language code and always leave at least en-US not to compromise the application
functionalities.
You must use the comma separator, without blank spaces. For example, to display Dutch resources,
type en-US,nl-NL.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 823


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

7. (Deprecated step) For compatibility reasons, you can still use the Master App list box to select the App that
includes the common UI Framework files. Note If the UI Framework Master App is selected, any files copied in
the UI Framework zip will be ignored (step Copying the custom localized UI Framework Resources).
8. Save changes.

 The resource files available in the package will overwrite any resource files available in the App zip.

3.15.2.2.4 Building and Deploying Custom Localization Packages


After you have properly set the UI Application language and you have manually copied the localization packages to
the required folders, build or reload files and deploy the solution.
In case of UI application resource updates, you can reload the packages and then build and deploy the solution.

Procedure
1. Click Deployment in the sidebar and then select Package Management.
2. If you have only changed the UI localization packages click , the UI applications will be set to ToBeUpdated.
3. Click to build solution packages according to the latest modifications (for details see Creating the
Deployment Package).
4. Deploy the solution packages to the solution hosts as described in Deploying the Solution Package to Hosts.

3.15.2.3 Localizing Solution Studio into a Custom Language


You can localize Solution Studio into a custom Language and, if needed, the sidebar menu, by performing the steps
described in the procedures below.

Workflow
1. Localize Solution Studio screens.
2. Localize Solution Studio sidebar menu.

Localizing Solution Studio screens


1. Download the locale files for the required language from https://github.com/angular/bower-angular-i18n. For
each language, you have to download two files. For example, if you want to use Dutch, the following files are
required: angular-locale_nl.js, angular-locale_nl-nl.js.
2. Copy the downloaded locale files to %ProgramFiles%
\Siemens\SimaticIT\Unified\UI\Apps\studio\common\scripts\i18n.
3. Copy localized Solution Studio resource files to %ProgramFiles%
\Siemens\SimaticIT\Unified\UI\Apps\studio\studio\resources.
4. Copy localized UI Framework resource files to %ProgramFiles%
\Siemens\SimaticIT\Unified\UI\Apps\studio\common\resources.
5. Navigate to %ProgramFiles%\Siemens\SimaticIT\Unified\UI\Apps\studio.
6. Open the studio-config.js file in edit mode and type the code of the language you want to load, without
removing any other available code. For example, to display Dutch you must modify the configuration file by
adding 'nl-NL' to the language list:

'languages': ['en-US', 'it-IT', 'fr-FR', 'de-DE', 'es-ES', 'zh-CN', [...], 'nl-


NL'],

824 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

Localizing Solution Studio sidebar menu


You can translate the Sidebar Menu in Solution Studio by performing the steps below:
1. Navigate to %ProgramFiles%\Siemens\SimaticIT\Unified\UI\Apps\studio\assets\config and create language
specific localized file i18n_language.json if it is not listed in the folder. For example if you need support for
Dutch language used in Netherland, create a copy of existing i18n.json and rename it to i18n_nl_NL.json.
2. Open the newly created file in a text editor and search for containerMessages javascript object in the file. The
entire content in this object needs to be translated in the desired language, for example in
the i18n_nl_NL.json file, the containerMessages object will appear as:

"containerMessages": {
"administration": "Administratie",
"appManagement": "Applicatiebeheer",
"account": "Account",
"auditTrail": "Audit trail",
"maintenance": "Onderhoud",
"userInterface": "Gebruikersinterface",
"settings": "Instellingen",
"deployment": "Implementatie",
"users": "Gebruikers",
"groups": "Groepen",
"role": "Rollen",
"registry": "Register",
"configuration": "Configuratie",
"swacComponents": "SWAC Components",
"mashups": "Mashups",
"uiApplications": "UI-toepassingen",
"dataSources": "Gegevensbronnen",
"workerRoles": "Worker Roles",
"packageManagement": "Pakketbeheer",
"hostManagement": "Hostbeheer",
"hostMonitoring": "Hostbewaking",
"general": "Algemeen",
"advanced": "Geavanceerd",
"logout": "Uitloggen",
"home": "Huis",
"about": "Over",
"help": "Helpen"
}

3. Add the new language entry in the installedLocales.json file in %ProgramFiles%


\Siemens\SimaticIT\Unified\UI\Apps\studio\assets\config as below:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 825


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

{
"installedLocales": [
"en_US",
"cs_CZ",
"de",
"es",
"fr",
"it",
"ja_JP",
"ko_KR",
"pl_PL",
"pt_BR",
"ru_RU",
"zh_CN",
"zh_TW",
"nl_NL"
]
}

3.15.2.4 Setting the Runtime Language for Custom Languages


To display Solution Studio and the UI Application in the required custom language, you must run the application
with an authenticated user and set the language.
The User Login dialog box of Solution Studio and UI Application does not directly support the selection of a custom
language and consequently you must either configure the language for each UMC user (and skip the selection in the
User Login dialog box) or avoid any UMC user configuration and use the browser language settings (thus skipping
the selection in the User Login dialog box as well).
The system applies the language settings by checking them in the following order:
1. UMC settings
2. Browser language settings
First the system checks the UMC language settings. If no user language is defined in UMC, then the system applies
the language defined in the browser settings.
By default, to log on to Solution Studio or to the UI Application, you must enter user and password in an interactive
dialog box.
By means of User Management Component, you can enable different login modes such as for example the
Integrated Windows Authentication (also called Autologin in UMC), PKI and so on.
To properly configure these authentication modes, you must refer to the UMC Web UI User Manual.

Preliminary operation
Do either of the following to set the default language:
• (a) in the UMC user settings, enter the language code in the Language and Data Language edit boxes, as
documented How to Manage Users in the UMC Web User Interface Manual (e.g. add nl-NL for Dutch),
• (b) in the browser settings, choose the required default language (in this way you can avoid to configure each
user language).

Procedure

826 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Manage a Manufacturing Solution in Solution Studio

How to Use Opcenter Execution Foundation in Multilanguage

1. Open Solution Studio or UI Application.


2. In the User Login dialog box, enter a properly authenticated UMC user.
3. Regardless of the preliminary option you have chosen, leave the language to Default and click Sign In.

3.15.2.5 Configuring Custom Languages for Login Page


UMC is providing English, French, Spanish, German, Italian and Chinese as Built-in languages.
For additional Languages like Japanese, Russian and Korean you need to provide the translation files (they can be
found on the installation media) in the UMC installation path and then update UMC IDP Configuration so that the
Login page will be properly rendered in the requested language.

Workflow
1. Create and provide resource files with translations.
2. Add new languages.

3.15.2.5.1 Creating and providing resource files with translations


Before configuring a new language, you have to install the resource files that contain the translations for the new
languages.
Copy the resource files to %ProgramFiles%\UserManagement\WEB\IPSimatic-Logon\IDPAuthSite\locales for
the login page of the Identity Provider application. For languages such as Japanese, Russian and Korean the
resource files are available in Instdata\UMC64\resources\loginpage.

3.15.2.5.2 Adding new languages


1. Open UMC web UI interface (for more information, see Quick Start to Using the User Management Component
Web User Interface in the UMC Web UI User Manual).
2. Navigate to IDP Configuration.
3. Select the Language Configuration tab.
4. In the Custom languages area, click Add language.
5. Insert a language identifier and a name with which the language will be displayed in the system. The language
identifier must be compliant with RFC 5645.
6. Click Apply.
7. Click Save all changes.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 827


Best Practices for Software Development

Best Practices for Developing Business Logic

4 Best Practices for Software Development


It is highly suggested that you go through the following guidelines before you start writing your code:
• Best Practices for Developing Business Logic
• Best Practices for Implementing Queries
• Best Practices for Implementing Reading Functions
• Best Practices for Developing UIs
• Best Practices for Maintaining Project Studio Solution

4.1 Best Practices for Developing Business Logic


To implement business logic, keep in mind the following implementation guidelines:
• Best Practices for Business Continuity
• Best Practices for Submit Operations
• Best Practices for Automation Writing Operations

4.1.1 Best Practices for Business Continuity


In order to support business continuity and minimize the risks of inconsistencies during any planned Windows
updates (see How to Install Windows Updates in Business Continuity in the Opcenter Execution
Foundation Installation Guide), you should develop your business logic by keeping in mind the following best
practices:
• For any critical events, define the related event handlers as reliable because during the stop for maintenance
procedure, the execution of handlers related to unreliable events might not be completed or re-executed.
Unreliable event handlers, indeed, generate temporary queues that are deleted when the process is stopped.
The same happens when the queues that are generated by event subscriptions via
IUnifiedSdkLean SubscribeEvent method are set in either of the following ways:
• with the queueName property set to null or
• with the ListenerOptions.QueueAutoDeletable property set to true.
For more information on these topics, see Configuring Reliable Event Handlers and Developing Third-
Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface.
• Develop command handlers/event handlers by considering that your logic could be re-executed (we
recommend that you implement applications according to the idem potency principles).
• Whenever invoking the SendCommand IUnifiedSdk API, use C# statements to wait for the command
result.

 Remote commands are always out of transaction. This means that, in case of error, no rollback is
automatically performed.
For this reason, we recommend that you use them in a non-transactional context (e.g. in Composite
commands), or in any situation where:
• it is not required an atomic execution of the involved business logic;
• it is possible to deal with the scenario where the same remote call is invoked more than once due to
the retry mechanism of a command handler execution in case of commit failure.
In future implementations, Foundation will provide compensation logics that are now in charge of the
user.
Compensation logic, which is now under the user responsibility, are planned for future implementations.

828 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Developing Business Logic

For more information, see How to Manage Remote Calls

4.1.2 Best Practices for Submit Operations


When implementing submit operations you should:
• Keep transactions (root-commands) as short as possible:
• since every root-command keeps a database transaction open for its entire lifespan, optimistic
concurrency has an increasing risk of failure the longer the root-command;
• submit as few entities as possible in every root-command (the more entities kept in memory, i.e.
submitted, in the same transaction, the longer the submit operation). Try to split operations, which do
not need to be transactional, into several smaller root-command requests.
• Minimize the quantity of submit operations, i.e. try to group the linked entities together into a small number of
graphs which will be submitted.
Example:

// SLOW WAY
var materialDefinition =
Platform.Create<Siemens.SimaticIT.MasterData.Foundation.DataModel.IMaterialDefinition
>();
materialDefinition.Name = "MyEntity";

var bom1 = Platform.Create<Siemens.SimaticIT.MasterData.Foundation.DataModel.IBoM>();


bom1.Name = "Bom1";
bom1.MaterialDefinition = materialDefinition;
Platform.Submit(bom1);

var bom2 = Platform.Create<Siemens.SimaticIT.MasterData.Foundation.DataModel.IBoM>();


bom2.Name = "Bom2";
bom2.MaterialDefinition = materialDefinition;
Platform.Submit(bom2);

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 829


Best Practices for Software Development

Best Practices for Developing Business Logic

// FAST WAY
var materialDefinition =
Platform.Create<Siemens.SimaticIT.MasterData.Foundation.DataModel.IMaterialDefinition
>();
materialDefinition.Name = "MyEntity";

var bom1 = Platform.Create<Siemens.SimaticIT.MasterData.Foundation.DataModel.IBoM>();


bom1.Name = "Bom1";
bom1.MaterialDefinition = materialDefinition;

var bom2 = Platform.Create<Siemens.SimaticIT.MasterData.Foundation.DataModel.IBoM>();


bom2.Name = "Bom2";
bom2.MaterialDefinition = materialDefinition;

// This submit operation will submit the material definition.


// The BoMs are all automatically linked by the
// backward navigation property, so all 3 entities will be submitted at once.
Platform.Submit(materialDefinition);

4.1.3 Best Practices for Automation Writing Operations


The current implementation of the Automation Gateway is based on IOWA, a platform that hides the management
of the field by providing reliable and performant services through its interfaces.
High performances often mean compromises that software designers have to make and when it comes to the
writing mechanism, it is mandatory to deeply understand how it works in order to make the best possible choices.

Writing model
The writing model depends on the data the users want to write. There are two categories of data:
• Internal: no peripheral address is configured i.e. data is only kept in the Process Image
• External: peripheral address is configured e.g. OpcUa address
As shown in the figure below, when internal data is written, the request flows from the client to the Event Manager
that writes it to the Process Image and returns the control to the client. The whole chain (A, B1, B2) is synchronous.
When external data is written, the request flows from the client to the Event Manager that tries to queue it in the
target driver (e.g. OpcUa). As soon as the queueing operation succeeds, the control returns to the client (A, C1, C2),
without waiting for any feedback from the driver (D) about the writing operation. During this phase, the Process
Image is not updated until the driver completes the operation successfully and consequently any read operations
would return the old value.

830 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Developing Business Logic

Error management
The error management related to the writing requests is not easy and straightforward.
The table below aims to summarize all the possible scenarios and how you could handle different situations:

ID Data Operation Execution What happens


Categor Result Mode
y

1 Internal Operation Synchrono Data is written immediately.


data succeeds & us
If a subscription is active on the written data, the event will be
AutomationVa
fired.
lue.Error is set
to 0

2 Internal Exception Synchrono A global error occurs.


data raised us Client gets notified immediately.
No data is written.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 831


Best Practices for Software Development

Best Practices for Developing Business Logic

ID Data Operation Execution What happens


Categor Result Mode
y

3 External Operation Asynchron As soon as the driver processes the request in the queue and it
data succeeds & ous completes the writing operation, the Event Manager updates
AutomationVa the Process Image. Data can be considered written only when
lue.Error is set the Process Image is updated.
equal to 0
If a subscription is active on the written data, the event will be
fired.
If a problem occurs while the driver is processing the element it
has removed from the queue (e.g. the OpcUa server has the
queue full or an out-of-range value and does not permit the
client to write the element) the write operation will fail and
consequently the Process Image will never be updated (and of
course no event will be fired).
To handle this situation, mostly in use cases where a TAKT time
must be guaranteed, the approach ‘write…wait(delta)…read’
can be applied.

4 External Exception Synchrono A global error occurs.


data raised us Client gets notified immediately.
No data is written.

5 External Operation Synchrono A local error occurs.


data succeeds & us Client gets notified immediately.
AutomationVa No exception is raised.
lue.Error is set
Parameters that have the Automation Value Error field
different from
different from 0 are not written. Consequently, the Process
0
Image will never be updated and the event will never be fired
(if subscriptions are configured).
Note: since the write request will typically contain more than
one parameter/tag to be written, ‘local’ means ‘belonging to
the parameter’.
Example: the write request contains the tags T1 and T2, which
are bound to different channels that point to different OpcUa
servers. If the driver has lost the connection only to the OpcUa
server for T1, the AutomationValue.Error of the parameter
linked to the T1 will be different from 0 while the one linked to
the T2 will be equal to 0 and it will be written as expected
(unless other problems occur as explained at table row 3).

The considerations explained above apply also when dealing with mixed data (i.e. writing requests that contain
both internal and external data together). In this case, all the explanations are still valid and in particular mode the
check on the AutomationValue.Error is mandatory, as shown in the following code example:

832 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Implementing Queries


try {
AutomationWrite(entity);
foreach(var par in entity.AutomationParameters)
{
if (par.Value.AutomationValue.Error != 0)
{
string message = $"Failed writing parameter '{par.Key}'
[Error: {par.Value.AutomationValue.Error}]";
_tracer.Write("<provider>", Category.Error, message);
// Error management
}
}
}
catch(…)
{
// Error management
}

How to manage automation parameter values


Another error scenario implies the management of automation parameter values.
If the array dimension of the AutomationWrite method is different from the one set on the OPC UA server, only the
parameters with correct dimension are written, and no error is returned. In this case, the method cannot be
invoked.
In this case, to get the correct array dimension, do as follows:
1. Check the data type from the MasterData entity. A list of supported data types is provided in:
• Automation Parameter Data Types in Opcenter Execution Foundation User Manual for Automation data
types.
• http://reference.opcfoundation.org/v104/core/docs/part5/3.3 for OPC examples.
2. Check the parameter type from the MasterData entity.
3. To retrieve the array dimension of the automation node parameter, use the following snippet of code
where <datatype> is the base type of the automation node parameter:

int arrayLen = ((<datatype>[])nodeParamVal.Value).Length

4.2 Best Practices for Implementing Queries


Before reading the following best practices, go through the follow introductory sections:
• Data Model Domains
• What are Entities
• Using the Query Methods and the Data Model Assemblies

Golden rules
While implementing queries, keep in mind the following rules:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 833


Best Practices for Software Development

Best Practices for Implementing Queries

• Carefully use the Include method


• Use parameterized queries
• Do not use evaluations inside lambda expressions

When not to use the Include method


Retrieve only the number of records that are needed, thus do not use the Include method unless you really need all
the returned data.
When you use the Include method on a referenced entity, the number of returned rows is represented by the
product of the number of rows in the two source tables (cartesian product).
Consequently, you should carefully evaluate whether to use the Include method (performance issue), or rather
restrict the amount of data that is retrieved from the database.
Remember that any unnecessary data retrieval operation has costs in terms of application performances.

When to use the Include method


Contrary to what was said before, it is sometimes more effective in terms of time reduction if you retrieve all
possible records by using once and for all the Include method, instead of segmenting the query to restrict the
returned entities inside Foreach loops.

Creating parameterized queries


When you create a query by adding a where condition, you should always assign the expression to a variable rather
than to an alphanumeric value.

\\\bad example
platform.Query<IMyEntity>().Where(x => x.MyProperty == 10);

\\\good example
var value = 10;
platform.Query<IMyEntity>().Where(x => x.MyProperty == value);

The first code example is bad because the query is not cashed at database level (actually, only the query with value
10 is cashed, which will be presumably not required anymore) . This prevents Entity Framework from reusing the
execution plans whenever the query is invoked again. The parameterized query would save time and CPU resources
by reusing the execution plans.

How to use evaluation expressions


Expression evaluations in lambda expressions make the code harder to be debugged, as they can lead to exceptions
that are not easy to understand.
Consequently, when writing conditions for the queries, do not include the evaluation of expressions in lambda
expressions. The following code:

int myNumber = 10;


platform.Query<IMyEntity>().Where(x => x.StringQuantity == myNumber.ToString());

should be changed to:

834 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Implementing Queries

int myNumber = 10;


string myNumberInString = myNumber.ToString();
platform.Query<IMyEntity>().Where(x => x.StringQuantity == myNumberInString);

and the following code:

platform.Query<IMyEntity>().Where(x => x.MyProperty == myObject.MyProperty);

should be also changed to:

var value = myObject.MyProperty;


platform.Query<IMyEntity>().Where(x => x.MyProperty == value);

Expression evaluations in lambda expressions make the code hard to debug, as it can lead to exceptions which are
not easy to understand.
In the second example, if myObject was null, the user would see a reflection-exception instead of a simple null-
reference.
In the first example the queries could be generated less efficiently.

Further guidelines
The Select operator must be used as soon as possible, and limited to the top-level projection of the
query. Consequently, the following code:

platform.Query<IMaterial>().Select(m => m.Name)


.Where(name => name.StartWith("Fl")).ToList();

should be changed to:

platform.Query<IMaterial>().Where(m => m.Name.StartWith("Fl"))


.Select(m => m.Name).ToList();

Avoid specifying conditions in the stream operators (such as First, FirstOrDefault, etc.) when they follow the select
operator. The following code:

platform.Query<IMaterial>()
.OrderBy(m => m.Name).Select(m => m.Quantity)
.FirstOrDefault(q => q > 10)

should be changed to:

platform.Query<IMaterial>()
.OrderBy(m => m.Name).Where(m => m.Quantity > 10)
.Select(m => m.Quantity).FirstOrDefault()

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 835


Best Practices for Software Development

Best Practices for Implementing Reading Functions

Some filtering operations cannot be translated into server-side statements. Consequently, avoid using user-code in
filtering expressions such as:

platform.Query<IMaterial>()
.Where(m => ClientEvaluationMethod(m.Quantity))

Avoid specifying additional arguments, such as the comparison culture, on comparisons because they can produce
client-side evaluation. You cannot mix client-side and server-side evaluation when performing queries.
Consequently, avoid the following example:

platform.Query<IMaterial>()
.Where(m => string.Compare(m.Name, "Test",
StringComparison.CurrentCultureIgnoreCase))

Instead of the Last/LastOrDefault stream operator, use the First/FirstOrDefault operator with reverse ordering.
Moreover, queries materialized with stream operators like First, should always specify an ordering.

4.3 Best Practices for Implementing Reading Functions


Reading Functions are often used for returning data:
• which is not based on the Opcenter EX FN database
• which is based on complex queries you could not implement using OData.
In the second case, if Reading Functions are not properly implemented, the queries (via ProjectionQuery) can raise
performance issues if they are materialized in the database before applying any OData filters or ordering logic. In
this implementation, the OData filtering is performed client side on the materialized data.
Consequently, to ensure query scalability, you should make sure that your Reading Functions are not materialized
in their body (with expressions such as [...].ToList, [...].Single, [...].First, or ForEach loops and so on) and that they
return an IQueryable object result. When you handle this result using OData, you should use filtering and ordering
expressions based on simple fields only, and avoid transformations that may result in disregarding indexes.

4.4 Best Practices for Developing UIs


You should implement UI screens that handle engineering and runtime data by following a set of rules aimed at
harmonizing runtime UI Applications.

Wireframe

836 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Developing UIs

General rules for all UI screens


UI Element Description

Filter The Filter is not available inside Small (360px) and Large (480px) panels.

Tile/Grid Both view modes should be always available and the Grid mode should be set as default.
mode

Infinite Infinite scrollbar (with server side pagination) must be selected.


Scrollbar

Quick The quick search should always filter by the NId entity property.
Search

Drill Down The Drill Down button ( Open) should be always present in:
• Tiles, Grids and vertical command bars of Master Layout screens
• Tiles and Grids of tabs in the Master Details screens

Breadcrumb The breadcrumb should provide:


• only the screen title in Master Layout screens (without specifying any other fields)
• the screen title, along with the entity NId, in Master Details screens.

Labels All labels should be provided for the multilanguage support.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 837


Best Practices for Software Development

Best Practices for Developing UIs

UI Element Description

Actions Action buttons must be ordered in the Command Bar as follows:


• Add action
• Open action (Drill Down)
• Edit actions (for example, Edit, Cancel/Save, Copy/Paste)
• Import/Export actions
• Specific actions for the involved entity (for example Lock, Freeze, Change Status, Release)
• Delete action (always the last one).
If an action takes in input a value that must be retrieved from multiple items, the action field
input box should be an Entity Picker UI element, configured as server side, without pagination.
The Entity Picker should be configured with filter, sort by, search by NId and with the screen title
containing the action along with the entity name in singular (for example, Select a Quality
Action). Created On and Last Updated On should be shown in the grid as the last columns.

User User Preferences should provide display preferences for all the available entity properties except
Preferences for GUIDs.

Rules for Master Layout screens


Each screen, which is in charge of managing either engineering or runtime data, must provide a Master Layout page
that comes up with the entity instances and the main actions.
The navigation menu will provide the link only to the Master Layout pages (and the Master-Details will be
configured as not visible).

When the user clicks the Open button, the visualization will change from the Master Layout page only to the
Master and Details Layout.
All Master Layout pages are based on the Master template and contain a list of entities such as Materials, Lots,
Material Tracking Units and so on.
Master Layout pages should be implemented by keeping in mind the following guidelines:

UI Element Description

Screen Title The title must contain the entity name in plural (for example
Materials, Lots, Work Instruction Definitions and so on). The title
should not contain "management".

Filter The Filter should open a filter panel on the left of the page or a filter
builder below the contextual command bar.
The Filter should include all fields that have been configured as
visible in the grid, except for the Segregation Tags.

Tile/Grid Mode Data must available both in Grid and in Tile mode. If possible,
choose the Grid mode visualization as default.

Sort by The Sort by should include all fields that have been configured as
visible in the grid. By default, data should be sorted by the logical
key field (for example, the NId), and in Ascending order.

838 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Developing UIs

UI Element Description

Group by Use the fields that have not been designed to be unique (for
example, you should not use Id, Last Updated On, Created On and
so on). See note about revision entities.

Data Drill Down From the Master Layout page, it should be always possible to
navigate to the Master and Details Layout.

Multi selection Enabled. If the commands already support the multi selection, the
corresponding actions can be shown when multiple instances are
selected.

Data to be displayed Grids should display the following data, in the following order: Id,
Name, [...], any boolean fields (e.g. Is Frozen, Is Default and so
on), Created On, Last Updated On, Segregation Tags.
Tiles should display Id, Name, some few additional fields that you
consider important for the involved entity (maximum 2-3 fields, for
example Last Updated On) and boolean fields shown as indicators.

Revised Data to be displayed Grids should display the following data, in the following order: Id,
Name, Revision, Is Current, [...], any boolean fields (e.g. Is Frozen, Is
Default and so on), Created On, Last Updated On, Segregation Tags.
Tiles should display Id, Revision, some few additional fields that you
consider important for the involved entity (maximum 2-3 fields, for
example Last Updated On) and boolean fields shown as indicators.

Actions The screen should display all actions that have been defined to
manage the involved entity instances (e. g. Add, Edit, Delete, Freeze/
Unfreeze, Add new revision, Copy revision and so on).
Action buttons must be ordered in the command bar as follows:
• Add action
• Open action (Drill Down)
• Edit action
• Specific actions for the involved entity (for example Lock,
Freeze, Change Status, Release and so on)
• Delete action (always the last one).
The title of the side panel should contain the action verb and the
entity name (e. g. Add Material).

Export functionality The Export action should be available on the Contextual Command
bar for the supported entity types.

Segregation Tags The Segregation Tags button and the Segregation Tags column
should be present in the Master Layout page. In case of Tile display
mode, Segregation Tags chips will be automatically displayed
within the tiles.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 839


Best Practices for Software Development

Best Practices for Developing UIs

UI Element Description

Breadcrumb In Master Layout screens, breadcrumbs are not displayed but they
must be configured providing only the screen title without
specifying any other field). In this way, the breadcrumb of the
Master Details screen will include the title of the Master Layout
screen.

Rules for Master Details Layout screens


Master Details Layout screens should be implemented by keeping in mind the following guidelines:

UI Element Description

Screen Title The title must contain:


• the entity name in singular (for example Material, Lot, Work Instruction Definition and so
on)
• and the NId of the selected entity (this part is automatically managed by the Model-Driven
UI Editor).

Filter The Filter is not available in the Master section of the Master-Details page. It could be present in
the tab grid where it should open a builder below the contextual command bar (not a filter
panel).

Tab Title The title must contain:


• the entity name in plural if several entities are available (for example State Machines,
Material Tracking Units and so on), except if the plural form does not exist in English (for
example Equipment)
• the entity name in singular if only one entity can be manage.

Tiles Tiles must contain a restricted set of properties, indicators for boolean values (for the indicators
you should use svg icons that start with 'indicator' in the file name).

Sort by The Sort by should include all fields that have been configured as visible in the grid or tile. By
default, data should be sorted by the logical key field (for example, the NId), and in Ascending
order.

Tile/Grid The Master side of the Master Details screen is only shown in Tile view mode.
mode
Tiles should display the minimal set of the properties (at least Id, Name, some very few
additional fields that you consider important for the involved entity) and boolean fields shown
as indicators.
Inside tabs, data must be shown both in Grid and in Tile view mode (Grid is the default).

840 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Developing UIs

UI Element Description

Actions If an action takes in input a value that must be retrieved from multiple items, the action field
input box should be an Entity Picker UI element, configured as server side, without pagination.
The Entity Picker should be configured with filter, sort by, search by NId. Created On and Last
Updated On should be shown in the grid as the last columns.
Action buttons must be ordered in the command bar as follows:
• Add action
• Edit action
• Specific actions for the involved entity (for example Lock, Freeze, Change Status, Release
and so on)
• Delete action (always the last one).
The Open (Drill Down) action is available inside grids (and tiles) within the tabs.

Segregation The Segregation Tags button should be present in the Master section of the Master-Details page
Tags and the Segregation Tags column should not be present in the page tabs.

Breadcrumb Breadcrumb must be configured providing the screen title, along with the entity NId. If the
breadcrumb has been configured also for the Master Layout screen, in the Master Details the
complete breadcrumb will be <Master Layout Title> + <Master Details title> + <selected Entity
NId>.

Rules for Screens with Revision entities


If the entities are submit to revision management, you should apply the following best practices:

UI Element Description

Filter If the application needs to retrieve entities under revision, you should provide
a filter by Current Revision as possible filter.

Actions Actions for setting an entity revision to current, locking and unlocking entities
should be present.
The action for adding a new entity and adding a new entity revision should be
grouped together and configured as a group button. The group button should
provide the action for adding a new entity revision only if an entity is selected,
otherwise a simple create action should be provided.

Group by Only for revision entities, along with the fields that have not been designed to
be unique, it could be useful to provide the Id field (in order to group by items
with the same Id but with a different revision).

Rules for Screens with Unit of Measure (UoM) entities

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 841


Best Practices for Software Development

Best Practices for Maintaining Project Studio Solution

UI Element Description

Sort by UoM entities should be ordered by NId property (corresponding to the Id


label in the UI) and in ascending mode.

 UoM entities which are set as hidden will be filtered out from
the UoM list and will not be displayed.

4.5 Best Practices for Maintaining Project Studio Solution


In Project Studio a Manufacturing Solution is often developed creating many building blocks (Functional
Blocks, Apps and Extension Apps) which make the solution structure rather complex and hard to manage (see How
to Develop a Manufacturing Solution in Project Studio).
Hence, we strongly suggest that you go through these guidelines to better approach the management and
maintenance of your solution.
• Best Practices for Managing Solution References
• Best Practices for Compiling Project Studio Solutions

4.5.1 Best Practices for Managing Solution References


When defining your model in Project Studio, it often useful to reference the models of Functional Blocks for which
you do not have the source files, for example if you want to use the capabilities provided by a Functional Block and
extend them with some custom-specific implementations, such as if you need to add properties to existing entities,
create relationships among entities, implement event handlers.
Functional Blocks can be easily referenced by using Reference Manager (see What Is Reference Manager).
When creating or updating the references to Functional Blocks both from other Functional Blocks and from Apps
or Extension Apps, you must keep in mind the following.

Creation of References to Functional Blocks


• You need to perform the Restore packages operation in order to be sure to correctly update all existing solution
references (see Installing a Referenced Functional Block). This implies that all packages (.zip) referenced in the
App/Extension App are retrieved from the location %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages and locally extracted in the SimaticITPackages folder.
• References to other Functional Blocks will be automatically installed if their .zip files are available in the
folder %ProgramData%\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks, otherwise you
will receive an error message.
• The packages you have installed will be displayed in the Installed tab and will have a green tick icon next to
them.
• According to the projects contained in the referenced Functional Block, the Solution Explorer tree view will
contain, under the References folder of each project, the .um, .umd and .dlls of the referenced projects. The
folder SimaticITPackages, if it does not already exist, will be created in the folder where your project files are
saved. A subfolder will be created for each referenced Functional Block, its name is comprised of the name and
version of the referenced Functional Block. The files contained in the .zip file are saved in this folder, with the
following structure:
• config folder, with the Dbinit.xml file for initializing the database
• handlers folder, with the command and event handlers

842 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Maintaining Project Studio Solution

• model folder, with the data model files and assemblies


• ExternalDependencies folder, with third-party files required by the Functional Block you are referencing
• Manifest.xml file
• The .um file of the original Functional Block displays all the referenced artifacts in the Model Explorer.

• By referencing other Functional Blocks from Apps or Extension Apps via Reference Manager, you will populate
and enrich the Public Object Model (POM) importing entities, types, events and protected commands of the
Functional Blocks.

Update of References to Functional Blocks


• You need to perform the Restore packages operation in order to be sure to correctly update all existing solution
references (see Updating a Functional Block Reference). This implies that all packages (.zip) referenced in the
App/Extension App are retrieved from the location %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages and locally extracted in the SimaticITPackages folder.
• You need to update your project version in the following cases:
• when performing changes to your model
• when the version of the Functional Block you are referring to is changed. In this case, the references you
can update depend on the version you are working on, as described in the following table:
Functional Block you are working on Functional Block you are referring to

Patch Version You can update your reference to a new Patch version.
For example, if you referenced version 01.00.00 of the
Functional Block x, and 01.00.01 is available in Reference
manager you can update the reference. You could not
update to version 01.01.00 as this would imply a new
minor version.

Minor version You can update your reference to anew Patch or Minor
version. For example, if you referenced version 01.00.00
of
Functional Block x, and 01.01.00 is available in Reference
manager you can update the reference. You could not
update
to version 02.00.00 as this would imply a new major
version.

Major version You can update all references to any version.


• You can also update your reference and keep the same version of the referenced Functional Block. For example,
if you add a dll in the package of your referenced Functional Block and update its reference, the reference
section of the Functional Block's handler project is automatically recalculated , i.e. the reference is added to the
new dll.
• If two referenced Functional Blocks themselves reference the same Functional Block (i.e. A and B both reference
C) Reference Manager checks to see whether they reference the same version. If they differ by patch or minor
version the highest version is loaded. For example:
• A references version 01.00.01 of Functional Block C
• B references version 01.00.02 of Functional Block C

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 843


Best Practices for Software Development

Best Practices for Maintaining Project Studio Solution

Reference Manager will load version 01.00.02 as this should not cause compatibility issues. If they differ by
major version an error is returned and the operation will not be possible.
• If a referenced Functional Block is missing in the file system repository (i.e. %ProgramData%
\Siemens\SimaticIT\Unified\Engineering\Packages\FunctionalBlocks), and the system prevents you from
building the solution, we suggest that you perform the procedure described in the document Troubleshooting:
How to fix a Project Studio Solution if a referenced Functional Block is missing available on GTAC site. The
article will help you to manually remove the missing references from the project and be able to install or restore
the packages you need.
• In case of migration from platform version 3.0 or previous, the .um file of the original Functional Block must be
deleted from the model project. If you double-click this file, a warning message will inform you that it is no
longer supported and needs to be removed. After deleting this file and building the solution, you can open the
model double-clicking the .dm file from the Diagrams sub-folder, containing the graphical representation of the
data model (see How to Migrate a Manufacturing Solution).

 For additional detail, refer to the dedicated documentation:


• How to Extend Referenced Functional Blocks
• Referencing Functional Blocks from an App
• Referencing Other Functional Blocks from an Extension App

4.5.2 Best Practices for Compiling Project Studio Solutions


When compiling your Project Studio Solutions you must keep in mind the following.

Building Order of Projects within the Solution


The build order in which projects are built within the solution is very important to ensure errors do not occur.
To avoid any problem, you must start from the referenced projects and then move up to the source projects, in
order to take into account the existing dependencies (see the table below).

Source Project Referenced Project

Command Handler Model Project

Event Handler Model Project

Installer Model Project


Command Handler
Event Handler

Hence, you must build the projects in the following order:


1. Build the Model Project
2. Build the Command Handler
3. Build the Event Handler
4. Build the Installer

844 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


Best Practices for Software Development

Best Practices for Maintaining Project Studio Solution

Building Order of Solutions


The build order in which solutions (Functional Blocks, Apps, Extension Apps) are built is very important to
ensure errors do not occur.
To avoid any problem, you must start from the lowest level Functional Block (for example, the Functional Block
which does not reference any others) and then move up to Apps and Extension Apps, in order to take into account
existing dependencies.
Example 1: if you have a scenario made up of 2 Functional Blocks, 1 App and 1 Extension App, which reference each
other, you must build them in the following order:
1. Build the Functional Block which does not contain any reference
2. Build the Functional Block which references the previous Functional Block
3. Build the App
4. Build the Extension App
Example 2: if you have a scenario made up of 3 Functional Blocks (one per domain), 1 App and 1 Extension App,
which reference each other, you must build them in the following order:
1. Build Reference Data Functional Block
2. Build Master Data Functional Block
3. Build Operational Data Functional Block
4. Build App
5. Build Extension App

Artifact Deletion
If you have deleted artifacts (entities, events, commands, and so on) in your Functional Block, inconsistencies will
be created in the related App/Extension App. This occurs because in these projects artifacts will not automatically
deleted. In this case, the project compiling will fail. In the App/Extension App, in the Public Object Model,
these inconsistencies will be marked with a question mark. Hence, you can identify these inconsistencies and
remove them manually. Once performed this operation, you can correctly compile your projects.

In addition, we suggest that you delete artifacts selecting the Delete On Cascade option, otherwise any extension
of the deleted artifacts will not be deleted and you may encounter errors during the project compiling.

 For additional detail, refer to the dedicated documentation:


• Defining the Build Order of a Functional Block
• Building your Model
• Building the Public Object Model Project

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 845


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Creating a Manufacturing Integration Solution

5 How to Integrate Opcenter Execution Foundation with Third-


Party Business Logic
You can integrate external applications with Opcenter Execution Foundation by taking in considerations the
following procedures:
• Executing third-party business logic or reading data from external data sources through an integrated
manufacturing solution
• Developing an integrated third-party application through the IUnifiedSdkLean interface
• Subscribing/unsubscribing to signals inside third-party applications by using the Opcenter EX FN Signal C#
library
• Managing client authorization

5.1 Creating a Manufacturing Integration Solution


A manufacturing integration solution (also known as injection solution) is the Opcenter Execution
Foundation solution that is configured to integrate with third-party applications in terms of executing external
business logic and reading data from external data sources.
This type of solution is useful if you have your own business application and you want to use Opcenter Execution
Foundation on top of it in order to maintain your implementations and, at the same time, take advantage of the
product architecture benefits in terms of performance enhancement, work load scalability and user interface
usability.
For example, you may want to execute the following operations:
• develop new user interfaces by using Opcenter EX FN Widgets and Components
• read data from an external data source (by importing views and create a read data model)
• modeling composite commands to invoke external logic and write data on your third-party data source.

846 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Invoking Third-Party Business Logic

If you want to achieve the above mentioned goals, you can use the following indications as a guideline for
developing your solution.

Reading from third-party data model


1. Create a Functional Block (Library) based on User domain and import views from the external data source .
2. Create an App that references the Functional Block.
3. In Solution Studio execute all the operations that are required to deploy your App.
4. Create a client application that reads from the entities of the imported data model.

Calling third-party business logic


1. Create a Functional Block (Library) or use the same Functional Block (based on User domain) you have created
to import views from the external data source.
2. Create commands for the external functionalities you want to call.
3. Import command handlers and implement calls to third-party business logic (for example, a .NET class, a G2
rule, a web service).
4. Create an App that references the implemented Functional Block.
5. Import commands to POM commands.
6. In Solution Studio execute all the operations that are required to deploy your App.
7. Create a client application that calls the modeled commands.

5.2 Invoking Third-Party Business Logic


This page contains an example of logic developed inside the command handler of a Functional Block or an App
used to invoke third-party logic. This example can be re-used inside an integrated manufacturing solution.

Invoking business logic to write data on a third-party data source


1. The first step to write data to a third-party database is to implement a request from your web application to the
command exposed on the Service Layer, which has been modeled to map your third-party functionality. This
request can be implemented by using Opcenter Execution Foundation Presentation Services.
2. Then, for each of the modeled commands, which map the functionalities you want to execute, you must
implement code inside command handlers in order to call third-party business logic.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 847


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Invoking Third-Party Business Logic

Example of Handler class containing a call to a .NET API class

1 [Handler(HandlerCategory.BasicMethod)]
2 public partial class StartOperationHandlerShell
3 {
4 /// <summary>
5 /// This is the handler the MES engineer should write
6 /// This is the ENTRY POINT for the user in VS IDE
7 /// </summary>
8 /// <param name="command"></param>
9 /// <returns></returns>
10 [HandlerEntryPoint]
11 private StartOperation.Response
StartOperationHandler(StartOperation command)
12 {
13 StartInputClass inputStart = new StartInputClass(command);
14
15 string xml =
RtStartClass.GenerateXmlInputForStartOperation(inputStart);
16
17 IOrderBread ordBread = new OrderBread();
18 bool res = false;
19 string errorMessage = string.Empty;
20 string infoMsg = string.Empty;
21
22 using (RtStartClass rtStartClass = new RtStartClass(ordBread))
23 {
24 PmRequestOutput outArgs;
25 res = rtStartClass.StartOperation(xml, ref errorMessage,
ref infoMsg);
26 }
27
28 StartOperation.Response response = new
StartOperation.Response();
29 response.ResponseMessage = infoMsg;
30 if (!res)
31 {
32 response.Error = new ExecutionError(errorMessage);
33 }
34
35 return response;
36 }
37 }

In this example, RtStartClass is the class that hosts the third-party functionality, StartOperation is the
functionality to be executed.

848 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Executing Queries on a Third-Party Data Model

Example of Handler class containing a call to a Web Service method

1 [HandlerEntryPoint]
2 private CreateDefect.Response CreateDefectHandler(CreateDefect command)
3 {
4 try
5 {
6 handlerTracer = Platform.Tracer;
7 handlerTracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",
Category.Informational, "Starting CreateDefectHandler", "CreateDefect");
8 CreateDefect.Response response = new CreateDefect.Response();
9 //Get QIS-Webservice
10 IQISService client = QisModel.GetService();
11 //Create NcDefect
12 QISService.NcDefect defect = new QISService.NcDefect();
13 defect.DmlCommand = new NcDmlCommandField { Value = "I" };
14 defect.DefectId = new NcStringField { Value = command.DefectId };
15 defect.DefectDescription = new NcStringField { Value =
command.DefectDescription };
16 defect.PlantOfDefect = new NcStringField { Value =
command.PlantOfDefect };
17 defect.Classification = new NcStringField { Value =
command.Classification };
18 handlerTracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",
Category.Informational, "Creating defect ({0}/{1}/{2}/{3})",
defect.DefectId.Value, defect.DefectDescription.Value,
defect.PlantOfDefect.Value, defect.Classification.Value, "CreateDefect");
19
20 response.Result =
client.NetComProcessObject(defect).EventId.ToString();
21 return response;
22 }
23 catch (Exception ex)
24 {
25 handlerTracer.Write("Siemens-SimaticIT-Trace-BusinessLogic",
Category.Error, ex.Message, "CreateDefect");
26
27 return new CreateDefect.Response(){Error = new ExecutionError(-2,
ex.Message)};
28 }
29 }

5.3 Executing Queries on a Third-Party Data Model


Once you have imported an external data model into a dedicated Opcenter Execution Foundation Functional Block,
and then deployed the entire solution that references it, you can perform read operations on it.
Additionally, you can create links between imported entities and platform entities inside your App.

Reading from a third-party data model

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 849


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

Opcenter Execution Foundation supports queries on entities imported from third-party data sources in the
following ways:
• through the standard $metadata OData syntax, if you are querying from consumer clients (such as single page
applications) through the Service Layer. When you query, you can add the required navigation properties to set
logical connections among entities that belong to different data models.
• through the ProjectionQuery() method available inside the command handler and event handler code,
or inside applications that use the IUnifiedSdkLean interface. In both cases you execute a LINQ query. This
method also reads cross domain inside Opcenter Execution Foundation data model.
• through Presentation Services listed in the Opcenter Execution Foundation Product Overview, and documented in
the UI Framework Reference.
To write on the third-party databases, create a manufacturing integration solution to execute third-party business
logic.

5.4 Developing Third-Party Applications Integrated with Opcenter EX


FN via IUnifiedSdkLean interface
You can develop third-party applications integrated with Opcenter Execution Foundation through the
IUnifiedSdkLean interface. In particular you can execute queries, send commands and handle events (subscribe to
events, unsubscribe from events and fire events). You cannot directly write data but you must call the custom
business command that implements that functionality.

Overview of the possible operations


UnifiedSdkLean is the object that can be used inside the code of a third-party application. This object is
instantiated through its factory class (LeanFactory). For more information see Opcenter Execution
Foundation Platform Reference Online Help.

850 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

Operation Type SIT Unified Local Application (SDKLean)

Read data from the writing model of a Functional Block


domain

Read data from the POM reading model of an App Recommended

Read data from the reading model of a Functional Block


domain
(<Prefix>.<DomainName>.<FunctionalBlockName>.<Acro
nym>Model.ProjectionModel namespace)

Read from Automation entities

Write on Automation entities

Write data (create, update, delete entity instance)

Call protected commands, belonging to the Functional (Not recommended. Use the public commands
Block namespace (if associated to a Worker role) exposed by Apps instead (see below).
<Prefix>.<DomainName>.<FunctionalBlockName>.<Acron
ym>Model.Commands)

Call public commands exposed by Apps, be Recommended


they composite commands or commands that have
been imported from Functional Blocks and published in
the App (if associated to a worker role). See Modeling
Commands in the POM.

Call remote commands

Get remote entities

Call private commands

Trigger events

Subscribe to events (see Handling event subscriptions


below)

Write trace logs

Access to the current user identity (Principal property)

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 851


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

Operation Type SIT Unified Local Application (SDKLean)

Invoke Reading Functions

Prerequisites for using UnifiedSdkLean


• The application that uses the IUnifiedSdkLean interface must always run on the Opcenter EX FN server.
• The Windows user identity of the running process:
• must belong to the SIT_UNIFIED_LOW Windows group.
• if the application is using the Integrated Windows Authentication, the UMC user must also be imported
and associated to the proper role.
• has the proper permissions on the database as specified below.
The following versions are installed (if you are using other software versions, you must update them to the
supported ones):
• Json.NET - 11.0.2
• System.Collections.Immutable - 1.7.1
• System.Reflection.Metadata - 1.6.0

Accessing UnifiedSdkLean functionalities from your code


1. Create a C# project (for example, of WPF Application or Windows Forms type), by choosing the correct version
of .NET Framework as specified in Prerequisites of the Opcenter Execution Foundation Installation Guide.
2. Copy the following assemblies from the binary folder of the product installation path
(%SITUnifiedSystemRoot%\bin) to any dedicated folder (for example C:\ExternalDependenciesFolder):
• SimaticIT.DataModel (i.e. the assembly which is required to use the model data)
• SimaticIT.Runtime.Common
• SimaticIT.SDK.Diagnostics (i.e. the assembly which is required to use Platform tracing functionalities)
• SimaticIT.Unified.Common
• SimaticIT.Unified.Lean
3. Add these assemblies to the project references by browsing to the copy folder.
4. If needed, add the references to your Functional Block or App model assemblies (model, commands, events).
These files can be found inside the Functional Block or App packages. For more information see Functional
Block package or App package sections within this guide. If you want to read from Automation entities, you
must add the reference to the Automation Gateway App and the related Functional Blocks (see Automation
App).
5. To use the UnifiedSdkLean object in your application, instantiate its class with the required user authentication
and add the logic you need (a code example is provided below).
6. Set the Copy Local build property to True for all the assemblies you have copied (and referenced) which are
listed at step 2 (by right-clicking each assembly and selecting Properties): Visual Studio will copy these
assemblies automatically to the output assembly folder. Since this option is usually set by default, just verify it.
7. Manually copy the SimaticIT.Governance.AliasDictionary assembly from the %SITUnifiedSystemRoot%bin
product folder to the output assembly folder. This assembly is internally used to resolve references to Opcenter

852 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

EX FN product assemblies.

8. If you want to test your application, and you have not deployed your solution yet, you can
temporarily set the Copy Local build property to True of the referenced Functional Block assemblies
(e.g. MyFB.OperationalData.MyFB.Model.dll). Bear in mind that you must change it after you have deployed
the solution.

 Before you execute your application, check that the assemblies you have copied belong to the last
available product version.

Code Examples
The following code snippets can be properly modified to be used in your project.

 IUnifiedSdk interface methods are documented in the Platform Reference documentation. The following
code snippet contains only a subset of the functionalities that can be used.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 853


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

UnifiedSdkLean use example - Dispose method explicit call

using Siemens.SimaticIT.Runtime.Common;
using Siemens.SimaticIT.Unified.Lean;
[...]
public static void Main(string[] args)
{
try
{
LeanFactory.Initialize("MyApplication");
IUnifiedSdkLean unifiedSdkLean = LeanFactory.Create();
unifiedSdkLean.SetWindowsAuthentication();
var command = new CreatePS()
{
PSName = "My PS",
PSVersion = 02.01
};
var response = unifiedSdkLean.CallCommand<CreatePS,
CreatePS.Response>(command);
if (!response.Succeeded)
{
unifiedSdkLean.Tracer.Write("MyApplicationLog", Category.Error, "PS 1 Not
created");
}
unifiedSdkLean.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
LeanFactory.ShutDown();
}

 Additional information on Dispose method


The Dispose method call is not mandatory but it is recommended, and it must be executed at the end of
the logic: once invoked on the IUnifiedSdkLean instance it cannot be used anymore and an
ObjectDisposedException is returned after any subsequent call (see ObjectDisposedException in the
Microsoft MSDN documentation). To perform another operation after calling the Dispose method, it is
necessary to create a new IUnifiedSdkLean instance calling the LeanFactory.Create method.
Alternatively, it is possible to implicitly call the Dispose method through the using statement, as shown in
the example below.
The memory allocation relative to the queries is freed when the IUnifiedSdkLean instance is disposed. So
consider to generate a new IUnifiedSdkLean instance on request/session basis.

854 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

UnifiedSdkLean use example - Dispose method implicit call

using Siemens.SimaticIT.Runtime.Common;
using Siemens.SimaticIT.Unified.Lean;
[...]
public static void Main(string[] args)
{
try
{
LeanFactory.Initialize();
using (IUnifiedSdkLean unifiedSdkLean = LeanFactory.Create())
{
unifiedSdkLean.SetWindowsAuthentication();
var command = new CreatePS();
var response = unifiedSdkLean.CallCommand<CreatePS,
CreatePS.Response>(command);
if (!response.Succeeded)
{
unifiedSdkLean.Tracer.Write("MyApplicationLog", Category.Error,
string.Format("PS 1 Not created"));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
LeanFactory.ShutDown();
}

Handling user authorization


Applications that access Opcenter EX FN service resources must be integrated with User Management and Access
Control. Each request that you carry out from your code to execute a functionality exposed by Opcenter EX FN must
be authenticated and authorized. As a consequence, each instance of the UnifiedSdkLean object must be properly
initialized by providing a valid identity.
Identity can be validated through the Windows Integrated Authentication mode (WIA Authentication) by using
the SetWindowsAuthentication public method.
After the initialization of the UnifiedSdkLean object with a valid identity, you can call all the exposed methods. But
if you provide an authenticated identity whose identity is not properly authorized, methods invocation will fail.
If you need to implement a different type of authentication, see Managing Client Authorization.
To execute operations on entities, commands, events and reading functions defined as securable objects, the user
must be properly authorized in a role.
When protected commands are imported from a referenced Functional Block to the POM Model of an App, the
commands of the Functional Block and the commands of the App are handled as independent securable objects
and you can consequently configure them separately. If you assign execution permissions to the commands
imported in the App, the system does not automatically assign the same permissions to the source commands.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 855


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

Consequently, before executing commands, you should verify that the permissions have been correctly assigned
otherwise the operations will return an authorization error.
Queries can be implemented only on the entities that are present in the POM Model of the App. If you try to execute
queries on entities of the Functional Block ProjectionModel namespace, the system returns an authorization error.

Debugging the UnifiedSdkLean application


If you are running in debug mode a client application that uses IUnifiedSdkLean and you want to recompile an App
which was previously deployed (for example, because you may need to add some logic, such as commands or
entities to your project) you must first stop the UnifiedSdkLean client application, otherwise you cannot compile
the App (an error on locked files will be returned).

Accessing SQL Server / Oracle databases


From your application that uses IUnfiedSdkLean you can perform operations both on Opcenter EX FN database
and on external data sources (either on SQL Server or Oracle database).
Before you can do this, you must verify whether the user who runs the process of your client application is properly
granted on the target database.
The procedure for granting this user varies according to the involved database server type: SQL Server or Oracle.
SQL Server database:
• If the target database is the Opcenter EX FNdatabase, you must add the new user to the SIT_UNIFIED_LOW
Windows group because for this group the corresponding SQL login already exists.
• If the target database is an external data source, you can either directly create the SQL login for this user, or
create the login for a Windows group (such as SIT_UNIFIED_LOW) and then add the user to this group (in order
to manage different Windows users without changing the logins in SQL Server). This operation can be also
executed through a configuration script (for more information, see Configuring SQL Server Database in the
Opcenter Execution Foundation Installation Guide).
• All Opcenter EX FN hosts that remotely connect to a SQL Server instance must be able to ping the SQL machine
by its hostname and IP address.
Oracle Server:
• Both for the Opcenter EX FN database and for an external data source, you must create the new user on the
Oracle database by running the same script used for configuring Oracle user permissions (for more information,
see Configuring the Oracle Database in the Opcenter Execution Foundation Installation Guide. In this case, it is
sufficient that you associate this user with the lowest user profile (by setting low_profile_user).
• The user name must not exceed 10 characters. If you want to use a longer user name, you must consider that the
actual user name is the result of a concatenation of strings and it cannot exceed 30 characters. Thus, if you want
to use a longer name, you must also consider the length of the following strings:
• the parameter which is returned by query: SELECT VALUE FROM V$PARAMETER WHERE NAME =
‘os_authent_prefix query. By default this parameter is OPS$ (containing 4 characters);
• the machine name on which Oracle Server is running;
• the slash character (/, corresponding to 1 character).

Managing direct database access with Microsoft Entity Framework


In Opcenter Execution Foundation, database access is performed through Microsoft Entity Framework.
The currently supported version is Microsoft Entity Framework 6.1.3.

856 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Developing Third-Party Applications Integrated with Opcenter EX FN via IUnifiedSdkLean interface

 If you are using another version of Entity Framework, you must update it to the version supported by
Opcenter Execution Foundation.

If you are implementing the Opcenter Execution Foundation project (functional block or App) that uses standard
IUnifiedSdk functionalities to access Opcenter EX FN database or external data sources, Microsoft Entity
Framework is automatically configured.
If you are implementing a project which only uses IUnifiedSdkLean functionalities and you want to directly use MS
Entity Framework to run queries or perform operations on a database without using Opcenter Execution
Foundation IUnifiedSdkLean APIs, you must manually configure Entity Framework in order to set the connections
required by Opcenter EX FN.
This configuration must be performed inside the configuration file of your project (app.config or web.config,
according to the project type).
If the file is already configured, verify that the <entityFramework> section contains the following mandatory
configurations, or add the entire configuration from scratch:
• <Section>, containing the Entity Framework name and details (for more information on Entity Framework
configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468:

<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

• <Providers>, containing the details of the SQL provider (mandatory) and the Oracle provider (only if you want
to use Oracle):

<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.Sq


lProviderServices, EntityFramework.SqlServer"/>

<provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAcc


ess.EntityFramework.EFOracleProviderServices,
Oracle.ManagedDataAccess.EntityFramework, Version=6.122.19.1, Culture=neutral,
PublicKeyToken=89b483f429c47342" />

• <Interceptors>, containing both of the following:

<interceptor

type="Siemens.SimaticIT.Information.Common.EntityFramework.Interception.UnifiedComman
dInterceptor,
SimaticIT.Information.Common" />

<interceptor

type="Siemens.SimaticIT.Information.Common.EntityFramework.Interception.UnifiedTransa
ctionInterceptor,
SimaticIT.Information.Common" />

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 857


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Subscribing to Signals from C# Client Applications

Handling event subscriptions


Two overloads of the SubscribeEvent method are available for configuring the acknowledgment of the event
handling. In particular, you can define if you want to send an acknowledge message before the subscribed blocks of
custom code have started (immediate option), that is, without waiting for their execution, or after all blocks of
custom code have been completed (deferred option).
Events are persisted in the communication infrastructure only if you have assigned a name to the queue
(queueName parameter). If a name is provided, the queue will persist in the system after the process has been
closed or crashed. If the queueName is null, the queue will only exist as long as the process is alive.
Consequently, only if you use the deferred acknowledge option together with a specified queue name, you are sure
to delete an Event from the specified queue once all subscribed blocks of code have been effectively executed and
conversely, recover this event once the host or the process have crashed.
By specifying the threading model options, you can define whether you want to process the incoming event
instances in parallel or sequentially. For subscriptions to the CommittedEvent, see Handling the CommittedEvent.
If you needed to clean queues, you can follow the indications described inDebugging Commands and Reading
Functions via App Debugging Tool for purging RabbitMQ queues with the RabbitMQ Management Plugin by
replacing the worker name with the queue name you have specified in the subscription method.
If you leave the queueName parameter unspecified, the queue name can be worked out from the specified Lean
process name as follows:
• If you have used LeanFactory.Create (“ApplicationName”)), you can filter by "ApplicationName"
• If you have used LeanFactory.Create(), you can filter by "Application.<EMPTY>"
If you configure event subscriptions by using the IUnifiedSdkLean SubscribeEvent method in either of the
following ways, the execution of the related handlers might not be completed or re-executed (data-loss):
• with the queueName property set to null or
• with the ListenerOptions.QueueAutoDeletable property set to true.

5.5 Subscribing to Signals from C# Client Applications


You can use the Signal C# public library, if you need to access Opcenter EX FN signal functionalities from a client
application.
This page describes the configuration steps required to correctly compile and run your project.

Prerequisites
The user that will run the application is a UMC user and is associated to the proper role.

Procedure
1. Create a C# project (for example, of WPF Application or Windows Forms type), by choosing the correct version
of .NET Framework as specified in Prerequisites of the Opcenter Execution Foundation Installation Guide.
2. Copy the %SITUnifiedSystemRoot%ClientLibrary folder from any Opcenter EX FN host to the client machine
(on which Opcenter Execution Foundation is not installed). This folder contains all the files that are required to
correctly use signalling functionalities.
3. Add the following assemblies to the project references by browsing to the copy folder:
• SimaticIT.Signalling.ClientModel.dll

858 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Subscribing to Signals from C# Client Applications

• SimaticIT.Signalling.ClientSdk.dll
4. If needed, follow the provided examples to implement your code. An example for setting up a custom tracer is
also provided.
5. Copy the following files to the folder where your executable will run:
• SimaticIT.Signalling.ClientModel.dll
• SimaticIT.Signalling.ClientSdk.dll
• Newtonsoft.Json.dll
• System.Net.Http.Formatting.dll
• System.Net.Http.dll

 Opcenter Execution Foundation supports the following versions:


• Newtonsoft.Json.dll version 11.0.0.0, available in the Newtonsoft.Json v11.0.2 NuGet package
• System.Net.Http.Formatting.dll version 5.2.2.0, available in the
Microsoft.Aspnet.Webapi.Client v5.2.2 NuGet package
• System.Net.Http.dll version 4.1.1.0, available in the System.Net.Http 4.3.0 NuGet package

Setting up a custom file tracer


Modify the App.config file of your client application and add the following configuration to
the <configuration> element by specifying the output file name as follows:

<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="monitorListener" type="System.Diagnostics.TextWriterTraceListener"
initializeData="YOUR_APPLICATION_NAME_OutputTrace.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>

Implementing a subscription
The following code snippet represents an example of library use within a console application:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 859


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Subscribing to Signals from C# Client Applications

C# example of a console application

using System;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
using Siemens.SimaticIT.Signalling.ClientModel;
using Siemens.SimaticIT.Signalling.ClientModel.Remoting;
using Siemens.SimaticIT.Signalling.ClientSdk;
using Siemens.SimaticIT.Signalling.ClientSdk.Security;

namespace MyFirstSignalClient
{
public class Program
{
private static Action<object> onNext = t => Task.FromResult(0);
private static Action<Exception> onError = t => new Exception("Error");
private static Action onCompleted = () => Console.WriteLine("Done");
private static Uri ConfigUri = new Uri("http://localhost/sit-svc/config");
private static string username = "root";
private static string password = "root";
private static string clientId = "test";
private static string secret = "test";
private static string SignalName = "TankFillSignal";

public static void Run(string[] args)


{
//STEP 1: Retrieve dynamic configuration from /sit-svc/config
var endpointConfig = new
UafServiceDiscovery().GetEndpoints(ConfigUri).Result;
var scf = new SecurityClientFactory(endpointConfig);

//STEP 2.1: Prepare Secure Strings for managing security critical data
SecurityClient securityClient = null;
using (var securePwd = BuildSecureString(password))
{
using (var secureSecret = BuildSecureString(secret))
{

//STEP 2.2: Obtain Opcenter Foundation Execution security object


to use Platform functionalities
securityClient = scf.Create(username, securePwd, clientId,
secureSecret).Result;
}
}
if (securityClient != null)
{

//STEP 3: Retrieve the endpoints for the signals and retrieve the
signals
var smc = new SignalMetadataClient(securityClient);

860 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Subscribing to Signals from C# Client Applications

string signalUrl = string.Format("{0}/metadata",


endpointConfig.ApplicationSignalManagerUrls.FirstOrDefault().Value);
var sm = smc.GetSignalsMetadata(new Uri(signalUrl));

SignalsMetadata s = sm.Result;
//STEP 4: Retrieve specific endpoint for a specific Signal (e.g.
TankFillSignal)
SignalEndpoint se = s.GetSignalEndpoint(SignalName);

//STEP 5: Choose protocol to receive signal notification


var signalClient = new SingleChannelClient(se.SignalMainAddress, true,
securityClient);

//STEP 6: Subscribe to the Signal


var subscriptionId = signalClient.Subscribe(SignalName, string.Empty,
onNext, onError, onCompleted).Result;

// STEP 7.1: check if Ping-Pong protocol is already enabled on the


connection
if (!signalClient.IsHeartbeatActive)
{

// STEP 7.2: Enable Ping-Pong protocol


var pingInterval = TimeSpan.FromSeconds(5);
var pongTimeout = TimeSpan.FromSeconds(10);
var enabled =
signalClient.EnableHeartbeat<PayloadPing>(pingInterval, pongTimeout,
OnHeartbeat).Result;
if (!enabled)
{
TraceMessage("Ping-Pong protocol cannot be enabled.");
}
}

//STEP 8: Unsubscribe from the Signal


if (subscriptionId != null)
{
Task<bool> res = signalClient.Unsubscribe(subscriptionId.Value);
}
}
else
{
TraceMessage("Authorization Server is unreachable!");
}
}
public static void TraceMessage(string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{
System.Diagnostics.Trace.WriteLine(string.Format("{0} [{1}::{2}] {3}",
DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), nameof(Program), memberName, message));
System.Diagnostics.Trace.Flush();
}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 861


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Subscribing to Signals from C# Client Applications

private static SecureString BuildSecureString(string s)


{
SecureString sec = new SecureString();
Array.ForEach(s.ToArray(), sec.AppendChar);
sec.MakeReadOnly();
return sec;
}
private static void OnHeartbeat(ISignalClient client, PayloadPing payload)
{

// STEP 7.3: Check the server Pong


if (payload == null)
{
// Insert your code here to manage the missing Pong...
Console.WriteLine("Missing Pong!");
}
else
{
Console.WriteLine("Pong from server arrived at {0}", DateTime.Now);
}
}
}
}

The following code snippet represents an example of library use within a Windows Form application:

862 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Subscribing to Signals from C# Client Applications

C# example of a Windows Form application

using System;
using System.Linq;
using System.Security;
using System.Windows.Forms;
using Siemens.SimaticIT.Signalling.ClientModel;
using Siemens.SimaticIT.Signalling.ClientModel.Remoting;
using Siemens.SimaticIT.Signalling.ClientSdk;
using Siemens.SimaticIT.Signalling.ClientSdk.Security;
namespace MyFirstSignalClient
{
public partial class MainForm : Form
{
private static string Username = "root";
private static string Password = "root";
private static string ClientId = "test";
private static string ClientSecret = "test";
private static string AppName = "MyApp";
private static string SignalName = "TankFillSignal";
private SecurityClient _securityClient;
private EndpointsConfiguration _endpointConfig;
private SignalsMetadata _metadata;
private ISignalClient _signalClient;
private long _subscriptionId;
private async void MainForm_Load(object sender, EventArgs e)
{
//STEP 1: Retrieve dynamic configuration from /sit-svc/config
_endpointConfig = await new UafServiceDiscovery(new Uri("http://
localhost/sit-svc/config")).GetEndpoints();
// Insert your code here to manage the result and update the UI..
}
private async void AuthenticateBtn_Click(object sender, EventArgs e)
{
//STEP 2.1: Prepare Secure Strings for managing security critical data
using (var securePwd = BuildSecureString(Password))
{
using (var secureSecret = BuildSecureString(ClientSecret))
{
//STEP 2.2: Obtain Opcenter Foundation Execution security object
to use Platform functionalities
_securityClient = await new
SecurityClientFactory(_endpointConfig).Create(Username, securePwd, ClientId,
secureSecret);
}
}
// Insert your code here to manage the result and update the UI..
}
private async void GetMetadataBtn_Click(object sender, EventArgs e)
{
//STEP 3: Retrieve the endpoints for the signals and retrieve the signals

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 863


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Subscribing to Signals from C# Client Applications

var address = string.Concat(_endpointConfig.ApplicationSignalManagerUrls[


AppName], "/metadata");
_metadata = await new
SignalMetadataClient(_securityClient).GetSignalsMetadata(new Uri(address));
// Insert your code here to manage the result and update the UI..
}
private async void SubscribeBtn_Click(object sender, EventArgs e)
{
//STEP 4: Retrieve specific endpoint for a specific Signal (e.g.
TankFillSignal)
SignalEndpoint signalEndpoint = _metadata.GetSignalEndpoint(SignalName);
//STEP 5: Choose protocol to receive signal notification
_signalClient = new SingleChannelClient(signalEndpoint, true,
_securityClient);
Action<object> onNext = (obj) => { /* Manage Signal data received...
*/ };
Action<Exception> onError = (ex) => { /* Insert your code here to manage
the error... */};
Action onCompleted = () => { /* Insert your code here... */ };
//STEP 6: Subscribe to the Signal
var subscriptionId = await _signalClient.Subscribe(SignalName, string.Emp
ty, onNext, onError, onCompleted);
if (subscriptionId.HasValue && subscriptionId.Value > 0)
{
_subscriptionId = subscriptionId.Value;
// Insert your code here to manage the result and update the UI..
}
}
private async void EnablePingPongBtn_Click(object sender, EventArgs e)
{
if (_signalClient != null)
{
// STEP 7.1: check if Ping-Pong protocol is already enable on the
connection
if (!_signalClient.IsHeartbeatActive)
{
// STEP 7.2: Enable Ping-Pong protocol
var pingInterval = TimeSpan.FromSeconds(5);
var pongTimeout = TimeSpan.FromSeconds(10);
var enabled = await
_signalClient.EnableHeartbeat<PayloadPing>(pingInterval, pongTimeout, OnHeartbeat);
if (!enabled)
{
// Ping-Pong protocol cannot be enabled.
// Insert your code here to manage the result and update the
UI..
}
}
}
}
private void OnHeartbeat(ISignalClient client, PayloadPing payload)
{

864 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

// STEP 7.3: Check the server Pong


if (payload == null)
{
// Insert your code here to manage the missing Pong response from the
server.
}
}
private async void UnsubscribeBtn_Click(object sender, EventArgs e)
{
//STEP 8: Unsubscribe from the Signal
var result = await _signalClient.Unsubscribe(_subscriptionId);
// Insert your code here to manage the result and update the UI..
}
private SecureString BuildSecureString(string s)
{
SecureString sec = new SecureString();
Array.ForEach(s.ToArray(), sec.AppendChar);
sec.MakeReadOnly();
return sec;
}
}
}

5.6 Managing Client Authorization


All Opcenter Execution Foundation service requests must be authenticated and authorized. This section goes
through two possible interaction scenarios, according to the type of requests that you could perform:
• Requests that use the IUnifiedSdkLean public interface
• Requests that use the Opcenter EX FN Service Layer and that are not developed with the Opcenter Execution
Foundation UI Framework service infrastructure.

Requests performed using IUnifiedSdkLean interface


If your interaction scenario uses the IUnifiedSdkLean public interface, your requests must provide a valid identity.
This identity can be initialized either starting from an access token obtained through a specific method
(see SetAuthenticationToken method) or by using the Windows Integrated Authentication functionality by
deriving the identity information from the user that is running the process (see
SetWindowsAuthentication method).
To use the SetAuthenticationToken method you have to make sure that you have a valid access token, which can
be provided in either of the following ways:
• by requesting the token from the Opcenter EX FN Authorization Server
• by obtaining the token from an X.509 certificate

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 865


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

 For more details on the IUnifiedSdkLean interface, refer to the IUnifiedSdkLean public interface in the
Opcenter Execution Foundation Platform Online Help.

Requests performed on the Web Service Layer


If your interaction scenario uses the Opcenter EX FN Web Service Layer, you can develop a client application either
with the Opcenter EX FN UI Framework services offered by the development tools of Project Studio or without
Opcenter EX FN UI Framework. The UI Framework infrastructure internally manages authentication and
authorization.
If you are not using UI Framework services, you will have to make sure that your requests contain a valid access
token, which can be provided in either of the following ways:
• by requesting the token from the Opcenter EX FN Authorization Server
• by obtaining the token from an X.509 certificate

5.6.1 Requesting an Access Token from Opcenter EX FN Authorization


Server
The Authorization Server has been developed following the OAuth2 reference and implements the following
authorization flows:
• Implicit Grant Flow
• Resource Owner Password Credential
For more details, see The OAuth 2.0 Authorization Framework.

Implicit Grant Flow


Based on the OAuth description, the Implicit Grant Flow is a redirection-based flow, where clients must be able to
interact with the resource owner's user agent (typically a web browser) and to receive incoming requests
(via redirection) from the authorization server.

866 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

The Implicit Grant Flow is represented by the following schema:

How to implement a client


The client must send a GET request to the /OAuth/Authorize endpoint with a set of predefined parameters. An
example of request is the following:

GET https://localhost:9000/OAuth/Authorize?
response_type=token&client_id=MyApp&redirect_uri=https://localhost:44300/
callback.cshtml&scope=global&state=14553710.733142

The accepted parameters are:


• client_Id: a string that identifies the application. At the moment Opcenter Execution Foundation does not allow
you to register a custom client. Nevertheless, the system correctly authorizes applications that are not
registered but that follow the required constraints. If this is the case, the system will trace this event and labels
the application as unregistered.
• redirect_uri: if your application is unregistered, you must specify a redirection_uri path that contains the same
domain as the origin URL of the application, otherwise the request will be rejected. If your application is
registered, the redirect_uri must contain the registered path of the application. Note At the moment an
application can be registered only if you have used Opcenter Execution Foundation UI Framework services.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 867


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

• scope: a string (case insensitive, with space separator) that identifies the scope for which the access token will
be used. Once the scope is declared, it cannot be changed on the returned token. The currently accepted value
is global.
• state: this parameter represents the value used by the client to establish a correlation between the request and
the response. The authorization server includes this value in the response to the client.
The client will then be redirected to the Identity Provider login page, where the login will be executed.
After a successful login, the client will be redirected again to the URI specified in the redirect_uri parameter in the
first request. The access token will be attached as a fragment to the URI.

https://localhost:44300/
callback.cshtml#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX...&token_type=bearer&ex
pires_in=1200&state=14553710.733142

ACCESS_TOKEN indicates the token encoded in Base64.


The client can extract other parameters from the fragment, such as the token type (e.g. Bearer) and the token
expiration time and the state, which must correspond to the state parameter in the first request in order to verify
the correlation between the request and the response.

 Be aware that for this type of clients, future versions of Opcenter Execution Foundation may require, for
security reasons, that you add a call to a new registration command containing an explicit declaration of
the application name.

Resource Owner Password Credentials


Based on the OAuth description, the Resource Owner Password Credential flow is suitable in cases where the
resource owner has a trust relationship with the client, such as the device operating system or a highly privileged
application. The authorization server should take special care when enabling this grant type and only allow it when
other flows are not viable.
A client application, which has a trust relationship with the resource owner (here meant as a MES/MOM User
profiled in the system) can obtain an Access Token by following the Resource Owner Password Credentials Grant as
described in the OAuth2 reference (see http://tools.ietf.org/html/rfc6749).

 In a distributed environment with more than one Opcenter Execution Foundation ready application node,
this flow is guaranteed if you configure the network load balancing in client affinity mode.

The Resource Owner Password Credential is represented by the following schema:

868 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

How to implement a client

 If an application is developed by using Project Studio and deployed with Solution Studio, it will be
automatically registered in the system. So this section only regards those custom client applications that
are developed outside Project Studio.

The actual implementation phase does not provide any endpoints that allow a Resource Owner to register/un-
register a client application.
Parameters described in the OAuth2 standards for a client registration
(i.e. Client_ID, Client_Secret and Client_RedirectionURI) must be set by the resource owner and provided to the
client.

 Important
We recommend that you configure Authorization Server binding on HTTPS only.

To do this you must go through the following steps:


1. Compose an Access Token request.
2. Refresh an Access Token.

Composing an Access Token request

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 869


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

The client uses the HTTP Basic authentication scheme to authenticate with the authorization server. The client
identifier must be encoded using the "application/x-www-form-urlencoded" encoding algorithm, and the encoded
value is used as the user name. In the same way client secret has to be encoded using the same algorithm and used
as the password.
For further details, see Section 2 of "HTTP Authentication: Basic and Digest Access Authentication" at http://
tools.ietf.org/html/rfc2617#section-2.

For example (with extra line breaks for display purposes only):
Authorization: Basic czZCaGRSa3F0Mzo3RmpmcDBaQnIxS3REUmJuZlZkbUl3

The client composes an Access Token request, which is compliant with OAuth2 specifications.
Clients make a request to the /OAuth/Token endpoint by adding the following parameters using the "application/x-
www-form-urlencoded" format with a UTF-8 character encoding in the entity-body of the HTTP request:
• grant_type (required): The value must be set to "password".
• username (required): The resource owner user name.
• password (required): The resource owner password.
• scope (required): The value must be set to "global".

Request Header

POST /token HTTP/1.1


Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

Request body

scope=global&grant_type=password&username=johndoe&password=A3ddj3w

If the outcome is successful, the client receives an Access Token response containing an Access Token that can be
used to send requests to resources exposed by the Service Layer or on the IUnifiedSdkLean.
Together with the response, the client also receives a refresh token that will be used to ask for a new access token
when the previous one has expired.

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
"example_parameter":"example_value"
}

870 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

Refreshing an Access Token


Starting from a refresh token, a client can ask for a new AccessToken if the previous one has expired.
The request can be composed in the same way as the access token, by using client_ID and Client_Secrets for the
HTTP basic authentication (see previous section) and by adding the following parameters using the "application/x-
www-form-urlencoded" format with a UTF-8 character encoding in the entity-body of the HTTP request:
• grant_type (required): the value must be set to "refresh_token".
• refresh_token (required): the refresh token issued to the client.
• scope (optional): the value must be set to "global".

POST /token HTTP/1.1


Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA

5.6.2 Obtaining the Access Token starting from an X.509 certificate


This page describes how to generate a certificate, how to use this certificate to generate an access token and then
how to import the certificate for validation.
You can use an x.509 standard certificate to authorize requests that arrive from the Opcenter EX FN Service Layer
exposition or from the IUnifiedSdkLean interface.
A certificate represents a specific module and it can be associated with one or more authorization roles in order to
grant a subset of user rights required by that module. In this way a certificated module can authenticate/authorize
requests without human interaction (this methodology is specific for server applications).

Workflow
1. Generate a valid certificate and its private key.
2. Create a JWT Access Token and use the certificate private key to sign it.
3. Import the Certificate to the Opcenter EX FN Manufacturing Solution.

 Time synchronization
Bear in mind that the machine on which you generate the certificate (client) and the machine on which the
certificate is validated (server) must be synchronized. If these machines are inside the same domain, time
synchronization is guaranteed by Active Directory. If machines are not in the same domain, you must
properly enable the Windows Time Service.

5.6.2.1 Generating a valid certificate and its private key


To create an access token from an X509 certificate, you must first generate a valid certificate and its private key.
There are several tools on the market that allow you to create an X.509 valid certificate. The current page does not
explain how to use these tools as the Opcenter Execution Foundation documentation is meant to only describe the
mandatory parameters required to create a valid certificate.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 871


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

 Here below you can find an example based on OpenSSL, which must be additionally installed on your
client machine, see https://www.openssl.org/.

Generating a file certificate and its private key

 This procedure must be executed on the client machine.

Generate a file certificate and its private key by using the following commands:

Operating Command Notes


System

• Windo PowerShell: The New-SelfSignedCertificate parameters must be used as follows:


ws 10
• New- • Subject, which must be specified as follows:
• Windo
SelfSigned "CN=MyProjectName,T=SimaticIT UA Foundation". While CN can be
ws
Certificate freely specified, T must be set to SimaticIT UA Foundation. This parameter
Server
• Export- contains the string of the project unique identifier it and must be
2016
PfxCertific specified as described, in order be a valid certificate for Opcenter
• Windo
ate Execution Foundation.
ws
Server • CertStoreLocation, which specifies where the file is installed (e.g. cert:
2019 \LocalMachine\My),
• HashAlgorithm, which must be set to sha512.
The Export-PfxCertificate can be used to create the secure PFX container.
This step is useful if you are using a C# application running on Windows) as
shown in the following example:

All OpenSSL: The example generates the certificate inside the PFX container. The certificate
operating openssl can be either loaded directly from the PFX container as described at Creating a
systems JWT Access Token and using a certificate to sign it or it can be manually
imported to the Certificate Store.

Examples

872 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

PowerShell example

#Generate the certificate


$cert = New-SelfSignedCertificate -Subject "CN=MyProjectName,T=SimaticIT UA
Foundation" -CertStoreLocation "cert:\LocalMachine\My" -Type "CodeSigningCert"
-HashAlgorithm "sha512" -KeyLength "2048" -NotAfter (Get-Date).AddYears(1)
-KeyExportPolicy Exportable -KeySpec Signature

#Generate a secure password for the PFX container


$psw = ConvertTo-SecureString "passwordtest" -AsPlainText -Force

#Export certificate to PFX file and associate the secure password


Export-PfxCertificate -Cert $cert -FilePath c:\temp\cert.pfx -Password $psw

OpenSSL example

//Generate the certificate


.\openssl req -config openssl.cnf -newkey rsa:2048 -nodes -keyout key.pem -x509 -days
365 -out certificate.pem -subj /CN="MyProjectManu1,T=SimaticIT UA Foundation"/

//Export the certificate to PFX file and associate the inserted password
.\openssl pkcs12 -inkey key.pem -in certificate.pem -export -out certificate.pfx

 You can generate a self-signed certificate or sign it by using a specific certification authority, according to
the project requirements.
For security reasons it is recommended that you use self-signed certificates only for testing reasons and
that you do not use SHA-1 algorithm to generate certificates.

5.6.2.2 Creating a JWT Access Token and using a certificate to sign it


To create an access token from an X509 certificate, you must first load the previously generated certificate and then
use it to generate a valid token.
The Access Token is the token required to invoke any Opcenter Execution Foundation exposed service (i.e. invoking
REST/OData services over the Web or directly using IUnifiedSdkLean methods). The token is built based on
the JSON Web Token (JWT) industry standard, and contains all the claims belonging to the certificate that has
originated it.
The provided code examples refer to C# / .NET platforms. Any different development that uses different
programming languages is outside the scope of this documentation.

Workflow

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 873


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

 This procedure must be executed on the client machine.

1. Load the certificate you have previously created in either of the following ways:
• directly from the file system
• from the Certificate Store
2. Create the JWT access token and sign it with the loaded certificate

Loading the certificate from the file system


You can load the certificate from the .PFX file directly from the file system by using the following code example:

X509Certificate2 certificate = new X509Certificate2(pfxPath, password);

Loading the certificate from the Certificate Store


1. Import the .PFX file via PowerShell script as shown in the following example

$psw = ConvertTo-SecureString "passwordtest" -AsPlainText -Force

Import-PfxCertificate -CertStoreLocation Cert:\LocalMachine\My -FilePath C:


\sample\cert.pfx -Password $psw

 This example is compatible with Windows 10 and Windows Server 2016. On Windows 2012 R2 you
should refer to the manual import procedure below (Importing the PFX file with Wizard note).

2. Load the certificate from the Windows local machine certificate store. The following snippet represents only an
example and you can change the way you select the certificate from the Certificate Store depending on the
needed use case:

using System.Security.Cryptography.X509Certificates;
...

// Load x.509 certificate, in this sample it is assumed that the certificate


is installed on the LocalMachine account under the Personal store
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindByIssuerName,
"custom module unique name", false);

874 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

 Importing the PFX file with Wizard


You can import the certificate from the .PFX file to the Certificate Store with the Certificate Import Wizard
as follows:
1. Double click the .PFX file to start the Certificate Import Wizard. If the wizard does not start, contact
your IT administrators for correctly using the Certificate Import Wizard utility.
2. Select the certificate store location (e.g. Local Machine) and click Next. If you are on the Opcenter EX
FN host, the store location must be set to Local Machine.
3. Enter the path of the .PFX file and click Next.
4. Type the password for the private key, leave the default options and click Next.
5. Select Place all certificates in the following store option and Personal as certificate store, and then
click Next.
6. Click Finish.

Creating the access token and signing it with the loaded certificate
Starting from the loaded certificate, your application can instantiate the Opcenter Execution Foundation access
token using the JwtSecurityTokenHandler class from the System.IdentityModel.Tokens.Jwt nuget package.
To correctly create an access token for Opcenter Execution Foundation, you must respect a set of rules:
• The token must contain the claim type with the certificate issuer name (ClaimType.Name).
• The token must contain the claim type with the certificate thumbprint (ClaimType.Thumbprint).
• The token must contain the "urn:realm" custom claim type, including the string "x.509".
• The TokenIssuerName attribute must be set to "urn:unifiedoauth".
• The AppliesToAddress attribute must be set to "urn:unified".
• The LifeTime attribute must be set to the life time of the chosen session. The LifeTime class has two
parameters: the first parameter indicates the time before which the JWT token must not be accepted for
processing. The second parameter indicates the expiration time after which the JWT token must not be
accepted for processing. Developers may add some leeway, usually no more than few minutes, to account for
clock skew.
• The SigningCredential attribute must be set using the X509SigningCredentials class built with the module
certificate.
A code example, which shows how to create the access token and sign it with the loaded certificate, is provided.

 Compatibility
The following code example works with version 4.0.0 of the System.IdentityModel.Tokens.Jwt package.
If you have a more recent version, the code must be adapted accordingly.
If you are generating a token within the code of an application that uses the IUnifiedSdkLean interface,
you can only use the System.IdentityModel.Tokens.Jwt assembly version that is already installed by
Opcenter Execution Foundation.
Add the following references to your project:
• a reference to the System.IdentityModel.Tokens.Jwt NuGet package,
• a reference to the System.IdentityModel assembly (which can be found in the Assemblies system
folder).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 875


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
...

// Create x.509 signed token


var now = DateTime.UtcNow;
var tokenHandler = new JwtSecurityTokenHandler();

// certificate was previously loaded either from the filesystem or from


the X509Store (see code examples above)
X509SigningCredentials x509SigningCredentials = new
X509SigningCredentials(certificate);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject =
new ClaimsIdentity(
new Claim[]
{
new Claim(ClaimTypes.Name,
certificate.Issuer),
new
Claim(ClaimTypes.Thumbprint, certificate.Thumbprint),
new Claim("urn:realm", "x.
509"),
}),
TokenIssuerName = "urn:unifiedoauth",
AppliesToAddress = "urn:unified",
Lifetime = new Lifetime(now.AddMinutes(-2),
now.AddMinutes(15)),
SigningCredentials = x509SigningCredentials
};

SecurityToken securityToken = tokenHandler.CreateToken(tokenDescriptor);


string token = tokenHandler.WriteToken(securityToken);

5.6.2.3 Importing the Certificate into the Opcenter EX FN Solution


To create an access token from an X509 certificate, you must install and import the previously generated certificate
into the Opcenter EX FN hosts and then associate the certificate to the Opcenter EX FN user roles.

 This procedure must be executed on all the Opcenter EX FN hosts (both on the Engineering host and on all
Runtime hosts).

Installing and importing the certificate


Install the custom module certificate on all Opcenter EX FN hosts (Engineering and Runtime) by adding the newly
created certificate to the local machine account in the Windows certificate personal store.

876 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Managing Client Authorization

For this operation you only need the .CER file containing the certificate public key:
1. Double click the .CER file to start the Certificate Import Wizard.
2. Select Local Machine as store location and click Next.
3. Enter the path of the certificate .CER file and click Next.
4. Select Place all certificates in the following store option and Personal as certificate store, and then
click Next.
5. Click Finish.

Associating the certificate with user roles


This procedure must be executed on the Engineering host.
After deploying the Opcenter EX FN Manufacturing Solution and after you have started the Engineering host at least
once, you must import the certificate associated into your custom module and assign it to one or more user
roles (defined in the Opcenter EX FN Manufacturing Solution) by using the Opcenter EX
FN importcert.exe application.
The code example below assumes that you have already configured two user roles: Role1 and Role2, which must
have been associated with the required operation types as described in the Configuring user roles page.
1. Start a Windows command prompt with a user that is associated with the Opcenter EX FN SysAdmin role.
2. Run importcert.exe file which can be found in the binary folder of the Opcenter EX FN installation path.
3. Set the following mandatory parameters:
• /thumbprint: the thumbprint associated to the installed certificate. If you need to know how to retrieve
the thumbprint value, see the Retrieving the thumbprint from the certificate note below.
• /roles: full name of one or more Opcenter EX FN security roles (comma separated) previously configured
in Solution Studio. The role full name can be copied from the Role Details pane in Solution Studio, which
is accessible from the Roles page in Solution Studio (see page Creating Roles).

importcert /thumbprint:C83B8EAEF577BFA4476DFAE2CCF9556D85F82F6E /roles:Role1,Role2

Note After you have run importcert.exe, the association between certificate and roles is immediately active.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 877


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

 Retrieving the thumbprint from the certificate


1. In the Microsoft Management Component, double-click the .CER file you have created.
2. In the Certificate dialog box, click the Details tab and select Thumbprint (verify that the Show
All option is enabled in the Show list box).
3. In the details area below, copy the displayed string and paste it to the command line by removing all
the blank spaces.

 A user can be associated to the Opcenter EX FN SysAdmin role either with the Opcenter Execution
Foundation Configuration tool, as described at Configuring the Engineering Host in the Opcenter Execution
Foundation Installation Guide, or by following procedure described at Assigning the SysAdmin Role in the
Opcenter Execution Foundation Installation Guide.

5.7 Interacting with Opcenter Execution Foundation by Using cURL


It is possible to interact with the public exposition of Opcenter Execution Foundation by using a cURL project.
This page describes how to set the environment, how to retrieve an access token, execute a query or a command
exposed through the Opcenter EX FN Service Layer.
The procedure applies to Windows and Linux operating systems.

878 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

 All code snippets are only examples and must be consequently adapted to your environment and data
model.

Prerequisites
For Windows, either of the following:
• Cygwin and cURL package
• The Windows Subsystem for Linux feature on Windows 10
For Linux:
• cURL

Preliminary operations
1. Manually create the following scripts in the Cygwing home, starting from the provided code snippets:
• getToken.sh
• getTokenFromRefresh.sh
• unifiedget.sh
• unifiedpost.sh
2. Using the Cygwin terminal, execute the following command to enable the execution of the scripts:

chmod +x *.sh

3. Execute the getToken.sh script by passing in the following arguments:


• the host name where the Opcenter EX FN Authorization Server is installed,
• user name and password of the user you to authorize

./getToken.sh localhost test test

Note: Passwords might contain special characters that must be substituted by literal characters
introduced by single quotes (e.g. supersecret$1 would become 'supersecret$1') as exemplified in the
following snippet:

./getToken.sh localhost "test" 'supersecret$1'

 After the execution of the getToken.sh script, the home folder contains two new files containing the
access token and refresh token. These files are used from other scripts as input parameters.
If you need to refresh the token, execute the getTokenFromRefresh.sh script, and remember that an
access token expires after 10 minutes (so, when it expires you have to refresh it).

./getTokenFromRefresh.sh

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 879


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

 If you need information on the utility, display the inline help by running the ./getToken.sh -h command.

Querying data from Opcenter EX FN Service Layer


To query data, you can copy the unifiedget.sh script to another file (e.g. unifiedgetxml.sh) and then modify the
script by entering as argument the endpoint where you can retrieve the metadata of the Opcenter EX FN OData
model:

./unifiedget.sh 'http://localhost/sit-svc/application/odata/$metadata'

To retrieve the $metadata, the unifiedget.sh utility sends its requests in JSON format, while the $metadata URL is
structured in XML format. Consequently, you must appropriately modify the script by entering the following cURL
command invocation:

CURL='curl -X GET '"'$URL'"' -H "Authorization: Bearer '$TOKEN'" -H "Accept:


application/xml, text/plain, */*"'

Invoking commands exposed on the Opcenter EX FN Service Layer


1. In the Cygwing folder home, add a file named input.json.txt.
2. Enter in JSON format the parameters that have been defined for the command you want to invoke in the
command section. The basic template of the input.json.txt is formatted as follows:

{
command:
{
}
}

{command:{Id:"4C45FD6F-D0ED-4B01-8BAD-45FE24520012", Name:"SampleName",
Description:"SampleDescription"}}

3. To invoke a command, execute the following script:

./unityPost.sh 'http://localhost/sit-svc/application/odata/testcommand'

5.7.1 Code Snippets for cURL projects


The following code snippets can be used as examples to develop cURL projects scripts required to interact with
Opcenter EX FN.

Code snippets

880 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

getToken.sh

#!/bin/bash
##
# getToken.sh
#
# Implement a Grant Resource Owner Credentials OAUTH scheme.
# Usage: getToken "OAUTH Host" "User" "password"
# or
# Usage: getToken "OAUTH Host" "User"
# and input the password interactively (hidden)
# Revision 01/09/2016:
# change the interactive input of the password to enclose the literal string for
special characters escaping in the urlencoded form
##
: ${1?"Usage: $0 \"<OAUTH Host IP or name> <user> [password]\" remember to escape \$
in user and password or enclosing the string with single ' char in the command line.
Es: 'super\$ecret'"}
SITAUTH_HOST=$1
: ${2?"Usage: $0 \"<OAUTH Host IP or name> <user> [password]\" remember to escape \$
in user and password and enclosing the string with single ' char in the command line.
Es: 'super\$ecret'"}
USER=$2
if [ -z "$3" ]
then
echo -n Password: 1>&2
read -s PASSWORD
echo
else
PASSWORD=$3
fi
rm response.txt > /dev/null 2>&1
shopt -s extglob # Required to trim whitespace; see below
CLIENT_ID="1234"
CLIENT_SECRET="kijcdsnfdsknjucd"
SCOPE="global"
AUTHORIZE="$CLIENT_ID:$CLIENT_SECRET"
AUTHORIZEB64=$(echo $AUTHORIZE | base64)
CURL='curl -X POST -is "http://'$SITAUTH_HOST'/sit-auth/OAuth/Token" -H "Content-
Type: application/x-www-form-urlencoded" --data-urlencode "client_id='$CLIENT_ID'" --
data-urlencode "client_secret='$CLIENT_SECRET'" --data-urlencode "scope='"$SCOPE"'"
--data-urlencode "grant_type=password" --data-urlencode "username='$USER'" --data-
urlencode ''password="$PASSWORD"'' --connect-timeout 5 2>/dev/null'
echo $CURL
eval $CURL > response.txt
#
# Request to QoS OAUTH Authentication Provider...
#
while IFS=':' read key value; do
# trim whitespace in "value"
value=${value##+([[:space:]])}; value=${value%%+([[:space:]])}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 881


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

case "$key" in
Content-Type) CT="$value"
;;
HTTP*) read PROTO STATUS MSG <<< "$key{$value:+:$value}"
;;
esac
done < response.txt
if [ -z "$STATUS" ]; then
echo "Host Connection failed: " "$SITAUTH_HOST" 1>&2
echo "Invalid Token" > access_token
echo "Invalid Token" > refresh_token
exit -1
fi

#echo $STATUS # DEBUG


#echo $LOCATION # DEBUG
#echo $SITAUTH_COOKIE #DEBUG
#echo
if [ $STATUS -ne 200 ]; then
echo "Authentication failed with status: " "$STATUS" 1>&2
cat response.txt
echo "Invalid Token" > access_token
echo "Invalid Token" > refresh_token
exit -2
fi
TOKEN=$(cat response.txt | grep -Po '\"access_token\"\:\"\K.*?(?=")')
REFRESH=$(cat response.txt | grep -Po '\"refresh_token\"\:\"\K.*?(?=")')
echo $TOKEN
#Initiate the 'session' in the local directory
echo $TOKEN > access_token
echo $REFRESH > refresh_token
echo $SITAUTH_HOST > oauth_host

882 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

getTokenFromRefresh.sh

#!/bin/bash
##
# getTokenFromRefresh.sh
#
# Implement a Grant Resource Owner Credentials OAUTH scheme.
# Refresh token request
# Return a new valid token (and a refresh token) from a previous refresh token,
# This can be used when the access_token expires in order to prolong the already
validated credentials.
# Usage: getTokenFromRefresh
# Note: the refresh token must be available in file refresh_token and acquired by
getToken.sh previously
##

# use the first getToken OAuth host.


SITAUTH_HOST=$(cat oauth_host)
rm response.txt > /dev/null 2>&1
shopt -s extglob # Required to trim whitespace; see below
CLIENT_ID="1234"
CLIENT_SECRET="kijcdsnfdsknjucd"
AUTHORIZE="$CLIENT_ID:$CLIENT_SECRET"
AUTHORIZEB64=$(echo $AUTHORIZE | base64)
REFRESH_TOKEN=$(cat refresh_token)
CURL='curl -X POST -is "http://'$SITAUTH_HOST'/sit-auth/OAuth/Token" -H "Content-
Type: application/x-www-form-urlencoded" -H "Authorization: Basic '$AUTHORIZEB64'" --
data-urlencode "grant_type=refresh_token" --data-urlencode
"refresh_token='$REFRESH_TOKEN'" --data-urlencode "scope='$SCOPE'" --connect-timeout
5 2>/dev/null'
#echo $CURL
eval $CURL > response.txt
#
# Request to QoS OAUTH Authentication Provider...
#
while IFS=':' read key value; do
# trim whitespace in "value"
value=${value##+([[:space:]])}; value=${value%%+([[:space:]])}
case "$key" in
Location) LOCATION="$value"
;;
Content-Type) CT="$value"
;;
HTTP*) read PROTO STATUS MSG <<< "$key{$value:+:$value}"
;;
Set-Cookie) SITAUTH_COOKIE="$value"
;;
access_token) TOKEN="$value"
;;
esac
done < response.txt

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 883


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

if [ -z "$STATUS" ]; then
echo "Host Connection failed: " "$SITAUTH_HOST" 1>&2
exit -1
fi

#echo $STATUS # DEBUG


#echo $LOCATION # DEBUG
#echo $SITAUTH_COOKIE #DEBUG
#echo
if [ $STATUS -ne 200 ]; then
echo "Authentication failed with status: " "$STATUS" 1>&2
cat response.txt
echo "Invalid Token" > access_token
echo "Invalid Token" > refresh_token
exit -2
fi
TOKEN=$(cat response.txt | grep -Po '\"access_token\"\:\"\K.*?(?=")')
REFRESH=$(cat response.txt | grep -Po '\"refresh_token\"\:\"\K.*?(?=")')
echo $TOKEN
echo $TOKEN > access_token
echo $REFRESH > refresh_token

884 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

unifiedget.sh

#!/bin/bash
# Generate a single request to the Service Layer runtime (or engineering) URI using
the test token (see UnityStress if you need a login token)
# Input is the URL of the request.
# Output is the response to stdout and resonse.txt
RED='\033[1;31m'
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
NOCOL='\033[0m' # No Color
TOKEN=$(cat access_token)
echo
#echo $1
URL="${1:?Usage $0 \'Service Layer Request URL\'; -h for help}"
CURL='curl -X GET '"'$URL'"' -H "Authorization: Bearer '$TOKEN'" -H "Accept:
application/json, text/plain, */*" -D header.txt'
echo $CURL
if [ "$1" = "-h" ]
then
echo "Usage:" $0 " 'Service Layer URL'"
echo "example: $0 '"'http://127.0.0.1/runtime/odata/$metadata'"'"
echo BEWARE of quoting URL with single quote \(like the example above\) to avoid
'"$metadata"' expansion!!!
exit -1
fi

rm response.txt > /dev/null 2>&1


rm stderr.txt > /dev/null 2>&1
rm header.txt > /dev/null 2>&1

echo 'Sending '$URL' request...'


# ---- Perform the request/response ----
eval $CURL > response.txt 2>stderr.txt
# Wait some time to check the results...
echo
#
# VALIDATING RESULTS
#
NUMOK=$(cat response.txt | grep -o "@odata" | wc -l)
if [ $NUMOK -gt 0 ]
then
# EVERYTHING's FINE!
echo -e ${GREEN}$NUMOK responses OK over $n requests.${NOCOL}
cat response.txt
else
echo -e ${YELLOW}$NUMOK responses OK over $n requests.${NOCOL}
TOKERR=$(cat response.txt | grep -o "\"code\":\"3002\"" | wc -l)
if [ $TOKERR -gt 0 ]
then
echo -e ${YELLOW}Reporting $TOKERR token authentication failures. ${NOCOL}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 885


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

fi
echo Error messages are:
echo -en ${RED}
cat response.txt | grep -o -P "\"message\":\".[^\"]*"\" | uniq
echo -en ${NOCOL}
exit -1
fi

886 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

unifiedpost.sh

#!/bin/bash
# Generate a single request to the Service Layer runtime (or engineering) URI using
the test token (see UnityStress if you need a regular login token)
# Input is the URL of the request and input.json.txt (the json object to send as a
body of the POST).
# Output is the response to stdout and response.txt
RED='\033[1;31m'
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
NOCOL='\033[0m' # No Color
TOKEN=$(cat access_token)
echo
#echo $1
URL="${1:?Usage $0 \'Service Layer Request URL\'; -h for help}"
CURL='curl -X POST '"'$URL'"' -H "Authorization: Bearer '$TOKEN'" -H "Content-Type:
application/json" -H "Accept: application/json, text/plain, */*" --data-binary
@input.json.txt'
echo $CURL
if [ "$1" = "-h" ]
then
echo "Usage:" $0 " 'Service Layer URL'"
echo "example: $0 '"'http://127.0.0.1/runtime/odata/$metadata'"'"
echo BEWARE of quoting URL with single quote \(like the example above\) to avoid
'"$metadata"' expansion!!!
exit -1
fi

rm response.txt > /dev/null 2>&1


rm stderr.txt > /dev/null 2>&1

echo 'Sending '$URL' request...'


# ---- Perform the request/response ----
eval $CURL > response.txt 2>stderr.txt
# Wait some time to check the results...
echo
#
# VALIDATING RESULTS
#
NUMOK=$(cat response.txt | grep -o "\"Succeeded\":true" | wc -l)
if [ $NUMOK -gt 0 ]
then
# EVERYTHING's FINE!
echo -e ${GREEN}$NUMOK responses OK over $n requests.${NOCOL}
cat response.txt
else
echo -e ${YELLOW}$NUMOK responses OK over $n requests.${NOCOL}
TOKERR=$(cat response.txt | grep -o "\"code\":\"3002\"" | wc -l)
if [ $TOKERR -gt 0 ]
then

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 887


How to Integrate Opcenter Execution Foundation with Third-Party Business Logic

Interacting with Opcenter Execution Foundation by Using cURL

echo -e ${YELLOW}Reporting $TOKERR token authentication failures. ${NOCOL}


fi
echo Error messages are:
echo -en ${RED}
cat response.txt | grep -o -P "\"message\":\".[^\"]*"\" | uniq
echo -en ${NOCOL}
exit -1
fi

888 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker Runtime Instances

6 How to Monitor Opcenter EX FN Runtime Processes


You can use the following monitoring applications for troubleshooting and diagnostics purposes, for example to
debug an application, or to determine where performance issues are occurring in the application:
• Solution Studio Host Monitoring to view Host status and subsystem status information (see Monitoring Hosts
with Host Monitoring)
• Solution Studio Host Management to view Host status (see Deploying the Solution Package to Hosts)
• Opcenter EX FN Runtime Monitor, to monitor worker roles, worker instances, and hosts from Opcenter EX
FN servers (see Monitoring Worker Runtime Instances)
• custom Web Clients to monitor worker roles, worker instances, and hosts (see Monitoring Worker and Host
Status from Web Clients)
• Opcenter EX FN Trace Viewer, to log application messages such as errors, warnings and information to a file or
consume them in real time (see Logging and Analyzing Application Traces with Trace Viewer and Analyzing
Application Traces with Trace Viewer Stand-Alone)
• Microsoft Event Viewer, to view security-related traces and save them to a file (see Persisting System, Security
and Application Messages on Microsoft Event Viewer)
• Opcenter EX FN Dumps (see Viewing Opcenter EX FN Application Dumps)
• Automation Gateway Server Monitor (see How to Monitor Automation Gateway Server documented in the
Opcenter Execution Foundation User Manual).
• Application Log App to log application-defined events (see Application Log App documented in the Opcenter
Execution Foundation User Manual).

6.1 Monitoring Worker Runtime Instances


The Opcenter Execution Foundation - Worker Monitor is a system monitor application that allows you to retrieve
information about:
• The environment hosts and the related status
• The Worker Roles and their Worker instances
• For each Worker instance, the list of the loaded commands, event subscriptions (with the related envelopes),
signals
• The active Signal Manager and the running Signal Rules and Timers (Availability Groups)
• In case of Active/Standby RabbitMQ configuration, the active RabbitMQ leader instance (Availability Group)
• If configured, the active Sequential Worker instance (Availability Group)
• The Automation Worker Role (only on the Engineering host)
• General information about Signal manager, Worker instances and their status, critical errors

Prerequisite
The user who runs the Worker Monitor:
• belongs to the SIT_UNIFIED_LOW Windows group, both on the Opcenter EX FN hosts and, in case of separate
database server, on the SQL Server host.
• is a User Management Component user (for more information on how to import users to UMC, see Import
Windows Local Users in the UMC UMX User Manual).

Opening the Worker Monitor


1. Run the WorkerMonitor.exe application from %SITUnifiedSystemRoot%bin.
2. Click the required tab according to the information you want to retrieve (see section below).

Worker Monitor dashboard details


The Worker Monitor shows information on three tabs:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 889


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker Runtime Instances

• The Hosts tab shows the list of environment hosts with the related workers.
• The Worker Roles tab shows the configured Worker Roles, the assigned workers and for each selected worker
the following information:
• the worker type (Engineering, Administration, Application and Signal Manager),
• the running CPU type (x64 bit or x32 bit),
• the configured retries' number (see Creating a New Worker Role),
• the execution mode (either parallel or sequential),
• the parallel executions admitted, which are automatically set to 1 for the sequential worker roles and are
automatically calculated by the system for parallel workers (as explained at page Parallel vs. Sequential
Command and Event Handler Execution).
• The HA Groups tab shows the list of the of the High Availability Groups, which are currently used for Signal Rules
and Timers, for Sequential Worker Roles and for the RabbitMQ leader instance. This tab shows where each
group is active and the status on each host.

 The HA Groups status returns an error (and the system switches to another HA group, if available) if the HA
Group fails repeatedly and rapidly within a system-defined time frame. See Deploying the Solution
Package to Hosts.

Worker Monitor graphic elements


The following icons identify the displayed items:

Ico Element identified


n

Host

Worker Role

Worker

Protected command

Private command

Public command, visible on the Service Layer, which can be either Protected or Composite

Command associated with a Worker Role

Composite command

Signal

890 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Ico Element identified


n

Event

Event Handler subscription

Post-Action, enabled in Solution Studio to be running

Signal Rule. Colors are used to indicate the rule execution status:

• : Rule error
• : Rule loaded
• : Rule running
• : Rule unknown

Placed on the bottom left corner of the dashboard, it indicates the presence of critical errors. Click on it to
see the list of errors.
The Worker Monitor displays the states of the elements that can have an error and a descriptive string.

Troubleshooting Worker Monitor


If you have an instance of the Worker Monitor that is opened while configuring any Opcenter EX FN host with the
Opcenter Execution Foundation Configuration tool, you must close and reopen the Worker Monitor instance to
refresh the displayed items.

6.2 Monitoring Worker and Host Status from Web Clients


Understanding the state of the Opcenter EX FN environment is essential for ensuring system reliability and stability.
Information about system health and performances not only helps you to face and solve issues, but it also ensures
that actions are carried out with confidence.
One of the best ways to gain this insight within the system is by means of a robust monitoring system that gathers
metrics, visualizes data, and alerts operators when issues arise.
For this purpose, the platform provides you with a dedicated endpoint that can be queried from custom web client
applications in order to retrieve information about environment hosts and running workers. In order to access this
endpoint you must be authenticated and authorized.
The monitoring endpoint (monitoring) returns a JSON structure with the information explained below.

Characteristics of the monitoring endpoint


Compared to other platform monitoring applications/services, the monitoring endpoint offers infrastructure
independence and multi-source information.
• The monitoring endpoint is independent from the Opcenter EX FN infrastructure:
The monitoring endpoint can be reached from any web clients connected to the Opcenter EX FN environment
by means of a reverse proxy server. In this way, querying the monitoring endpoint has a low impact on the
environment performances, still granting reliability in case of problems occurring to other systems.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 891


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

• The monitoring endpoint aggregates information coming from different sources:


The monitoring endpoint accesses the Opcenter EX FN infrastructure state by means of different information
types. The endpoint returns any information that helps you understand the underlying system interactions
and the overall platform status. Some of the information is also visible in the Host Management in Solution
Studio and the Worker Monitor.
• The monitoring endpoint can only be accessed with a valid authentication token that permits authentication
and authorization.

How to query the monitoring endpoint


To correctly access the endpoint you need to:
• compose the request with a valid authentication token (i.e. with a user that belongs either to the Opcenter EX
FN SysAdmin or to the SystemMonitoring role, see How to Configure Accounts),
• generate the token as described at page Managing Client Authorization,
• perform the query by sending a GET request to the url: http://<hostname>/sit-svc/monitoring.

Monitoring Endpoint Response – Detailed field description


Structure Name Field Name Description

Environment Name The name of the Opcenter EX FN


Environment as defined in the system
configuration phase (i.e either in the
Opcenter Execution Foundation
Configuration tool or via scripts as
documented in the Opcenter Execution
Foundation Installation Manual).

Environment Hosts List of the hosts that compose the


Opcenter EX FN Environment.

Environment\Hosts Name The name of the host.

892 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Structure Name Field Name Description

InternalStatus The overall running status of the host.


The following statuses can be returned:
• Unknown: It occurs when it is not
possible to determine the host
status.
• Initial: Initial node state (node state
machine initial state).
• Initializing: Node initialization
intermediate state.
• Maintenance: Node maintenance
state.
• Offline: Offline node state.
• StoppedError: Node error state
(occurred when the node is stopped).
• Deploying: Node deploying
intermediate state.
• DbScaffolding: Node database
scaffolding intermediate state.
• Ready: Node ready state.
• Starting: Node starting intermediate
state.
• Stopping: Node stopping
intermediate state.
• UIMaintenance: Node maintenance
state (UI only).
• UIDeploying: Node deploying
intermediate state (UI only).
• Run: Node running state.
• RunningError: Node error state
(occurred when the node is running).
• ShuttingDown: Node shutting down
state.
• RuntimeUpdating: Packages
Runtime update intermediate state.

Environment\Hosts LastUpdate The datetime of the last information


update.

Environment\Hosts Workers List of the workers running on the host.

Environment\Hosts HostUpdateTime The datetime of the last time the host


updated its state.

Environment\Hosts\Workers Name The name of the Worker.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 893


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Structure Name Field Name Description

Environment\Hosts\Workers Type The type of Worker Role to which the


Worker belongs.
The possible types are:
• Undefined
• Engineering
• Application
• Administration

Environment\Hosts\Workers Role The Role of the Worker.

Environment\Hosts\Workers Status The status of the Worker.


The possible values are:
• Unknown
• Ready
• Running
• Stopped
• Error
• Start
• Initializing
• Uninitializing
• PendingWorkCleanUp
• Close,Created
• PendingStart
• PendingStop
• Failed

Environment\Hosts\Workers PID The Process ID assigned to the Worker.

Environment\Hosts\Workers Last Update The datetime of the latest information


update.

Environment\Hosts\Workers Statistics List of relevant counters for the Host


Worker.

Environment\Hosts\Workers\Statisti Runtime The Category of the Statistics.


cs

Environment\Hosts\Workers\Statisti Name The name of the Statistic.


cs\Runtime

Environment\Hosts\Workers\Statisti Counters The counters of the Statistic.


cs\Runtime

Environment\Hosts\Workers\Statisti RunningHandlers The counters for running handlers.


cs\Runtime\Counters

894 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Structure Name Field Name Description

Environment\Hosts\Workers\Statisti Id The Id of the Handler


cs\Runtime\Counters\RunningHandl
ers

Environment\Hosts\Workers\Statisti Name The Name of the Handler


cs\Runtime\Counters\RunningHandl
ers

Environment\Hosts\Workers\Statisti Value The counter value


cs\Runtime\Counters\RunningHandl
ers

Environment\Hosts\Workers\Statisti AggregationType Criteria for counter aggregation


cs\Runtime\Counters\RunningHandl
ers

Environment\Hosts\Workers\Statisti RunningRootCommands The counters for running commands.


cs\Runtime\Counters

Environment\Hosts\Workers\Statisti Id The Id of the Command


cs\Runtime\Counters\RunningRootC
ommands

Environment\Hosts\Workers\Statisti Name Then Name of the Command


cs\Runtime\Counters\RunningRoot
Commands

Environment\Hosts\Workers\Statisti Value The counter Value


cs\Runtime\Counters\RunningRoot
Commands

Environment\Hosts\Workers\Statisti Aggregation Type Criteria for counter aggregation


cs\Runtime\Counters\RunningRoot
Commands

Environment\Hosts Statistics List of relevant counters for the host.

Environment\Hosts\Statistic System The Category of the Statistic.

Environment\Hosts\Statistic\System Name The Name of the Statistic.

Environment\Hosts\Statistic\System Counters List of relevant counters for the statistic.

Environment\Hosts\Statistic\System NumberOfCPUCores List of relevant information for CPU


\Counters Cores.

Environment\Hosts\Statistic\System Id The Id of the counter.


\Counters\NumberOfCPUCores

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 895


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Structure Name Field Name Description

Environment\Hosts\Statistic\System Name The Name of the counter.


\Counters\NumberOfCPUCores

Environment\Hosts\Statistic\System Value The actual value of the counter.


\Counters\NumberOfCPUCores

Environment\Hosts\Statistic\System Description The description for the counter.


\Counters\NumberOfCPUCores

Environment\Hosts\Statistic\System Aggregation Type The criteria for counter aggregation.


\Counters\NumberOfCPUCores

Environment\Hosts License Information related to the actual license


assigned to the Host.

Environment\Hosts\License Expiration The expiration date time of the license


assigned to the Host.

Environment\Hosts\License Product Name The product name for the license


assigned to the Host.

Environment\Hosts\License Product Version The product version for the license


assigned to the Host.

Environment\Hosts\License Type The type of the license assigned to the


Host.

Environment\Hosts Solution Information about the actual solution


deployed on the Host.

Environment\Hosts\Solution Name The name of the solution deployed on


the Host.

Environment\Hosts\Solution Version The version of the Solution deployed on


the Host.

Environment\Hosts\Solution Build The build number of the solution


deployed on the Host.

Environment\Hosts Warnings List of relevant warning messages


generated by the Host.

Environment\Hosts\Warning ReasonId The Id of the warning.

Environment\Hosts\Warning ReasonDescription The description of the warning.

896 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Structure Name Field Name Description

Environment\Hosts Errors List of relevant error messages generated


by the Host.

Environment\Hosts\Errors ReasonId The Id of the error.

Environment\Hosts\Errors ReasonDescription The description of the error.

Environment\Hosts\Subsystems Id Unique identifier of the subsystem. For


more information on subsystems,
see Retrieving Information from Scenario
Subsystems.

Name Name of the subsystem.

Description A short description of the meaning of the


subsystem.

Properties List of values, containing:


• Id, Unique identifier of the property
• Displayname
• Value

Status The status of the subsystem referred to


the specific host.

Environment\WorkerRoles WorkerType The type of the Worker Role.


Possible values are:
• Undefined
• Engineering
• Application
• Administration

Environment\WorkerRoles TargetCPU The CPU type on which the Worker


belonging to the Worker Role will run.
Possible values are:
• x64
• x86

Retries The maximum number of retries.

Environment\WorkerRoles ExecutionMode The mode in which Worker belonging to


the Worker Role will execute.
Possible values are
• Parallel
• Sequential

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 897


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Structure Name Field Name Description

NumberOfParallelExecutio The number of parallel executions.


ns

Environment AvailabilityGroups List of the current availability groups


configured in the environment.

Environment\AvailabilityGroups Name The name of the availability group.

Environment\AvailabilityGroups LeaderHost The Host name of the current leader in


the availability group.

Environment\AvailabilityGroups AliveTime The date time of the latest leader


heartbeat.

Environment\AvailabilityGroups ErrorDescription The error description.

Environment\AvailabilityGroups ErrorId The error Id.

Environment\AvailabilityGroups LastUpdate The date time of the latest information


update.

Environment\AvailabilityGroups Status The actual overall status of the


availability group.
Possible values are:
• Unknown
• Initializing
• Standby
• Error
• PendingOnline
• PendingOffline
• Active
• Closing
• Close

Environment\AvailabilityGroups ResourceGroup Details for resources managed by the


group

Environment\Subsystems Id Unique identifier of the subsystem

Name Name of the subsystem

Description A short description of the meaning of the


subsystem

898 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Structure Name Field Name Description

Properties List of values, containing:


• Id, Unique identifier of the property
• Displayname
• Value
• Host: At this level the property is
aggregated. This is the host the
property value refers to.

Status The status of the subsystem returned as


an aggregation of the values of all the
hosts where the subsystem is active.

Monitoring Endpoint Response – Raw Data Example


The following snippet shows an example of data structure returned by the endpoint query, i.e. a JSON data
structure object.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 899


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Document object format

{
"Environment": {
"Name": "Opcenter EX FN Environment",
"Hosts": [
{
"Name": "VM-OpcenterEXFN-1",
"InternalStatus": "Run",
"LogicalStatus": "Started",
"LastUpdate": "2019-09-04T14:41:51.9828876+00:00",
"HostUpdateTime": "2019-09-04T14:39:59.5447192+00:00",
"Workers": [
{
"Type": "Administration",
"Name": "VM-OpcenterEXFN-1.ADM.0",
"Role": "ADM",
"Status": "Ready",
"PID": 15628,
"LastUpdate": "2019-09-04T16:41:52.5952863+02:00",
"Statistics": {
"Runtime": {
"Name": "Runtime",
"Counters": {
"RunningHandlers": {
"Id": "RunningHandlers",
"Name": "RunningHandlers",
"Value": 0.0,
"AggregationType": "None"
},
"RunningRootCommands": {
"Id": "RunningRootCommands",
"Name": "RunningRootCommands",
"Value": 0.0,
"AggregationType": "None"
}
}
}
}
},
{
"Type": "Application",
"Name": "VM-OpcenterEXFN-1.Default WorkerRoleDefinition (x64).0",
"Role": "Default WorkerRoleDefinition (x64)",
"Status": "Ready",
"PID": 19852,
"LastUpdate": "2019-09-04T16:41:48.7021088+02:00",
"Statistics": {
"Runtime": {
"Name": "Runtime",
"Counters": {

900 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"RunningHandlers": {
"Id": "RunningHandlers",
"Name": "RunningHandlers",
"Value": 0.0,
"AggregationType": "None"
},
"RunningRootCommands": {
"Id": "RunningRootCommands",
"Name": "RunningRootCommands",
"Value": 0.0,
"AggregationType": "None"
}
}
}
}
},
{
"Type": "Application",
"Name": "VM-OpcenterEXFN-1.SignalManager.0",
"Role": "SignalManager",
"Status": "Ready",
"PID": 18196,
"LastUpdate": "2019-09-04T16:41:49.6563591+02:00",
"Statistics": {
"Runtime": {
"Name": "Runtime",
"Counters": {
"RunningHandlers": {
"Id": "RunningHandlers",
"Name": "RunningHandlers",
"Value": 0.0,
"AggregationType": "None"
},
"RunningRootCommands": {
"Id": "RunningRootCommands",
"Name": "RunningRootCommands",
"Value": 0.0,
"AggregationType": "None"
}
}
}
}
},
{
"Type": "Engineering",
"Name": "VM-OpcenterEXFN-1.ENG.0",
"Role": "ENG",
"Status": "Ready",
"PID": 17156,
"LastUpdate": "2019-09-04T16:41:52.626541+02:00",
"Statistics": {
"Runtime": {

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 901


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Name": "Runtime",
"Counters": {
"RunningHandlers": {
"Id": "RunningHandlers",
"Name": "RunningHandlers",
"Value": 0.0,
"AggregationType": "None"
},
"RunningRootCommands": {
"Id": "RunningRootCommands",
"Name": "RunningRootCommands",
"Value": 0.0,
"AggregationType": "None"
}
}
}
}
}
],
"Statistics": {
"System": {
"Name": "System",
"Counters": {
"NumberOfCPUCores": {
"Id": "NumberOfCPUCores",
"Name": "NumberOfCPUCores",
"Value": 4.0,
"AggregationType": "None"
}
}
}
},
"License": {
"Expiration": "0001-01-01T00:00:00+00:00",
"ProductName": "SIT UAF",
"ProductVersion": "3.0",
"Type": "Entry server"
},
"Solution": {
"Name": "MonitoringTests",
"Version": null,
"Build": 2
},
"Warnings": [],
"Errors": [],
"AvailabilityGroups": [
{
"Name": "SignalManager-Timers",
"HostLeader": "",
"AliveTime": "2019-09-04T14:39:59.1608717+00:00",
"UpdateAliveTime": false,
"ErrorDescription": "",

902 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"ErrorId": 0,
"LastUpdate": "2019-09-04T14:41:54.0642628+00:00",
"CheckTime": null,
"Status": "Active",
"ResourceGroup": []
},
{
"Name": "SignalManager-Rules",
"HostLeader": "",
"AliveTime": "2019-09-04T14:39:59.1784467+00:00",
"UpdateAliveTime": false,
"ErrorDescription": "",
"ErrorId": 0,
"LastUpdate": "2019-09-04T14:41:54.0642628+00:00",
"CheckTime": null,
"Status": "Active",
"ResourceGroup": []
}
],
"Subsystems": [
{
"Name": "Archiving DB",
"Status": "Fail",
"Properties": [
{
"Id": "ArchivingStatus",
"Displayname": "Archiving Status",
"Value": "Active",
"Description": ""
},
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-OpcenterEXFN-1\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 903


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Description": ""
},
{
"Id": "Enabled",
"Displayname": "Enabled",
"Value": "True",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "MonitoringTestsArchiving",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "500",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Id": "MOMArchive",
"Description": "Archiving database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7357795+00:00"
},
{
"Name": "Automation Gateway",
"Status": "Fail",
"Properties": [],
"Id": "AGW",
"Description": "",
"StatusDescription": "HmiRuntimeService Startup failed.",
"LastUpdate": "2019-09-04T14:41:51.6859783+00:00"
},
{
"Name": "Engineering DB",
"Status": "Pass",
"Properties": [
{

904 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "90000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-OpcenterEXFN-1\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "SIT_UA_Eng",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "50",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Id": "EngineeringRepository",
"Description": "Engineering database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7162444+00:00"

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 905


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

},
{
"Name": "RabbitMQ",
"Status": "Pass",
"Properties": [
{
"Id": "cluster_name",
"Displayname": "Cluster Name",
"Value": "rabbit@VM-OpcenterEXFN-1.SWQA.TST",
"Description": ""
},
{
"Id": "configuration_mode",
"Displayname": "Configuration Mode",
"Value": "Cluster",
"Description": ""
},
{
"Id": "platform",
"Displayname": "Platform Version",
"Value": "Erlang/OTP 20.2",
"Description": ""
},
{
"Id": "version",
"Displayname": "RabbitMQ Version",
"Value": "3.6.14",
"Description": ""
}
],
"Id": "RabbitMQ",
"Description": "RabbitMQ Messaging Broker",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:52.2104677+00:00"
},
{
"Name": "Runtime DB",
"Status": "Pass",
"Properties": [
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{

906 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-OpcenterEXFN-1\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "MonitoringTests",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "500",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Id": "MOM",
"Description": "Runtime database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7162444+00:00"
},
{
"Name": "System DB",
"Status": "Pass",
"Properties": [
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 907


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-OpcenterEXFN-1\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "SIT_UA_sys",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "50",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Id": "SystemFileStore",
"Description": "System database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7162444+00:00"
},
{
"Name": "Temporary DB",
"Status": "Pass",
"Properties": [
{

908 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-OpcenterEXFN-1\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "SIT_UA_tmp",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "50",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Id": "TemporaryFileStore",
"Description": "Temporary database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.717228+00:00"

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 909


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

},
{
"Name": "User Management Component",
"Status": "Pass",
"Properties": [
{
"Id": "Connected to",
"Displayname": "Connected to",
"Value": "VM-OpcenterEXFN-1",
"Description": "The ring master machine."
},
{
"Id": "Electronic Log",
"Displayname": "Electronic Log",
"Value": "Running",
"Description": "Electronic Log server status."
},
{
"Id": "Resource Authenticator",
"Displayname": "Resource Authenticator",
"Value": "Running",
"Description": "Resource Authenticator server status."
},
{
"Id": "Role",
"Displayname": "Role",
"Value": "ring",
"Description": "The machine role."
},
{
"Id": "Safemode",
"Displayname": "Safemode",
"Value": "0",
"Description": "It is equal to 1 if the machine is a UM ring server
in safe mode, 0 otherwise."
},
{
"Id": "Status",
"Displayname": "Status",
"Value": "master",
"Description": "Umc Workstation status."
},
{
"Id": "UM Authenticator",
"Displayname": "UM Authenticator",
"Value": "Running",
"Description": "UM Authenticator server status."
},
{
"Id": "UM Broker Server",
"Displayname": "UM Broker Server",
"Value": "Running",

910 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Description": "UM Broker Server server status."


},
{
"Id": "UM File Server",
"Displayname": "UM File Server",
"Value": "Running",
"Description": "UM File Server server status."
},
{
"Id": "UM Join Server",
"Displayname": "UM Join Server",
"Value": "Running",
"Description": "UM Join Server server status."
},
{
"Id": "UM Key Server",
"Displayname": "UM Key Server",
"Value": "Running",
"Description": "UM Key Server server status."
},
{
"Id": "UM Remote IPC Service",
"Displayname": "UM Remote IPC Service",
"Value": "Running",
"Description": "UM Remote IPC Service server status."
},
{
"Id": "UM Ring Server",
"Displayname": "UM Ring Server",
"Value": "Running",
"Description": "UM Ring Server server status."
},
{
"Id": "UM Secure Communication Service",
"Displayname": "UM Secure Communication Service",
"Value": "Running",
"Description": "UM Secure Communication Service server status."
},
{
"Id": "UM Server Proxy",
"Displayname": "UM Server Proxy",
"Value": "Running",
"Description": "UM Server Proxy server status."
},
{
"Id": "Version",
"Displayname": "Version",
"Value": "207.100.301.11",
"Description": "Installed UMC version."
}
],
"Id": "UMC",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 911


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Description": "",
"StatusDescription": null,
"LastUpdate": "2019-09-04T14:41:51.8871698+00:00"
}
]
}
],
"WorkerRoles": [
{
"Name": "ADM",
"Description": "",
"WorkerType": "ADM",
"TargetCPU": "x64",
"Retries": 5,
"ExecutionMode": "Parallel",
"NumberOfParallelExecutions": 0
},
{
"Name": "SignalManager",
"Description": "",
"WorkerType": "APP",
"TargetCPU": "x64",
"Retries": 0,
"ExecutionMode": "Parallel",
"NumberOfParallelExecutions": 0
},
{
"Name": "ENG",
"Description": "",
"WorkerType": "ENG",
"TargetCPU": "x64",
"Retries": 5,
"ExecutionMode": "Parallel",
"NumberOfParallelExecutions": 1
},
{
"Name": "Default WorkerRoleDefinition (x86)",
"Description": "",
"WorkerType": "APP",
"TargetCPU": "x86",
"Retries": 3,
"ExecutionMode": "Parallel",
"NumberOfParallelExecutions": 0
},
{
"Name": "maz",
"Description": "",
"WorkerType": "APP",
"TargetCPU": "x64",
"Retries": 3,
"ExecutionMode": "SequentialHA",
"NumberOfParallelExecutions": 1

912 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

},
{
"Name": "Default WorkerRoleDefinition (x64)",
"Description": "",
"WorkerType": "APP",
"TargetCPU": "x64",
"Retries": 3,
"ExecutionMode": "Parallel",
"NumberOfParallelExecutions": 0
}
],
"AvailabilityGroups": [
{
"Name": "SignalManager-Rules",
"HostLeader": "VM-OpcenterEXFN-1",
"AliveTime": "2019-09-04T14:39:59.1784467+00:00",
"UpdateAliveTime": false,
"ErrorDescription": "",
"ErrorId": 0,
"LastUpdate": "2019-09-04T14:41:54.0642628+00:00",
"CheckTime": null,
"Status": "Active",
"ResourceGroup": []
},
{
"Name": "SignalManager-Timers",
"HostLeader": "VM-OpcenterEXFN-1",
"AliveTime": "2019-09-04T14:39:59.1608717+00:00",
"UpdateAliveTime": false,
"ErrorDescription": "",
"ErrorId": 0,
"LastUpdate": "2019-09-04T14:41:54.0642628+00:00",
"CheckTime": null,
"Status": "Active",
"ResourceGroup": []
}
],
"Subsystems": [
{
"Name": "Archiving DB",
"Status": "Failed",
"Properties": [],
"Id": "MOMArchive",
"Description": "Archiving database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7357795+00:00"
},
{
"Name": "Automation Gateway",
"Status": "Failed",
"Properties": [],
"Id": "AGW",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 913


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Description": "",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.6859783+00:00"
},
{
"Name": "Engineering DB",
"Status": "Running",
"Properties": [],
"Id": "EngineeringRepository",
"Description": "Engineering database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7162444+00:00"
},
{
"Name": "RabbitMQ",
"Status": "Running",
"Properties": [
{
"Id": "cluster_name",
"Displayname": "Cluster Name",
"Value": "rabbit@VM-OpcenterEXFN-1.SWQA.TST",
"Description": ""
},
{
"Id": "configuration_mode",
"Displayname": "Configuration Mode",
"Value": "Cluster",
"Description": ""
},
{
"Id": "platform",
"Displayname": "Platform Version",
"Value": "Erlang/OTP 20.2",
"Description": ""
},
{
"Id": "version",
"Displayname": "RabbitMQ Version",
"Value": "3.6.14",
"Description": ""
}
],
"Id": "RabbitMQ",
"Description": "RabbitMQ Messaging Broker",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:52.2104677+00:00"
},
{
"Name": "Runtime DB",
"Status": "Running",
"Properties": [],
"Id": "MOM",

914 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Description": "Runtime database",


"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7162444+00:00"
},
{
"Name": "System DB",
"Status": "Running",
"Properties": [],
"Id": "SystemFileStore",
"Description": "System database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.7162444+00:00"
},
{
"Name": "Temporary DB",
"Status": "Running",
"Properties": [],
"Id": "TemporaryFileStore",
"Description": "Temporary database",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.717228+00:00"
},
{
"Name": "User Management Component",
"Status": "Running",
"Properties": [
{
"Id": "Status",
"Displayname": "Status",
"Value": "master",
"Description": "Umc Workstation status."
}
],
"Id": "UMC",
"Description": "",
"StatusDescription": "",
"LastUpdate": "2019-09-04T14:41:51.8871698+00:00"
}
]
}
}

Request examples
The following PowerShell example queries the endpoint by performing a request with a valid token and getting
environment information (such as the status host, or workers' status).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 915


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

param (
[parameter(mandatory=$true, HelpMessage="The username of the Opcenter Execution
Foundation user")]
[string] $Username,
[parameter(ValueFromPipeline=$true, mandatory=$false, HelpMessage="Password")]
#The User Password
[securestring] $SecurePassword,
[parameter(mandatory=$false, HelpMessage="The base url for Opcenter Execution
Foundation")]
[string] $base_url
)

<#
.DESCRIPTION
Perform a [user,password] authentication and returns an object containing
the OAuth access_token and refresh_token
#>
function Get-UA-Token
{
param (
[parameter(mandatory=$true, HelpMessage="The protocol://host[:port] base url")]
#The protocol://host[:port] base url
[string] $Base_url,
[parameter(mandatory=$true, HelpMessage="User Name")] #The User Name to
authenticate
[string] $User,
[parameter(ValueFromPipeline=$true, mandatory=$true, HelpMessage="Password")] #The
User Password
[securestring] $SecurePassword
)
process {
$url = "$($Base_url)/sit-auth/OAuth/Token"
$UnsecurePassword = (New-Object PSCredential "user",
$SecurePassword).GetNetworkCredential().Password

$creds = @{
username = $User
password = $UnsecurePassword
grant_type = "password"
client_id = "pws_scripting_client"
client_secret = [string][guid]::NewGuid()
scope = "global"
}

$headers = @{
ContentType = "application/x-www-urlencoded"
}

$Token = ""
$RefreshToken = ""

try {

916 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

$result = Invoke-RestMethod -Uri $url -Method Post -Body $creds -Headers


$headers -SessionVariable Session 2>$null
$Token = $result.access_token
$RefreshToken = $result.refresh_token
$ClientId = $creds.client_id
$ClientSecret = $creds.client_secret

}
catch
{
if ($_.Exception.Response)
{

$http_error = $_.Exception.Response.StatusCode.value__
$http_error_msg = $_.Exception.Response.StatusCode
try {
$stream = $_.Exception.Response.GetResponseStream();
$reader = New-Object System.IO.StreamReader($stream);
$reader.BaseStream.Position = 0;
$reader.DiscardBufferedData();

$responseBody = $reader.ReadToEnd() | ConvertFrom-Json


$host.UI.WriteErrorLine("ERROR: $($responseBody.error) - $
($responseBody.error_description)" )
$reader.Close()
}
catch {
$host.UI.WriteErrorLine("Generic Error: $($_.Exception.message), Http error
$($http_error) - $($http_error_msg) " )
}
}
else {
$host.UI.WriteErrorLine("Generic Error: $($_.Exception.message)" )
}
return $null
}
$Auth = [pscustomobject]@{
Token = $Token
RefreshToken= $RefreshToken
ClientId = $ClientId
ClientSecret= $ClientSecret
Session = $Session
}
$env:UAToken = $Auth.Token

return $Auth
}
}

<#
.DESCRIPTION
Get Monitoring information

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 917


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

#>
function Get-UA-Info
{
param (
[parameter(mandatory=$true, HelpMessage="The protocol://host[:port] base url")]
#The protocol://host[:port] base url
[string] $Base_url,
[parameter(mandatory=$true, HelpMessage="The OAuth Token to use")] #The OAuth Token
to use
[string] $Token
)

$url = "$($Base_url)/sit-svc/monitoring"
$headers = @{
"Authorization" = "Bearer $($Token)"
"Accepts" = "application/json"
}

$result = $null
try {
$result = Invoke-RestMethod -Uri $url -Method Get -Headers $headers
-SessionVariable Session 2>$null
}
catch
{
if ($_.Exception.Response)
{

$http_error = $_.Exception.Response.StatusCode.value__
$http_error_msg = $_.Exception.Response.StatusCode
$host.UI.WriteErrorLine("Http Error: $($_.Exception.message), Http error $
($http_error) - $($http_error_msg) " )
}
else {
$host.UI.WriteErrorLine("Generic Error: $($_.Exception.message)" )
}
return $null
}

return $result
}

if ($base_url -eq "")


{
$base_url = $env:COMPUTERNAME
}

if($Username -eq "")


{
$Username = $env:USERNAME
}

918 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

if ($SecurePassword) {
# Retrieve token from the authorization server
$TokenResp = Get-UA-Token -Base_url "http://$base_url" -User $Username
-SecurePassword $SecurePassword
}else{
$TokenResp = Get-UA-Token -Base_url "http://$base_url" -User $Username
}

# Retrieve json structure from monitoring endpoint


$result = Get-UA-Info -Base_url "http://$base_url" -Token $TokenResp.Token

# Print the status of the first host of the Opcenter EX FN cluster configuration
Write-Output ("Status of the host " +$result.Environment.Hosts[0].Name+ ": "+
$result.Environment.Hosts[0].InternalStatus)

# Print the status of all the workers related to the first host
Write-Output "Workers"
foreach ($worker in $result.Environment.Hosts[0].Workers)
{
("Name: " + $worker.Name + ", Status: " + $worker.Status)
}

Write-Output "Availability groups"


foreach ($avg in $result.Environment.AvailabilityGroups)
{
("Name: " + $avg.Name + ", HostLeader: " + $avg.HostLeader)
}

6.2.1 Retrieving Information from Scenario Subsystems


The monitoring endpoint returns among the other information also details from the scenario subsystems. This
information consists in details about the status information of RabbitMQ (with additional properties referring to the
leader RabbitMQ host, in an Active/Standby configuration), Automation Gateway, User Management Component
and Data Sources.
This information can be retrieved either via monitoring endpoint (see Monitoring Worker and Host Status from Web
Clients) or in the Solution Studio Host Monitoring screen (see Monitoring Hosts with Host Monitoring).

RabbitMQ subsystem
The information returned from the RabbitMQ subsystem is:

Attribute Value Description

Id RabbitMQ The identifier of the subsystem.

Name RabbitMQ The name of the RabbitMQ subsystem.

Description RabbitMQ Messaging Broker The description of the RabbitMQ subsystem.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 919


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Attribute Value Description

Status Pass or Fail The status of the host subsystem:


• Pass: The subsystem responds correctly to
the request information.
• Fail: An error occurs during the request.

StatusDescription The description of the status. The description


is an empty string if the status is equal to Pass
otherwise it will return the error description.

Properties An array containing the specific properties of


the RabbitMQ subsystem. See below for
further details.

LastUpdate The date time (in UTC format) of the last poll
cycle for the subsystem. The value is
calculated by the Monitoring endpoint
automatically.

The Properties attribute contains:

Id DisplayName Value

configuration_mode Configuration Mode The applied configuration:


• Cluster
• Active/Standby
See RabbitMQ Cluster and RabbitMQ Active or
Standby Configurations in Opcenter Execution
Foundation Installation Guide.

cluster_name Cluster Name The name of the RabbitMQ cluster node.

platform Platform Version The version of Erlang.

version RabbitMQ Version The version of RabbitMQ.

 The properties will be environment relevant only for the leader host of the RabbitMQ subsystem.

920 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

{
"Id": "RabbitMQ",
"Name": "RabbitMQ",
"Description": "RabbitMQ Messaging Broker",
"Properties": [
{
"Id": "cluster_name",
"Displayname": "Cluster Name",
"Value": "rabbit@my-host-full-name"
},
{
"Id": "configuration_mode",
"Displayname": "Configuration Mode",
"Value": "Cluster"
},
{
"Id": "platform",
"Displayname": "Platform Version",
"Value": "Erlang/OTP 20.2"
},
{
"Id": "version",
"Displayname": "RabbitMQ Version",
"Value": "3.6.14"
}
],
"Status": "Pass",
"StatusDescription": "",
"LastUpdate": "0001-01-01T00:00:00+00:00"
}

Automation Gateway subsystem


The returned information from the Automation Gateway subsystem is:

Attribute Value Description

Id AGW The identifier of the subsystem.

Name Automation Gateway The name of the subsystem.

Status Pass or Fail The status of the host subsystem:


• Pass : The subsystem responds correctly to
the request information.
• Fail : An error occurs during the request.

StatusDescription string The description of the status. The description is


an empty string if the status is equal
to Pass otherwise it will return the error
description.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 921


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Attribute Value Description

Properties Array The specific properties of the AGW subsystem.


See below for further details.

LastUpdate Timestamp The date time (in UTC format) of the last poll
cycle for the subsystem. The value is calculated
by the Monitoring endpoint automatically.

The Properties attribute contains:

Id DisplayName Value

ActiveNod Active node Either of the following:


e
• the name of the server where the AGW Server is running, in case of
standalone configuration
• the name of the server where the AGW Server is active, in case of redundant
configuration

{
"Id": "AGW",
"Name": "Automation Gateway",
"Description": "",
"Properties": [
{
"Id": "ActiveNode",
"Displayname": "Active node",
"Value": "NODE-A"
}
],
"Status": "Pass",
"StatusDescription": null,
"LastUpdate": "2019-07-17T16:20:30.2225437+00:00"
}

UMC subsystem
The returned information from the UMC subsystem is:

Attribute Value Description

Id UMC The identifier of the subsystem.

Name User The name of the subsystem.


Management
Component

922 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Attribute Value Description

Status Pass or Fail The status of the host subsystem:


• Pass: The subsystem responds correctly to the request information.
• Fail: An error occurs during the request.

StatusDes string The description of the status. The description is an empty string if the status
cription is equal to Pass otherwise it will return the error description.

Properties Array The specific properties of the UMC subsystem. See below for further details.

LastUpdat Timestamp The date time (in UTC format) of the last poll cycle for the subsystem. The
e value is calculated by the Monitoring endpoint automatically.

The Properties attribute contains:

Id DisplayNa Value
me

Connecte Connecte The Ring Master server host.


d to d to

Electroni Electronic Electronic Log server status.


c Log Log

Machine Machine The number of days before the certificate expires. If 0 is returned, the certificate is
Certificat Certificat expired. If the property is empty, the certificate is missing.
e e
Expiratio Expiration
n

Network Network The number of days before the certificate expires. If 0 is returned, the certificate is
Certificat Certificat expired. If the property is empty, the certificate is missing.
e e
Expiratio Expiration
n

Resource Resource Resource Authenticator server status.


Authenti Authentic
cator ator

Role Role The machine role.

Safemod Safemode It is equal to 1 if the machine is a UM ring server in safe mode, 0 otherwise.
e

Status Status UMC Workstation status.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 923


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Id DisplayNa Value
me

UM UM UM Authenticator server status.


Authenti Authentic
cator ator

UM UM UM Broker Server server status.


Broker Broker
Server Server

UM File UM File UM File Server server status.


Server Server

UM Join UM Join UM Join Server server status.


Server Server

UM Key UM Key UM Key Server server status.


Server Server

UM UM UM Remote IPC Service server status.


Remote Remote
IPC IPC
Service Service

UM Ring UM Ring UM Ring Server server status.


Server Server

UM UM UM Secure Communication Service server status.


Secure Secure
Commun Communi
ication cation
Service Service

UM UM Server UM Server Proxy server status.


Server Proxy
Proxy

Version Version Installed UMC version.

The Properties attribute contains:

924 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

{
"Name": "User Management Component",
"Status": "Pass",
"Properties": [
{
"Id": "Connected to",
"Displayname": "Connected to",
"Value": "vm-vdip37-069",
"Description": "The ring master machine."
},
{
"Id": "Electronic Log",
"Displayname": "Electronic Log",
"Value": "Running",
"Description": "Electronic Log server status."
},
{
"Id": "Resource Authenticator",
"Displayname": "Resource Authenticator",
"Value": "Running",
"Description": "Resource Authenticator server status."
},
{
"Id": "Role",
"Displayname": "Role",
"Value": "ring",
"Description": "The machine role."
},
{
"Id": "Safemode",
"Displayname": "Safemode",
"Value": "0",
"Description": "It is equal to 1 if the machine is a UM ring server
in safe mode, 0 otherwise."
},
{
"Id": "Status",
"Displayname": "Status",
"Value": "master",
"Description": "Umc Workstation status."
},
{
"Id": "UM Authenticator",
"Displayname": "UM Authenticator",
"Value": "Running",
"Description": "UM Authenticator server status."
},
{
"Id": "UM Broker Server",
"Displayname": "UM Broker Server",
"Value": "Running",
"Description": "UM Broker Server server status."

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 925


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

},
{
"Id": "UM File Server",
"Displayname": "UM File Server",
"Value": "Running",
"Description": "UM File Server server status."
},
{
"Id": "UM Join Server",
"Displayname": "UM Join Server",
"Value": "Running",
"Description": "UM Join Server server status."
},
{
"Id": "UM Key Server",
"Displayname": "UM Key Server",
"Value": "Running",
"Description": "UM Key Server server status."
},
{
"Id": "UM Remote IPC Service",
"Displayname": "UM Remote IPC Service",
"Value": "Running",
"Description": "UM Remote IPC Service server status."
},
{
"Id": "UM Ring Server",
"Displayname": "UM Ring Server",
"Value": "Running",
"Description": "UM Ring Server server status."
},
{
"Id": "UM Secure Communication Service",
"Displayname": "UM Secure Communication Service",
"Value": "Running",
"Description": "UM Secure Communication Service server status."
},
{
"Id": "UM Server Proxy",
"Displayname": "UM Server Proxy",
"Value": "Running",
"Description": "UM Server Proxy server status."
},
{
"Id": "Version",
"Displayname": "Version",
"Value": "206.0.402.7",
"Description": "Installed UMC version."
}
],
"Id": "UMC",
"Description": "",

926 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"StatusDescription": null,
"LastUpdate": "2019-08-06T10:21:32.6273893+00:00"
}

Data Source subsystems


The information returned from the Data Source subsystems is:

Attribute Value Description

Id One of the The identifier of the Data Source subsystem.


following values:
• EngineeringR
epository
• MOMArchive
• MOM
• SystemFileSt
ore
• TemporaryFil
eStore

Name One of the The name of the Data Source subsystem.


following values:
• Engineering
DB
• Archiving DB
• Runtime DB
• System DB
• Temporary
DB

Descripti One of the The description of the Data Source subsystem.


on following values:
• Engineering
database
• Archiving dat
abase
• Runtime data
base
• System datab
ase
• Temporary d
atabase

Status Pass, Fail or The status of the host subsystem:


Ignore
• Pass: The subsystem responds correctly to the request information.
• Fail: An error occurs during the request.
• Ignore (Archiving only): The connection to archiving database has not
been checked.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 927


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Attribute Value Description

StatusDe The description of the status. The description is an empty string if the status
scription is equal to Pass otherwise it will return the error description.

Propertie An array containing the specific properties of the Data Source subsystem.
s See below for further details.

LastUpda The date time (in UTC format) of the last poll cycle for the subsystem. The
te value is calculated by the Monitoring endpoint automatically.

The Properties attribute contains:

Id DisplayName Value

CommandTimeout Command Timeout The execution timeout (in milliseconds) of any


database statement.

ConnectionTimeout Connection Timeout The timeout for the database connection (in
milliseconds).

DataSource Data Source In MSSQL, the computer and instance name of


the data source.
In Oracle, the computer name of the data
source.

DatabaseType Database Type The data provider type.

InitialCatalog Initial Catalog The name assigned to the database.

NumberOfRetries Number Of Retries The number of retries for a command.

RetriesDelay Retries Delay The delay (in milliseconds) after which a new
command retry will start.

Schema Schema The name assigned to the database schema.

Enabled Enabled It is returned for Archiving only.


It is true if archiving has been enabled
otherwise false.

928 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

Id DisplayName Value

ArchivingStatus Archiving Status It is returned for Archiving only.


• NotConfigured : The archiving is not
configured.
• Active : The archiving is configured and
activated.
• Suspended : The archiving is configured
and suspended.
The properties will not be environment relevant

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 929


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

{
"Name": "Archiving DB",
"Status": "Ignore",
"Properties": [
{
"Id": "ArchivingStatus",
"Displayname": "Archiving Status",
"Value": "NotConfigured",
"Description": ""
},
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-VDIP37-046\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "Enabled",
"Displayname": "Enabled",
"Value": "False",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "MySolArchiving",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "500",
"Description": ""
},

930 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Statistics": null,
"Id": "MOMArchive",
"Description": "Archiving database",
"StatusDescription": "",
"LastUpdate": "2019-09-06T08:19:01.621901+00:00"
},
{
"Name": "Engineering DB",
"Status": "Pass",
"Properties": [
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "90000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-VDIP37-046\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "SIT_UA_Eng",
"Description": ""

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 931


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "50",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Statistics": null,
"Id": "EngineeringRepository",
"Description": "Engineering database",
"StatusDescription": "",
"LastUpdate": "2019-09-06T08:19:10.3270881+00:00"
},
{
"Name": "Runtime DB",
"Status": "Pass",
"Properties": [
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-VDIP37-046\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",

932 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "MySol",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "500",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Statistics": null,
"Id": "MOM",
"Description": "Runtime database",
"StatusDescription": "",
"LastUpdate": "2019-09-06T08:19:10.3270881+00:00"
},
{
"Name": "System DB",
"Status": "Pass",
"Properties": [
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{
"Id": "ConnectionTimeout",
"Displayname": "Connection Timeout",
"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 933


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Value": "VM-VDIP37-046\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "SIT_UA_sys",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "50",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Statistics": null,
"Id": "SystemFileStore",
"Description": "System database",
"StatusDescription": "",
"LastUpdate": "2019-09-06T08:19:09.5292215+00:00"
},
{
"Name": "Temporary DB",
"Status": "Pass",
"Properties": [
{
"Id": "CommandTimeout",
"Displayname": "Command Timeout",
"Value": "30000",
"Description": ""
},
{
"Id": "ConnectionTimeout",

934 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Monitoring Worker and Host Status from Web Clients

"Displayname": "Connection Timeout",


"Value": "15000",
"Description": ""
},
{
"Id": "DataSource",
"Displayname": "Data Source",
"Value": "VM-VDIP37-046\\MES",
"Description": ""
},
{
"Id": "DatabaseType",
"Displayname": "Database Type",
"Value": "SqlServer",
"Description": ""
},
{
"Id": "InitialCatalog",
"Displayname": "Initial Catalog",
"Value": "SIT_UA_tmp",
"Description": ""
},
{
"Id": "NumberOfRetries",
"Displayname": "Number Of Retries",
"Value": "50",
"Description": ""
},
{
"Id": "RetriesDelay",
"Displayname": "Retries Delay",
"Value": "500",
"Description": ""
},
{
"Id": "Schema",
"Displayname": "Schema",
"Value": "dbo",
"Description": ""
}
],
"Statistics": null,
"Id": "TemporaryFileStore",
"Description": "Temporary database",
"StatusDescription": "",
"LastUpdate": "2019-09-06T08:19:09.5292215+00:00"
}

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 935


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

6.3 Logging and Analyzing Application Traces with Trace Viewer


Opcenter Execution Foundation Trace Viewer is an application that allows you to view application messages such
as errors, warnings and information. The Trace Viewer lets you monitor events in real time, export chosen providers
to a configuration file and log events for exported providers to a persistent storage, to perform analysis operations.
Before you start logging messages, you can specify the trace channels to listen to (providers and keywords), set the
information level you want to trace (critical, error, warning, informational, verbose), choose the columns to be
displayed and customize various visualization settings.
Messages that are traced by commands and events and that are executed inside the same flow are tied together
through a correlation ID. This ID can be used to filter and group messages that belong to the same execution flow.
To speed up filtering, you can use the selected context to filter by a desired field.
Once you have logged messages or exported them to file, you can filter by categories and verbosity, apply highlight
color rules, change the sorting order, search for text, choose which columns to view, filter for specific messages and
highlight the ones that have been issued by specific providers.
The Trace Viewer also lets you monitor the state of the providers for troubleshooting purposes and check which
providers are installed.

Available operations
You can log and analyze application traces by referring to the following available operations, and logging options,
listed below.
• Functional options:
• Starting Trace Viewer
• Choosing trace providers
• Splitting ETL Files
• Setting the Logging Mode
• Exporting Traces to a Persistent Storage
• Exporting Traces To Windows Performance Monitor
• Generating Custom Trace Providers

Differences between Application Log and Trace Viewer


To trace logs you can also use Application Log. There are differences between the two logging applications. Take a
look at them in a glance before choosing the most suitable way.

Trace Viewer Application Log Description

Traces all actions Traces only application level Trace Viewer logs all the actions carried out by
messages the platform (such as command execution,
authentication, queries on the database), while
Application Log traces only application level
messages.

936 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Trace Viewer Application Log Description

Is more development Is more end-user oriented Trace Viewer is more suitable for advanced
oriented troubleshooting issues since it is highly verbose
and technical. Moreover it can contain logs
generated by the business logic, in terms of
command/event handlers, if the code uses them.
On the other hand Application Log is more
functional and end-user oriented. Consequently,
its messages are also more readable, and they
can be translated.

Stores logs in a database Stores logs in a database Both applications can store logs in a database,
but database maintenance and database maintenance but while Application Log can apply standard
is custom is standard provided maintenance procedures to clean old messages,
for Trace Viewer the database maintenance is
custom.

Logs can be filtered and Logs can be filtered by level, In Trace Viewer, logs are classified in levels (from
sorted out by level and business command and verbose to critical), and in providers (representing
provider source Functional Block or the "component" which has generated a certain
App log). Levels and providers can be used to filter
messages, both in view mode and in storage
mode (to avoid that logs let the database grow in
uncontrolled way). In Application Log, logs can be
defined as different levels (from verbose to
critical as in Trace Viewer), return the name of the
business command that generated them, as well
as the "owners" of the commands (typically
Functional Blocks, Apps or Extension Apps).

For more information on Application logs, refer to How To Manage Application Logs and Application Log App in the
Opcenter Execution Foundation User Manual.
• Viewing options:
• Choosing Columns
• Sorting Events
• Grouping Correlated Messages
• Applying Filters and Highlights
• Setting the Display Configuration
• Setting the Display Options in the Main Panel

If you only want to analyze application traces in a local machine, you can use the Trace Viewer Stand-Alone.

6.3.1 Analyzing Application Traces with Trace Viewer Stand-Alone


Opcenter Execution Foundation Trace Viewer provides functionalities to analyze and monitor events in real time
and can also be used in stand-alone mode to perform specific operations without installing Opcenter EX FN.
Unlike Trace Viewer, the stand alone application must be installed in a local machine and can only perform few
operations; this application is suggested, for example, to see ETL and ETZ traces from file.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 937


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Prerequisites
• No Opcenter EX FN version is installed in the local machine.
• Visual Studio 2017 run-time Redistributable is installed.
• .NET framework 4.7.2 or 4.8.
• Windows 10, Windows Server 2016, or Windows Server 2019.

Procedure
1. From an already installed system, open the bin folder located in %SITUnifiedSystemRoot% and copy
the EtwViewer.exe file.
2. From the local machine, paste the EtwViewer.exe file in a dedicated folder.
3. Double-click EtwViewer.exe to open the application.

Available Operations
• Splitting ETL Files
• Choosing Columns
• Applying Filters and Highlights
• Setting the Display Configuration
• Sorting Events
The following operations are described in Setting the Logging Mode:
• Opening recorded ETL files
• Converting ETL files
• Opening an ETZ file

6.3.2 Starting Trace Viewer Session


This topic explains how to start Opcenter Execution Foundation Trace Viewer and how to set the minimum required
options to log messages.
It also describes additional operations regarding how to monitor and troubleshoot the provider status.

Prerequisite
You must be logged on with a Windows administrator user. If you use the tool with a non-administrative user, you
can read and save ETZ files, but you cannot access real time functionalities.

Procedure
1. From %SITUnifiedSystemRoot%bin run the EtwViewer.exe file with administrative rights.
2. Choose only the required providers whose traces you want to monitor and set the verbosity level.
3. Set the limit of the displayed messages by using the spin buttons in the Max Messages list box. The maximum
accepted number is 500.000 and you cannot change it. Once this number is reached, any older messages will no
longer be displayed.
4. Select one of the available logging modes and start analysis.

938 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

 Make sure that each session does not remain open for too long or you might encounter problems with the
new incoming messages.
If you need long tracing sessions, consider non real-time logging modes or any export to a persistent
storage.

Available operations for monitoring and troubleshooting the provider status


In Trace Viewer you can perform the following operations:

Operation Description

Tools > Check Opcenter Execution It allows you to check which providers are installed on the current
Foundation providers Installed node. If required, you can specify the machine to which you want to
connect.
This window is read-only and can be used to check whether all
SIMATIC IT providers have been correctly installed.

Tools > ETW Sessions Monitor It allows you to monitor and troubleshoot the state of the active
sessions. If required, you can specify the node you want to
monitor.
This functionality allows you to see if any sessions are open (for
example, after an error occurred a session may remain open).
All sessions have a name. SIMATIC IT sessions start with
"SIMATICIT" inside the session name.
If the number of open sessions is too large, you can either
• close all sessions by clicking Clean SIMATIC Sessions or
• close only the selected one by clicking Close Selected
Sessions.
After this operation, you must always restart Trace Viewer.

Tools > Options It allows you to set the visualization options for all traces, by
choosing the column separator, the timestamp format and the
message color in order to create the default schema.

Double-click the element You can see the details of each single trace by double-clicking on
the required row.

Automatically saving and reloading applied settings


The application automatically saves the last applied configurations for the following settings and then reloads them
upon the next restart.
The related settings files are saved in the User Application Data standard folder c:
\Users\loggedOnUser\AppData\Roaming\Siemens AG\Opcenter Execution Foundation\productVersion\.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 939


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Settings Description File Name

Tools > Options General options, including position and EtwViewer.opt


size of the main window.

Edit > Highlight Highlight settings. EtwViewer.hightLight

Edit > Filter View filter. EtwViewer.filter

Providers > Choose providers Input providers. EtwViewer.providerSet

Providers > Choose providers > Input filter. EtwViewer.Inputfilter


Setup Input Events Filter

6.3.3 Choosing Trace Providers


Before logging messages with Trace Viewer, you can set filters on the trace channels you want to listen to as well as
select specific channels. You can configure the Trace Viewer to listen to both Opcenter Execution Foundation and
non-Opcenter Execution Foundation providers. You can set a filter on the verbosity level
(critical, error, warning, informational, verbose) as well as specify an additional sub-filtering level by using
keywords. This page also provides you with the description of the platform providers.

 You can disable any trace providers you do not require.


In particular it is advisable to disable the Siemens-SimaticIT-Trace-SQLProfiling provider, if not
required, to enhance performance.

Procedure
1. In the main Trace Viewer window, select the Providers > Choose providers command: the Trace Viewer loads a
default list of platform providers (be aware that User Management Component providers are not included in the
default list).
2. To reduce the providers list, select the providers you want to exclude and click Remove Selected.
3. Select the Default Level of verbosity that will be applied to all providers. You can also set the verbosity level for
each provider by selecting the provider in the grid and then the required filter level from the Level drop-
down list.
4. Only for the Microsoft-Windows-DotNETRuntime provider, select the Enable Exception Listening check box
to capture exceptions.
5. Set the Keyword filtering level for each provider and click OK. If you do not apply any filter, all keywords are
applied (for keyword explanation, see below).

940 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Available Operations
Click ... To...

Restore Default Restore the default providers configuration and other settings.
Settings

Undo Last Changes Restore the settings to the active configuration (the one set at the moment in which the
window open).

Add All Opcenter Add all Opcenter Execution Foundation providers.


EX FN

Add all UMC Add all UMC providers.

Add all UDM Add all UDM providers.

Add By Name Add non-Opcenter Execution Foundation providers.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 941


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Click ... To...

Remove Selected Remove Selected provider.

Remove All UMC Remove All UMC providers.

Remove All UDM Remove All UDM providers.

Remove All Remove All providers.

Filter by process Filter by a specific process by entering the name of the required process (e.g.
name WorkerMonitor.exe, LogRouterService.exe, etc...)
Note If you do not save the provider configuration to an XML file, the given provider
configuration will only be used for the current Trace Viewer instance.

Setup Input Events Set a filter on the incoming events. This filter will be applied before inserting events in
Filter the buffer, thus reducing the memory usage when the user knows in advance which
events are not useful.
Note: When an input filter is active, the text color of the button is red.

Export Export traces as described at:


• Exporting Traces To Windows Performance Monitor
• Exporting Traces to a Persistent Storage

Import from Import and export a template to be used for Performance Monitor.
PerfMon Template

Load Providers Load a list of providers from an XML file.

Save Providers Save the list of chosen providers to an XML file.

Using trace keywords (trace sub-levels)


In the Choose Providers dialog box you can apply a filter on keywords.
A keyword is a label that identifies a sub-group of traces for a specific provider. For SIMATIC IT providers, you can
use VeryLow, Low, Medium, High, VeryHigh keywords to identify sub-messages.
You can associate one or more keywords to the same trace. If you add a specific keyword, the system automatically
adds all the keywords from the lower levels (for example, if you associate Low, the system also
associates VeryLow to the same trace). The keyword level is based on the following
scale: VeryLow, Low, Medium, High, VeryHigh.
Trace Viewer automatically filters for the highest keyword among the ones that you have associated. This allows
you to view all the messages you have traced.
Sessions0, Sessions1, Sessions2, Sessions3 keywords are for Windows internal use.
If you do not associate any keywords to a message, the provider sends messages with keyword set to Medium (and
its lower levels, i.e. Low and Very Low).
The Write method, when used with platform providers, exposes a field that maps information on the keywords (see
Opcenter Execution Foundation Platform Reference Online Help).

942 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Opcenter Execution Foundation trace providers


Platform components use internal providers to trace events. You can filter on these providers to monitor platform
internal processes. If you have developed custom logic inside Event or Command Handlers, you can use dedicated
trace providers as described in the following table:

Provider Related traces displayed


Name

Siemens- SIMATIC IT UAF Log Router Service provider.


SimaticIT
-Trace-
LogRoute
rService

Siemens- Execution of Automation Event and Command Handlers.


SimaticIT
-Trace-
Automati
on

Siemens- Execution of the Command and Event Handlers inside the execution engine (execution pipeline) of
SimaticIT all Worker types (Application, Administration and Engineering Workers).
-Trace-
Runtime

Siemens- Execution of custom Event and Command Handlers.


SimaticIT
If you have used the Opcenter Execution Foundation Platform ITracer Write method inside the
-Trace-
custom handler you can specify this provider. See Tracing process executions.
Handler

Siemens- Exchange of communication messages on Manufacturing Services Bus.


SimaticIT
-Trace-
Commun
ication

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 943


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- Execution of Command Handlers related to previous versions of the Unified Data Model
SimaticIT component.
-Trace-
The platform offers providers that are dedicated to UDM (see below).
Business
Logic
 If you retrieve traces from this provider in verbose mode, you will receive personal data
configured in the Personnel App.
The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The product processes / stores the following personal data: FirstName, LastName, Email
Addresses, Phone Numbers, Date Of Birth, Nationality, State, City, Address, ZipCode,
UserName.
It is essential to collect this information to identify the authorized operators. We only
store the data for as long as necessary. Please contact customer support with any
questions.

Siemens- Operations executed to check the license validity.


SimaticIT
-Trace-
License

Siemens- Authentication operations at several levels (Workers, Service Layers, Authorization Server),
SimaticIT authorization operations executed by Workers and Service Layer, and cryptography.
-Trace-
Security

Siemens- Reading and writing operations at Event and Command Handler level, reading operations
SimaticIT performed by applications that use IUnifiedSdkLean interface, reading operations performed via
-Trace- OData, and reading or writing operations executed on the system file store databases.
Informati
on

Siemens- Debugging of internal operations on Domain Specific Language layers.


SimaticIT
-Trace-
Dsl

944 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- Execution of:


SimaticIT
• engineering commands used to manage the Manufacturing Solution
-Trace-
• execution of reading and writing operations on the Governance registry and on the Engineering
Governan
Repository
ce
• execution of system configuration tool operations (SIMATIC IT UA Configuration).

Siemens- Internal debugging operations of engineering logic execution, which is used to manage the
SimaticIT Manufacturing Solution.
-Trace-
Engineeri
ng

Siemens- Operations executed by the Opcenter EX FN Service Layer, i.e. all the requests for entities and
SimaticIT commands that arrive from clients. The traces contain the name of the App to which the requested
-Trace- command or entity belong. The traces also provide you with initialization information. The
ServiceLa initialization takes place when a client invokes the Service Layer for the first time. The traces refer
yer to all Service Layer applications: Administration, Engineering and Application.

Siemens- The operations executed by the SIMATIC IT UAF Service (which is used internally to launch the
SimaticIT platform Workers).
-Trace-
Launcher

Siemens- The operations executed by the Worker Monitor: loading data from the Governance Registry and
SimaticIT errors that might be returned during this operation.
-Trace-
WorkerM
onitor

Siemens- The operations executed by the Authorization Server, which is the component that generates
SimaticIT authorization tokens.
-Trace-
Authoriza
tionServe
r

Siemens- The operations traced by SQL Profiler. These operations refer to the SQL or PL/SQL statements
SimaticIT regarding the reading operations (Query and ProjectionQuery) and the writing operations (Submit/
-Trace- Delete) involving either the Opcenter EX FN database or any external databases.
SQLProfil
ing

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 945


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- The operations executed by the Signal Manager and the SignalRuleStatusChangedEvent event.
SimaticIT
-Trace-
Signallin
g

Siemens- The operations executed by the Timer Scheduler.


SimaticIT
-Trace-
Timer-
Schedule
r

Siemens- The commands executed by the Administration Worker.


SimaticIT
-Trace-
Administ
ration

Siemens- The execution of remote invocations.


SimaticIT
-Trace-
Discovery
Service

Siemens- The execution of custom defined Commands and Events.


SimaticIT
It traces when Commands and Events start or finish and when they fail with errors.
-Trace-
Executio
n-Engine

Siemens- Execution of Command and Event Handlers related to generic operations in UDM.
SimaticIT
-Trace-
UDM

Siemens- Execution of Commands and Event Handlers related to Application Log in UDM.
SimaticIT
The main entities involved are ApplicationLog, Rule, Schedule and CleaningCondition.
-Trace-
UDM-
Applicati
onLog

946 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- Execution of Command and Event Handlers related to Equipment management in UDM.
SimaticIT
The main entities involved are Machine and Storage in the Master Data and Operational Data
-Trace-
domains.
UDM-
Equipme
nt

Siemens- Execution of Command and Event Handlers related to Material management in UDM.
SimaticIT
The main entities involved are:
-Trace-
UDM- • Material Group, Bill of Materials and Material in the Master Data domain.
Material • Material Tracking Unit, Material Lot and Material Tracking Unit Aggregate in the Operational
Data domain.

Siemens- Execution of Command and Event Handlers related to Operation management in UDM.
SimaticIT
The main entities involved are Bill of Operations, Operation and Work Procedure in the Master Data
-Trace-
domain.
UDM-
Operatio
n

Siemens- Execution of Command and Event Handlers related to Production Rule management in UDM.
SimaticIT
The main entities involved are Product-driven Production Rule and Process-driven Production Rule
-Trace-
in the Master Data domain.
UDM-
Producti
onRule

Siemens- Execution of Command and Event Handlers related to State Machine management in UDM.
SimaticIT
The main entities involved are State Machine and Status Definition in the Reference Data domain.
-Trace-
UDM-
StateMac
hine

Siemens- Execution of Command and Event Handlers related to Task management in UDM.
SimaticIT
The main entities involved are:
-Trace-
UDM- • Task Types and Task Definitions in the Master Data domain.
Task • Tasks in the Operational Data domain.
If the verbosity level is set to Verbose, the input and output parameters of commands are also
logged.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 947


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- Execution of Command and Event Handlers related to Unit of Measure management in UDM.
SimaticIT
The main entities involved are UoM Group and UoM in the Reference Data domain.
-Trace-
UDM-
UnitOfMe
asure

Siemens- Execution of Command and Event Handlers related to Work Calendar management in UDM.
SimaticIT
The main entities involved are Time Slice, Time Period, Working Pattern, Work Calendar Rule and
-Trace-
Work Calendar in the Master Data domain.
UDM-
WorkCale
ndar

Siemens- Execution of Command and Event Handlers related to Work Order management in UDM.
SimaticIT
The main entities involved are Work Order, Work Order Operation and Work Order Operation Task
-Trace-
in the Operational Data domain.
UDM-
WorkOrd
er

Siemens- The operations executed by Monitoring subsystems.


SimaticIT
-Trace-
Subsyste
m

Siemens- The operations traced by User Management Component Audit Trail.


SimaticIT
-Trace-
 If you retrieve traces from this provider, you will receive personal data configured in the
UMC- User Management Component.
Audit-
Trail The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The products processes / stores the following personal data: FirstName, LastName,
Description, Phone Number, Email Address, Email SID, Initials, and Associated Groups.
It is essential to collect this information to identify the authorized users. We only store the
data for as long as necessary. Please contact customer support with any questions.

948 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- The authentication operations and the database modifications related to users or groups, traced
SimaticIT by User Management Component.
-Trace-
UMC-
 If you retrieve traces from this provider, you will receive personal data configured in the
Authentic User Management Component.
ation
The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The products processes / stores the following personal data: FirstName, LastName,
Description, Phone Number, Email Address, Email SID, Initials, and Associated Groups.
It is essential to collect this information to identify the authorized users. We only store the
data for as long as necessary. Please contact customer support with any questions.

Siemens- The communication layer (server and client) operations traced by User Management Component.
SimaticIT
-Trace-
 If you retrieve traces from this provider, you will receive personal data configured in the
UMC- User Management Component.
Commun
ication The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The products processes / stores the following personal data: FirstName, LastName,
Description, Phone Number, Email Address, Email SID, Initials, and Associated Groups.
It is essential to collect this information to identify the authorized users. We only store the
data for as long as necessary. Please contact customer support with any questions.

Siemens- The configuration operations traced by User Management Component (e.g. UMConf traces).
SimaticIT
-Trace-
 If you retrieve traces from this provider, you will receive personal data configured in the
UMC- User Management Component.
Conf
The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The products processes / stores the following personal data: FirstName, LastName,
Description, Phone Number, Email Address, Email SID, Initials, and Associated Groups.
It is essential to collect this information to identify the authorized users. We only store the
data for as long as necessary. Please contact customer support with any questions.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 949


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- The operations traced by User Management Component applications that are not managed by
SimaticIT other UMC Providers.
-Trace-
UMC-
 If you retrieve traces from this provider, you will receive personal data configured in the
Default User Management Component.
The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The products processes / stores the following personal data: FirstName, LastName,
Description, Phone Number, Email Address, Email SID, Initials, and Associated Groups.
It is essential to collect this information to identify the authorized users. We only store the
data for as long as necessary. Please contact customer support with any questions.

Siemens- The engineering operations related to users/groups traced by User Management Component.
SimaticIT
-Trace-
 If you retrieve traces from this provider, you will receive personal data configured in the
UMC- User Management Component.
Engineeri
ng The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The products processes / stores the following personal data: FirstName, LastName,
Description, Phone Number, Email Address, Email SID, Initials, and Associated Groups.
It is essential to collect this information to identify the authorized users. We only store the
data for as long as necessary. Please contact customer support with any questions.

950 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Provider Related traces displayed


Name

Siemens- The operations traced by User Management Component Provisioning Service (import and
SimaticIT alignment of domain users).
-Trace-
UMC-
 If you retrieve traces from this provider, you will receive personal data configured in the
Provision User Management Component.
ing
The principles of data protection are important to Siemens and out affiliates. Our
products, including Opcenter Execution Foundation, are designed with privacy in mind
and adhere to Siemens’ data protection requirements. Please visit our privacy statement
for more details.
The products processes / stores the following personal data: FirstName, LastName,
Description, Phone Number, Email Address, Email SID, Initials, and Associated Groups.
It is essential to collect this information to identify the authorized users. We only store the
data for as long as necessary. Please contact customer support with any questions.

 The following trace providers are for testing internal use, and can be disabled if not required for internal
testing:
• Siemens-SimaticIT-Trace-Log1
• Siemens-SimaticIT-Trace-Log2
• Siemens-SimaticIT-Trace-Test

6.3.4 Setting the Logging Mode


You can log messages in Trace Viewer in either of following ways:
• in Real Time mode, by displaying messages at runtime without automatically persisting them,
• in Recording mode, by directly persisting messages without displaying them at runtime.
Messages and filters are automatically cleared while changing the logging mode.

Viewing messages in real time


When you display messages in real time, the application does not automatically save them in a file or repository.
You can afterwards save them to file and perform analysis operations.
You can specify the node of the network for which you want to view messages, or alternatively merge in the same
Trace session, all the messages generated on all nodes.
1. In Trace Viewer select one of the following commands:
• Mode > Real Time
• Mode > Real Time from all nodes
• Mode > Real Time from one remote node
2. Select Action > Start. In case of single node, you must specify the node.
3. Select either of the following to display all the messages previously generated:
• Action > Stop
• Action > Pause.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 951


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Saving the Real Time messages to files (ETZ, CSV)


If you want to save the displayed messages:
1. When you are in the Real Time mode, select either Action > Stop or Action > Pause command.
2. Select any specific rows you want to save (or do not select anything if you want to export all messages) and
proceed with either of the following options:
• File > Save messages to ETZ file, to save messages and their metadata to the ETZ proprietary format.
• File > Export messages to CSV file, to save messages in a CSV formatted file.
3. Browse for the destination folder to export or save the message and click Save: the system displays the path,
the file name and the number of messages that are going to be saved.
4. Click OK to confirm the operation.

Opening an ETZ file


You cannot open a CSV file with Trace Viewer but you can use a standard application to do so.
If you want to open and analyse an ETZ file:
1. When you are in the Real Time mode, select either Action > Stop or Action > Pause command.
2. Select the Mode > Reload ETZ file command to reopen the ETZ file.
3. Select one of the following commands:
• Action > Load from file, to load an entire file without applying any filter.
• Action > Load with filter, to set a filter after choosing the file.
• Action > Reload File, to open the previously selected file without applying any filter.
• Action > Reload with filter, to open the previously selected file and set the filter.
4. Choose the file to be opened and confirm.
You can now execute display operations on messages, such as changing the sorting order, searching for text,
choosing columns to view, highlighting specific messages.

Recording messages to ETL files


If you directly want to capture messages and save them to an ETL file, without viewing them at runtime:
1. Select the Mode > Recording ETL file command.
2. Select the Action > Start command.
3. Set the name of the file you want to save, its path and click Save: the system starts recording.
4. If you want to stop recording, select either of the following commands:
• Action > Stop to simply stop the recording
• Action > Stop And Load recorded to stop the recording and load the newly created file, all related
messages are displayed in order to execute display operations such as changing the sorting order,
searching for text, choosing columns to view, highlighting specific messages.
5. Optionally, to reduce the size of the final ETL file, you can split the ETL file.

Converting ETL files


If you want to reduce the dimension of the log trace in order to speed up the reading and management of the files,
convert the ETL file into ETZ :
1. Select either of the following commands:
• File > Convert ETL file to ETZ
• Tools/Export > Convert ETL file to ETZ
2. In the Convert ETL file to ETZ dialog box, do the following:

952 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

In the box Do To

Source ETL File Browse for the ETL file Select the ETL file to convert.

Target file Browse for the converted ETZ file Create the ETZ file with the
suffix _progressivenumber.etz and locate
it in the desired folder.

Number of files Click the spin button Set the number of ETZ files that will
contain the converted ETL file.
3. Click OK: the newly-converted ETZ file is displayed in the selected location in order to perform the same
operations of the ETL file.

Opening recorded ETL files


You can open a previously recorded ETL file. You can also open and read ETL files that have been saved by Windows
with the limitation that they can be opened separately.
1. Select the Mode > Load ETL file command.
2. Select the Action > Load recent ETL files command.
3. Select the file you want to open and click OK.

Analyzing messages
On ETL files, ETZ files or messages displayed in runtime (in Pause mode), you can execute display operations on
messages, such as changing the sorting order, grouping correlated messages, choosing columns to view,
highlighting messages.

6.3.5 Splitting ETL Files


This page describes how to split ETL files (used to record event traces) in order to reduce their size and speed up the
operations performed (the bigger the ETL file, the slower the ETL reading).

 Reducing the size of the ETL files saves the disk capacity but does not affect the memory and the runtime
working time.

Suggestions
• Split the ETL file if its size is greater than 1GB.
• Set the number of split files between 2 and 30 files.

Procedure
1. In Trace Viewer, select either of the following commands:
• File > Split ETL File
• Tools/Export > Split ETL File
2. In the Split ETL file dialog box, do the following:
In the box Do To

Source ETL File Browse for the ETL file Select the ETL file to split.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 953


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

In the box Do To

Target file Browse for the target files Select the destination directory that will
contain the split ETL files, and enter the base
name.
The split files will be created in this directory,
and their names will be generated with a
progressive number starting from zero.
E.g. if you enter the base name "XYZ.etl" and
set Number of files to 3, the generated files
will be named "XYZ_0.etl", "XYZ_1.etl",
"XYZ_2.etl".

Number of files Click the spin button Set how many files will contain the source
split ETL file.

Compress Target file Select the check box Reduce the size of the split ETL files.
(Optional)
3. Click OK.

6.3.6 Choosing Columns


This page describes how you can display or hide the columns of the Trace Viewer.

Procedure
1. In Starting Trace Viewer Session, select the Tools > Choose Columns command.
2. Select (or unselect) the check boxes corresponding to the columns you want to display and click OK to confirm.
Note that the columns Event Name, Time Stamp, Level and Provider Name are selected by default and cannot
be unselected since they are the message identifiers.
3. If you want to restore the default settings, click the Restore Default button and return to the post-setup
configuration.

Trace Viewer available columns


The following columns are available:

Column Description

Event Name Name of the trace (assigned by the operating system).

Time Stamp Time stamp of the trace.

Level Severity level associated with the trace.

Provider Name Name of the trace provider.

Formatted Message String containing trace information (defined by each provider).

954 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Column Description

Process ID Identifier of the process inside the system (assigned by the operating
system).

Thread ID Identifier of the thread inside the system (assigned by the operating
system).

Op Code Name Information details about the executed operation (defined by each
provider).

Task Name Information details about the executed operation (defined by each
provider).

Provider GUID Identifier of the trace provider.

Process Name Name of the executable that sends the trace.

Generic Payload String containing all the trace information (that can be used when the
providers do not send the formatted message).

Keyword Value Numeric representation of the applied keywords.

Keywords Name of all applied keywords.

Verbosity The highest keyword among the ones that have been associated with
the trace. If you have set a keyword in the Choose Provider dialog box
(only for SIMATIC IT providers), this column shows that keyword. For
external providers this column remains empty.

Call Stack Information details that are specific for exceptions and that are only
traced by Microsoft-Windows-DotNETRuntime provider. You can
enable Trace Viewer to show a specific trace when a process, which
originated some message, throws an exception. Exceptions can be
captured and displayed by selecting the Enable Exception
Listening check box inside the Choose Providers dialog box. If you add
the Call Stack column from within the Choose Columns dialog box and
then you click on the exception message you can see the sequence of
operations that the program was executing before throwing the
exception.

Opcenter EX FN Context Information details about the SIMATIC IT provider. Select this check box
to show its related columns, otherwise remove the selection and click
the desired column you want to show in the message.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 955


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Column Description

Component ID Identifier of the component that executes a Command or an Event. It


identifies the following components:
• Worker (i.e. <MachineName>.ADM.0 for the Administration Worker,
<MachineName>.ENG.0 for the Engineering Worker,
<MachineName>.<Worker Role name>.<Instance number> for
Application Workers, <MachineName>.SignalManager.0 for Signal
Manager),
• Service Layer (i.e. one of the following: ServiceLayer.Runtime,
ServiceLayer.Administration, Service.Layer.Engineering or
ServiceLayer. Runtime.Archiving),
• Authorization Service,
• applications that use SDK Lean (IUnifiedSdkLean public interface).
These applications can be both internal Opcenter EX
FN applications as well as custom applications. For custom
applications the string contains an additional prefix to avoid any
possible conflicts with the internal applications (i.e.
Application.<Custom Application Name>).

Host Name The name of the machine that sends the trace.

AppName Identifier of the target application that will receive the command
request exposed by the backend application.

MethodName The name of method that sends the trace, if specified.

ClassName The name of class that sends the trace, if specified.

Artifact Type Filled in only for the beginning and ending messages of a Handler in the
Siemens-SimaticIT-Trace-Execution-Engine provider. Its possible
values
are: CommandHandler, CompositeCommandHandler, EventHandler
, PreCheckHandler, PostActionHandler, ReadingFunctionHandler.

DurationMs In the Siemens-SimaticIT-Trace-Execution-Engine provider:


• for the beginning message of a Handler, this is always zero.
• for the ending messages of a Handler, the duration of the Handler,
in milliseconds
In the Siemens-SimaticIT-Trace-SQLProfiling provider:
• the duration of a query, in milliseconds
Otherwise, this is set to -1. Note that negative values are exported in the
Persistent Storage (if enabled) but they are not visible in Trace Viewer
(and they are exported as empty string in CSV format).

Message Complete user text string.

956 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Column Description

From Name of the host sending the message. It is useful to determine the
exact node and application which is sending the message. The string
contains the host name, the host logical name and PID.
Host name is the computer name of the originator node. Logical name
is the name of the application passed by the user application. PID is the
process ID of the sending process.

Origin Identifies the origin from which a command arrives. It is associated to


the security context of the 'client application' which is requesting the
command. This is validated by the authorization server. For example,
the name of the UI Applications.

User User context (when available) validated by the authorization server.

CorrelationId ID that groups a set of traces that follow the same execution logic. This
field is useful to set filters and view related traces.

CurrentId Identifier of the current event or command. This identifier can be used
to select the traces related to a particular command or event.

Retry Retry counter string, with the following format: "current_retry" /


"max_retry" ("optimistic_counter"), where:
• max retry corresponds to the maximum number of command
execution retries configured in Governance.
• current retry corresponds to the number of retries that have
actually been executed.
• optimistic counter is the number of optimistic retries that the
system has executed to write on the database if optimistic
concurrency occurs.
The retry operation always refers to command execution (not to event
execution).

Name Name of the current command or event (full qualified name).

ParentId Identifier of the parent command within the command chain. This
identifier represents the relationship in the command execution chain.

RootRequestId Identifier of the root command inside the command chain. This
identifier is used to group the same command execution chain, from
the logical root where it is originated and for all related children.

6.3.7 Sorting Events


This page describes how you can sort and arrange the events displayed in the Trace Viewer.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 957


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

By default, the displayed events are arranged by columns and sorted chronologically in ascending order, so the first
column displayed is the Time Stamp, but you can change the visualization order of the columns and its content as
explained below.

Procedure
1. In Trace Viewer, select the Edit > Sort command.
2. From the First drop-down list, select the column whose events you want to sort and then set its content order
(Ascending, Descending, NoSort).
3. From the Then drop-down list, select the column whose events you want to sort afterwards, and set its content
order. Optionally, you can sort another 3 columns.
4. Click OK.

Additional operations
• Click the column's header to change the visualization order of the column: the column selected is the first
displayed and the Time Stamp the second.
• Click Unsort to reset the sorting order.
• Click the column's header to change the order of the event content (Ascending, Descending).

6.3.8 Grouping Correlated Messages


Inside Starting Trace Viewer Session, you can group the traces related to the execution flow triggered by command
or events by filtering by the CorrelationId field. You can obtain more detailed information about the execution flow
if you display the RootRequestId, ParentId and CurrentId columns. This page describes how the displayed
information can be useful in your analysis, and in particular in the following use cases:
• Tracing a Command invoking another Command
• Tracing an Event invoking a Command
• Tracing a Composite Command invoking another Composite Command
• Tracing a Composite Command invoking a Command
• Tracing an Event invoking a Composite Command

Context information overview


The CorrelationId can be used to select a complete command chain, from where it is generated (typically from the
Runtime Service Layer or a client application) to its remote execution and its final reply. It can also be used to
aggregate all the commands executed inside a single event handler instance. Every event handler, triggered from a
single event on the Bus, will have a different Correlation ID that groups together the complete command chain
executed inside the particular implementation of that event handler instance. Note that the correlation is not
meaningful when an execution context switches from a command to an event chain. Between an event (which is
fired by a command or an external application that uses SDK Lean interface), and the related event handlers, there
is no direct chain involved. All involved event handlers are independent entities that are simultaneously triggered
from a single event. In order to trace the event to all its event handlers, you can use the CurrentId field.
The ParentId is a reference to the caller command during an execution of a command chain. This field is
meaningful only inside the execution of a command. You can use to see the unrolled call-stack traces (using the
CorrelationId filter) and to isolate the parent caller of a particular command in the traces.
RootRequestId can be used to follow a call chain: for commands, to trace a single command chain from the root
request to its children, for event chains, to trace different root requests which are executed inside a single event
handler. This field is the same as the CorrelationId for the command execution only inside a command handler.
Command handlers call their children commands while event handlers call new command roots, with the same
Correlation ID.

958 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

CurrentId is the current GUID of a single command or event. It can be used to select the current context of
execution for a particular command or to follow the event to its handlers for a fired event on the bus.

 Command execution chains must be intended as nested calls to local commands except for
the CorrelationId use case, whose value is propagated also when the called command is remote.

To have an example of the correlation logic, consider the following use cases for command and event execution.

Tracing a Command invoking another Command


The following example shows how the system handles the traces originated by a root command invocation.
The Service Layer or an external application (via SDK Lean) calls Command0 command. The
related CommandHandler0 handler is executed and the code of this handler invokes a number of sub-commands
(Command1 and Command2 and their sub-commands) and fires an event (EventA).
• Send Command0 command
• Execute CommandHandler0 handler
• Send Command1 (child command)
• Send SubCommand11 (child command)
• Send SubCommand112 (child command)
• Send Command2 (child command)
• Send SubCommand21 (child command)
• Send SubCommand22 (child command)
• Fire EventA
All IDs (CorrelationId, RootRequestId, ParentId and CurrentId) are automatically generated. The actual example
values shown in the Trace Viewer screen below will not be inserted in the table for space reasons.

CorrelationId RootRequestId ParentId CurrentId Name

Send Command0:

ID1 (new) ID1 Empty ID1 Command0 (fully


qualified name)

CommandHandler0:

ID1 ID1 Empty ID1 Command0 (fully


qualified name)

Command1:

ID1 ID1 ID1 ID2 Command1 (fully


qualified name)

SubCommand11:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 959


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

CorrelationId RootRequestId ParentId CurrentId Name

ID1 ID1 ID2 ID3 SubCommand11 (fully


qualified name)

SubCommand112:

ID1 ID1 ID3 ID4 SubCommand112 (fully


qualified name)

Command2:

ID1 ID1 ID1 ID5 Command2 (fully


qualified name)

SubCommand21:

ID1 ID1 ID5 ID6 SubCommand21 (fully


qualified name)

SubCommand22:

ID1 ID1 ID5 ID7 SubCommand22 (fully


qualified name)

Fire EventA:

ID1 Empty Empty ID8 EventA (fully qualified


name)
Since the correlation ID is automatically generated, you cannot directly filter by it.
You could filter by the name of the root command you have invoked first (e.g. Command0), and then use the
related CorrelationId to filter by the entire execution chain.
The first command of the chain (Command0) has no ParentId. Command1 and Command2 have as ParentId the
CurrentId of Command0. SubCommand11 has as ParentId the CurrentId of Command1. SubCommand112 has as
ParentId the CurrentId of SubCommand11. The RootRequestId is propagated to the sub-command chain except
for the fired event. The CorrelationId is the same for the entire chain starting from the first invoked command,
including the fired event.

Tracing an Event invoking a Command


The following example shows how the system handles the traces of a command flow originated by an event.
The code inside the EventHandlerA event handler calls the commands Command1 and Command2 (and their sub-
commands) and fires an event (EventB).
• Fire EventA
• Execute EventHandlerA handler

960 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

• Send Command1 (root command)


• Send SubCommand11 (child command)
• Send SubCommand112 (child command)
• Send Command2 (root command)
• Send SubCommand21 (child command)
• Send SubCommand22 (child command)
• Fire EventB
All IDs (CorrelationId, RootRequestId, ParentId and CurrentId) are automatically generated. The actual example
values shown in the Trace Viewer screen below will not be inserted in the table for space reasons.

CorrelationId RootRequestId ParentId CurrentId Name

Fire EventA:

ID1 Empty Empty ID1 EventA (fully qualified


name)

EventHandlerA:

ID2 (new) Empty Empty ID1 EventHandlerA (fully


qualified name)

Command1:

ID2 ID3 Empty (Root) ID3 (RootRequestID) Command1 (fully


qualified name)

SubCommand11:

ID2 ID3 ID3 ID4 SubCommand11 (fully


qualified name)

SubCommand112:

ID2 ID3 ID4 ID5 SubCommand112


(fully qualified name)

Command2:

ID2 ID6 Empty (Root) ID6 (RootRequestID) Command2 (fully


qualified name)

SubCommand21:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 961


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

CorrelationId RootRequestId ParentId CurrentId Name

ID2 ID6 ID6 ID7 SubCommand21 (fully


qualified name)

SubCommand22:

ID2 ID6 ID6 ID8 SubCommand22 (fully


qualified name)

Fire EventB:

ID2 Empty Empty ID9 EventB (fully qualified


name)
Since the CorrelationId is automatically generated, you cannot directly filter by it.
You could filter by the name of the event handler that has been associated to the first fired event (EventA) and then
use the related CorrelationId to filter by the entire execution chain.
The first command of the chain (Command1) has no ParentId. SubCdommand11 has as ParentId the CurrentId
of Command1. SubCommand112 has as ParentId the CurrentId of SubCommand11.
The RootRequestId is generated for each root command and then it is propagated to the sub-command chain. The
CorrelationId is the same for the entire chain starting from the first event handler to the last fired event.

Tracing a Composite Command invoking another Composite Command


• SendCommand (CompositeCommand1)
• CompositeCommandHandler1
• SendCommand (CompositeCommand2)
• CompositeCommandHandler2

CorrelationId RootRequestId ParentId CurrentId Name

CompositeCommand0:

ID1 (new) ID1 Empty ID1 CPCommand0FQN

CompositeCommandHand
ler0:

ID1 ID1 Empty ID1 CPCommand0FQN

CompositeCommand1:

ID1 ID1 ID1 ID2 CPCommand1FQN

962 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

CorrelationId RootRequestId ParentId CurrentId Name

CompositeCommandHand
ler1:

ID1 ID1 ID1 ID2 CPCommand1FQN

Tracing a Composite Command invoking a Command


• SendCommand (CompositeCommand)
• CompositeCommandHandler
• SendCommand (Command)
• CommandHandler

CorrelationId RootRequestId ParentId CurrentId Name

CompositeCommand0:

ID1 (new) ID1 Empty ID1 CPCommand0FQN

CompositeCommandHand
ler0:

ID1 ID1 Empty ID1 CPCommand0FQN

Command1:

ID1 ID1 ID1 ID2 Command1FQN

CommandHandler1:

ID1 ID1 ID1 ID2 Command1FQN

Tracing a Composite Command firing an Event


• SendCommand (CompositeCommand)
• CompositeCommandHandler
• FireEvent
• EventHandler

CorrelationId RootRequestId ParentId CurrentId Name

CompositeCommand0:

ID1 (new) ID1 Empty ID1 CPCommand0FQN

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 963


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

CorrelationId RootRequestId ParentId CurrentId Name

CompositeCommandHand
ler0:

ID1 ID1 Empty ID1 CPCommand0FQN

FireEventA:

ID1 Empty Empty ID2 EventNameFQN

EventHandlerA

ID3 (new) Empty Empty ID2 EventNameFQN

Tracing an Event invoking a Composite Command


• FireEvent
• EventHandler
• CompositeCommand

CorrelationId RootRequestId ParentId CurrentId Name

FireEventA:

ID1 Empty Empty ID1 EventNameFQN

EventHandlerA:

ID2 (new) Empty Empty ID1 EventNameFQN

CompositeCommand1:

ID2 ID3 Empty (Root) ID3 (RootID) CPCommand1FQN

CompositeCommandHa
ndler1

ID2 ID3 Empty (Root) ID3 (RootID) CPCommand1FQN

Retrieving the context execution information


You can programmatically retrieve execution information (CorrelationId, CurrentId, ParentId, RootRequestId) on
the current command/event handler by using the IUnifiedSdkExecutionContextInfo.RetrieveExecutionContext
method, documented in the Opcenter Execution Foundation Platform Reference online help.

964 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

6.3.9 Applying Filters and Highlights


Inside Trace Viewer you can set filters and highlight rules to better analyze execution traces. This analysis can be
consequently refined by choosing the analysis function to filter and the messages to display.

Procedure
To filter and highlight messages, apply condition rules as follows:
1. In Starting Trace Viewer Session, select either of the following commands:
• Edit > Highlight
• Edit > Filter
2. Set a value inside the Field drop-down list to filter by certain fields (such as time stamp, provider name, thread
Id etc)
3. Select the logical operator of the condition and set the value to filter by (such as the date time for the time
stamp, provider name ,thread Id).
4. (Only for highlighting) Set the color to highlight the messages that match the previously set condition.
5. Optionally, you can select the analysis type by clicking Advanced and then choose one of the following analysis
functions:
• Host Process
• All Host Process Thread
• UAF relevant Host Process Thread
• Process Thread
6. Repeat steps 1-5 for each additional condition.
These rules can be saved as a filter and loaded afterwards.

Using shortcuts to filtering and highlighting traces


Right-click on a field of the trace and select the following commands:
• Copy: to copy the selected field and set the column separator in order to paste it in any text document.
• Add to Filter: to set the selected field as new condition and add it to the existing filters.
• Set As Filter: to set the selected field as unique filtering condition and reset all the previous filters.
• HighLight Field: to set the selected field as highlight rule and associate it with a predefined color. This
condition is added to the existing highlight rules.
• Parent Find: to show the selected handler parent in case of nested handlers.
• Children Find: to show the selected handler children in case of nested handlers.
• Near This time: to filter chronologically any field near to the selected message.

Removing conditions
• Click Clear All Rules to remove any active conditions for highlights and filters. Trace Viewer updates the
displayed traces and resets any condition.
• Click Highlight or Filter to display the previously defined conditions.
• Select the red cross icon to directly remove a single filter or highlight condition.
• Select the toggle button to temporarily disable a single filter or highlight condition.
• Select an empty option inside a condition to delete all subsequent rules.
• Click Restore Initial Rules to reset any modified or removed conditions.

6.3.10 Setting the Display Configuration


This page describes how you can define the data visualization in the Trace Viewer when you export messages in csv
format or display them in real time.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 965


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Procedure
1. In Starting Trace Viewer Session, select the Tools > Options command.
2. In the Column Separator area, select either of the following check boxes:
• System to use the system default separator (set in Regional Settings).
• Semicolon (selected by default)
• Tab
• Other, and enter the desired separator in the adjacent box.
The box below displays an example of the data visualization in the exported file.
3. In the TimeStamp Format area, modify the date and time format of the event messages to display.
The box below displays an example of the timestamp visualization.
4. Optionally, do either of the following:
• Click Revert to Initial to keep the previous timestamp.
• Click Restore to Default to reset the default timestamp.
5. In the Message Color Schema, set the color for each information level, otherwise click Restore Default
Schema.
6. In the Font Name combo box, set the font to be used in the whole user interface. Available fonts are: Microsoft
Sans Serif, Arial, Tahoma, Calibri, Segoe UI, Trebuchet MS, Verdana, Consolas.
7. In the Text Size combo box, set the size of the text. Available values are: Small, Medium, Large.
8. In the Zoom combo box, set the zoom level to apply to the whole user interface. Available values are: 100%,
125%, 150%, 175%.
9. In the Max Messages list box, set the default value of the limit of the displayed messages, by using the spin
buttons (the maximum limit is 500.000).
10. Select the Show enum with numeric Values check box to display the information levels together with the
equivalent number to better filter the messages.
11. Click Ok.

6.3.11 Setting the Display Options in the Main Panel


This page describes how you can the display options in the main panel of Trace Viewer.

Available Operations on Display Options


Operation Description

View > Show Action Panel You can select or unselect this option to increase the available view
space during Real Time Monitoring.
In Real Time mode, when the Action Panel is hidden, some
additional buttons, such as for example Start, Pause/Resume, Stop
or Choose Providers, are still visible to perform the required actions.

View > Show Full Message When this option is selected, the main area is split in two panels: in
the upper panel you have the list of the incoming events and in the
lower panel you have a multi-line text box containing the message.
In this way you can see all relevant data at the same time and can
set the size of the list view pane and message box.

966 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Operation Description

Break on Error If you are receiving many events at the same time, you might miss
errors. If this check box is selected, when an error is inserted in the
list view, the Trace Viewer goes automatically in Pause. In this way,
you can better analyze the messages.

Adjust font size as described In order to adjust the font size of the list view panel and the
message text box, place the focus on the list view panel and use the
combination [Ctrl] + [Mouse Wheel].
This combination is the same used to set the zoom on Chrome or
Visual Studio.
The allowed font size is in the range [4 - 64].

6.3.12 Exporting Traces to a Persistent Storage


The Trace Viewer supports real-time trace logging as well as exporting application traces for troubleshooting
purposes.
Traces can be exported either to a persistent storage (SQL Server database), as described here, or by performing the
operation:
• via script (see Configuring the SIMATIC IT UAF Log Router Service via Script ),
• in the Windows Performance Monitor (see Exporting Traces To Windows Performance Monitor).

Prerequisites
The Trace Viewer is properly configured: providers are chosen and logging modes are selected.

Procedure
1. In the Choose Providers page in Trace Viewer, click Export.
2. Select the Persistent Storage option to export the traces generated from the selected providers to a SQL Server
database.
3. Insert the required connection string details (Data Source and Initial Catalog), including the credentials
required to perform the SQL Server database Authentication (User ID and Password) on the SQL Server
database instance.
4. Do one of the following:
• Select the Start logging to Persistent Storage check box to enable the provided configuration and
make it ready for writing on the database after the first SIMATIC IT UAF Log Router service restart (i.e.
with the element <SqlServerEntityFrameworkDatabaseSink ….. mode="writeMsgByID" in the
configuration file).
• Leave the Start logging to Persistent Storage check box unselected in order to only save the provided
configuration, without writing on the database (i.e. with the
element <SqlServerEntityFrameworkDatabaseSink ….. mode="listeningOnly"> in the configuration
file).
5. Click OK.
6. Restart the SIMATIC IT UAF Log Router service to make any configuration change effective (i.e. if you have just
selected the start logging mode option, or if you have disabled a previously active session and you want to stop
writing on the database).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 967


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

 For further details on these parameters, as well as on the parameters that can be manually modified in an
xml configuration file (LogRouterService.TraceEventService.xml), see Modifying Trace Viewer Persistent
Logging Parameters.

 When Persistent Storage is configured and the Start logging to Persistent Storage is enabled, the Log
Router will continuously write traces to the specified database, even when the Trace Viewer is stopped or
not executing at all.
To stop it, run Trace Viewer, go to the Choose Providers page, click Export, select the Persistent
Storage option, disable the Start logging to Persistent Storage check box, click OK, restart the SIMATIC
IT UAF Log Router service.

 Troubleshooting migration
Databases generated by the Persistent Storage functionality in previous versions are not compatible with
Opcenter Execution Foundation 4.1. Before migrating, if Persistent Storage is enabled, you should disable it
and drop the related database. If you forget to drop the database, after the migration you will get errors in
Trace Viewer and Event Viewer, such as:
• Opcenter EX FN Log Router - service for ETW Log Routing and Remoting started and running with error:
Exception: The model backing the 'LogModel' context has changed since the database was created.
• [SqlServerEntityFrameworkDatabaseSink::BulkCopyDataTable] for sink = PersistentLogs receive an
exception
Exception: The given ColumnMapping does not match up with any column in the source or destination.
In this case, you can follow this procedure:
• stop the SIMATIC IT UAF Log Router service
• drop the Persistent Storage database (since all logged messages will be lost you should create a
backup before dropping it)
• start the SIMATIC IT UAF Log Router service. A new empty database with the same name will be
generated, and the Log Router will start writing log events into it.

6.3.12.1 Exporting Traces To Windows Performance Monitor


The Trace Viewer supports real-time trace logging as well as exporting application traces for troubleshooting
purposes.
Traces can be exported either to Windows Performance Monitor, as described here, or in persistent storage
(see Exporting Traces to a Persistent Storage).
You can save the export configuration in an XML template file in order to import it later without re-configuring the
export settings.

Prerequisites
The Trace Viewer is properly configured: providers are chosen and logging modes are selected.

Procedure
1. In the Choose Providers page in Trace Viewer, click Export.
2. Select the Performance Monitor option to export the provider configuration to Windows Performance Monitor.
3. Select the required export mode:

968 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Option Description

Export as User Select this mode if you want to export your provider configuration to Windows
Defined Data Performance Monitor and define the ETL file where traces will be persisted. Provide a
Collector Set name and a description for the data collector, and then browse to the directory where you
want to save the ETL file. If you choose this option, the tracing activity must be either
manually started in the Performance Monitor, or scheduled at predefined times, and you
can also modify previous configurations (file name, directory location, tracing duration) .
Exported data will be displayed in the Data Collector Sets > User Defined node in the
Performance tree view in Windows Performance Monitor.

Export as Select this mode if you want to automatically start the trace recording after the first
Startup Event available machine startup. Provide a name and a description for the data collector, and
Trace Session then browse to the directory where you want to save the ETL file. Browse to the directory
where you want to save the ETL file and click Save. Exported data will be displayed in the
Data Collector Sets > Startup Event Trace Sessions node in the Performance tree view
in Windows Performance Monitor.

 This option is preferable if you want to debug problems that may occur at the
machine startup, when it is impossible to activate interactive applications such
as the Trace Viewer.

4. (Optional) Select the Save as XML Template File check box to save the export settings as an XML file and then
browse to a proper location.
Note To import a previously saved XML template, either click the Import from PerfMon Template button or
right-click the providers table and then select Import from PerfMon Template from the Choose Providers
page in the Trace Viewer.
5. Click OK.

6.3.12.2 Modifying Trace Viewer Persistent Logging Parameters


The traces generated from the platform tracing providers can be exported from Trace Viewer to a persistent SQL
database by choosing the proper export option.
You can enable this functionality by selecting the providers of interest from the Trace Viewer and configuring the
database server connection details (server name, database and authentication data).
You can modify this data any time by modifying a dedicated configuration XML file as described below.

Prerequisites
You have already configured the required export settings in Trace Viewer.

Procedure
1. Stop the SIMATIC IT Log Router Windows service.
2. Browse to %SITUnifiedSystemRoot%bin\etw.
3. Open the LogRouterService.TraceEventService.xml configuration file.
4. Modify only the customizable parameters or the connection string details (except for user ID and password) as
described in the following table:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 969


How to Monitor Opcenter EX FN Runtime Processes

Logging and Analyzing Application Traces with Trace Viewer

Property Description

Data Source The database server instance that will host the database.

Initial Catalog The name of the database.

user ID The user name used for the database server authentication.
This value cannot be edited in the XML file, but only via Trace
Viewer interface.

Password The encrypted password used for the database server


authentication. This value cannot be edited in the XML file, but
only via Trace Viewer interface.

bufferingFlushAllTimeoutInSeconds The time interval to clear the cache.

bufferingIntervalInSeconds The time interval to log messages, irrespective of the count of


messages.

maxBufferSize The maximum count of messages to be logged before buffering


time interval has reached.

bufferingCount The count of messages to be logged before buffering time


interval has reached.
5. Save the XML file.
6. Export at least one provider using the Trace Viewer. For information on how to export providers, refer to
the Exporting Traces To Windows Performance Monitor.
7. Restart the SIMATIC IT UAF Log Router Windows service.

Result
The providers that you export in the Trace Viewer are automatically added to the XML file as a child of the
<SqlServerEntityFrameworkDatabaseSink> element.

 Note
The xml file must contain at least one provider otherwise improper event logging will be caused.

6.3.13 Generating Custom Trace Providers


You can configure the Trace providers for troubleshooting issues with more specific information which will refer to
your custom application. The following steps describe how to configure a Custom Trace Provider.

Prerequisites
Project Studio is required for installing the providers.

Procedure
1. Stop the SIMATIC IT Log Router Windows service.
2. Browse to %SITUnifiedSystemRoot%bin\etw.

970 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

3. Run Uninstall ETW providers.bat as Administrator to uninstall all the Trace Providers.
4. Browse to %SITUnifiedSystemRoot%bin.
5. Run cmd as Administrator and navigate to cd %SITUnifiedSystemRoot%bin.
6. Execute the required command:
Command Description

generatetraceprovider This command updates an existing Trace Provider in the


-u <CustomTrace location %SITUnifiedSystemRoot%bin\etw.
Provider Name>
Siemens-SimaticIT-Trace-<CustomTrace Provider
Name>.etwManifest.dll, Siemens-SimaticIT-Trace-<CustomTrace Provider
Name>.etwManifest.man should available in the location
%SITUnifiedSystemRoot%bin\etw. and
SimaticIT.<CustomTrace Provider Name>.TraceEx.dll available in the location
%SITUnifiedSystemRoot%bin\etw\TraceProviders.
Before updating, make sure that in the Windows Registry Editor there are no
keys linked to the custom provider (You can find the key in Regedit by Clicking
on Edit ->Find (or ctrl+f)). If there are any existing keys in the registry after the
uninstall operation, delete all keys.

generatetraceprovider This command creates the custom Trace Provider with name "Siemens-
-n <CustomTrace SimaticIT-Trace-<CustomTrace Provider Name>".
Provider Name>
7. Browse to %SITUnifiedSystemRoot%bin\etw.
8. Run Install ETW providers with Path.bat as Administrator for installing all the Trace Providers.
9. Restart the SIMATIC IT UAF Log Router Windows service.

Result
The Trace Viewer can listen to the providers that you created or updated.

6.4 Persisting System, Security and Application Messages on


Microsoft Event Viewer
The SIMATIC IT UAF Log Router service is a platform service that allows you to permanently save security, system
and application related messages to file repository.
The service has been implemented as a Windows Service, integrated with Event Viewer for Windows.
It is installed by the Opcenter Execution Foundation setup, it is always active in the background, and is configured
to listen to Trace Viewer events in order to permanently save them.
In particular, it enables event tracing sessions for the Siemens-SimaticIT-Security, Siemens-SimaticIT-
System and Siemens-SimaticIT-Application providers (see Choosing Trace Providers) and listens to their related
events.

 You can only view these messages inside Microsoft Event Viewer (they cannot be displayed in Trace
Viewer).

The service can be manually started and stopped from Windows Services environment.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 971


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

Viewing Opcenter EX FN security and system traces in Microsoft Event Viewer


SIMATIC IT Log Router Service is configured to log and save Opcenter EX FN system and security administration
messages in the Windows Event Viewer repository.
To view them:
1. Open Microsoft Event Viewer by accessing Windows Administrative Tools environment and then
selecting Event Viewer.
2. Inside Event Viewer application, expand Application and Services Logs.
3. To view security messages, expand Siemens > SimaticIT > Security and open the Siemens-SimaticIT-
Security-Admin file.
4. To view system messages, expand Siemens > SimaticIT > System and open the Siemens-SimaticIT-System-
Admin file.
5. To view application messages for command handler execution errors,
expand Siemens > SimaticIT > Application and open the Siemens-SimaticIT-System-Admin file.
6. To view system configuration messages for configuration execution errors, expand Siemens > SimaticIT >
System and open the Siemens-SimaticIT-System-Admin file.
SIMATIC IT Log Router Service sets to 100MB the size of Windows Log file where traces are stored when it runs for
the first time after the fresh installation or after the migration from version 3.0 or prior.
Bear in mind that if Windows Event Viewer changes the log file size, SIMATIC IT Log Router Service cannot change it.

 In a development environment you can use the script UnistallETWProviders.bat to fix provider issues.
This operation reverts the configuration and the size of log files to their initial values but it does not delete
stored traces.

Messages in Windows Logs


If the service is unable to write messages to the Applications and Service Logs repository, for example during the
installation process, two messages are saved in the Windows Logs > System node in Microsoft Event Viewer:
• A message ('Message 1' in the example below) contains a warning that the original message was not written
successfully and consequently an alternative message has been generated.
• A message ('Message 2' in the example below) contains the contents of the original message but written in a
simpler format.
Examples of specific error messages:
• 'Message 1' - a warning that the original message was not written successfully:

Provider [Siemens-SimaticIT-SystemLogger]
Timestamp [2016/02/17 15:31:42.397] - Level [Critical]
Id: 31 - Task [1512 - Write] - OpCode [31 - LogRouterError]
Keywords [0x0000000000000200 - LogRouter]

SIMATIC IT UAF Log Router - service in not able to Write Information to Event Log
- error writing message with id SIMATIC IT UAF Log Router

- with Payload
appName=SIMATIC IT UAF Log Router
msgId=26

972 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

• 'Message 2' - the contents of the original message in a simpler format:

Provider [Siemens-SimaticIT-SystemLogger]
Timestamp [2016/02/17 15:31:42.413] - Level [Informational]
Id: 26 - Task [1001 - Start] - OpCode [29 - LogRouterSucess]
Keywords [0x0000000000000200 - LogRouter]

SIMATIC IT UAF Log Router - service for SIMATIC IT UAF Log Router started

- with Payload
appName=SIMATIC IT UAF Log Router

The following screenshot contains an example of a standard error message:

6.4.1 Opcenter EX FN System, Security and Application Traces


The SIMATIC IT UAF Log Router service is configured to log and save messages in the Windows Event Viewer
repository on the following subjects:
• system logs
• security logs
• application logs

system logs

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 973


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

System logs are stored in the Siemens-SimaticIT-System-Admin file.


provider Name : Siemens-SimaticIT-System
provider guid: {662dd083-a2d9-4020-a75e-2807e60908ae}
resource file: SimaticIT.Integration.Diagnostics.Core.Siemens-SimaticIT-System.etwManifest.dll
The following events are logged in the file:

 The version is 1 for all the following events.

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

1 The '%1' service has been started. (%1) Informatio Start LauncherSucces
componentId nal s
--
(Launcher)
UnicodeString

2 The '%1' service has been stopped. (%1) Informatio Stop LauncherSucces
componentId nal s
--
(Launcher)
UnicodeString

3 The '%1' service has been restarted. (%1) Informatio Restart LauncherSucces
componentId nal s
--
(Launcher)
UnicodeString

4 The '%1' service has got a failure with (%1) Error Check LauncherFailure
this message: '%2' componentId
(Launcher)
--
UnicodeString
(%2) exception
--
UnicodeString

5 Fatal Exit of the Worker Process '%1'. (%1) Informatio Check WorkerFailure
This process has raised the following componentId nal
(Worker)
exception: '%2' --
UnicodeString
(%2) exception
--
UnicodeString

974 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

6 Deployment '%1' of app '%2' started. (%1) Informatio Start SolutionSuccess


componentId nal
(Solution
--
Deployment)
UnicodeString
(%2) appName
--
UnicodeString

7 Deployment '%1' of app '%2' (%1) Informatio Deploy SolutionSuccess


succeeded. componentId nal
(Solution
--
Deployment)
UnicodeString
(%2) appName
--
UnicodeString

8 Deployment '%1' of app '%2' failed (%1) Informatio Deploy SolutionFailure


with eror: '%3' componentId nal
(Solution
--
Deployment)
UnicodeString
(%2) appName
--
UnicodeString
(%3)
failureExplanat
ion --
UnicodeString

9 Deployment '%1' of app '%2' started. (%1) Informatio Start LocalDeploymen


componentId nal t
-- Success
UnicodeString
(Local
(%2) appName
Deployment)
-- :UnicodeStri
ng

10 Deployment '%1' of app '%2' (%1) Informatio Deploy LocalDeploymen


succeeded. componentId nal t
-- Success
UnicodeString
(Local
(%2) appName
Deployment)
--
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 975


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

11 Deployment '%1' of app '%2' failed (%1) Informatio Check LocalDeploymen


with error: '%3' componentId nal t
-- Failure
UnicodeString
(Local
(%2)
Deployment)
appName --
UnicodeString
(%3)
failureExplanat
ion
--
UnicodeString

12 Application '%1': loading app '%2'. (%1) Informatio Start AppSuccess


componentId nal
(App)
--
UnicodeString
(%2) appName
--
UnicodeString

13 Application %1: load app %2 (%1) Informatio Load AppSuccess


completed. componentId nal
(App)
--
UnicodeString
(%2) appName
--
UnicodeString

14 Application '%1': load app '%2' failed (%1) Informatio Check AppFailure
with error: '%3' componentId nal
(App)
--
UnicodeString
(%2) appName

UnicodeString
(%3)
failureExplanat
ion
-- :UnicodeStri
ng

976 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

15 The administrative command '%2' is (%1) Informatio Process StateMachine


being componentId nal Success
processed on the host '%3' from the --
(NodeState)
user '%4'. UnicodeString
(Machine)
(%2)
commandSym
bolicName
--
UnicodeString
(%3)
computerNam
e --
UnicodeString
(%4) username
--
UnicodeString

16 The runtime system on host '%2' has (%1) Informatio Start StateMachine
started successfully. componentId nal Success
--
(NodeState)
UnicodeString
(Machine)
(%2)
computerNam
e --
UnicodeString

17 The host '%2' has changed its status (%1) Informatio Change StateMachine
to '%3'. componentId nal d Success
--
(NodeState)
UnicodeString
(Machine)
(%2)
computerNam
e–
UnicodeString
(%3)
statusSymbolic
Name –
UnicodeString

18 The runtime system on host '%2' is (%1) Informatio Stop StateMachine


stopped successfully. componentId nal Success
--
(NodeState)
UnicodeString
(Machine)
(%2)
computerNam
e --
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 977


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

19 The host '%2' is in status '%3' with the (%1) Warning Restart StateMachine
following errors: '%4'. componentId Warning
A recovery procedure is in progress. --
(NodeState)
UnicodeString
(Machine)
(%2)
computerNam
e --
UnicodeString
(%3)
statusSymbolic
Name –
UnicodeString
(%4)
expandedReas
onsIdStrings --
UnicodeString

20 The host '%2' has changed its status (%1) Error Change StateMachine
to '%3' componentId d Failure
with the following reason: '%4' --
(NodeState)
UnicodeString
(Machine)
(%2)
computerNam
e --
UnicodeString
(%3)
statusSymbolic
Name --
UnicodeString
(%4)
expandedReas
onsIdString --
UnicodeString

21 The Worker Process '%1' is being (%1) Informatio Start LauncherProces


launched. workerName -- nal s
UnicodeString Sucess
(Launcher)

22 The Worker Process '%1' has been (%1) Informatio Comple LauncherProces
started successfully. workerName -- nal ted s
UnicodeString Sucess
(Launcher)

978 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

23 The Worker Process '%1' has died (%1) Warning Check LauncherProces
unexpectedly. workerName -- s
A restart action is underway to recover UnicodeString Warning
from the problem.
(Launcher)

24 The Worker Process '%1' has failed (%1) Error Check LauncherProces
with error: '%2'. workerName -- s
UnicodeString Error
(%2) reason --
(Launcher)
UnicodeString

25 The Worker Process '%1' has been (%1) Informatio Stop LauncherProces
stopped successfully. workerName -- nal s
UnicodeString Sucess
(Launcher)

26 SIMATIC IT UAF Log Router - service (%1) appName Informatio Start LogRouterSuces
for %1 started -- nal s
UnicodeString
(LogRouter)

27 SIMATIC IT UAF Log Router - service (%1) appName Informatio Stop LogRouterSuces
for %1 stopped -- nal s
UnicodeString
(LogRouter)

28 SIMATIC IT UAF Log Router - service (%1) appName Critical Start LogRouterError
for %1 --
(LogRouter)
cannot start due to error: %2 UnicodeString
(%2)
description --
UnicodeString

29 SIMATIC IT UAF Log Router - service (%1) appName Error Process LogRouterWarin
for %1 -- g
started and running with error: %2 UnicodeString
(LogRouter)
(%2)
description --
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 979


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

30 SIMATIC IT UAF Log Router - service (%1) appName Error Start LogRouterWarin
for %1 started -- g
and running with error in Sink/Worker: UnicodeString
(LogRouter)
%3 - sink or (%2)
worker may not work properly - error description --
details: %2 UnicodeString
(%3) name --
UnicodeString

31 SIMATIC IT UAF Log Router - service in (%1) appName Critical Write LogRouterError
not able to Write --
(LogRouter)
Infomation to Event Log - error writing UnicodeString
message with id %1 (%2) msgId --
Int32

32 SIMATIC IT UAF Log Router - service (%1) appName Warning Stop LogRouterWarin
for %1 -- g
stopped with error UnicodeString
(LogRouter)
%2 (%2)
description
-- :UnicodeStri
ng

33 The administrative command '%2' has (%1) Informatio Comple StateMachine


been componentId nal ted Success
successfully processed on the host --
(NodeState)
'%3' from UnicodeString
(Machine)
the user '%4' (%2)
commandSym
bolicName --
UnicodeString
(%3)
computerNam
e --
UnicodeString
(%4) username
--
UnicodeString

980 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

34 The administrative command '%2' on (%1) Error Check StateMachine


the host '%3' componentId Failure
from the user '%4' failed for the --
(NodeState)
following reason: %5 UnicodeString
(Machine)
(%2)
commandSym
bolicName --
UnicodeString
(%3)
computerNam
e --
UnicodeString
(%4) username
--
UnicodeString
(%5)
expandedReas
onsIdString
--
UnicodeString

35 The administrative command '%2' on (%1) Error Comple StateMachine


the host '%3' componentId ted Failure
from the user '%4' failed with error: --
(NodeState)
%5 UnicodeString
(Machine)
(%2)
commandSym
bolicName --
UnicodeString
(%3)
computerNam
e --
UnicodeString
(%4) username
--
UnicodeString
(%5)
errorMessage --
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 981


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

36 The host '%2' cannot change its status (%1) Warning Start StateMachine
to '%3' for the componentId Warning
following reason: '%4' --
(NodeState)
UnicodeString
(Machine)
(%2)
computerNam
e --
UnicodeString
(%3)
statusSymbolic
Name --
UnicodeString
(%4) reason --
UnicodeString

37 The host '%2' is in status '%3' and all (%1) Informatio Restart StateMachine
errors have been componentId nal Success
successfully recovered --
(NodeState)
UnicodeString
(Machine)
(%2)
computerNam
e–
UnicodeString
(%3)
statusSymbolic
Name --
UnicodeString

38 Launcher '%1' '%1' is waiting for (%1) Warning Wait LauncherProces


Rabbit connection. componentId s
-- Waring
UnicodeString
(Launcher)

39 An error has occurred during the (%1) path -- Error Start LauncherFailure
start of service layer of '%1', reason: UnicodeString
(Launcher)
'%2' (%2) reason --
UnicodeString

40 An error has occurred during the (%1) path -- Error Stop LauncherFailure
stop of service layer of '%1', reason: UnicodeString
(Launcher)
'%2' (%2) reason --
UnicodeString

982 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

41 An error has occurred during the (%1) path -- Error Write LauncherFailure
creation of the state runtime file UnicodeString
(Launcher)
'%1', (%2) reason --
reason: '%2' UnicodeString

42 License Server succesfully connected Informatio Process LicenseServer


by nal Connected
Administration Worker
(License)

43 License Server connection failed by Error Process LicenseServer


Administration Worker Connection
Failed
(License)

44 the license server has been Informatio Process LicenseServer


disconnected nal Disconnected
by Administration Worker
(License)

45 The license server has failed to Error Process LicenseServer


disconnect DisconnectionFa
by Administration Worker iled
(License)

46 the license module %1 has been (%1) Informatio Process LicenseAcquired


acquired moduleDescrip nal
(License)
tion --
UnicodeString

47 Administration Worker has failed to (%1) Error Process LicenseAcquireF


acquire the license moduleDescrip ailed
module%1 for SIT UAF tion --
(License)
UnicodeString

48 the license module %1 has been (%1) Informatio Process LicenseReleased


released moduleDescrip nal
(License)
tion --
UnicodeString

49 Administration Worker has failed to (%1) Error Process LicenseReleaseF


release the moduleDescrip ailed
license module %1 tion --
(License)
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 983


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

50 The '%1' service has detected a (%1) Informatio Info LauncherPreshu


machine shutdown componentId nal tdown
--
(Launcher)
UnicodeString

51 The Worker Process '%1' has been (%1) Informatio Info LauncherProces
recovered workerName -- nal s
successfully. Recovered
UnicodeString
(Launcher)

52 The Rule '%1' '%2' on Host '%3' has (%1) ruleId -- Informatio Start SignalManagerR
been UnicodeString nal ule
successfully started. (%2) revision -- Started
UnicodeString
(SignalManager)
(%3) hostName
--
UnicodeString

53 The Rule '%1' '%2' on Host '%3' has (%1) ruleId -- Informatio Stop SignalManagerR
been UnicodeString nal ule
successfully stopped. (%2) revision -- Stopped
UnicodeString
(SignalManager)
(%3) hostName
--
UnicodeString

54 The Rule '%1' '%2' on Host '%3' has (%1) ruleId -- Error Load SignalManagerR
terminated with failure UnicodeString ule
due to this error: '%4' (Error Code: (%2) revision -- Failed
%5). UnicodeString
(SignalManager)
The rule is now stopped. (%3) hostName
--
UnicodeString
(%4)
errorDescriptio
n --
UnicodeString
(%5) errorCode
-- Int32

984 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

55 The Rule '%1' '%2' on Host '%3' has (%1) ruleId -- Error Process SignalManagerR
raised this error during UnicodeString ule
the processing of block '%4': (%2) revision -- ExecutionError
'%5' (Error Code: %6). UnicodeString
(SignalManager)
The rule is still running. (%3) hostName
--
UnicodeString
(%4)
blockType --
UnicodeString
(%5)
errorDescriptio
n --
UnicodeString
(%6) errorCode
-- Int32

56 Automation: configuration is being (%1) Informatio Start AutomationUpd


updated. componentId nal ate
(ComponentId=%1). --
(Automation)
UnicodeString

57 Automation: configuration update (%1) Informatio Comple AutomationUpd


ended successfully. componentId nal ted ate
(ComponentId=%1). --
(Automation)
UnicodeString

58 Automation: configuration update (%1) Error Stop AutomationUpd


failed for the following reason: %2. componentId ate
(ComponentId=%1). --
(Automation)
UnicodeString
(%2) error --
UnicodeString

59 Automation: configuration is being (%1) Informatio Start AutomationIOW


sent to IOWA system. componentId nal A
(ComponentId=%1). -- Update
UnicodeString
(Automation)

60 Automation: configuration sent to (%1) Informatio Comple AutomationIOW


IOWA system successfully. componentId nal ted A
(ComponentId=%1). -- Update
UnicodeString
(Automation)

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 985


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

61 Automation: IOWA system refused the (%1) Error Stop AutomationIOW


configuration for the componentId A
following reason: %2. -- Update
(ComponentId=%1). UnicodeString
(Automation)
(%2) error --
UnicodeString

62 Automation: connections are being (%1) Informatio Start Automation


updated. componentId nal ConnectionsUpd
(ComponentId=%1). -- ate
UnicodeString
(Automation)

63 Automation: connections update (%1) Informatio Comple Automation


ended successfully. componentId nal ted ConnectionsUpd
-- ate
UnicodeString
(Automation)

64 Automation: connections update (%1) Error Stop Automation


failed componentId ConnectionsUpd
for the following reason: %2. -- ate
(ComponentId=%1). UnicodeString
(Automation)
(%2) error --
UnicodeString

65 Automation: configuration reset (%1) Informatio Start Automation


started. (ComponentId=%1). componentId nal ConfigurationRe
-- set
UnicodeString
(Automation)

66 Automation: configuration reset (%1) Informatio Comple Automation


ended successfully. componentId nal ted ConfigurationRe
(ComponentId=%1). -- set
UnicodeString
(Automation)

67 Automation: configuration reset failed (%1) Error Stop Automation


for the following reason: %2. componentId ConfigurationRe
(ComponentId=%1). -- set
UnicodeString
(Automation)
(%2) error --
UnicodeString

986 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

68 Automation: environment reset (%1) Informatio Start Automation


started. (ComponentId=%1). componentId nal EnvironmentRes
-- et
UnicodeString
(Automation)

69 Automation: environment reset ended (%1) Informatio Comple Automation


successfully. componentId nal ted EnvironmentRes
(ComponentId=%1). -- et
UnicodeString
(Automation)

70 Automation: environment reset (%1) Error Stop Automation


failed for the following reason: %2. componentId EnvironmentRes
(ComponentId=%1). -- et
UnicodeString
(Automation)
(%2) error --
UnicodeString

71 Automation: engineering project (%1) Informatio Start AutomationNew


creation started.(ComponentId=%1). componentId nal Project
--
(Automation)
UnicodeString

72 Automation: engineering project (%1) Informatio Comple AutomationNew


creation ended successfully. componentId nal ted Project
(ComponentId=%1). --
(Automation)
UnicodeString

73 Automation: engineering project (%1) Error Stop AutomationNew


initialize failed for the componentId Project
following reason: %2. --
(Automation)
(ComponentId=%1). UnicodeString
(%2) error --
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 987


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

74 Automation: Subscription successfully (%1) Informatio Comple AutomationSubs


done with identifier %2 componentId nal ted cribe
for automation node type %3 with -- By Type
triggers %4, selected UnicodeString
(Automation)
properties %5 and expression filter (%2) guid --
%6. (ComponentId=%1). UnicodeString
(%3) typeName
--
UnicodeString
(%4) triggers --
UnicodeString
(%5)
selectedProper
ties --
UnicodeString
(%6) filter --
UnicodeString

75 Automation: Subscription successfully (%1) Informatio Comple AutomationSubs


done with identifier %2 componentId nal ted cribe
for automation node identifiers %3 -- ByNode
with triggers %4, selected UnicodeString
(Automation)
properties %5 and expression filter (%2) guid --
%6. (ComponentId=%1). UnicodeString
(%3) nodeIds --
UnicodeString
(%4) triggers --
UnicodeString
(%5)
selectedProper
ties –
UnicodeString
(%6) filter --
UnicodeString

76 Automation: Subscription closed for (%1) Informatio Comple AutomationSubs


identifier %2. componentId nal ted cribe
(ComponentId=%1). -- Closed
UnicodeString
(Automation)
(%2) guid --
UnicodeString

988 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

77 Automation: trigger configuration (%1) Informatio Change AutomationTrig


changed due to delta componentId nal d ger
download for identifier %2 with -- Changed
message %3. UnicodeString
(Automation)
(ComponentId=%1). (%2) guid --
UnicodeString
(%3) message
--
UnicodeString

78 Automation: selected properties (%1) Informatio Change AutomationSele


configuration changed componentId nal d cted
due to delta download for identifier -- PropertiesChang
%2. UnicodeString ed
The original selected properties is %3 (%2) guid --
(Automation)
while the notified list is is %4. UnicodeString
(ComponentId=%1). (%3)
originalPropert
ies --
UnicodeString
(%4)
selectedProper
ties --
UnicodeString

79 Automation: automation gateway (%1) Informatio Start AutomationGate


correctly started. componentId nal way
(ComponentId=%1). --
(Automation)
UnicodeString

80 Automation: automation gateway (%1) Informatio Comple AutomationGate


correctly shutdown. componentId nal ted way
(ComponentId=%1). --
(Automation)
UnicodeString

81 Automation: connection lost for (%1) Warning Change AutomationSubs


subscription identifier %2 with componentId d cribe
message %3 and error %4. -- Disconnected
(ComponentId=%1). UnicodeString
(Automation)
(%2) guid --
UnicodeString
(%3) message
--
UnicodeString
(%4) code --
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 989


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

82 Automation: Subscription failed due (%1) Error Stop AutomationSubs


to %2. componentId cribe
(ComponentId=%1). --
(Automation)
UnicodeString
(%2) error --
UnicodeString

83 Automation: automation gateway not (%1) Error Stop AutomationGate


correctly started due to %2. componentId way
(ComponentId=%1). --
(Automation)
UnicodeString
(%2) error --
UnicodeString

84 Automation: Read automation nodes (%1) Error Stop AutomationRea


%2 failed due to %3. componentId d
(ComponentId=%1). -- Nodes
UnicodeString
(Automation)
(%2)
automationNo
des --
UnicodeString
(%3) error --
UnicodeString

85 Automation: Write automation nodes (%1) Error Stop AutomationWrit


%2 failed due to %3. componentId e
(ComponentId=%1). -- Nodes
UnicodeString
(Automation)
(%2)
automationNo
des --
UnicodeString
(%3) error --
UnicodeString

990 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

86 Automation: Write automation node (%1) Error Stop AutomationWrit


%2 with filter componentId e
expression %3 failed due to %4. -- NodesFiltered
(ComponentId=%1). UnicodeString
(Automation)
(%2)
automationNo
de --
UnicodeString
(%3) filter --
UnicodeString
(%4) error --
UnicodeString

86 Automation: Write automation node (%1) Error Stop AutomationWrit


%2 with filter componentId e
expression %3 failed due to %4. -- NodesFiltered
(ComponentId=%1). UnicodeString
(Automation)
(%2)
automationNo
de –
UnicodeString
(%3) filter --
UnicodeString
(%4) error --
UnicodeString

87 Automation: Query automation node (%1) Error Stop AutomationQuer


type %2 with selected componentId y
properties %3 and filter expression -- NodesByType
%4 failed due to %5. UnicodeString
(Automation)
(ComponentId=%1). (%2)
automationNo
deType --
UnicodeString
(%3) properties
--
UnicodeString
(%4) filter --
UnicodeString
(%5) error --
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 991


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

88 Automation: Query automation nodes (%1) Error Stop AutomationQuer


%2 with componentId y
selected properties %3 and filter -- Nodes
expression UnicodeString
(Automation)
%4 failed due to %5. (%2)
(ComponentId=%1). automationNo
des --
UnicodeString
(%3) properties
--
UnicodeString
(%4) filter --
UnicodeString
(%5) error --
UnicodeString

89 The Rule '%1' '%2' is going to be (%1) ruleId -- Informatio Start AttemptStartRul
started on Host '%3'. UnicodeString nal e
(%2) revision --
(SignalManager)
UnicodeString
(%3) hostName
--
UnicodeString

90 The Rule '%1' '%2' is going to be (%1) ruleId -- Informatio Stop AttemptStopRul
stopped on Host '%3'. UnicodeString nal e
(%2) revision --
(SignalManager)
UnicodeString
(%3) hostName
--
UnicodeString

91 The Rule '%1' '%2' is going to updated (%1) ruleId -- Informatio Restart AttemptUpdate
and UnicodeString nal Rule
restarted on Host '%3'. (%2) revision --
(SignalManager)
UnicodeString
(%3) hostName
--
UnicodeString

992 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

92 The Rule '%1' '%2' on Host '%3' has (%1) ruleId -- Warning Process SignalManagerR
raised this UnicodeString ule
warning during the processing of (%2) revision -- Warning
block '%4': '%5' UnicodeString
(SignalManager)
(Error Code: %6). The rule is still (%3) hostName
running. --
UnicodeString
(%4)
blockType --
UnicodeString
(%5)
errorDescriptio
n --
UnicodeString
(%6) errorCode
-- Int32

93 The Rule '%1' '%2' on Host '%3' has (%1) ruleId -- I Process SignalManager
raised this informational UnicodeString nformatio RuleInformation
message during the processing of (%2) revision -- nal al
block '%4': '%5'. UnicodeString Message
(%3) hostName
(SignalManager)
--
UnicodeString
(%4)
blockType --
UnicodeString
(%5)
description --
UnicodeString

94 The Availability Group '%1' on Host (%1) Informatio Change HighAvailability


'%2' has changed its status from '%3' groupName – nal d Message
to '%4' UnicodeString
(Worker)
(%2) hostName

UnicodeString
(%3)
initialState –
UnicodeString
(%4) finalState

UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 993


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

95 The Availability Group '%1' on Host (%1) Error Process HighAvailability


'%2' has failed with this error: '%3'. groupName – Message
UnicodeString
(Worker)
(%2) hostName

UnicodeString
(%3)
errorMessage –
UnicodeString

96 The Availability Group '%1' on Host (%1) Error Process HighAvailability


'%2' has failed with an internal error: groupName – MessageInternal
'%3'. UnicodeString
(Worker)
(%2) hostName

UnicodeString
(%3)
errorMessage –
UnicodeString

97 The Opcenter Connect MOM Client is Informatio Check Success


ready to work nal
(DataIntegration
)

98 The Opcenter Connect MOM Client Error Check ConfigurationErr


configuration is incomplete or or
unavailable
(DataIntegration
)

99 Failure to connect to the configured (%1) checks – Error Check FailureAndChec


address/port. Perform with success UnicodeString k
the follow checks: %1
(
DataIntegration)
)

100 Failure to connect to the configured (%1) checks – Error Check GatewayError
address/port. Perform with fail the UnicodeString
(DataIntegration
follow checks: %1
)

101 A generic error occured during http (%1) Error Stop Failure
request. Error message: %1 errMessage –
(DataIntegration
UnicodeString
)

994 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

102 The number of elements in the (%1) Warning Info AutomationMes


Automation Gateway Queue is %2 for ComponentId sage
subscription id %3 and it exceeds the (%2) QueuingExceedL
limit of 1000. (ComponentId=%1) currentElemen imit
tsInQueue -
(Automation)
UnicodeString
(%3) guid
UnocodeString

103 The number of elements in the (%1) Informatio Info AutomationMess


Automation Gateway Queue does not ComponentId nal age
exceed the limit of 1000 for (%2) guid QueuingNotExce
subscription id %2. UnicodeString eds
(ComponentId=%1). Limit
(Automation)

104 Timeout on retrieving missing {0} Last Warning Info EventWarning


committed event. Last ordering {0} processed
event

105 Module already acquired, {0} {0} Module Informatio Process LicenseAlready
description nal Acquired

106 Timers Engine status updated to {1}. {0} Identifier of Informatio Change TimersStatusUp
(ComponentId={0}) the component nal d date
{1} status

107 Timers Engine {1} routine has stopped {1} routine Error Stop TimersRoutineEr
with the following error {2}. name ror
(ComponentId={0}).
{2} error
{0}) identifier of
the component

108 The '{%1}' service cannot be started. {%1} simatic it Critical Check LauncherFailure
There is configuration version service name
mismatch. Open SIMATIC IT
UAConfiguration tool and perform the
migration.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 995


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level Task OpCodes


(%number)
(Keyword)
Name –
Type

109 The '{%1}' service has got a critical {%1} simatic it Critical Check LauncherFailure
failure and has been closed. The service name
reason is: '{%2}'
{%2} message
of the
exception

110 The StartHost Command has been Informatio Start ErrorHostInfo


launched. nal
(GovernanceLay
er)

111 The StopHost Command has been Informatio Stop ErrorHostInfo


launched. nal
(
GovernanceLaye
r)

112 {%1} Error Start ErrorHostInfo


(
GovernanceLaye
r)

113 The local Host has been correctly Informatio Start ErrorHostInfo
started. nal
(
GovernanceLaye
r)

114 The local Host has been correctly Informatio Start ErrorHostInfo
stopped. nal
(
GovernanceLaye
r)

115 The local Host has been correctly {%1} Warning Start ErrorHostInfo
stopped, but services %1 has/have killedservices -
(
been killed due to timeout exceeded. Unicode String
GovernanceLaye
r)

The values corresponding to the tasks used are as follows:

Tasks Value

Start 1001

996 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

Tasks Value

Stop 1002

Restart 1004

Deploy 1008

Load 1016

Check 1032

Completed 1064

Process 1128

Changed 1256

Write 1512

Wait 2024

Info 3048

EventSourceMessage 65534

The values corresponding to the OpCodes are as follows:

OpCodes Value

LauncherFailure 11

LauncherSuccess 12

WorkerFailure 13

WorkerSuccess 14

SolutionFailure 15

SolutionSuccess 16

AppFailure 17

AppSuccess 18

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 997


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

OpCodes Value

LocalDeploymentFailure 19

LocalDeploymentSuccess 20

StateMachineSuccess 21

StateMachineWarning 22

StateMachineFailure 23

GatewayError 24

GatewayWarning 25

LauncherProcessSucess 26

LauncherProcessWaring 27

LauncherProcessError 28

LogRouterSucess 29

LogRouterWaring 30

LogRouterError 31

LicenseServerConnected 32

LicenseServerConnectionFailed 33

LicenseServerDisconnected 34

LicenseServerDisconnectionFailed 35

LicenseAcquired 36

LicenseAcquireFailed 37

LicenseReleased 38

LicenseReleaseFailed 39

LauncherPreshutdown 40

LauncherProcessRecovered 41

SignalManagerRuleStarted 42

SignalManagerRuleStopped 43

998 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

OpCodes Value

SignalManagerRuleFailed 44

SignalManagerRuleExecutionError 45

WorkerUserException 46

AutomationUpdate 47

AutomationIOWAUpdate 48

AutomationConnectionsUpdate 49

AutomationConfigurationReset 50

AutomationEnvironmentReset 51

AutomationNewProject 52

AutomationSubscribeByType 53

AutomationSubscribeByNode 54

AutomationSubscribeClosed 55

AutomationTriggerChanged 56

AutomationSelectedPropertiesChanged 57

AutomationSubscribeDisconnected 58

AutomationSubscribe 59

AutomationGateway 60

AutomationReadNodes 61

AutomationWriteNodes 62

AutomationWriteNodesFiltered 63

AutomationQueryNodes 64

AutomationQueryNodesByType 65

AttemptStopRule 66

AttemptStartRule 67

AttemptUpdateRule 68

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 999


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

OpCodes Value

SignalManagerRuleWarning 69

SignalManagerRuleInformationalMessage 70

HighAvailabilityMessage 71

HighAvailabilityMessageInternal 72

ConfigurationError 73

FailureAndCheck 74

AutomationMessageQueuingExceedLimit 75

AutomationMessageQueuingNotExceedsLimit 76

ErrorHostInfo 82

Failure 100

Success 101
The values corresponding to the keywords are as follows:

KeyWord Value

Laucher 0x1

Worker 0x2

SolutionDeployment 0x4

LocalDeployment 0x8

App 0x10

InformationLayer 0x20

IntegrationLayer 0x40

GovernanceLayer 0x80

NodeStateMachine 0x100

LogRouter 0x200

Generic 0x400

License 0x800

1000 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

KeyWord Value

SignalManager 0x1000

Automation 0x2000

DataIntegration 0x4000

Session3 0x100000000000

Session2 0x200000000000

Session1 0x400000000000

Session0 0x800000000000

 Session3, Session2, Session1, Session0 are system Keywords that are not relevant for Opcenter Execution
Foundation.

security logs
Security logs are stores in the Siemens-SimaticIT-Security-Admin file.
provider Name : Siemens-SimaticIT-Security
provider guid: {395037a1-c886-5860-caed-d589e34eea6a}
resource file: SimaticIT.Security.Lean.Siemens-SimaticIT-Security.etwManifest.dll
The following events are logged in the file:

 The version is 1 for all the following events.

ID Message Parameters Level task OpCode Keyword


s

1 User '%1' does not (%1) user -- Error CommandAuth Failure AuditFailure
have the UnicodeString orization Command
authorization to (%2) operation -- Check
perform operation UnicodeString
'%2' on object '%3' (%3) secObj –
UnicodeString

2 User '%1' successfully (%1) user -- Informatio CommandAuth Success AuditSuccess


performed operation UnicodeString nal orization Command
'%2' on object '%3'. (%2) operation -- Check
UnicodeString
(%3) secObj --
UnicodeString

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1001


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level task OpCode Keyword


s

3 User '%1' does not (%1) user -- Error EventAuthoriz Failure AuditFailure
have the UnicodeString ationCheck Event
authorization to (%2) operation --
perform operation UnicodeString
'%2' on object '%3' of (%3) secObj --
Event category. UnicodeString

4 User '%1' successfully (%1) user -- Informatio EventAuthoriz Success AuditSuccess


performed operation UnicodeString nal ationCheck Event
'%2' on object '%3' (%2) operation --
of Event category. UnicodeString
(%3) secObj –
UnicodeString

5 User '%1' does not (%1) user -- Error EntityAuthoriz Failure AuditFailure
have the UnicodeString ationCheck Entity
authorization to (%2) operation --
perform operation UnicodeString
'%2' on object '%3' (%3) secObj --
UnicodeString

6 User '%1' successfully (%1) user -- Informatio EntityAuthoriz Success AuditSuccess


performed operation UnicodeString nal ationCheck Entity
'%2' on object '%3'. (%2) operation --
UnicodeString
(%3) secObj --
UnicodeString

7 An attempt to access Error TokenValidatio 0 AuditFailure


a resource with an nCheck Token
invalid token was
made.

8 An attempt to access (%1) user -- Error AccountValidat 0 AuditFailure


a resource with an UnicodeString ionCheck Account
invalid identity was
made.
User: %1.

9 An attempt to decrypt Error EncryptionChe 0 AuditFailure


a resource encrypted ck Encryption
with invalid
encryption
parameters was
made.

1002 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

ID Message Parameters Level task OpCode Keyword


s

10 The encryption key Error MasterKeyExpi 0 AuditFailure


required by the red
current operation is
expired.
The values corresponding to the tasks used are as follows:

Tasks Value

CommandAuthorizationCheck 101

EventAuthorizationCheck 102

EntityAuthorizationCheck 103

TokenValidationCheck 104

AccountValidationCheck 105

EncryptionCheck 106

MasterKeyExpired 65524

EventSourceMessage 65534
The values corresponding to the OpCodes are as follows:

OpCodes Value

Failure 101

Success 102
The values corresponding to the keywords are as follows:

KeyWord Value

AuditSuccess 0x1

AuditFailure 0x2

Command 0x4

Event 0x8

Entity 0x10

Token 0x20

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1003


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

KeyWord Value

Account 0x40

Encryption 0x80

Session3 0x100000000000

Session2 0x200000000000

Session1 0x400000000000

Session0 0x800000000000

 Session3, Session2, Session1, Session0 are system Keywords that are not relevant for Opcenter Execution
Foundation.

Application Logs
Application logs are stores in the Siemens-SimaticIT-Application-Admin file.
• provider Name : Siemens-SimaticIT-Application
• provider guid: {581e9f3a-620f-416f-b1e3-962676a46a8d}
• resource file: SimaticIT.Integration.Diagnostics.Core.Siemens-SimaticIT-Application.etwManifest.dll
The following events are logged in the file:

 The version is 1 for the following event.

ID Message Parameters Level task OpCodes Key


word

1 The %1 %2 '%3' on host '%4' failed (%1) appName -- Error Stop HandlerUser Work
due to this error: %5. UnicodeString Exception er
Stack tace: %6 (%2) handlerType --
UnicodeString
(%3) name --
UnicodeString
(%4) host --
UnicodeString
(%5) message --
UnicodeString
(%6) fullStack --
UnicodeString
The values corresponding to the tasks used are as follows:

1004 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

Tasks Value

Start 1001

Stop 1002

Restart 1004

Deploy 1008

Load 1016

Check 1032

Completed 1064

Process 1128

Changed 1256

Write 1512

Wait 2024

Info 3048

EventSourceMessage 65534
The values corresponding to the OpCodes are as follows:

OpCodes Value

HandlerUserException 103
The values corresponding to the keywords are as follows:

KeyWord Value

Worker 0x2

Generic 0x400

License 0x800

SignalManager 0x1000

Session3 0x100000000000

Session2 0x200000000000

Session1 0x400000000000

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1005


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

KeyWord Value

Session0 0x800000000000

 Session3, Session2, Session1, Session0 are system Keywords that are not relevant for Opcenter Execution
Foundation.

6.4.2 Configuring the SIMATIC IT UAF Log Router Service via Script
The SIMATIC IT UAF Log Router service is a platform service that allows you to permanently save security, system
and application related messages to file repository. This operation can be performed via script through the file
LogRouterConf.exe.

LogRouterService Configuration
The LogRouterConf.exe configuration is based on sinks and persisted in the file
LogRouterService.TraceEventService.xml located in the folder %SITUnifiedSystemRoot%bin\ETW.
It contains global parameters and one entity for each sink , that is, a destination to which LogRouterService writes
ETW traces.
Each sink is composed by parameters to manage the destination and a list of sources (ETW providers to be
subscribed) with its own level and keywords; both parameters and sources are used to collect ETW traces.
The LogRouterService.TraceEventService.xml file contains the following system sinks that write Windows Event
logs (see Persisting System, Security and Application Messages on Microsoft Event Viewer) and must not be
modified:
• SecurityAudit
• SystemLog
• ApplicationLog

Available operations on Sinks


In addition to read the configuration modifications in runtime without stopping the Service, the SIMATIC IT
UAF Log Router service can perform the following sink operations:
• Add sinks
• Update sinks
• Delete sinks

Adding Sinks
This operation allows you to add in the LogRouterService.TraceEventService.xml file two types of sinks:
• simaticEventLogSink : writes to Windows Event Log
• SqlServerEntityFrameworkDatabaseSink : Persistent Log Sink to write to SQL database
Procedure
1. In the %SITUnifiedSystemRoot%bin folder, execute the command

LogRouterConf.exe -cmd = add

1006 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

2. Set the following parameters:


Parameter Description

type (Mandatory) The type of the sink to add. Possible values:


• PersistentLogSinkType: to add a destination in order to locate
ETW traces in the selected database.
• EventLogSinkType: to add a destination in order to locate ETW
traces in the Windows log.

name (Mandatory) The name of the sink to add.

providerfile (Mandatory) The provider file name generated by ETWViewer (see Choosing
Trace Providers). It defines the sources for the sink to be added.

Log (Mandatory) The value of the Log attribute (see Opcenter EX FN System,
Security and Application Traces) valid for sinks of type EventLogSinkType,
PersistentLogSinkType.

mode (Mandatory) The value of the mode attribute is valid for sinks of type
EventLogSinkType, PersistentLogSinkType. Possible attribute values:
• listeningOnly
• in case of persistent log, it does not write in the database.
Sink is prepared but not active.
• in case of event log, the traces are not saved in the
Windows Log except for the providers registered
according to Microsoft documentation (see https://
docs.microsoft.com/en-us/previous-versions/
aa385225(v=vs.85)?redirectedfrom=MSDN).
• writeMsgByID
• in case of persistent log, it writes all traces to the
database. Sink is prepared and active.
• in case of event log, it writes all traces for all providers.

datasource (Mandatory) The value of the datasource attribute valid only for sinks of
type PersistentLogSinkType

catalog (Mandatory) The value of the catalog attribute valid for sinks of type
PersistentLogSinkType

user (Mandatory) The value of the user attribute valid for sinks of type
PersistentLogSinkType

password (Mandatory) The value of the password attribute for sinks of type
PersistentLogSinkType

bufferingCount The value of the bufferingCount attribute valid for sinks of type
PersistentLogSinkType

maxBufferSize The value of the maxBufferSize attribute valid for sinks of type
PersistentLogSinkType

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1007


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

Parameter Description

bufferingIntervalInSeconds The value of the bufferingIntervalInSeconds attribute valid for sinks of type
PersistentLogSinkType

The value of the bufferingFlushAllTimeoutInSeconds attribute valid for sinks


bufferingFlushAllTimeoutInS of type PersistentLogSinkType
econds

Example 1: Adding a Sink of type EventLogSinkType

LogRouterConf.exe -cmd=add -sink=sinkname -type=EventLogSinkType --


providerFile=test.providerSet --Log=SitTestLog --mode=writeMsgByID

Example 2: Adding a Sink of type PersistentLogSinkType

LogRouterConf.exe -cmd=add -sink=sinkname -type=PersistentLogSinkType --


providerFile=test.providerSet --Log=SitTestLog --mode=writeMsgByID --
datasource=localhost\MES --catalog=PerststebLog --user=sa --password=Password123

Updating Sinks
Procedure
1. in the %SITUnifiedSystemRoot%bin folder, execute the command

LogRouterConf.exe -cmd = update

2. Set the following parameters:

Parameter Description

name (Mandatory) The name of the sink to add.

providerfile The provider file name generated by ETWViewer. It defines the sources for
the sink to be updated.

Log The value of the Log attribute (see Opcenter EX FN System, Security and
Application Traces) valid for sinks of type EventLogSinkType,
PersistentLogSinkType.

1008 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

Parameter Description

mode The value of the mode attribute valid for sinks of type EventLogSinkType,
PersistentLogSinkType. Possible attribute values:
• listeningOnly
• in case of persistent log, it does not write in the database.
Sink is prepared but not active.
• in case of event log, the traces are not saved in the
Windows Log except for the providers registered
according to Microsoft documentation (see https://
docs.microsoft.com/en-us/previous-versions/
aa385225(v=vs.85)?redirectedfrom=MSDN).
• writeMsgByID
• in case of persistent log, it writes all traces to the
database. Sink is prepared and active.
• in case of event log, it writes all traces for all providers.

datasource The value of the datasource attribute valid only for sinks of type
PersistentLogSinkType

catalog The value of the catalog attribute valid for sinks of type
PersistentLogSinkType

user The value of the user attribute valid for sinks of type PersistentLogSinkType

password The value of the password attribute valid for sinks of type
PersistentLogSinkType

bufferingCount The value of the bufferingCount attribute valid for sinks of type
PersistentLogSinkType

maxBufferSize The value of themaxBufferSize attribute valid for sinks of type


PersistentLogSinkType

bufferingIntervalInSeconds The value of the bufferingIntervalInSeconds attribute valid for sinks of type
PersistentLogSinkType

datasource (Mandatory) The value of the datasource attribute valid only for sinks of type
PersistentLogSinkType.

catalog (Mandatory) The value of the catalog attribute valid for sinks of type
PersistentLogSinkType

user (Mandatory) The value of the user attribute valid for sinks of type
PersistentLogSinkType

password (Mandatory) The value of the password attribute for sinks of type
PersistentLogSinkType

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1009


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

Parameter Description

bufferingCount The value of the bufferingCount attribute valid for sinks of type
PersistentLogSinkType

maxBufferSize The value of the maxBufferSize attribute valid for sinks of type
PersistentLogSinkType

bufferingIntervalInSeconds The value of the bufferingIntervalInSeconds attribute valid for sinks of type
PersistentLogSinkType

The value of the bufferingFlushAllTimeoutInSeconds attribute valid for sinks


bufferingFlushAllTimeoutInS of type PersistentLogSinkType
econds

Example 1: Update Sources

LogRouterConf.exe -cmd=update -sink=sinkname --providerFile=test.providerSet

Example 2: Update Password

LogRouterConf.exe -cmd=update -sink=sinkname --providerFile=test.providerSet --


password=Password345

Deleting Sinks
Procedure
1. in the %SITUnifiedSystemRoot%bin folder, execute the command

LogRouterConf.exe -cmd = delete

2. Set the following parameter:

Parameter Description

name The name of the sink to delete

Example: Delete a Sink

LogRouterConf.exe -cmd=delete --sink=sinkname

6.4.3 Subscribing to Security and System Events in a Cluster Scenario


Each machine in a cluster runs a separate SIMATIC IT UAF Log Router service, which allows you to save security
and system related messages to file repository.

1010 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

It is possible to view this service for each machine in the cluster from one machine in the scenario, in order to
analyze all the event messages together.
For further information see Microsoft documentation: https://technet.microsoft.com/en-us/library/cc722010.aspx

Prerequisites
• The same version of Opcenter Execution Foundation is installed on each machine.
• The machines must be part of the same domain.
• Administrator status for each machine in the cluster is required to perform this operation.
• The SIMATIC IT UAF Log Router service and Windows Event Collector Service must be running.

Procedure
1. Open Microsoft Event Viewer by accessing Windows Administrative Tools environment and then
selecting Event Viewer.
2. Inside the Event Viewer application, right click Subscriptions and select Create Subscription.
3. In Subscription name provide a unique name for the subscription.

4. From the Destination log drop-down list select Siemens-SimaticIT - Security/Admin.


5. Click Select Computers to specify from which computers you want to receive event messages.
6. Click Add Domain Computers and select and add the required computers.
7. Click Select Events > Edit to select to which specific message events you want to subscribe. The selection made
for event types and levels must be the same for all computers in the cluster. The minimum information is the
event level and event log.
8. Click Advanced to configure user settings.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1011


How to Monitor Opcenter EX FN Runtime Processes

Persisting System, Security and Application Messages on Microsoft Event Viewer

9. Click Specific User and specify a user that has Administrator status.

10. Click OK.


11. Repeat the procedure selecting Siemens-SimaticIT - System/Admin instead of Siemens-SimaticIT - Security/
Admin in step 4.

Result
If the connection has been successfully made a green row is displayed in the Subscriptions table, with details on
your connection.
To check the status of the connection, right-click the row and select Runtime Status.

1012 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Monitor Opcenter EX FN Runtime Processes

Viewing Opcenter EX FN Application Dumps

6.5 Viewing Opcenter EX FN Application Dumps


During the environment configuration, the Opcenter Execution Foundation Configuration tool enables the Windows
Error Reporting service. The service should not be manually disabled afterwards, otherwise Opcenter EX FN dumps
will not be generated.
In case of crash, some of the Opcenter EX FN applications generate dumps.
In case of crash of some Opcenter EX FN processes, mini dumps are generated by default in
%SITUnifiedSystemData%\Dumps. The default maximum number of dump files, which the Dump folder can
contain, is set to 10.

Manually modifying the Dump directory


You can change the folder where dumps are saved, or even the maximum number of dumps that can be saved, by
running the following script:
1. Open the PowerShell command shell.
2. Use the following code snippet to invoke the Set-WerEnabled function, contained in the UnifiedHelp.ps1
script. The location of the script is specified in the snippet. The code example recalls the internal online help,
which provides you with the function required parameters:
• dump_folder, which specifies the path of the new folder (e.g. C:\MyFolder)
• count, which specifies the maximum number of dumps allowed for this folder.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1013


How to Monitor Opcenter EX FN Runtime Processes

Viewing Opcenter EX FN Application Dumps

Example

PS C:\Program Files\Siemens\SimaticIT\Unified\bin\PreConf\Fragments\unified> . .
\UnifiedHelp.ps1
PS C:\Program Files\Siemens\SimaticIT\Unified\bin\PreConf\Fragments\unified> Set-WerE
nabled -?
NAME
Set-WerEnabled

SYNTAX
Set-WerEnabled [-dump_folder] <string> [[-count] <int>] [<CommonParameters>]

ALIASES
None

REMARKS

None

PS C:\Program Files\Siemens\SimaticIT\Unified\bin\PreConf\Fragments\unified> Set-WerE


nabled -count 20

User permissions
If the Windows user running Opcenter EX FN processes is not a local administrator or does not belong to any
Opcenter EX FN Windows groups, the dumps will not be generated.

1014 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How To Perform Database Maintenance Operations

Managing Indexes in Opcenter Execution Foundation

7 How To Perform Database Maintenance Operations


In order to improve the performances of the Foundation system databases, you can refer to the following
operations:
• Managing Indexes in Opcenter Execution Foundation
• Performing Maintenance on Timer Tables
• Using Maintenance Stored Procedures

7.1 Managing Indexes in Opcenter Execution Foundation


Database vendor's documentation suggests that you always improve database performance by using database
indexes.
For information regarding how to create and drop indexes, see your database system documentation.
Opcenter Execution Foundation manages indexes in three different ways, distinguishing between system indexes,
user indexes and custom indexes.
• System indexes: these indexes are system-defined. The system adds them by default as they regard logical key
definitions, navigation property definitions and specific internal implementations of which the user is not
aware. These indexes are implicitly added during the database update operation and you cannot drop them or
disable them.
• User indexes: these indexes are user-defined. You can manually create/remove them in Project Studio (see
Creating Indexes for Entities) but you do not have any control on their specification details. These indexes are
configured as simple indexes, they are part of the data model and are thought to be known at development
time, according to the main queries performed inside the user-defined commands. Opcenter Execution
Foundation provides the minimal set of specifications that guarantees database provider independence.
• Custom indexes: these indexes are custom-defined directly inside the database. In this way, you can create
indexes that are more provider-specific and moreover, you can handle them at runtime, when the development
phase is finished and the package is released. Opcenter Execution Foundation tries to preserve these indexes
during the database update. To achieve this, the system scans the database, searching for the indexes that are
not part of the model. If custom indexes are found, the system adds them to the model as if they were part of of
the data model definition in Project Studio. Henceforward, these indexes are dropped if they include columns
that are going to be renamed/modified and then they are re-created afterwards, once the updated database
operation is finished. But if the definition of these custom indexes includes columns that have been removed
from the model they will be definitively dropped and no longer re-created.
Consequently, you do not need to re-create them after each database update, unless at least one of the columns
inside their definition has been removed.

Rebuilding indexes with the Online Option


To avoid index fragmentation, which can degrade query performances and cause your application to respond
slowly, database platform providers suggest that you reorganize or rebuild indexes.
Opcenter Execution Foundation fully supports the online index rebuild functionality that is offered by Microsoft SQL
Server Enterprise Edition.
Rebuilding indexes with the Online option means that you can access and read data even while the index rebuild
operation is still running. To do this, SqlServer Enterprise Edition creates a copy of the old indexes and uses this
copy to run queries during the rebuild operation. When the rebuild operation terminates, and the system switches
to the new indexes, all the commands that were in execution during the rebuild and that were using the old index
copy will fail for a specific optimistic concurrency error. Opcenter Execution Foundation internally manages this
failure by automatically re-executing the failed commands (see immediate retry at Command Retry Management).
You can specify the online index rebuild by adding the WITH (ONLINE=ON) instruction to the script.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1015


How To Perform Database Maintenance Operations

Managing Indexes in Opcenter Execution Foundation

Rebuilding indexes with the system-provided Stored Procedure


Opcenter Execution Foundation provides you with a stored procedure, named [dbo].[Index_Maintenance], which
performs the index rebuild. The stored procedure is provided inside all foundation databases.
You can execute it either by using the default input parameter values, or by specifying the following parameters:

Parameter Description
Name

@minFragme In percentage. The stored procedure will not perform the defragmentation, if the
ntation fragmentation is lower than the specified value.
The default value is 10%.

@rebuildThr In percentage. A value greater than this threshold will result in a rebuild instead of a
eshold reorganization.
The default value is 30%, as recommended by Microsoft.

@executeSQ For debugging purposes.


L
Valid options are:
• 1 = executes the SQL generated by the stored procedure
• 0 = prints SQL only in the Messages panel
The default value is 1.

@defragOrde Defines how to prioritize the order of defragmentation. Only used if @executeSQL = 1.
rColumn
Valid options are:
• range_scan_count = cumulative count of range and table scans started on the index or
heap. This option is recommended.
• fragmentation = amount of fragmentation in the index; the higher the number, the worse
it is.
• page_count = number of pages in the index; affects how long it takes to defrag an index.
The default value is range_scan_count.

@defragSort The sort order of the ORDER BY clause.


Order
Valid options are:
• ASC = ascending
• DESC = descending
The default value is DESC.

@timeLimit Limits how much time can be spent in performing index defragmentation. The value is
expressed in minutes.
Note: The time limit is checked BEFORE an index defragmentation is begun, thus a long index
defragmentation can exceed the time limitation.
The default value is 720 minutes (12 hours).

1016 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How To Perform Database Maintenance Operations

Managing Indexes in Opcenter Execution Foundation

Parameter Description
Name

@tableName Specifies if you only want to defrag indexes for a specific table. This parameter must be
provided by using the following format: database_name.schema.table_name
If not specified, all tables will be defragged.
The default value is NULL (i. e. all tables in the current database will be defragged).

@forceResca Specifies whether you want to force a re-scan of the indexes.


n
Valid options are:
• 1 = forces a re-scan
• 0 = uses a previous scan, if there are indexes left to be defragged
The default value is 0.

@scanMode Specifies which scan mode you want to use to determine fragmentation levels.
Valid options are:
• LIMITED = scans the parent level; quickest mode, recommended for most cases.
• SAMPLED = samples 1% of all data pages; if less than 10k pages, performs a DETAILED
scan.
• DETAILED = scans all data pages. This option must be used carefully because it can cause
performance issues.
The default value is LIMITED.

@minPageCo Specifies how many pages must exist in an index in order to be considered for a
unt defragmentation.
The default value is 8, as Microsoft recommends only defragging indexes with more than 1
extent (8 pages).

@maxPageC Specifies the maximum number of pages that can exist in an index and that must be
ount considered for a defragmentation.
This option is useful for scheduling a rebuild of small indexes during business hours and a
rebuild of large indexes for non-business hours.
Note: The @maxPageCount will restrict the indexes that are defragged during the current
operation.
The default value is NULL (no limit).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1017


How To Perform Database Maintenance Operations

Managing Indexes in Opcenter Execution Foundation

Parameter Description
Name

@excludeMa If an index is partitioned, this option specifies whether to exclude the right-most populated
xPartition partition. Typically, this is the partition that is currently being written to in a sliding-window
scenario. Enabling this feature may reduce contention. This may not be applicable in other
types of partitioning scenarios. Non-partitioned indexes are unaffected by this option.
Valid options are:
• 1 = excludes right-most populated partition
• 0 = does not exclude the right-most populated partition
The default value is 0.

@onlineRebu When online rebuild mode is active, users can continue to work on underlying data. When
ild offline rebuild mode is active, tables/indexes are locked for the duration of the action.

 The offline rebuild is supported only by Enterprise versions of Microsoft SQL Server.

Valid options are:


• 1 = online rebuild
• 0 = offline rebuild
The default value is 1.

@sortInTemp Specifies whether to defrag the index in TEMPDB or in the database the index belongs to.
DB Enabling this option may result in faster defragmentations and prevents database file size
inflation.
Valid options:
• 1 = performs sort operation in TEMPDB
• 0 = performs sort operation in the index's database
The default value is 1.

@maxDopRe Specifies the number of processors for the index rebuild operation.
striction
 The offline rebuild is supported only by Enterprise versions of Microsoft SQL Server.

The default value is NULL.

@printComm For debugging purposes.


ands
Valid options are:
• 1 = prints commands to Messages panel
• 0 = does not print commands to Messages panel
The default value is 0.

1018 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How To Perform Database Maintenance Operations

Managing Indexes in Opcenter Execution Foundation

Parameter Description
Name

@printFragm For debugging purpose.


entation
Valid options are:
• 1 = prints fragmentation to Messages panel
• 0 = does not print fragmentation to Messages panel
The default value is 0.

@defragDela Time to wait between defragmentation commands.


y
The default value is 00:00:05.

@debugMod For debugging purpose. If enabled, the stored procedure displays some useful comments to
e help determine if or where issues occur.
Valid options are:
• 1 = displays debug comments (helps you with troubleshooting)
• 0 = does not display debug comments
The default value is 0.

@SkipReorg Specifies if the stored procedure needs to execute also indexes reorganization.
Valid options are:
• 1 = performs also reorganize
• 0 = performs only rebuild
The default value is 0.

@LockTimeo Specifies the number of seconds a command waits for a lock. After timeout elapsed, the
ut command returns an error.
The default value is NULL.

@DataCompr Specifies if the data compression is enabled and the related type.
essionType
If not set, the stored procedure does not perform data compression.
Valid options are:
• '' = no data compression
• PAGE = compression at page level
• ROW = compression at row level
The default value is ''.

The following example shows how to call the stored procedure.

 The stored procedure should be executed either by a SQL Server Job or by a DBA.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1019


How To Perform Database Maintenance Operations

Performing Maintenance on Timer Tables

EXECUTE dbo.Index_Maintenance
@executeSQL = 1
, @printCommands = 1
, @debugMode = 1
, @printFragmentation = 1
, @forceRescan = 1
, @maxDopRestriction = 1
, @minPageCount = 8
, @maxPageCount = NULL
, @minFragmentation = 1
, @rebuildThreshold = 30
, @defragDelay = '00:00:10'
, @defragOrderColumn = 'page_count'
, @defragSortOrder = 'DESC'
, @excludeMaxPartition = 1
, @timeLimit = NULL

7.2 Performing Maintenance on Timer Tables


You can perform maintenance operations on Timer tables either manually, via stored procedure, or automatically,
via stored procedure job.

Purge of Timer tables via Stored Procedure


When Opcenter EX FN operations are scheduled (e.g. Cleaning or Archiving), the timer scheduling engine produces a
lot of records inside a list of tables inside the Opcenter EX FN system database.
To prevent the size of these tables from growing too much over time, you can invoke the PurgeTimeLineInstance
stored procedure, which is provided inside the Opcenter EX FN system database.
You can execute it either by using the default input parameter values, or by specifying the following parameters:
SQL Server

Parameter name Description

hours Specify which data to preserve on tables based on


• Scheduled date/time for timer instances.
• End date/time for timer definitions.
The default value is 72 (preserve the last 3 days of data on database).

chunkSize Specify the chunk size for delete operations.


This value impacts the performance of stored procedure in case of large amounts
of data.
The default value is 10000.

Oracle

1020 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How To Perform Database Maintenance Operations

Performing Maintenance on Timer Tables

Parameter name Description

pHours Specify which data to preserve on tables based on


• Scheduled date/time for timer instances.
• End date/time for timer definitions.
The default value is 72 (preserve the last 3 days of data on database).

 Avoid settings less than 72 hours (3 days): the stored procedure deletes even the timer instances still
marked as Planned. So, if you set a very low number of hours, you may end up with deleting instances that
were Planned but not executed for some reason (e.g. the Worker was down) so the system will not try to
re-execute them.

The following examples shows how to call the stored procedure.

 The stored procedure should be executed either by a SQL Server/Oracle Job or by a DBA.

Example on SQL Server database

EXECUTE [dbo].[PurgeTimeLineInstance]
@hours = 24,
@chunkSize = 5000

Example on Oracle database

exec "MyDb_sys"."PurgeTimeLineInstance"(24);

Purge of Timer tables via database job


It is possible to configure automatic deletion of timer tables using the database job that is provided inside the
Opcenter EX FN system databases. The procedure is different on SQL Server and Oracle.
SQL Server
On SQL Server side, a stored procedure named UAF_CREATE_TIMER_PURGING_JOB is provided.
By invoking this stored procedure you can create a database job in order to automate the purging operation on
timer tables.
You can execute it either by using the default input parameter values, or by specifying the following parameters:

Parameter name Description

day_freq Specify the frequency (days) of the job execution.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1021


How To Perform Database Maintenance Operations

Performing Maintenance on Timer Tables

Parameter name Description

hoursToPreserve Specify which data to preserve on tables based on


• Scheduled date/time for timer instances.
• End date/time for timer definitions.
The default value is 72 (preserve the last 3 days of data on database).

chunkSize Specify the chunk size for delete operations.


This value impacts the performance of stored procedure in case of
large amounts of data.
The default value is 10000.

start_time Specify the start date of the job (expressed in local time).

iRet This is an output parameter.


It contains info about the stored procedure execution.
Possible values are:
• 0 = the creation has been completed successfully
• -1 = the start_time parameter has not been specified
• -3 = the start_time parameter specified is invalid
The following examples show how to call the stored procedure on SQL Server.

 The stored procedure must be executed by a DBA.

1022 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How To Perform Database Maintenance Operations

Using Maintenance Stored Procedures

Example on SQL Server database

DECLARE @day_freq int


DECLARE @hoursToPreserve int
DECLARE @chunkSize int
DECLARE @start_time datetime
DECLARE @iRet int

SET @day_freq = 1
SET @hoursToPreserve = 72
SET @chunkSize = 10000
SET @start_time = '2021-03-30 03:00'

EXECUTE [dbo].[UAF_CREATE_TIMER_PURGING_JOB]
@day_freq
,@hoursToPreserve
,@chunkSize
,@start_time
,@iRet OUTPUT
GO

Oracle
On Oracle, the job named <schema>_TimerPurge (e.g. SIT_UA_sys_TimerPurge) is already provided inside
Opcenter EX FN system databases.
This job is created in a disabled state, and by default it is activated every day at midnight (local time), purging the
timer tables preserving data for the last 72 hours.
You can activate it or change its time scheduling. Please check the Oracle documentation for the required steps.

7.3 Using Maintenance Stored Procedures


The following stored procedures are available to perform purge operations on database system tables:
• Purge of __MTLog table
• Purge of __SynchronizationLog table

 Be aware that the __MTLog table and the __SynchronizationLog table (and in general any table whose
name starts with ‘__’) are system tables. Any custom logic that you may implement is under your
responsibility as their compatibility is not ensured.

7.3.1 Purge of __MTLog table


When Maintenance operations are performed (i.e. Cleaning or Archiving), the logs that trace the progress of these
operations are written within the __MTLog system table.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1023


How To Perform Database Maintenance Operations

Using Maintenance Stored Procedures

To prevent this table size from growing over time, you can invoke the PurgeMaintenanceLog stored procedure,
which is provided inside all Foundation databases.
You can execute it either by using the default input parameter values, or by specifying the following parameters:

Parameter name Description

PurgeBehavior Specify which logs to remove from table based on msg column.
Valid options are:
• 0 = remove all logs from table
• 1 = remove only logs with an empty msg column
The default value is 0.

PurgeUntil Specify which logs to remove from table based on start_time


column.
The default value is NULL (i.e. all logs will be removed).

Verbose For debugging purposes.


Valid options are:
• 0 = execute the stored procedure in silent mode
• 1 = activate verbosity in order to monitor the procedure
progress
The default value is 0.

The following examples show how to call the stored procedure.

 The stored procedure should be executed either by a SQL Server/Oracle Job or by a DBA.

Example on Microsoft Sql Server database

EXECUTE[dbo].[PurgeMaintenanceLog]
@PurgeBehavior = 1,
@PurgeUntil = '2020-02-09',
@Verbose = 1

Example on Oracle database

declare
StartTime TIMESTAMP WITH TIME ZONE;
begin
DBMS_OUTPUT.ENABLE();
StartTime := SYSTIMESTAMP AT TIME ZONE 'UTC';
"MyDatabase"."PurgeMaintenanceLog" (1, StartTime, 1);
end;

1024 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How To Perform Database Maintenance Operations

Using Maintenance Stored Procedures

7.3.2 Purge of __SynchronizationLog table


When synchronization operations are performed (i.e. Audit Trail, Committed Event or Segregation Log generation),
the logs that trace the exceptions occurred during these operations are written within the __SynchronizationLog
system table.
To prevent this table size from growing over time it is possible to invoke the PurgeSynchronizationLog stored
procedure, that is provided inside all foundation databases.
You can execute it either by using the default input parameter values, or by specifying the following parameters:

Parameter name Description

PurgeUntil Specify which logs to remove from table based on LogTimeStamp


column.
The default value is NULL (i.e. all logs will be removed).

Verbose For debugging purposes.


Valid options are:
• 0 = execute the stored procedure in silent mode
• 1 = activate verbosity in order to monitor the procedure
progress
The default value is 0.

The following examples shows how to call the stored procedure.

 The stored procedure should be executed either by a SQL Server/Oracle Job or by a DBA.

Example on Microsoft Sql Server database

EXECUTE[dbo].[PurgeSynchronizationLog]
@PurgeUntil = '2020-02-09',
@Verbose = 1

Example on Oracle database

declare
StartTime TIMESTAMP WITH TIME ZONE;
begin
DBMS_OUTPUT.ENABLE();
StartTime := SYSTIMESTAMP AT TIME ZONE 'UTC';
"MyDatabase"."PurgeSynchronizationLog" (StartTime, 1);
end;

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1025


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

8 How to Migrate a Manufacturing Solution


You can migrate to Opcenter Execution Foundation 4.1 solutions that were created in:
• Any SIMATIC IT UAF 2.x versions
• Any Opcenter Execution Foundation 3.x versions
There are some variations in the procedures to be followed according to the product version you are starting from.

Prerequisites
The prerequisites vary according to the installation type:
• Over installation; after installing Opcenter Execution Foundation 4.1 on top of one of the previously mentioned
product versions, you must perform the post-installation migration tasks described in the Opcenter Execution
Foundation Installation Manual.
• Fresh installation; after installing Opcenter Execution Foundation 4.1 on a clean machine, you must configure
the whole environment as described in the Opcenter Execution Foundation Installation Manual.

Workflow
The migration process is made up of the following steps:
1. If needed, update the model in Project Studio. This step is required if you want to include any new feature in the
data model / business logic of your Functional Blocks and Apps or if the version of any referenced packages
changed.
2. Update the Solution in Solution Studio. This step is required to update/reload Apps and UIs to the current
platform version.
3. Build and deploy the updated solution in Solution Studio. This step is required to deploy and start the updated
solution.
4. Complete the migration by performing some post-migration steps for some specific Apps.

Compatibility

 We strongly recommend that you check the compatibility notes at Version Compatibility in the Opcenter
Execution Foundation Release Notes.
Moreover, keep in mind that In previous product versions, SWAC Components used earlier versions of the
SWAC Manifest (1.2.0 and 1.0). The manifest is automatically migrated for new SWAC Components,
whereas an icon is displayed on migrated SWAC Components indicating that manual manifest migration is
required. Although compatibility with previous versions in provided, it is advisable to migrate the
manifest to avoid problems occurring in the future.

8.1 Updating the Projects in Project Studio


This step is not mandatory inside the migration procedure. It is only required in either of the following use cases:
• if you want to incorporate any new features in the data model / business logic of your Functional Blocks and
Apps,
• if a version change occurred in the packages that are referenced by your custom Apps.
If these steps are not required, you can directly go to Updating the Solution in Solution Studio.

1026 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

 If your old packages do not reference any system functionalities, and your Solution does not contain any
Foundation Apps, you can still use old packages on a 4.1 version, without recompiling them.
This allows you to also use the old UDM App, and the related UDM Functional Blocks (if your solution does
not contain any other Foundation Apps).

Compiling projects to incorporate new features


To correctly migrate projects you must start from the lowest level Functional Block (for example, the Functional
Block which does not reference any others) and then move up to Apps and Extension Apps, in order to take into
account existing dependencies.
For example, if you have a scenario made up of 3 Functional Blocks (one per domain) and one App, which reference
each other as in the screenshot below, you must migrate them in the following order:
1. Migrate and build Reference Data Functional Block.
2. Migrate and build Master Data Functional Block.
3. Migrate and build Operational Data Functional Block.
4. Migrate and build App.
5. If present, migrate and build Extension App.

New Features in Opcenter Execution Foundation 4.1


All new features available from version 4.1 of Opcenter Execution Foundation are provided in What's New of the
Opcenter Execution Foundation Release Notes.

Project Studio migration steps


The steps you need to perform depend on the product version you are starting from. Use the links below to follow
the correct procedure:

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1027


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

Starting version Migration procedure

2.0 Updating SIMATIC IT UAF 2.0 Projects in Project Studio

2.1 or 2.1 Update 1 Updating SIMATIC IT UAF 2.1 or 2.1 Update 1 Projects in Project
Studio

2.2 Updating SIMATIC IT UAF 2.2 Projects in Project Studio

2.3 Updating SIMATIC IT UAF 2.3 Projects in Project Studio

2.4 Updating SIMATIC IT UAF 2.4 Projects in Project Studio

2.5 Updating SIMATIC IT UAF 2.5 Projects in Project Studio

3.0 Updating Opcenter EX FN 3.0 Projects in Project Studio

3.1 Updating Opcenter EX FN 3.1 Projects in Project Studio

3.2 Updating Opcenter EX FN 3.2 Projects in Project Studio

3.3 Updating Opcenter EX FN 3.3 Projects in Project Studio

4.0 Updating Opcenter EX FN 4.0 Projects in Project Studio

What to do next
In Solution Studio, update/reload the Solution Apps.

8.1.1 Updating SIMATIC IT UAF 2.0 Projects in Project Studio


The following procedure allows you to update the SIMATIC IT UAF 2.0 Projects in Project Studio and correctly
compile DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites
• You must perform the Rebuild operation in the SIMATIC IT UAF 2.0 Project before proceeding with the migration
procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-upof your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure

1028 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

1. In Project Studio (in Opcenter Execution Foundation 4.1), open and then close each 2.0 Functional Block and
App included in your final solution.
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In Project Studio (in Opcenter Execution Foundation 4.1), open each App you want to make extensible, and
then:
• right-click its Installer project, select Properties and set the Can be Extended option to True.
• build the POMModel project.
4. If you want to migrate signals, delete them and recreate them and create new filter subscriptions.
5. Since the feature Data Segregation has been implemented to limit data access to users or user groups that
satisfy specific criteria, if you have used the name SegregationTag (reserved for data segregation) for an entity
in your App, you must open the App and modify this name before deploying it.
6. If you want to implement Reading Functions right-click the top level solution in the Solution Explorer pane,
click Add > New Project, select the Reading Functions Handler Project Class Library project in the Simatic
IT folder and click OK.
7. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the new Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the AppUserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Component and UI Module
manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
8. Manually delete the references from your Handler projects to all the dlls whose name contains
"EndPoints". Starting from SIMATIC IT UAF 2.1, these dlls are not in use anymore. Consequently, it is advisable
to manually remove their references even if the project compilation is not affected. These dlls are named as
follows:
• <Prefix>.<DomainName>.<FunctionalBlockName>.<Acronym>Model.EndPoints.dll
• <Prefix>.<AppName>.<AppName>POMModel.EndPoints.dll
9. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.1.2 Updating SIMATIC IT UAF 2.1 or 2.1 Update 1 Projects in Project


Studio
The following procedure allows you to update SIMATIC IT UAF 2.1 (or 2.1 Update 1) Projects in Project Studio and
correctly compile DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1029


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

Prerequisites
• You must perform the Rebuild operation in the SIMATIC IT UAF 2.1 or 2.1 Update 1 Project before proceeding
with the migration procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. In Project Studio (in Opcenter Execution Foundation 4.1), open and then close each Functional Block and App
included in your final solution.
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to make an App extensible:
• open the App in Project Studio
• right-click its Installer project and select Properties.
• set the Can be Extended option to True
• build the POMModel project.
4. If you have migrated signals, modify the filter subscriptions according to the new data structure.
5. Since the feature Data Segregation has been implemented to limit data access to users or user groups that
satisfy specific criteria, if you have used the name SegregationTag (reserved for data segregation) for an entity
in your App, you must open the App and modify this name before deploying it.
6. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the new Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Component and UI Module
manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
7. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

1030 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

8.1.3 Updating SIMATIC IT UAF 2.2 Projects in Project Studio


The following procedure allows you to update SIMATIC IT UAF 2.2 Projects in Project Studio and correctly compile
DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps)..

Prerequisites
• You must perform the Rebuild operation in the SIMATIC IT UAF 2.2 Project before proceeding with the migration
procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. Since the feature Data Segregation has been implemented to limit data access to users or user groups that
satisfy specific criteria, if you have used the name SegregationTag (reserved for data segregation) for an entity
in your App, you must open the App and modify this name before deploying it.
4. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the new Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
5. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1031


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

8.1.4 Updating SIMATIC IT UAF 2.3 Projects in Project Studio


The following procedure allows you to update SIMATIC IT UAF 2.3 Projects in Project Studio and correctly compile
DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites
• You must perform the Rebuild operation in the SIMATIC IT UAF 2.3 Project before proceeding with the migration
procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the new Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
4. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.1.5 Updating SIMATIC IT UAF 2.4 Projects in Project Studio


The following procedure allows you to update SIMATIC IT UAF 2.4 Projects in Project Studio and correctly compile
DLLs for .NET Standard (see note at topic Updating the Projects in Project Studio).

1032 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites
• You must perform the Rebuild operation in the SIMATIC IT UAF 2.4 Project before proceeding with the migration
procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
4. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.1.6 Updating SIMATIC IT UAF 2.5 Projects in Project Studio


The procedure allows you to update SIMATIC IT UAF 2.5 Projects in Project Studio and correctly compile DLLs
for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1033


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

• You must perform the Rebuild operation in the SIMATIC IT UAF 2.5 Project before proceeding with the migration
procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate your Command Handler / Event Handler / Reading Function Handler / Composite Command
Handler projects, if the ES_SD Functional Block (referenced by default in the Audit Trail App) is used in your
application, you must replace the occurrences of ScenarioConfigurationId with
ScenarioConfigurationId.Value within the code to properly access the actual value of the
property ScenarioConfigurationId belonging to the ScenarioInstance entity.
4. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
• If you are using SWAC components and the SWAC version has been updated (as documented at Using
Third-Party Components), execute the procedure described at Migrating the SWAC Component Manifest.
5. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.1.7 Updating Opcenter EX FN 3.0 Projects in Project Studio


The procedure allows you to update Opcenter Execution Foundation 3.0 Projects in Project Studio and correctly
compile DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps).

1034 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

Prerequisites
• You must perform the Rebuild operation in the Opcenter Execution Foundation 3.0 Project before proceeding
with the migration procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate your Command Handler / Event Handler / Reading Function Handler / Composite Command
Handler projects, if the ES_SD Functional Block (referenced by default in the Audit Trail App) is used in your
application, you must replace the occurrences of ScenarioConfigurationId with
ScenarioConfigurationId.Value within the code to properly access the actual value of the
property ScenarioConfigurationId belonging to the ScenarioInstance entity.
4. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
• If you are using SWAC components and the SWAC version has been updated (as documented at Using
Third-Party Components), execute the procedure described at Migrating the SWAC Component Manifest.
5. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.1.8 Updating Opcenter EX FN 3.1 Projects in Project Studio


The procedure allows you to update Opcenter Execution Foundation 3.1 Projects in Project Studio and correctly
compile DLLs for .NET Standard (see note at Updating the Projects in Project Studio).

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1035


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

This step is required only if you want to incorporate new features, otherwise you can deploy your old packages (if
they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites
• You must perform the Rebuild operation in the Opcenter Execution Foundation 3.1 Project before proceeding
with the migration procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate your Command Handler / Event Handler / Reading Function Handler / Composite Command
Handler projects, if the ES_SD Functional Block (referenced by default in the Audit Trail App) is used in your
application, you must replace the occurrences of ScenarioConfigurationId with
ScenarioConfigurationId.Value within the code to properly access the actual value of the
property ScenarioConfigurationId belonging to the ScenarioInstance entity.
4. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
• If you are using SWAC components and the SWAC version has been updated (as documented at Using
Third-Party Components), execute the procedure described at Migrating the SWAC Component Manifest.
5. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

1036 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

8.1.9 Updating Opcenter EX FN 3.2 Projects in Project Studio


The procedure allows you to update Opcenter Execution Foundation 3.2 Projects in Project Studio and correctly
compile DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required if you want to incorporate new features in the Data Model/business logic of your Functional
Blocks and Apps or the major version of referenced packages is changed, otherwise you can deploy your old
packages (if they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites
• You must perform the Rebuild operation in the Opcenter Execution Foundation 3.2 Project before proceeding
with the migration procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate your Command Handler / Event Handler / Reading Function Handler / Composite Command
Handler projects, if the ES_SD Functional Block (referenced by default in the Audit Trail App) is used in your
application, you must replace the occurrences of ScenarioConfigurationId with
ScenarioConfigurationId.Value within the code to properly access the actual value of the
property ScenarioConfigurationId belonging to the ScenarioInstance entity.
4. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
• If you are using SWAC components and the SWAC version has been updated (as documented at Using
Third-Party Components), execute the procedure described at Migrating the SWAC Component Manifest.
5. Build the solution in Project Studio.

What to do next

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1037


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.1.10 Updating Opcenter EX FN 3.3 Projects in Project Studio


The procedure allows you to update Opcenter Execution Foundation 3.3 Projects in Project Studio and correctly
compile DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required if you want to incorporate new features in the Data Model/business logic of your Functional
Blocks and Apps or the major version of referenced packages is changed, otherwise you can deploy your old
packages (if they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites
• You must perform the Rebuild operation in the Opcenter Execution Foundation 3.3 Project before proceeding
with the migration procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate your Command Handler / Event Handler / Reading Function Handler / Composite Command
Handler projects, if the ES_SD Functional Block (referenced by default in the Audit Trail App) is used in your
application, you must replace the occurrences of ScenarioConfigurationId with
ScenarioConfigurationId.Value within the code to properly access the actual value of the
property ScenarioConfigurationId belonging to the ScenarioInstance entity.
4. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.
• If you are using SWAC components and the SWAC version has been updated (as documented at Using
Third-Party Components), execute the procedure described at Migrating the SWAC Component Manifest.
5. Build the solution in Project Studio.

1038 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Updating the Projects in Project Studio

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.1.11 Updating Opcenter EX FN 4.0 Projects in Project Studio


The procedure allows you to update Opcenter Execution Foundation 4.0 Projects in Project Studio and correctly
compile DLLs for .NET Standard (see note at Updating the Projects in Project Studio).
This step is required if you want to incorporate new features in the Data Model/business logic of your Functional
Blocks and Apps or the major version of referenced packages is changed, otherwise you can deploy your old
packages (if they do not reference any system functionalities and the Solution does not contain Foundation Apps).

Prerequisites
• You must perform the Rebuild operation in the Opcenter Execution Foundation 4.0 Project before proceeding
with the migration procedure to avoid misalignments between .um/.umd files and .ul files.
• You must restore any references to other Functional Blocks before proceeding with the following migration
procedure.
• You must verify if any Functional Block needs to be updated before proceeding with the following migration
procedure and, if needed, update the involved Functional Blocks.
• We recommend you create a back-up of your Functional Blocks before migrating them.
• Do not modify the data model, such as adding new entities, during the migration procedure.
• If you are working under source control with several machines, the migration procedure should be performed
on one machine only. You can successively align the other machines using the Get Latest function once the first
machine has checked-in the migrated model.

Procedure
1. Open your solution in Project Studio (in Opcenter Execution Foundation 4.1).
2. As the Model Project has been reviewed to improve usability when modelling Functional Blocks and Apps,
perform the following steps:
• Build your solution.
• Delete the .um file from the model project. If you double-click this file, a warning message will inform
you that it is no longer supported and needs to be removed.
• Build your solution again. Now you can open the model double-clicking the .dm file from the Diagrams
sub-folder, containing the graphical representation of the data model.
3. In order to migrate your Command Handler / Event Handler / Reading Function Handler / Composite Command
Handler projects, if the ES_SD Functional Block (referenced by default in the Audit Trail App) is used in your
application, you must replace the occurrences of ScenarioConfigurationId with
ScenarioConfigurationId.Value within the code to properly access the actual value of the
property ScenarioConfigurationId belonging to the ScenarioInstance entity.
4. In order to migrate User Interfaces:
• In case of code-based UI screens (without using Model Driven UI Editor), to integrate the Data
Segregation functionality that allows you to modify the list of segregation tags assigned to entity
instances (see Modifying the List of Segregation Tags Assigned to Entity Instances in the Opcenter
Execution Foundation User Manual), specify entityName and appName in the Item Collection Viewer
(unless you have configured the widget for server-side pagination).
• Right-click the App UserInterface project and click Generate UI Application Files.
• Right-click the App UserInterface project and click Migrate to migrate the UI Module manifest.
• Verify the versions of the supported third-party software you have used to develop UIs.
• Verify that the AngularJS dependencies specified in the file module.js still correspond to your
requirements.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1039


How to Migrate a Manufacturing Solution

Updating the Solution in Solution Studio

• If you are using SWAC components and the SWAC version has been updated (as documented at Using
Third-Party Components), execute the procedure described at Migrating the SWAC Component Manifest.
5. Build the solution in Project Studio.

What to do next
Perform the final step in Solution Studio, which will allow you to deploy your updated solution.

8.2 Updating the Solution in Solution Studio


In this step you perform the actions that are required to update your manufacturing solution to the current product
version.

Prerequisites
• If required, you have already updated your Model in Project Studio.
• You have cleaned the browser cache before opening Solution Studio.

Procedure
1. In the App Management page,
• Update (with the button) or reload (with the button) the Foundation Apps that are present in
your Solution (e.g. Automation App, Personnel App, Signal App and so on) according to the following
behavior: the Apps that require an update are marked with the indicator, while all the other Apps
that do not show this indicator require a reload ( ).
• If you have updated any custom Apps in Project Studio, either reload them ( ) or update them (
) according to the versioning logic you have used (see Creating a New Version of Functional Block or
App and Reloading Apps and Extension Apps in a Solution).
2. If you come from version SIMATIC IT UAF 1.3 Update 4, in the Mashup page you have to open each Mashup
module, check that the wiring page is well formatted and then generate the Mashup.
3. In the UI Applications page, open any UI Applications to verify the following:
• Ensure they do not contain UI Modules that are no longer used in the updated solution. If you find any UI
Modules whose status is deleted, select them and click Unassign deleted modules. If you fail to do this,
the UI Application will be invalid.
• Add/delete the required UI Modules; for example, you can add new UI Modules in order to display any
newly provided screens.
4. Run the scripts for upgraded Apps, if you have Apps that reference the Siemens.SimanticIT.EQU_MS
05.00.00, Siemens.SimaticIT.EQ_OP 05.00.00, Siemens.SimaticIT.TSK_MS 06.00.00,
Siemens.SimaticIT.TSK_OP 08.00.00 and Siemens.SimaticIT.UDM_RF 04.00.00 Functional Blocks.

What to do next
Build and deploy the updated Solution in Solution Studio.

8.2.1 Running scripts for Upgraded Apps


This step is part of the migration procedure, and must be performed during the Updating the Solution in Solution
Studio procedure, after you have updated the required Apps (see Prerequisites below) and before updating the
solution database.

Prerequisites

1040 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Building and Deploying the Updated Solution in Solution Studio

The Equipment App is upgraded to Opcenter Execution Foundation 4.1,


• The Apps that reference the Siemens.SimaticIT.EQU_MS 05.00.02 and Siemens.SimaticIT.EQU_OP
05.01.00 Functional Blocks have been updated in the Opcenter Execution Foundation 4.1 solution.
• The Siemens.SimaticIT.TSK_MS 06.00.02, Siemens.SimaticIT.TSK_OP
08.01.00 and Siemens.SimaticIT.UDM_RF 04.00.02 Functional Blocks have been updated in the Opcenter
Execution Foundation 4.1 solution.

Procedure
Depending on the database management platform, run the following scripts on the solution database (first on the
Master Data Domain, then on the Operational Data Domain, and finally on the Reference Data Domain) by manually
copying them from the provided location to the database server:
• On SQL Server:
• %SITUnifiedSystemRoot%Utility\OldReadingModelUpdate\MasterData\SqlServer\Post
• %SITUnifiedSystemRoot%Utility\OldReadingModelUpdate\OperationalData\SqlServer\Post
• %SITUnifiedSystemRoot%Utility\OldReadingModelUpdate\ReferenceData\SqlServer\Post
• Oracle:
• %SITUnifiedSystemRoot%Utility\OldReadingModelUpdate\MasterData\Oracle\Post
• %SITUnifiedSystemRoot%Utility\OldReadingModelUpdate\OperationalData\Oracle\Post
• %SITUnifiedSystemRoot%Utility\OldReadingModelUpdate\ReferenceData\Oracle\Post

What to do next
Go back to build and deploy the updated Solution in Solution Studio.

8.3 Building and Deploying the Updated Solution in Solution Studio


In this step you perform the actions that are required to deploy and start your manufacturing solution.

 Due to technological upgrades and the adoption of .NET Core/Standard technology, the SQL Server
FileStream data management functionality is not in use anymore.
Starting from 3.1, unstructured data file, such as images and documents, are internally managed within
the runtime Opcenter EX FN database.

Prerequisites
You have updated the Solution in Solution Studio.

Procedure

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1041


How to Migrate a Manufacturing Solution

Completing the App Migration

 If your Manufacturing Solution contains references to the entities that have been declared Obsolete in
version 4.0 (entities that were available with the UDM_RF Functional Block),
you will need to enable Data Loss before migrating your Solution to the current version. In particular, this
applies to the following use cases:
• if you have a Solution containing any custom Apps that reference
the Siemens.SimaticIT.UDM_RF Functional Block;
• if you have a Solution containing any Opcenter EX FN Apps except for Application Log and Personnel.
For a detailed list of the removed functionalities, refer to Obsolete Functionalities in the Opcenter
Execution Foundation Release Notes.

1. If you are in one of the above mentioned you cases, enable Data Loss by manually creating the
deploy_configuration.xml file as documented at Enabling Potentially Destructive Operations.
2. Build your Solution ( button, see Creating the Deployment Package).
3. In the Host Management page, deploy the Solution on all environment hosts ( button, see Deploying the
Solution Package to Hosts).
4. Update the database ( button, see Deploying the Solution Package to Hosts).
5. Start the runtime services on all hosts ( button, see Deploying the Solution Package to Hosts).

 • Make sure you delete the deploy_configuration.xml file before using your solution on the production
line.
• If the deployment of the Solution fails and you migrated the Signals App from a previous version, you
need to deploy the Signal Rules again.

What to do next
Complete the migration by performing some specific migration steps in the Foundation Apps.

8.4 Completing the App Migration


After building and deploying the updated Solution in Solution Studio, you need to complete the migration by
performing some specific steps in many Apps.
The following Apps require additional steps to complete the migration:
• Automation Gateway App
• Signal App
• (Only in case of migration from version 3.0) Work Instruction App

Prerequisites
You have already built and deployed the updated Solution in Solution Studio.

Automation Gateway App


If the Manufacturing Solution you are migrating has at least an Automation Gateway Engineering configuration
defined and you are migrating to Opcenter Execution Foundation 4.1, launch the MigrateAutomation command
from Automation Gateway Management homepage by clicking Migrate. If this button is not displayed, this
migration step is not required.

1042 Opcenter Execution Foundation 4.1 - Development and Configuration Guide


How to Migrate a Manufacturing Solution

Completing the App Migration

 During the migration of Opcenter Execution Foundation from lower version to version 4.0, the Automation
Gateway App configuration consisting of values for functionalities and entity properties that are declared
obsolete (see Obsolete Functionalities in the Opcenter Execution Foundation Release Notes, Automation
Gateway section, for the complete list), will be lost.
This information is traced in Trace Viewer with the Provider Name as Siemens-SimaticIT-Trace-UDM-
AutomationGateway, see Logging and Analyzing Application Traces with Trace Viewer in the Opcenter
Execution Foundation Development and Configuration Guide. The system allows you to export the
preliminary configuration containing the pre-migration configuration which can be lost (See Migrating
Automation Node Master Data in the Opcenter Execution Foundation User Manual).

 Until the Migrate operation is performed, any Engineering operation is allowed except for the following:
Reset Environment, Activate Channels, Activate Types and Instances, and Import with Replace.

 After a successful Migrate operation or an Activate operation from the previous platform version, to
properly restore the runtime communication with the Automation Gateway Server, for each secured
channel, retrieve the OPC UA server certificate, approve and then activate Automation Channels, Types
and Instances to the Automation Gateway Server (as described at Activating Runtime Integration in the
Opcenter Execution Foundation User Guide).

Signal App
If you are migrating the Signals App from a previous version, perform the following steps in the following order:
1. After restarting runtime services on all hosts, reactivate the configuration of Automation and deploy the Signal
Rules based on Automation entities again.
2. Since the model of the running solution changed (commands, entities, signals), Signal Rules configured in
the Signals App may be rendered invalid. In particular, an error may return when deploying the Signal Rule or
the Signal Rule may not work properly at runtime. Depending on the involved Signal Rule, do either of the
following:
• Open the query editor to update the rule structure to the most recent version of the solution and then
save the query to persist this information on the database.
• Click Reload to ensure the Signal source/action data you are viewing is aligned with the most recent
version and then save the information.
3. You have the possibility to specify if you want to receive the values of the Automation Type only when the Signal
Rule executes, and not the initial values from the first run and when the Automation Gateway reconnects. To
incorporate this feature in the source filter, you have to save the Signal rules in the Signal App in order to view
the Enable Initial State parameter in the source filter. Moreover, as a 2.3 Signal App feature, you can also filter
by the IsChanged attribute on each Automation Parameter, in order to trigger the Signal Rule only when the
configured Automation Parameter changes. If the Signal Rule is migrated from 2.2, open the Signal Rule and
save the source block first in order to see and use the new attribute.

 If you have migrated the solution from 2.3 version (or earlier), the system will set any migrated Signal Rules
to parallel and it will not be possible to convert them to sequential.

Opcenter Execution Foundation 4.1 - Development and Configuration Guide 1043


How to Migrate a Manufacturing Solution

Completing the App Migration

Work Instruction App


In version 3.0 of Opcenter Execution Foundation, Failures were created in the Work Instruction App and then
associated with Visual Characteristics. Starting from version 3.1, you can create Failures only in the Defect App,
whereas the association with Characteristics is managed in the Work Instruction App.
For this reason, to manage existing Failures, created in the platform version 3.0, migrate them from the Work
Instruction App to the Defect App. See How to Migrate existing Failures to the Defect App in the Opcenter Execution
Foundation User Manual.

1044 Opcenter Execution Foundation 4.1 - Development and Configuration Guide

You might also like