iX HMI solution - Scripting The world's most graphic HMI solution. Truly open.
Contents of course Day 1  C# Introduction  Getting started with VS 2010  Declaring variables  Data type conversion  MessageBox  Flow control (if, switch, for, foreach)  Writing methods/functions  Exception handling  Array and Collections  Debug  Object Oriented Programming (basics – if time is available) Day 2  Scripting in iX  iX Specific scripting − Access to tags − Access to screens − Services − Media Objects  Script Module  iX Events  Write/read data from file  Timers  Serial Port handling  Ethernet  Referenced assembly  Samples (Scheduler, Database, etc.)  Pitfalls
Day 1 – C# basic concepts The world's most graphic HMI solution. Truly open.
What is .Net and C#?  .Net  Managed Code  Garbage Collection  C#
.Net in a nutshell  .Net Framework: − Consists primarily of a gigantic library of code to be used by the programmer − Using object-oriented programming techniques (OOP)  Common Type System (CTS): − A Type is a representation of data − Common to all .Net programming languages as C#, VB.Net, Managed C++, F#, J#  Common Language Runtime (CLR) − Acting as a shell were .Net application executes within. A wellstructured, strict and complete program development platform Source: Beginning Visual C# 2005 .Net
What is .Net and C#?  .Net  Managed Code  Garbage Collection  C#
Managed Code  Managed Code − Common Language Runtime (CLR) looks after your application by managing memory, handling security, allowing cross-language debugging etc − Application(s) not running under the control of CLR are called Unmanaged Code Your array-index out-of-bounds are catched, instead of crashing your application Source: Beginning Visual C# 2005 Managed Code System Runtime .Net CLR Native Code Native Code Native Code
What is .Net and C#?  .Net  Managed Code  Garbage Collection  C#
Garbage Collection  Garbage Collection − Works by inspecting the memory of your computer every so often and removing anything from it that is no longer needed − Prevents Memory Leak − Simple to invoke Garbage Collection when ever needed Automatic functions to prevent hard-to-find Memory Leakage bugs Source: Beginning Visual C# 2005 Garbage Collection
What is .Net and C#?  .Net  Managed Code  Garbage Collection  C#
C#  C-Sharp − Invented entirely for .Net and is it’s main programming language − The only language fully supported by the CLR − Strong heritage from C/C++ and Java’s sleek OOP implementation − Type-safe, clear rules how to convert data from one type to other  What kind of Applications Can I Write with C# − Windows applications − Web Applications ASP.Net using “Code-Behind” that can use the same class librarys as for your Windows applications − Distributed solutions, client programs that uses server applications as their internal code, making applications changes to a entire computer infrastructure on a click − …and many other types with the main three as their ancestors Brings the power to your ideas Source: Beginning Visual C# 2005 C#
Getting Started – First Application  The objective is to create a basic application in Visual Studio 2010  First step is to create a new Application: First Application
Getting Started – First Application  Select Windows Forms Application  Give the application a name and press OK First Application
Getting Started – Properties  It’s possible to customize objects and forms. Each object has a number of properties that controls it’s look and behavior  Change the form’s Text property to “Name Presenter” First Application
Getting Started – Toolbox  The Toolbox contains objects that can be placed in the form  Add a label to the form, change it’s Name property to lblName and Text to “Please enter your name: ”: First Application
Getting Started – Toolbox  Add a TextBox below the Label and a Button as well  The Name of the TextBox should be txtName and the button btnOK  Adjust the size of the form First Application
Getting Started – Button click event  Double click on the Button, the script editor will open. An event procedure for the Button click has been added automatically.  Add the following code inside the event: First Application
Getting Started – Test/Run application  Click on the Play button (or F5), the application will now be compiled and a debug session will start (if there are no compile errors): First Application
Exercise 1 - Getting Started  Create your first application.  It should contain two labels (Name and Age).  Two textboxes shall be added as well (where the user can insert his name and age).  A button should open a MessageBox that informs the user about his Name and age. Exercise
Syntax  The keyword using declares “short cuts” to different frameworks that you want to use in your code.  “{“ indicates start of a Namespace, class, function, statement and “}” indicates end. Syntax
Declaring variables  Variables are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value. Variables
Declaring variables - .NET data types Variables
Declaring variables – Int variable  Declare an integer variable  Initialize it with a value  Carry out a calculation  Display the result in a MessageBox Variables
Int variables in calculations?  Declare an integer variable  Carry out a division calculation  Display the result in a MessageBox  The result will always be rounded up/down. We need to use another kind of data type to get decimal precision. Variables
Declaring variables – Float variable  Declare a float variable  Initialize it with a value  Carry out a floating point calculation  Display the result in a MessageBox Variables
Declaring variables – Boolean variable  A boolean variable can be either true or false.  It’s typically used when creating logic (for an example if- or while-statement) Variables
Declaring variables – String Variable  A string is an immutable, fixed-length string of Unicode-characters  Strings literals are enclosed with double quotes, e.g. “abcd”. Characters are enclosed with single quotes e.g ‘x’. Strings and characters can be concatenated with the + operator.  It’s possible to access characters in the string with the following syntax: Variables
String handling – Useful functions  Get length of string  Split string with delimiter  Build a string (e.g one string variable and one constant string) Variables
String handling – Useful functions  Uppercase/Lowercase:  Replace  Contains Variables
String handling - Efficiency  A string is an immutable sequential collection of Unicode characters, typically used to represent text. A String is called immutable because its value cannot be modified once it has been created.  Methods that appear to modify a String actually return a new String containing the modification. If it is necessary to modify the actual contents of a string-like object, System.Text.StringBuilder class is more efficient. This class allows string modifications to be done without the overhead of object creation and garbage collection. Approximately 24 seconds to execute Approximately 0,016 seconds to execute Variables
Formatting strings  The String.Format method can be useful when building strings that should contain variable values. Variables
Formatting strings  With String.Format it’s also possible to format the variable’s value (e.g number of decimals, if it should be presented in scientific way etc.)  The code section below shows some examples: Variables
Type conversion String <-> Int, Float, etc…  Quite often it’s necessary to convert data types. For an example a string in a textbox to an Integer or Float (or vice versa).  The Convert class has a lot of converters, a few examples below: Variables
 Add two TextBox objects to your application. − One will be used to insert the Resistance of an Resistor, the other one will be used to insert the Current. − Add a label. − When the button is clicked the Voltage should be calculated and presented in the label (V = R x I) − The result should be presented with a maximum of two decimal digits. Exercise 2 – Conversion, Formatting Exercise
 A MessageBox can be used to inform the user/operator about for an example errors in the application  The MessageBox is possible to customize via different parameters to the Show method  Example of “standard” MessageBox Message box Message Box
 The MessageBox can also work as a Yes/No dialog  A DialogResult object can “catch” the result from the MessageBox (if the user selected Yes or No)  The result can be used to execute code depending on the answer from the user  Example: Yes/No Message box Message Box
 The purpose with this exercise is to detect if the user really wants to close the application.  The Form has an event called FormClosing, add a MessageBox that asks the user if he/she wants to close the application or not  Hint: The event has an in-parameter “e”. This object has a property called Cancel. If it’s set to true the application will not close. Exercise 3 - Message box Exercise
C# coding style  In order to create structured and readable code there are many ”laws” to follow, a few examples: − Use indentation − The object names should describe the function of the object (for an example loginButton, passwordTextBox) − Variable names should be descriptive and meaningful − Add comments that explains the code (//) Coding Style
Indentation  Add indentation when using e.g − IF-statement − Loops − Functions/Methods  Use [TAB] to add an indentation Coding Style
Indentation – Bad Example  The code is very hard to ”read” – there is no flow Coding Style
Indentation – Good Example Coding Style
Comparison and loops  The execution of the code can be controlled with different comparison/loop functions  Comparison statements – If and Switch/Case  Loops – For, While, Do, ForEach Flow Control
If statement  With an IF-statement it’s possible to check if conditions are fulfilled. The if statement needs a boolean result, that is, true or false  Example Flow Control
If statement – Several conditions  Often an If-statement needs to consider several conditions. Typically AND (in C# syntax: &&) and OR (in C# syntax: ||)  AND Example:  OR Example: Flow Control
Switch/Case  When you want to do sevaral comparisons on the same variable then the SWITCH/CASE statement can be helpful  Syntax/Example: Flow Control
Exercise 4 – If/Switch statements  Insert a TextBox and a Button. When the user clicks on the button a Switch statement shall check if the user wrote Red, Blue, Yellow or Green. If yes, change the color of the Form (Hint: this.BackColor).  Change the background color of the Form based on the calculated Voltage. − < 10 -> Yellow − > 10 and < 15 -> Green − > 15 -> Red Exercise
Loops  There are often situations when you need to execute the same code several times, for an example − Read 10 files − Send e-mails to all service persons  C# supports a lot of different loops, we will discuss: − For (fixed number of iterations) − While (loops until a certain condition is met) Flow Control
The for loop  If you want to execute the same code a specific number of times then a for-loop can be used Flow Control
The while loop  The while loop will iterate until a certain condition is met  This means that the code can loop different amount of times  An eternal loop will most likely cause a crash Flow Control
Exercise 5 – For loop  Create a new application (WinForm).  Add a ComboBox to the Form.  Add a button, when it’s clicked a For loop shall be executed.  The loop shall populate the ComboBox with texts (Hint: ComboBox1.Items.Add(”Text”)) Exercise
Methods and functions  Why should I use methods and functions in my application? − Reduction of code duplication by offering re-usability − Simplifying program logic by decomposing the program into smaller blocks − Improving readability of the program Methods
Function – No return/in-parameters  If the function should not return a value then the Return type should be void  Leave the area inside of (..) empty -> no in-parameters Methods
Methods – return a value  The return type tells the function what it should return  If there are no in-parameters then leave the area inside of (..) empty -> no in-parameters Methods
Methods – receive in-parameters  If the method should take in-parameters then they are included in the parenthesis  If several in-parameters should be used then separate them with a “,”-character Methods
Exercise 6 – Reusable methods  Create a new application (WinForms)  Write at least 5 functions −Add (add two numbers and return the result) −Subtract (subtract two numbers and return the result) −Multiply (multiply two numbers and return the result) −Divide (divide two numbers and return the result) −Calculate Circular Area (you can hard code PI to 3.14 or use Math.PI to get a more exact value)  What will happen if you type in text instead of a number? Exercise
Error handling  Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. For example, validating user input, checking for null objects, and verifying the values returned from methods are what you expect, are all examples of good standard error handling that you should be doing all the time.  However, there are times when you don't know if an error will occur. For example, you can't predict when you'll receive a file I/O error, run out of system memory, or encounter a database error. These things are generally unlikely, but they could still happen and you want to be able to deal with them when they do occur. This is where exception handling comes in. Error Handling
Error handling  Identifying the exceptions you'll need to handle depends on the routine you're writing. For example, if the routine opened a file with the System.IO.File.OpenRead() method, it could throw any of the following exceptions: − SecurityException − ArgumentException − ArgumentNullException − PathTooLongException − DirectoryNotFoundException − UnauthorizedAccessException − FileNotFoundException − NotSupportedException  It's easy to find out what exceptions a method can raise by looking in the .NET Frameworks SDK Documentation. Error Handling
Error handling  When exceptions are thrown, you need to be able to handle them. This is done by implementing a try/catch block  Code that could throw an exception is put in the try block and exception handling code goes in the catch block  Examples (try + try with specific exception) Error Handling
 Make sure that the application does not crash if you for an example: − Divide by zero − Try to open a file that does not exist on the PC Exercise 7 – Error handling Exercise
Arrays  Arrays works as collections of items, for instance string or integers  Useful when working with many items of the same type, for an example user name or constants  Arrays are 0-based and of fixed size  It’s possible to easily access elements inside of the array. This makes it possible to loop through all elements quickly Collections
Arrays  Loop through an array: Collections
List  The List object is a collection of a specific defined object type.  An array is always fixed size (it’s possible to resize but not very convenient), the List object has functions for Add, Remove, Search etc. This makes life easier… Collections
Debug an application  When developing code it’s often necessary to debug and trouble shoot the code. There are many different techniques, for an example: − Using Visual Studio’s built-in Debugger (makes it possible to Execute code ”row for row”, look at different objects in the memory etc). − Printing debug messages (from the code)  This training will focus on Visual Studio’s debug capabilities  The first step is to start the Debug Session − F5 − Green Play button − Menu (Debug -> Start Debug Session) Debugging
Debugging - Breakpoint  When running the code it can be useful to add breakpoints. This way the Debugger halts when the selected row(s) is reached.  To add a breakpoint click on the desired row, when it has been added the row changes color to red:  When the code is reached Visual Studio will get focus and the color is changed to Yellow. By hoovering the cursor over an objects it’s possible to see it’s current value: Debugging
Debugging – Step through code  It’s often necessary to execute code ”row by row”. There are three different debug actions for stepping through the code:  Step Over (F10): Executes the current row, never jumps into Functions.  Step Into (F11): Executes the current row, if it’s a function call it will step into that Function and allow you to debug this as well.  Step Out (Shift + F11): This function can be used if you have stepped in to a Function but then change your mind. Be executing this function you are returned to the previous row (calling the function). Debugging
Debugging – Locals/Watch window  The Locals window shows all local variables (when a breakpoint is entered)  The Watch window allows the user to add any (local/global) object to the list (drag/drop or write name directly)  Both windows gives the user possibility to change object’s values Debugging
Debugging – Immediate window  The Immediate window allows the developer to test custom lines of code directly. For an example: Debugging
Debugging – Print Debug  If the code execution is time critical normal debugging might not be sufficient. A quite common technique to use under such circumstances is ”Print debugging”  The System.Diagnostics.Debug object can be used to print debug messages to the output window: Debugging
Developing our first Object  We are going to develop a small basic E-mail client.  The first class that we will develop is an E-mail logic class, this object should have: − A field for the SMTP-server’s IP-address − A Property so that the IP-address can be changed − A function that sends the e-mail  The UI should look something like this: OOP
Developing our first Object OOP
Exercise 8 – EmailLogic Object Exercise  Develop a UI similar to the one below, give all controls meaningful names (instead of standard TextBox1 etc.) .  Add a new Class to the application, name it EmailLogic. This Class shall contain a Constructor, a private Field for the IP, a Property so that the IP can be accessed and finally a function for sending an e-mail.  Test the application.
Developing our second Object  In order to create a basic Address book we need to create a User object. It should have: − A field for the User name and E-mail address − A Constuctor − A read property for the E-mail address − A ToString method OOP
Developing our second Object OOP
Exercise 8b – User Object Exercise  Add a new Class to the application  Name it User  Implement it according to the specification on the previous slide
Developing our third Class/Object  The Users in the address book needs to be stored. We therefore need to develop a UserCollection object. It should have: − A field List, that will contain all Users. − A Property so that we can read/write to the List. − A Function that allows us to Add a user to the collection. OOP
Exercise 8c – UserCollection Object Exercise  Add a new Class to the application  Name it UserCollection  Implement it according to the specification on the previous slide
Exercise 8d – Select/Add User UI Exercise  Develop a UI similar to the one below.  Create logic so that the application behaves like an E-mail client with a basic Address book:
Day 2 – C# scripting in iX Developer The world's most graphic HMI solution. Truly open.
C# scripting in iX Developer  Script language is C#, Full .NET framework is supported in PC/EPC-applications and Compact .Net framework in iX Panel applications  MSDN contains a lot of .NET related information − http://msdn.microsoft.com/en-us/library/67ef8sbd(VS.80).aspx  iX is event driven, objects fires events when certain conditions are met (for an example: ValueChange, ScreenOpened)  Screen script  Controller script  Alarm server script  Script module − Global Script − Possible to execute from other scripts − Great tool in order to create Libraries with functions  The scripts can be debugged with Microsoft Visual Studio 2010. The express edition is free of charge! Scripting in iX
Full vs compact framework  About 30 % of the full framework is supported by the compact framework  iX Developer supports the full framework when the target is PC and compact framework when the target system is iX Panels  iX Developer (2.0) will generate a compile error if the user attempts to use full framework functionality in a panel application:  A good overview of the biggest differences are available at: − http://msdn.microsoft.com/en-us/library/2weec7k5(v=vs.90).aspx  OpenNetCF has made compact framework implementations that covers some of the gaps between the full and compact framework: − http://www.opennetcf.com/Products/SmartDeviceFramework.aspx
Reuse code – Component Library  Script code can be dragged/dropped between the Component library and the script editor.  This way you can build nice script libraries that can be re-used in other applications Scripting in iX
Event driven programming  All scripts in iX are executed when a certain event is fired, for an example − ValueChange − ScreenOpened − AlarmAcknowledge − Click − …  An event can be fired when a user/operator executes an action (e.g Click on a button)  Events can also be fired when external events occurs. For an example when characters are received on the serial port Scripting in iX
iX Events  Change view to Script  All objects/events are available in the list Scripting in iX
 The Script Editor supports Code snippets. Press CTRL+K+X and select which function that should be added:  Use tab to jump between the parameters in the statement Scripts – Code snippet Scripting in iX
iX Events  A delegate method is added automatically when double clicking on an event (when the text is bold a method is assigned to the event)  The code inside of this method will be executed when the user clicks on the button Scripting in iX
Access to iX objects  To access iX objects (e.g Tags, Recipe, Security) start with the keyword Globals  Example: Scripting in iX
iX objects – Access to event handlers  Detect a tag value change event in one specific screen Scripting in iX
Exercise 1a – Event  Create a new iX-application  Open a MessageBox when a user clicks on a button  Add a script that opens a MessageBox if the value of a tag exceeds 150 Exercise
Exercise 1b – Event via code  Add a Tag ValueChanged event via code (in a Screen).  When the Tag changes it’s value, write it to an internal variable.
Script module  Script module − Global Script − Possible to execute from other scripts − Possible to re-use scripts − Easier to maintain Script Module
Script module  Why is it easier to maintain a function in the Script module compared to copy/paste code?  If the developer needs to modify the code he has to find all places where the code has been duplicated, in this case 6 places  In a big application it’s likely that he will forget to modify the code in all places where it’s being used -> Unexpected behavior Function1 Screen 1 Function1 Screen 2 Function1 Screen 3 Function1 Screen 4 Function1 Screen 5 Function1 Screen 6 Script Module
Script module  Why is it easier to maintain a function in the Script module compared to copy/paste code?  In this case the developer only needs to modify the function in the script module. This saves both time and reduces the likeliness of introducing bugs Screen 1 Screen 2 Screen 3 Screen 4 Screen 6 Screen 5 Function1 Script Module Script Module
Exercise - Script module  Why is it easier to maintain a function in the Script module compared to copy/paste code?  In this case the developer only needs to modify the function in the script module. This saves both time and reduces the likeliness of introducing bugs Screen 1 Screen 2 Screen 3 Screen 4 Screen 6 Screen 5 Function1 Script Module Exercise
Write/read data to a text file  The .NET framework supports at least two different ways to write/read data to/from a file, using either − StreamReader/StreamWriter objects − File object (System.IO)  System.IO.File contains several different functions that allows you to handle files − Write − Read − Check if file exists − Move − … Read/Write File
Write data to a text file - Example  Write to file – tell the function where the file should be stored and the text that should be saved Read/Write File
Read data from a text file - Example  Read from file – tell the function where the file is located  Make sure that the file exists before attempting to open it (File.Exists) Read/Write File
Exercise 2 – File handling  From now on all Functions should be placed in a script module.  Add two buttons to a screen, one for saving text to a file and one for reading text from a file.  Don’t forget to add error handling (otherwise the application will crash if the file is removed, the path is faulty etc.).  Run the application, make sure that it works as expected Exercise
Serial Port – Initialize port  The C# SerialPort object allows the application to open a serial port and send/receive data.  Sending data is easier than receiving data since all received data needs to be parsed and checked if it is correct (e.g checksum or end character).  There are two different ways of receiving data, “polled” mode (via a thread) or via a DataReceived event.  The SerialPort class is part of the System.IO.Ports namespace. Serial Port
Serial Port – Send data  The SerialPort class has two functions for writing data (Write and WriteLine).  In this example we will use the Write function, the in-parameter to this function is a string: Serial Port
Serial Port – Receive data  The easiest way to receive data from the SerialPort is to listen to it’s DataReceived event. The problem with this event is that it’s not easy to know when it’s fired (it could be fired when 8 characters have been received and another time when 10 characters have been received).  To be sure that everything has been received we need to know either how many bytes to expect in the reply or a checksum/end character.  This basic sample just writes the received data to an internal string variable: Serial Port
 Write code that sends data from a TxA panel’s serial port to a PC (use HyperTerminal/LKA to send and receive strings)  Write code that can receive data from HyperTerminal. Store the received data in an internal variable and connect it to an analog numeric (don’t forget to change the presentation format to string). Exercise 3a – Serial Port Exercise
 Write code that receives data from the barcode reader  The barcode reader uses 9600 bps, 8 databits, None Parity and 1 stopbit Exercise 3b – Serial Port Exercise
Exercise 3c – Serial Port  Reuse the code from 7a. The goal is to connect the panel to a GSM modem and send SMS via script.  The AT-command to send a SMS is:  Panel -> Modem: “AT+CMGS=+46703358477<CR>”  Modem -> Panel: “<CR><LF>> “ (in total 4 characters, the third is ‘>’  Panel -> Modem: “SMS Message<ctrl-Z>” Pseudo code −Initialize Port (and hook up DataReceived event) −Store the message in an instance variable −Send first message −Wait for a data received event −Evaluate the data received – is it a proper reply? −Yes? Send the second part of the request Character Hex code <CR> 0x0D <ctrl-z> 0x1A Exercise
TCP Client - Init  The TcpClient object allows an application to connect to a TCP-server and exchange data.  TcpClient is part of the System.Net.Sockets framework. Ethernet
TCP Client – Send data  Data can be sent to the server by using the Write function.  In this example a byte array is populated with a valid Modbus request and then sent to the Modbus TCP-server Ethernet
Ethernet – Receive data  The stream’s Read function can be used to receive a reply from the TCP-server.  Note! The Read function is blocking until a time out or data is received. Therefore this should typically be carried out in a Thread. This is not covered in this basic course. Ethernet
 Implement a basic Modbus request, send it to a Modbus Simulator  Receive the reply, make sure it’s a valid Modbus reply (length). Parse the value from the reply and display it in an internal variable. Exercise 4 – Ethernet Exercise
 A timer can be used when you want to execute some actions at a certain interval Timers Timers
 We want to create a basic data logger  Every 5 seconds we should save a few tag values in a text file − Add a timer that executes every 5 seconds − Append text to a text file (use the System.IO.File.AppendAllText function, a new line (a.k.a <CR>) can be added with Environment.NewLine) Exercise 5 – Timers Exercise
Exercise – Solution suggestion Exercise
Debug application with Visual Studio 2010  Microsoft Visual Studio Express 2010 can be used to debug scripts. It’s available free of charge from microsoft’s website.  Add the path to visual studio. Then you only need to click on the debug button, this means that Visual studio will start automatically preloaded with all source files. Debug iX Application
Referenced Assemblies  Sometimes a customer might want to use a .NET class library in his/her application. A class library is compiled to a dll.  In iX Developer it’s possible to add referenced assemblies via the Project Tab. Referenced Assembly
 Create a Class library in Visual studio  Copy/paste the code from the E-mail sample (from yesterday’s exercises)  Compile the solution, a dll will be generated  Reference and use this dll in an iX PC application Exercise 6 – Referenced assemblies Exercise
Samples  Database  ISchedulerJob  Syncronize HMI with PLC clock Source: Scipting Mode [F1] Samples
iX Objects – Properties/Functions  Mutiple Languages
iX Objects – Properties/Functions  Line object
iX Objects – Properties/Functions  Rectangle object
iX Objects – Properties/Functions  Ellipse object
iX Objects – Properties/Functions  Polyline object
iX Objects – Properties/Functions  Analog Numeric object
iX Objects – Properties/Functions  Button object
iX Objects – Properties/Functions  Picture object
iX Objects – Properties/Functions  MultiPicture object
iX Objects – Properties/Functions  AnimatedGIF object
iX Objects – Properties/Functions  Linear meter object
iX Objects – Properties/Functions  Slider object
iX Objects – Properties/Functions  CircularMeter object
iX Objects – Properties/Functions  TrendViewer object
iX Objects – Properties/Functions  Chart object
iX Objects – Properties/Functions  ActionMenu object
iX Objects – Properties/Functions  AnimatedLabel object
iX Objects – Properties/Functions  TouchComboBox object
iX Objects – Properties/Functions  TouchListBox object
iX Objects – Properties/Functions  RollerPanel object
iX Objects – Properties/Functions  DigitalClock object
iX Objects – Properties/Functions  AlarmViewer object
iX Objects – Properties/Functions  AuditTrailViewer object
iX Objects – Properties/Functions  MediaPlayer object
iX Objects – Properties/Functions  PDFViewer object
Develop a WPF-Control  Start Visual Studio 2010  Create a Class Library project, this means that the control will be embedded in a dll (that can be imported or referenced in iX Developer).
Develop a WPF-Control  Add a new Item to the application (Add -> New Item).  Select User Control (WPF), give the control a name.
Develop a WPF-Control - XAML  This control will only contain a TextBox  The TextBox’s Text property is bound to a property called Value, ElementName should be set to the name of the UserControl.
Develop a WPF-Control – C# Step 1/6  Add using System.ComponentModel to the code.  Add [DefaultProperty("Value")] to the class, to define which property the tag should be connected to.
Develop a WPF-Control – C# Step 2/6  Add a dependency property with same name as the attribute in step 1 (Value) − static readonly DependencyProperty ValueProperty;
Develop a WPF-Control – C# Step 3/6  Add a static constructor and register the dependency property.
Develop a WPF-Control – C# Step 4/6  Create a Value property of type object.
Develop a WPF-Control – C# Step 5/6  Create a Value property of type object.
Develop a WPF-Control – C# Step 6/6  Compile the Visual studio solution  If the compilation is successful a dll will be generated  The dll can now be imported to iX Developer, it will be possible to connect a tag directly to the control (just as for normal iX-objects).
Pitfalls – Timers  For a timer it’s not enough to unhook the event handler  It’s very important that the timer is disabled (.Enabled = false)  Example: Pitfalls
Pitfalls – OPC  Let’s say you want to detect that the value of a tag/analog numeric is changed. Depending on the value you want to execute different actions  The problem is that the value in the analog numeric is changed but there is small delay before the OPC-server gets the new value  This means that the we compare the old value of tag1 with 10 (and not the value that was inserted in the analog numeric)  Solution: Use the tags ValueChange event instead Pitfalls
Pitfalls – Event handlers  Memory leak when using events is very common if an eventhandler is not unhooked  Example: Pitfalls
Scripting  [Ctrl] + [Space] − Intellisense, drops the meny  [Ctrl] + [K] + [L] − Listing Members  [Ctrl] + [Shift] + [Space] − Parameter/argument information  [Ctrl] + [K] + [X] − Displays Code Snippets  [Tab] − Completes word in intellisense  [Ctrl] + [H] − Search and replace, opens dialog Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works! Source: Scripting Mode Help [F1] Key Shortcuts
Scripting  [Ctrl] + [F] − Find, opens dialog  [Ctrl] + [F3] − Find next  [Ctrl] + [E] + [C] − Comment out the selected lines  [Ctrl] + [E] + [U] − Uncomment the selected lines  [Ctrl] + [G] − Go to line Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works! Source: Scripting Mode [F1] Key Shortcuts
Tables  [F4] − Expands a listbox  [Enter] − Enters a typed in value  [Esc] − Leaves the cell, and remains unchanged  [Space] − Checks or unchecks checkboxes  [Ctrl] + [Tab] − Shifts between tabs Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works! Source: Scipting Mode [F1] Key Shortcuts

I x scripting

  • 1.
    iX HMI solution- Scripting The world's most graphic HMI solution. Truly open.
  • 2.
    Contents of course Day1  C# Introduction  Getting started with VS 2010  Declaring variables  Data type conversion  MessageBox  Flow control (if, switch, for, foreach)  Writing methods/functions  Exception handling  Array and Collections  Debug  Object Oriented Programming (basics – if time is available) Day 2  Scripting in iX  iX Specific scripting − Access to tags − Access to screens − Services − Media Objects  Script Module  iX Events  Write/read data from file  Timers  Serial Port handling  Ethernet  Referenced assembly  Samples (Scheduler, Database, etc.)  Pitfalls
  • 3.
    Day 1 –C# basic concepts The world's most graphic HMI solution. Truly open.
  • 4.
    What is .Netand C#?  .Net  Managed Code  Garbage Collection  C#
  • 5.
    .Net in anutshell  .Net Framework: − Consists primarily of a gigantic library of code to be used by the programmer − Using object-oriented programming techniques (OOP)  Common Type System (CTS): − A Type is a representation of data − Common to all .Net programming languages as C#, VB.Net, Managed C++, F#, J#  Common Language Runtime (CLR) − Acting as a shell were .Net application executes within. A wellstructured, strict and complete program development platform Source: Beginning Visual C# 2005 .Net
  • 6.
    What is .Netand C#?  .Net  Managed Code  Garbage Collection  C#
  • 7.
    Managed Code  ManagedCode − Common Language Runtime (CLR) looks after your application by managing memory, handling security, allowing cross-language debugging etc − Application(s) not running under the control of CLR are called Unmanaged Code Your array-index out-of-bounds are catched, instead of crashing your application Source: Beginning Visual C# 2005 Managed Code System Runtime .Net CLR Native Code Native Code Native Code
  • 8.
    What is .Netand C#?  .Net  Managed Code  Garbage Collection  C#
  • 9.
    Garbage Collection  GarbageCollection − Works by inspecting the memory of your computer every so often and removing anything from it that is no longer needed − Prevents Memory Leak − Simple to invoke Garbage Collection when ever needed Automatic functions to prevent hard-to-find Memory Leakage bugs Source: Beginning Visual C# 2005 Garbage Collection
  • 10.
    What is .Netand C#?  .Net  Managed Code  Garbage Collection  C#
  • 11.
    C#  C-Sharp − Inventedentirely for .Net and is it’s main programming language − The only language fully supported by the CLR − Strong heritage from C/C++ and Java’s sleek OOP implementation − Type-safe, clear rules how to convert data from one type to other  What kind of Applications Can I Write with C# − Windows applications − Web Applications ASP.Net using “Code-Behind” that can use the same class librarys as for your Windows applications − Distributed solutions, client programs that uses server applications as their internal code, making applications changes to a entire computer infrastructure on a click − …and many other types with the main three as their ancestors Brings the power to your ideas Source: Beginning Visual C# 2005 C#
  • 12.
    Getting Started –First Application  The objective is to create a basic application in Visual Studio 2010  First step is to create a new Application: First Application
  • 13.
    Getting Started –First Application  Select Windows Forms Application  Give the application a name and press OK First Application
  • 14.
    Getting Started –Properties  It’s possible to customize objects and forms. Each object has a number of properties that controls it’s look and behavior  Change the form’s Text property to “Name Presenter” First Application
  • 15.
    Getting Started –Toolbox  The Toolbox contains objects that can be placed in the form  Add a label to the form, change it’s Name property to lblName and Text to “Please enter your name: ”: First Application
  • 16.
    Getting Started –Toolbox  Add a TextBox below the Label and a Button as well  The Name of the TextBox should be txtName and the button btnOK  Adjust the size of the form First Application
  • 17.
    Getting Started –Button click event  Double click on the Button, the script editor will open. An event procedure for the Button click has been added automatically.  Add the following code inside the event: First Application
  • 18.
    Getting Started –Test/Run application  Click on the Play button (or F5), the application will now be compiled and a debug session will start (if there are no compile errors): First Application
  • 19.
    Exercise 1 -Getting Started  Create your first application.  It should contain two labels (Name and Age).  Two textboxes shall be added as well (where the user can insert his name and age).  A button should open a MessageBox that informs the user about his Name and age. Exercise
  • 20.
    Syntax  The keywordusing declares “short cuts” to different frameworks that you want to use in your code.  “{“ indicates start of a Namespace, class, function, statement and “}” indicates end. Syntax
  • 21.
    Declaring variables  Variablesare identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value. Variables
  • 22.
    Declaring variables -.NET data types Variables
  • 23.
    Declaring variables –Int variable  Declare an integer variable  Initialize it with a value  Carry out a calculation  Display the result in a MessageBox Variables
  • 24.
    Int variables incalculations?  Declare an integer variable  Carry out a division calculation  Display the result in a MessageBox  The result will always be rounded up/down. We need to use another kind of data type to get decimal precision. Variables
  • 25.
    Declaring variables –Float variable  Declare a float variable  Initialize it with a value  Carry out a floating point calculation  Display the result in a MessageBox Variables
  • 26.
    Declaring variables –Boolean variable  A boolean variable can be either true or false.  It’s typically used when creating logic (for an example if- or while-statement) Variables
  • 27.
    Declaring variables –String Variable  A string is an immutable, fixed-length string of Unicode-characters  Strings literals are enclosed with double quotes, e.g. “abcd”. Characters are enclosed with single quotes e.g ‘x’. Strings and characters can be concatenated with the + operator.  It’s possible to access characters in the string with the following syntax: Variables
  • 28.
    String handling –Useful functions  Get length of string  Split string with delimiter  Build a string (e.g one string variable and one constant string) Variables
  • 29.
    String handling –Useful functions  Uppercase/Lowercase:  Replace  Contains Variables
  • 30.
    String handling -Efficiency  A string is an immutable sequential collection of Unicode characters, typically used to represent text. A String is called immutable because its value cannot be modified once it has been created.  Methods that appear to modify a String actually return a new String containing the modification. If it is necessary to modify the actual contents of a string-like object, System.Text.StringBuilder class is more efficient. This class allows string modifications to be done without the overhead of object creation and garbage collection. Approximately 24 seconds to execute Approximately 0,016 seconds to execute Variables
  • 31.
    Formatting strings  TheString.Format method can be useful when building strings that should contain variable values. Variables
  • 32.
    Formatting strings  WithString.Format it’s also possible to format the variable’s value (e.g number of decimals, if it should be presented in scientific way etc.)  The code section below shows some examples: Variables
  • 33.
    Type conversion String<-> Int, Float, etc…  Quite often it’s necessary to convert data types. For an example a string in a textbox to an Integer or Float (or vice versa).  The Convert class has a lot of converters, a few examples below: Variables
  • 34.
     Add twoTextBox objects to your application. − One will be used to insert the Resistance of an Resistor, the other one will be used to insert the Current. − Add a label. − When the button is clicked the Voltage should be calculated and presented in the label (V = R x I) − The result should be presented with a maximum of two decimal digits. Exercise 2 – Conversion, Formatting Exercise
  • 35.
     A MessageBoxcan be used to inform the user/operator about for an example errors in the application  The MessageBox is possible to customize via different parameters to the Show method  Example of “standard” MessageBox Message box Message Box
  • 36.
     The MessageBoxcan also work as a Yes/No dialog  A DialogResult object can “catch” the result from the MessageBox (if the user selected Yes or No)  The result can be used to execute code depending on the answer from the user  Example: Yes/No Message box Message Box
  • 37.
     The purposewith this exercise is to detect if the user really wants to close the application.  The Form has an event called FormClosing, add a MessageBox that asks the user if he/she wants to close the application or not  Hint: The event has an in-parameter “e”. This object has a property called Cancel. If it’s set to true the application will not close. Exercise 3 - Message box Exercise
  • 38.
    C# coding style In order to create structured and readable code there are many ”laws” to follow, a few examples: − Use indentation − The object names should describe the function of the object (for an example loginButton, passwordTextBox) − Variable names should be descriptive and meaningful − Add comments that explains the code (//) Coding Style
  • 39.
    Indentation  Add indentationwhen using e.g − IF-statement − Loops − Functions/Methods  Use [TAB] to add an indentation Coding Style
  • 40.
    Indentation – BadExample  The code is very hard to ”read” – there is no flow Coding Style
  • 41.
    Indentation – GoodExample Coding Style
  • 42.
    Comparison and loops The execution of the code can be controlled with different comparison/loop functions  Comparison statements – If and Switch/Case  Loops – For, While, Do, ForEach Flow Control
  • 43.
    If statement  Withan IF-statement it’s possible to check if conditions are fulfilled. The if statement needs a boolean result, that is, true or false  Example Flow Control
  • 44.
    If statement –Several conditions  Often an If-statement needs to consider several conditions. Typically AND (in C# syntax: &&) and OR (in C# syntax: ||)  AND Example:  OR Example: Flow Control
  • 45.
    Switch/Case  When youwant to do sevaral comparisons on the same variable then the SWITCH/CASE statement can be helpful  Syntax/Example: Flow Control
  • 46.
    Exercise 4 –If/Switch statements  Insert a TextBox and a Button. When the user clicks on the button a Switch statement shall check if the user wrote Red, Blue, Yellow or Green. If yes, change the color of the Form (Hint: this.BackColor).  Change the background color of the Form based on the calculated Voltage. − < 10 -> Yellow − > 10 and < 15 -> Green − > 15 -> Red Exercise
  • 47.
    Loops  There areoften situations when you need to execute the same code several times, for an example − Read 10 files − Send e-mails to all service persons  C# supports a lot of different loops, we will discuss: − For (fixed number of iterations) − While (loops until a certain condition is met) Flow Control
  • 48.
    The for loop If you want to execute the same code a specific number of times then a for-loop can be used Flow Control
  • 49.
    The while loop The while loop will iterate until a certain condition is met  This means that the code can loop different amount of times  An eternal loop will most likely cause a crash Flow Control
  • 50.
    Exercise 5 –For loop  Create a new application (WinForm).  Add a ComboBox to the Form.  Add a button, when it’s clicked a For loop shall be executed.  The loop shall populate the ComboBox with texts (Hint: ComboBox1.Items.Add(”Text”)) Exercise
  • 51.
    Methods and functions Why should I use methods and functions in my application? − Reduction of code duplication by offering re-usability − Simplifying program logic by decomposing the program into smaller blocks − Improving readability of the program Methods
  • 52.
    Function – Noreturn/in-parameters  If the function should not return a value then the Return type should be void  Leave the area inside of (..) empty -> no in-parameters Methods
  • 53.
    Methods – returna value  The return type tells the function what it should return  If there are no in-parameters then leave the area inside of (..) empty -> no in-parameters Methods
  • 54.
    Methods – receivein-parameters  If the method should take in-parameters then they are included in the parenthesis  If several in-parameters should be used then separate them with a “,”-character Methods
  • 55.
    Exercise 6 –Reusable methods  Create a new application (WinForms)  Write at least 5 functions −Add (add two numbers and return the result) −Subtract (subtract two numbers and return the result) −Multiply (multiply two numbers and return the result) −Divide (divide two numbers and return the result) −Calculate Circular Area (you can hard code PI to 3.14 or use Math.PI to get a more exact value)  What will happen if you type in text instead of a number? Exercise
  • 56.
    Error handling  Exceptionsare unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. For example, validating user input, checking for null objects, and verifying the values returned from methods are what you expect, are all examples of good standard error handling that you should be doing all the time.  However, there are times when you don't know if an error will occur. For example, you can't predict when you'll receive a file I/O error, run out of system memory, or encounter a database error. These things are generally unlikely, but they could still happen and you want to be able to deal with them when they do occur. This is where exception handling comes in. Error Handling
  • 57.
    Error handling  Identifyingthe exceptions you'll need to handle depends on the routine you're writing. For example, if the routine opened a file with the System.IO.File.OpenRead() method, it could throw any of the following exceptions: − SecurityException − ArgumentException − ArgumentNullException − PathTooLongException − DirectoryNotFoundException − UnauthorizedAccessException − FileNotFoundException − NotSupportedException  It's easy to find out what exceptions a method can raise by looking in the .NET Frameworks SDK Documentation. Error Handling
  • 58.
    Error handling  Whenexceptions are thrown, you need to be able to handle them. This is done by implementing a try/catch block  Code that could throw an exception is put in the try block and exception handling code goes in the catch block  Examples (try + try with specific exception) Error Handling
  • 59.
     Make surethat the application does not crash if you for an example: − Divide by zero − Try to open a file that does not exist on the PC Exercise 7 – Error handling Exercise
  • 60.
    Arrays  Arrays worksas collections of items, for instance string or integers  Useful when working with many items of the same type, for an example user name or constants  Arrays are 0-based and of fixed size  It’s possible to easily access elements inside of the array. This makes it possible to loop through all elements quickly Collections
  • 61.
    Arrays  Loop throughan array: Collections
  • 62.
    List  The Listobject is a collection of a specific defined object type.  An array is always fixed size (it’s possible to resize but not very convenient), the List object has functions for Add, Remove, Search etc. This makes life easier… Collections
  • 63.
    Debug an application When developing code it’s often necessary to debug and trouble shoot the code. There are many different techniques, for an example: − Using Visual Studio’s built-in Debugger (makes it possible to Execute code ”row for row”, look at different objects in the memory etc). − Printing debug messages (from the code)  This training will focus on Visual Studio’s debug capabilities  The first step is to start the Debug Session − F5 − Green Play button − Menu (Debug -> Start Debug Session) Debugging
  • 64.
    Debugging - Breakpoint When running the code it can be useful to add breakpoints. This way the Debugger halts when the selected row(s) is reached.  To add a breakpoint click on the desired row, when it has been added the row changes color to red:  When the code is reached Visual Studio will get focus and the color is changed to Yellow. By hoovering the cursor over an objects it’s possible to see it’s current value: Debugging
  • 65.
    Debugging – Stepthrough code  It’s often necessary to execute code ”row by row”. There are three different debug actions for stepping through the code:  Step Over (F10): Executes the current row, never jumps into Functions.  Step Into (F11): Executes the current row, if it’s a function call it will step into that Function and allow you to debug this as well.  Step Out (Shift + F11): This function can be used if you have stepped in to a Function but then change your mind. Be executing this function you are returned to the previous row (calling the function). Debugging
  • 66.
    Debugging – Locals/Watchwindow  The Locals window shows all local variables (when a breakpoint is entered)  The Watch window allows the user to add any (local/global) object to the list (drag/drop or write name directly)  Both windows gives the user possibility to change object’s values Debugging
  • 67.
    Debugging – Immediatewindow  The Immediate window allows the developer to test custom lines of code directly. For an example: Debugging
  • 68.
    Debugging – PrintDebug  If the code execution is time critical normal debugging might not be sufficient. A quite common technique to use under such circumstances is ”Print debugging”  The System.Diagnostics.Debug object can be used to print debug messages to the output window: Debugging
  • 69.
    Developing our firstObject  We are going to develop a small basic E-mail client.  The first class that we will develop is an E-mail logic class, this object should have: − A field for the SMTP-server’s IP-address − A Property so that the IP-address can be changed − A function that sends the e-mail  The UI should look something like this: OOP
  • 70.
  • 71.
    Exercise 8 –EmailLogic Object Exercise  Develop a UI similar to the one below, give all controls meaningful names (instead of standard TextBox1 etc.) .  Add a new Class to the application, name it EmailLogic. This Class shall contain a Constructor, a private Field for the IP, a Property so that the IP can be accessed and finally a function for sending an e-mail.  Test the application.
  • 72.
    Developing our secondObject  In order to create a basic Address book we need to create a User object. It should have: − A field for the User name and E-mail address − A Constuctor − A read property for the E-mail address − A ToString method OOP
  • 73.
  • 74.
    Exercise 8b –User Object Exercise  Add a new Class to the application  Name it User  Implement it according to the specification on the previous slide
  • 75.
    Developing our thirdClass/Object  The Users in the address book needs to be stored. We therefore need to develop a UserCollection object. It should have: − A field List, that will contain all Users. − A Property so that we can read/write to the List. − A Function that allows us to Add a user to the collection. OOP
  • 76.
    Exercise 8c –UserCollection Object Exercise  Add a new Class to the application  Name it UserCollection  Implement it according to the specification on the previous slide
  • 77.
    Exercise 8d –Select/Add User UI Exercise  Develop a UI similar to the one below.  Create logic so that the application behaves like an E-mail client with a basic Address book:
  • 78.
    Day 2 –C# scripting in iX Developer The world's most graphic HMI solution. Truly open.
  • 79.
    C# scripting iniX Developer  Script language is C#, Full .NET framework is supported in PC/EPC-applications and Compact .Net framework in iX Panel applications  MSDN contains a lot of .NET related information − http://msdn.microsoft.com/en-us/library/67ef8sbd(VS.80).aspx  iX is event driven, objects fires events when certain conditions are met (for an example: ValueChange, ScreenOpened)  Screen script  Controller script  Alarm server script  Script module − Global Script − Possible to execute from other scripts − Great tool in order to create Libraries with functions  The scripts can be debugged with Microsoft Visual Studio 2010. The express edition is free of charge! Scripting in iX
  • 80.
    Full vs compactframework  About 30 % of the full framework is supported by the compact framework  iX Developer supports the full framework when the target is PC and compact framework when the target system is iX Panels  iX Developer (2.0) will generate a compile error if the user attempts to use full framework functionality in a panel application:  A good overview of the biggest differences are available at: − http://msdn.microsoft.com/en-us/library/2weec7k5(v=vs.90).aspx  OpenNetCF has made compact framework implementations that covers some of the gaps between the full and compact framework: − http://www.opennetcf.com/Products/SmartDeviceFramework.aspx
  • 81.
    Reuse code –Component Library  Script code can be dragged/dropped between the Component library and the script editor.  This way you can build nice script libraries that can be re-used in other applications Scripting in iX
  • 82.
    Event driven programming All scripts in iX are executed when a certain event is fired, for an example − ValueChange − ScreenOpened − AlarmAcknowledge − Click − …  An event can be fired when a user/operator executes an action (e.g Click on a button)  Events can also be fired when external events occurs. For an example when characters are received on the serial port Scripting in iX
  • 83.
    iX Events  Changeview to Script  All objects/events are available in the list Scripting in iX
  • 84.
     The ScriptEditor supports Code snippets. Press CTRL+K+X and select which function that should be added:  Use tab to jump between the parameters in the statement Scripts – Code snippet Scripting in iX
  • 85.
    iX Events  Adelegate method is added automatically when double clicking on an event (when the text is bold a method is assigned to the event)  The code inside of this method will be executed when the user clicks on the button Scripting in iX
  • 86.
    Access to iXobjects  To access iX objects (e.g Tags, Recipe, Security) start with the keyword Globals  Example: Scripting in iX
  • 87.
    iX objects –Access to event handlers  Detect a tag value change event in one specific screen Scripting in iX
  • 88.
    Exercise 1a –Event  Create a new iX-application  Open a MessageBox when a user clicks on a button  Add a script that opens a MessageBox if the value of a tag exceeds 150 Exercise
  • 89.
    Exercise 1b –Event via code  Add a Tag ValueChanged event via code (in a Screen).  When the Tag changes it’s value, write it to an internal variable.
  • 90.
    Script module  Scriptmodule − Global Script − Possible to execute from other scripts − Possible to re-use scripts − Easier to maintain Script Module
  • 91.
    Script module  Whyis it easier to maintain a function in the Script module compared to copy/paste code?  If the developer needs to modify the code he has to find all places where the code has been duplicated, in this case 6 places  In a big application it’s likely that he will forget to modify the code in all places where it’s being used -> Unexpected behavior Function1 Screen 1 Function1 Screen 2 Function1 Screen 3 Function1 Screen 4 Function1 Screen 5 Function1 Screen 6 Script Module
  • 92.
    Script module  Whyis it easier to maintain a function in the Script module compared to copy/paste code?  In this case the developer only needs to modify the function in the script module. This saves both time and reduces the likeliness of introducing bugs Screen 1 Screen 2 Screen 3 Screen 4 Screen 6 Screen 5 Function1 Script Module Script Module
  • 93.
    Exercise - Scriptmodule  Why is it easier to maintain a function in the Script module compared to copy/paste code?  In this case the developer only needs to modify the function in the script module. This saves both time and reduces the likeliness of introducing bugs Screen 1 Screen 2 Screen 3 Screen 4 Screen 6 Screen 5 Function1 Script Module Exercise
  • 94.
    Write/read data toa text file  The .NET framework supports at least two different ways to write/read data to/from a file, using either − StreamReader/StreamWriter objects − File object (System.IO)  System.IO.File contains several different functions that allows you to handle files − Write − Read − Check if file exists − Move − … Read/Write File
  • 95.
    Write data toa text file - Example  Write to file – tell the function where the file should be stored and the text that should be saved Read/Write File
  • 96.
    Read data froma text file - Example  Read from file – tell the function where the file is located  Make sure that the file exists before attempting to open it (File.Exists) Read/Write File
  • 97.
    Exercise 2 –File handling  From now on all Functions should be placed in a script module.  Add two buttons to a screen, one for saving text to a file and one for reading text from a file.  Don’t forget to add error handling (otherwise the application will crash if the file is removed, the path is faulty etc.).  Run the application, make sure that it works as expected Exercise
  • 98.
    Serial Port –Initialize port  The C# SerialPort object allows the application to open a serial port and send/receive data.  Sending data is easier than receiving data since all received data needs to be parsed and checked if it is correct (e.g checksum or end character).  There are two different ways of receiving data, “polled” mode (via a thread) or via a DataReceived event.  The SerialPort class is part of the System.IO.Ports namespace. Serial Port
  • 99.
    Serial Port –Send data  The SerialPort class has two functions for writing data (Write and WriteLine).  In this example we will use the Write function, the in-parameter to this function is a string: Serial Port
  • 100.
    Serial Port –Receive data  The easiest way to receive data from the SerialPort is to listen to it’s DataReceived event. The problem with this event is that it’s not easy to know when it’s fired (it could be fired when 8 characters have been received and another time when 10 characters have been received).  To be sure that everything has been received we need to know either how many bytes to expect in the reply or a checksum/end character.  This basic sample just writes the received data to an internal string variable: Serial Port
  • 101.
     Write codethat sends data from a TxA panel’s serial port to a PC (use HyperTerminal/LKA to send and receive strings)  Write code that can receive data from HyperTerminal. Store the received data in an internal variable and connect it to an analog numeric (don’t forget to change the presentation format to string). Exercise 3a – Serial Port Exercise
  • 102.
     Write codethat receives data from the barcode reader  The barcode reader uses 9600 bps, 8 databits, None Parity and 1 stopbit Exercise 3b – Serial Port Exercise
  • 103.
    Exercise 3c –Serial Port  Reuse the code from 7a. The goal is to connect the panel to a GSM modem and send SMS via script.  The AT-command to send a SMS is:  Panel -> Modem: “AT+CMGS=+46703358477<CR>”  Modem -> Panel: “<CR><LF>> “ (in total 4 characters, the third is ‘>’  Panel -> Modem: “SMS Message<ctrl-Z>” Pseudo code −Initialize Port (and hook up DataReceived event) −Store the message in an instance variable −Send first message −Wait for a data received event −Evaluate the data received – is it a proper reply? −Yes? Send the second part of the request Character Hex code <CR> 0x0D <ctrl-z> 0x1A Exercise
  • 104.
    TCP Client -Init  The TcpClient object allows an application to connect to a TCP-server and exchange data.  TcpClient is part of the System.Net.Sockets framework. Ethernet
  • 105.
    TCP Client –Send data  Data can be sent to the server by using the Write function.  In this example a byte array is populated with a valid Modbus request and then sent to the Modbus TCP-server Ethernet
  • 106.
    Ethernet – Receivedata  The stream’s Read function can be used to receive a reply from the TCP-server.  Note! The Read function is blocking until a time out or data is received. Therefore this should typically be carried out in a Thread. This is not covered in this basic course. Ethernet
  • 107.
     Implement abasic Modbus request, send it to a Modbus Simulator  Receive the reply, make sure it’s a valid Modbus reply (length). Parse the value from the reply and display it in an internal variable. Exercise 4 – Ethernet Exercise
  • 108.
     A timercan be used when you want to execute some actions at a certain interval Timers Timers
  • 109.
     We wantto create a basic data logger  Every 5 seconds we should save a few tag values in a text file − Add a timer that executes every 5 seconds − Append text to a text file (use the System.IO.File.AppendAllText function, a new line (a.k.a <CR>) can be added with Environment.NewLine) Exercise 5 – Timers Exercise
  • 110.
    Exercise – Solutionsuggestion Exercise
  • 111.
    Debug application withVisual Studio 2010  Microsoft Visual Studio Express 2010 can be used to debug scripts. It’s available free of charge from microsoft’s website.  Add the path to visual studio. Then you only need to click on the debug button, this means that Visual studio will start automatically preloaded with all source files. Debug iX Application
  • 112.
    Referenced Assemblies  Sometimesa customer might want to use a .NET class library in his/her application. A class library is compiled to a dll.  In iX Developer it’s possible to add referenced assemblies via the Project Tab. Referenced Assembly
  • 113.
     Create aClass library in Visual studio  Copy/paste the code from the E-mail sample (from yesterday’s exercises)  Compile the solution, a dll will be generated  Reference and use this dll in an iX PC application Exercise 6 – Referenced assemblies Exercise
  • 114.
    Samples  Database  ISchedulerJob Syncronize HMI with PLC clock Source: Scipting Mode [F1] Samples
  • 115.
    iX Objects –Properties/Functions  Mutiple Languages
  • 116.
    iX Objects –Properties/Functions  Line object
  • 117.
    iX Objects –Properties/Functions  Rectangle object
  • 118.
    iX Objects –Properties/Functions  Ellipse object
  • 119.
    iX Objects –Properties/Functions  Polyline object
  • 120.
    iX Objects –Properties/Functions  Analog Numeric object
  • 121.
    iX Objects –Properties/Functions  Button object
  • 122.
    iX Objects –Properties/Functions  Picture object
  • 123.
    iX Objects –Properties/Functions  MultiPicture object
  • 124.
    iX Objects –Properties/Functions  AnimatedGIF object
  • 125.
    iX Objects –Properties/Functions  Linear meter object
  • 126.
    iX Objects –Properties/Functions  Slider object
  • 127.
    iX Objects –Properties/Functions  CircularMeter object
  • 128.
    iX Objects –Properties/Functions  TrendViewer object
  • 129.
    iX Objects –Properties/Functions  Chart object
  • 130.
    iX Objects –Properties/Functions  ActionMenu object
  • 131.
    iX Objects –Properties/Functions  AnimatedLabel object
  • 132.
    iX Objects –Properties/Functions  TouchComboBox object
  • 133.
    iX Objects –Properties/Functions  TouchListBox object
  • 134.
    iX Objects –Properties/Functions  RollerPanel object
  • 135.
    iX Objects –Properties/Functions  DigitalClock object
  • 136.
    iX Objects –Properties/Functions  AlarmViewer object
  • 137.
    iX Objects –Properties/Functions  AuditTrailViewer object
  • 138.
    iX Objects –Properties/Functions  MediaPlayer object
  • 139.
    iX Objects –Properties/Functions  PDFViewer object
  • 140.
    Develop a WPF-Control Start Visual Studio 2010  Create a Class Library project, this means that the control will be embedded in a dll (that can be imported or referenced in iX Developer).
  • 141.
    Develop a WPF-Control Add a new Item to the application (Add -> New Item).  Select User Control (WPF), give the control a name.
  • 142.
    Develop a WPF-Control- XAML  This control will only contain a TextBox  The TextBox’s Text property is bound to a property called Value, ElementName should be set to the name of the UserControl.
  • 143.
    Develop a WPF-Control– C# Step 1/6  Add using System.ComponentModel to the code.  Add [DefaultProperty("Value")] to the class, to define which property the tag should be connected to.
  • 144.
    Develop a WPF-Control– C# Step 2/6  Add a dependency property with same name as the attribute in step 1 (Value) − static readonly DependencyProperty ValueProperty;
  • 145.
    Develop a WPF-Control– C# Step 3/6  Add a static constructor and register the dependency property.
  • 146.
    Develop a WPF-Control– C# Step 4/6  Create a Value property of type object.
  • 147.
    Develop a WPF-Control– C# Step 5/6  Create a Value property of type object.
  • 148.
    Develop a WPF-Control– C# Step 6/6  Compile the Visual studio solution  If the compilation is successful a dll will be generated  The dll can now be imported to iX Developer, it will be possible to connect a tag directly to the control (just as for normal iX-objects).
  • 149.
    Pitfalls – Timers For a timer it’s not enough to unhook the event handler  It’s very important that the timer is disabled (.Enabled = false)  Example: Pitfalls
  • 150.
    Pitfalls – OPC Let’s say you want to detect that the value of a tag/analog numeric is changed. Depending on the value you want to execute different actions  The problem is that the value in the analog numeric is changed but there is small delay before the OPC-server gets the new value  This means that the we compare the old value of tag1 with 10 (and not the value that was inserted in the analog numeric)  Solution: Use the tags ValueChange event instead Pitfalls
  • 151.
    Pitfalls – Eventhandlers  Memory leak when using events is very common if an eventhandler is not unhooked  Example: Pitfalls
  • 152.
    Scripting  [Ctrl] +[Space] − Intellisense, drops the meny  [Ctrl] + [K] + [L] − Listing Members  [Ctrl] + [Shift] + [Space] − Parameter/argument information  [Ctrl] + [K] + [X] − Displays Code Snippets  [Tab] − Completes word in intellisense  [Ctrl] + [H] − Search and replace, opens dialog Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works! Source: Scripting Mode Help [F1] Key Shortcuts
  • 153.
    Scripting  [Ctrl] +[F] − Find, opens dialog  [Ctrl] + [F3] − Find next  [Ctrl] + [E] + [C] − Comment out the selected lines  [Ctrl] + [E] + [U] − Uncomment the selected lines  [Ctrl] + [G] − Go to line Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works! Source: Scripting Mode [F1] Key Shortcuts
  • 154.
    Tables  [F4] − Expandsa listbox  [Enter] − Enters a typed in value  [Esc] − Leaves the cell, and remains unchanged  [Space] − Checks or unchecks checkboxes  [Ctrl] + [Tab] − Shifts between tabs Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works! Source: Scipting Mode [F1] Key Shortcuts