14.11.2019 Views

BEIJER-Slides-4-Training HMI iX Scripting [en]

BEIJER - HMI iX Slide da Formação Técnica iX - Script C# [en] Da empresa BRESIMAR AUTOMAÇÃO (Aveiro / Portugal) Autoria: BEIJER ELECTRONICS

BEIJER - HMI iX
Slide da Formação Técnica iX - Script C# [en]
Da empresa BRESIMAR AUTOMAÇÃO (Aveiro / Portugal)
Autoria: BEIJER ELECTRONICS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>iX</strong> <strong>HMI</strong> solution - <strong>Scripting</strong><br />

The world's most graphic <strong>HMI</strong> solution. Truly op<strong>en</strong>.


Cont<strong>en</strong>ts of course<br />

Day 1<br />

• C# Introduction<br />

• Getting started with VS 2010<br />

• Declaring variables<br />

• Data type conversion<br />

• MessageBox<br />

• Flow control (if, switch, for,<br />

foreach)<br />

• Writing methods/functions<br />

• Exception handling<br />

• Array and Collections<br />

• Debug<br />

• Object Ori<strong>en</strong>ted Programming<br />

(basics – if time is available)<br />

Day 2<br />

• <strong>Scripting</strong> in <strong>iX</strong><br />

• <strong>iX</strong> Specific scripting<br />

− Access to tags<br />

− Access to scre<strong>en</strong>s<br />

− Services<br />

− Media Objects<br />

• Script Module<br />

• <strong>iX</strong> Ev<strong>en</strong>ts<br />

• Write/read data from file<br />

• Timers<br />

• Serial Port handling<br />

• Ethernet<br />

• Refer<strong>en</strong>ced assembly<br />

• Samples (Scheduler, Database,<br />

etc.)<br />

• Pitfalls


Day 1 – C# basic concepts<br />

The world's most graphic <strong>HMI</strong> solution. Truly op<strong>en</strong>.


What is .Net and C#?<br />

• .Net<br />

• Managed Code<br />

• Garbage Collection<br />

• C#


.Net<br />

.Net in a nutshell<br />

• .Net Framework:<br />

− Consists primarily of a gigantic library of code to be used by the programmer<br />

− Using object-ori<strong>en</strong>ted programming techniques (OOP)<br />

• Common Type System (CTS):<br />

− A Type is a repres<strong>en</strong>tation of data<br />

− Common to all .Net programming languages as C#, VB.Net, Managed C++, F#, J#<br />

• Common Language Runtime (CLR)<br />

− Acting as a shell were .Net application executes within.<br />

A wellstructured, strict and complete program developm<strong>en</strong>t platform<br />

Source: Beginning Visual C# 2005


What is .Net and C#?<br />

• .Net<br />

• Managed Code<br />

• Garbage Collection<br />

• C#


Managed Code<br />

Managed Code<br />

• Managed Code<br />

− Common Language Runtime (CLR) looks after your application by managing memory,<br />

handling security, allowing cross-language debugging etc<br />

− Application(s) not running under the control of CLR are called Unmanaged Code<br />

System Runtime<br />

.Net CLR<br />

Native<br />

Code<br />

Native<br />

Code<br />

Native<br />

Code<br />

Your array-index out-of-bounds are catched, instead of crashing your application<br />

Source: Beginning Visual C# 2005


What is .Net and C#?<br />

• .Net<br />

• Managed Code<br />

• Garbage Collection<br />

• C#


Garbage Collection<br />

Garbage Collection<br />

• Garbage Collection<br />

− Works by inspecting the memory of your computer every so oft<strong>en</strong> and removing<br />

anything from it that is no longer needed<br />

− Prev<strong>en</strong>ts Memory Leak<br />

− Simple to invoke Garbage Collection wh<strong>en</strong> ever needed<br />

Automatic functions to prev<strong>en</strong>t hard-to-find Memory Leakage bugs<br />

Source: Beginning Visual C# 2005


What is .Net and C#?<br />

• .Net<br />

• Managed Code<br />

• Garbage Collection<br />

• C#


C#<br />

C#<br />

• C-Sharp<br />

− Inv<strong>en</strong>ted <strong>en</strong>tirely for .Net and is it’s main programming language<br />

− The only language fully supported by the CLR<br />

− Strong heritage from C/C++ and Java’s sleek OOP implem<strong>en</strong>tation<br />

− Type-safe, clear rules how to convert data from one type to other<br />

• What kind of Applications Can I Write with C#<br />

− Windows applications<br />

− Web Applications ASP.Net using “Code-Behind” that can use the same class librarys as<br />

for your Windows applications<br />

− Distributed solutions, cli<strong>en</strong>t programs that uses server applications as their internal<br />

code, making applications changes to a <strong>en</strong>tire computer infrastructure on a click<br />

− …and many other types with the main three as their ancestors<br />

Brings the power to your ideas<br />

Source: Beginning Visual C# 2005


First Application<br />

Getting Started – First Application<br />

• The objective is to create a basic application in Visual Studio 2010<br />

• First step is to create a new Application:


First Application<br />

Getting Started – First Application<br />

• Select Windows Forms Application<br />

• Give the application a name and press OK


First Application<br />

Getting Started – Properties<br />

• It’s possible to customize objects and forms. Each object has a number of<br />

properties that controls it’s look and behavior<br />

• Change the form’s Text property to “Name Pres<strong>en</strong>ter”


First Application<br />

Getting Started – Toolbox<br />

• The Toolbox contains objects that can be placed in the form<br />

• Add a label to the form, change it’s Name property to lblName and Text to<br />

“Please <strong>en</strong>ter your name: ”:


First Application<br />

Getting Started – Toolbox<br />

• Add a TextBox below the Label and a Button as well<br />

• The Name of the TextBox should be txtName and the button btnOK<br />

• Adjust the size of the form


First Application<br />

Getting Started – Button click ev<strong>en</strong>t<br />

• Double click on the Button, the script editor will op<strong>en</strong>. An ev<strong>en</strong>t procedure for<br />

the Button click has be<strong>en</strong> added automatically.<br />

• Add the following code inside the ev<strong>en</strong>t:


First Application<br />

Getting Started – Test/Run application<br />

• Click on the Play button (or F5), the application will now be compiled and a<br />

debug session will start (if there are no compile errors):


Exercise<br />

Exercise 1 - Getting Started<br />

• Create your first application.<br />

• It should contain two labels (Name and Age).<br />

• Two textboxes shall be added as well (where the user can insert his name and<br />

age).<br />

• A button should op<strong>en</strong> a MessageBox that informs the user about his Name and<br />

age.


Syntax<br />

Syntax<br />

• The keyword using declares “short cuts” to differ<strong>en</strong>t frameworks that you want<br />

to use in your code.<br />

• “{“ indicates start of a Namespace, class, function, statem<strong>en</strong>t and “}” indicates<br />

<strong>en</strong>d.


Variables<br />

Declaring variables<br />

• Variables are id<strong>en</strong>tifiers associated with values. They are declared by writing the variable's<br />

type and name, and are optionally initialized in the same statem<strong>en</strong>t by assigning a value.


Declaring variables - .NET data types<br />

Variables


Variables<br />

Declaring variables – Int variable<br />

• Declare an integer variable<br />

• Initialize it with a value<br />

• Carry out a calculation<br />

• Display the result in a MessageBox


Variables<br />

Int variables in calculations?<br />

• Declare an integer variable<br />

• Carry out a division calculation<br />

• Display the result in a MessageBox<br />

• The result will always be rounded up/down. We need to use another kind of data<br />

type to get decimal precision.


Variables<br />

Declaring variables – Float variable<br />

• Declare a float variable<br />

• Initialize it with a value<br />

• Carry out a floating point calculation<br />

• Display the result in a MessageBox


Variables<br />

Declaring variables – Boolean variable<br />

• A boolean variable can be either true or false.<br />

• It’s typically used wh<strong>en</strong> creating logic (for an example if- or while-statem<strong>en</strong>t)


Variables<br />

Declaring variables – String Variable<br />

• A string is an immutable, fixed-l<strong>en</strong>gth string of Unicode-characters<br />

• Strings literals are <strong>en</strong>closed with double quotes, e.g. “abcd”. Characters are <strong>en</strong>closed with<br />

single quotes e.g ‘x’. Strings and characters can be concat<strong>en</strong>ated with the + operator.<br />

• It’s possible to access characters in the string with the following syntax:


Variables<br />

String handling – Useful functions<br />

• Get l<strong>en</strong>gth of string<br />

• Split string with delimiter<br />

• Build a string (e.g one string variable and one constant string)


Variables<br />

String handling – Useful functions<br />

• Uppercase/Lowercase:<br />

• Replace<br />

• Contains


Variables<br />

String handling - Effici<strong>en</strong>cy<br />

• A string is an immutable sequ<strong>en</strong>tial collection of Unicode characters, typically used to<br />

repres<strong>en</strong>t text. A String is called immutable because its value cannot be modified once it has<br />

be<strong>en</strong> created.<br />

• Methods that appear to modify a String actually return a new String containing the<br />

modification. If it is necessary to modify the actual cont<strong>en</strong>ts of a string-like object,<br />

System.Text.StringBuilder class is more effici<strong>en</strong>t. This class allows string modifications to be<br />

done without the overhead of object creation and garbage collection.<br />

Approximately 24 seconds to execute<br />

Approximately 0,016 seconds to execute


Variables<br />

Formatting strings<br />

• The String.Format method can be useful wh<strong>en</strong> building strings that should contain variable<br />

values.


Variables<br />

Formatting strings<br />

• With String.Format it’s also possible to format the variable’s value (e.g number of decimals,<br />

if it should be pres<strong>en</strong>ted in sci<strong>en</strong>tific way etc.)<br />

• The code section below shows some examples:


Variables<br />

Type conversion String Int, Float, etc…<br />

• Quite oft<strong>en</strong> it’s necessary to convert data types. For an example a string in a textbox to an<br />

Integer or Float (or vice versa).<br />

• The Convert class has a lot of converters, a few examples below:


Exercise<br />

Exercise 2 – Conversion, Formatting<br />

• Add two TextBox objects to your application.<br />

− One will be used to insert the Resistance of an Resistor, the other one will be used to insert the<br />

Curr<strong>en</strong>t.<br />

− Add a label.<br />

− Wh<strong>en</strong> the button is clicked the Voltage should be calculated and pres<strong>en</strong>ted in the label (V = R x I)<br />

− The result should be pres<strong>en</strong>ted with a maximum of two decimal digits.


Message Box<br />

Message box<br />

• A MessageBox can be used to inform the user/operator about for an example errors in the<br />

application<br />

• The MessageBox is possible to customize via differ<strong>en</strong>t parameters to the Show method<br />

• Example of “standard” MessageBox


Message Box<br />

Yes/No Message box<br />

• The MessageBox can also work as a Yes/No dialog<br />

• A DialogResult object can “catch” the result from the MessageBox (if the user selected Yes<br />

or No)<br />

• The result can be used to execute code dep<strong>en</strong>ding on the answer from the user<br />

• Example:


Exercise<br />

Exercise 3 - Message box<br />

• The purpose with this exercise is to detect if the user really wants to close the<br />

application.<br />

• The Form has an ev<strong>en</strong>t called FormClosing, add a MessageBox that asks the user<br />

if he/she wants to close the application or not<br />

• Hint: The ev<strong>en</strong>t has an in-parameter “e”. This object has a property called<br />

Cancel. If it’s set to true the application will not close.


Coding Style<br />

C# coding style<br />

• In order to create structured and readable code there are many ”laws” to follow, a few<br />

examples:<br />

− Use ind<strong>en</strong>tation<br />

− The object names should describe the function of the object (for an example loginButton,<br />

passwordTextBox)<br />

− Variable names should be descriptive and meaningful<br />

− Add comm<strong>en</strong>ts that explains the code (//)


Coding Style<br />

Ind<strong>en</strong>tation<br />

• Add ind<strong>en</strong>tation wh<strong>en</strong> using e.g<br />

− IF-statem<strong>en</strong>t<br />

− Loops<br />

− Functions/Methods<br />

• Use [TAB] to add an ind<strong>en</strong>tation


Coding Style<br />

Ind<strong>en</strong>tation – Bad Example<br />

• The code is very hard to ”read” – there is no flow


Ind<strong>en</strong>tation – Good Example<br />

Coding Style


Flow Control<br />

Comparison and loops<br />

• The execution of the code can be controlled with differ<strong>en</strong>t comparison/loop functions<br />

• Comparison statem<strong>en</strong>ts – If and Switch/Case<br />

• Loops – For, While, Do, ForEach


Flow Control<br />

If statem<strong>en</strong>t<br />

• With an IF-statem<strong>en</strong>t it’s possible to check if conditions are fulfilled. The if statem<strong>en</strong>t needs<br />

a boolean result, that is, true or false<br />

• Example


Flow Control<br />

If statem<strong>en</strong>t – Several conditions<br />

• Oft<strong>en</strong> an If-statem<strong>en</strong>t needs to consider several conditions. Typically AND (in C# syntax: &&)<br />

and OR (in C# syntax: ||)<br />

• AND Example:<br />

• OR Example:


Flow Control<br />

Switch/Case<br />

• Wh<strong>en</strong> you want to do sevaral comparisons on the same variable th<strong>en</strong> the SWITCH/CASE<br />

statem<strong>en</strong>t can be helpful<br />

• Syntax/Example:


Exercise<br />

Exercise 4 – If/Switch statem<strong>en</strong>ts<br />

• Insert a TextBox and a Button. Wh<strong>en</strong> the user clicks on the button a Switch statem<strong>en</strong>t shall<br />

check if the user wrote Red, Blue, Yellow or Gre<strong>en</strong>. If yes, change the color of the Form<br />

(Hint: this.BackColor).<br />

• Change the background color of the Form based on the calculated Voltage.<br />

− < 10 -> Yellow<br />

− > 10 and < 15 -> Gre<strong>en</strong><br />

− > 15 -> Red


Flow Control<br />

Loops<br />

• There are oft<strong>en</strong> situations wh<strong>en</strong> you need to execute the same code several times, for an<br />

example<br />

− Read 10 files<br />

− S<strong>en</strong>d e-mails to all service persons<br />

• C# supports a lot of differ<strong>en</strong>t loops, we will discuss:<br />

− For (fixed number of iterations)<br />

− While (loops until a certain condition is met)


Flow Control<br />

The for loop<br />

• If you want to execute the same code a specific number of times th<strong>en</strong> a for-loop can be used


Flow Control<br />

The while loop<br />

• The while loop will iterate until a certain condition is met<br />

• This means that the code can loop differ<strong>en</strong>t amount of times<br />

• An eternal loop will most likely cause a crash


Exercise<br />

Exercise 5 – For loop<br />

• Create a new application (WinForm).<br />

• Add a ComboBox to the Form.<br />

• Add a button, wh<strong>en</strong> it’s clicked a For loop shall be executed.<br />

• The loop shall populate the ComboBox with texts (Hint: ComboBox1.Items.Add(”Text”))


Methods<br />

Methods and functions<br />

• Why should I use methods and functions in my application?<br />

− Reduction of code duplication by offering re-usability<br />

− Simplifying program logic by decomposing the program into smaller blocks<br />

− Improving readability of the program


Methods<br />

Function – No return/in-parameters<br />

• If the function should not return a value th<strong>en</strong> the Return type should be void<br />

• Leave the area inside of (..) empty -> no in-parameters


Methods<br />

Methods – return a value<br />

• The return type tells the function what it should return<br />

• If there are no in-parameters th<strong>en</strong> leave the area inside of (..) empty -> no in-parameters


Methods<br />

Methods – receive in-parameters<br />

• If the method should take in-parameters th<strong>en</strong> they are included in the par<strong>en</strong>thesis<br />

• If several in-parameters should be used th<strong>en</strong> separate them with a “,”-character


Exercise<br />

Exercise 6 – Reusable methods<br />

• Create a new application (WinForms)<br />

• Write at least 5 functions<br />

−Add (add two numbers and return the result)<br />

−Subtract (subtract two numbers and return the result)<br />

−Multiply (multiply two numbers and return the result)<br />

−Divide (divide two numbers and return the result)<br />

−Calculate Circular Area (you can hard code PI to 3.14 or use Math.PI to get a more exact<br />

value)<br />

• What will happ<strong>en</strong> if you type in text instead of a number?


Error Handling<br />

Error handling<br />

• Exceptions are unforese<strong>en</strong> errors that happ<strong>en</strong> in your programs. Most of the time, you can,<br />

and should, detect and handle program errors in your code. For example, validating user<br />

input, checking for null objects, and verifying the values returned from methods are what<br />

you expect, are all examples of good standard error handling that you should be doing all<br />

the time.<br />

• However, there are times wh<strong>en</strong> you don't know if an error will occur. For example, you can't<br />

predict wh<strong>en</strong> you'll receive a file I/O error, run out of system memory, or <strong>en</strong>counter a<br />

database error. These things are g<strong>en</strong>erally unlikely, but they could still happ<strong>en</strong> and you want<br />

to be able to deal with them wh<strong>en</strong> they do occur. This is where exception handling comes in.


Error Handling<br />

Error handling<br />

• Id<strong>en</strong>tifying the exceptions you'll need to handle dep<strong>en</strong>ds on the routine you're writing. For<br />

example, if the routine op<strong>en</strong>ed a file with the System.IO.File.Op<strong>en</strong>Read() method, it could<br />

throw any of the following exceptions:<br />

− SecurityException<br />

− Argum<strong>en</strong>tException<br />

− Argum<strong>en</strong>tNullException<br />

− PathTooLongException<br />

− DirectoryNotFoundException<br />

− UnauthorizedAccessException<br />

− FileNotFoundException<br />

− NotSupportedException<br />

• It's easy to find out what exceptions a method can raise by looking in the .NET Frameworks<br />

SDK Docum<strong>en</strong>tation.


Error Handling<br />

Error handling<br />

• Wh<strong>en</strong> exceptions are thrown, you need to be able to handle them. This is done by<br />

implem<strong>en</strong>ting a try/catch block<br />

• Code that could throw an exception is put in the try block and exception handling code goes<br />

in the catch block<br />

• Examples (try + try with specific exception)


Exercise<br />

Exercise 7 – Error handling<br />

• Make sure that the application does not crash if you for an example:<br />

− Divide by zero<br />

− Try to op<strong>en</strong> a file that does not exist on the PC


Collections<br />

Arrays<br />

• Arrays works as collections of items, for instance string or integers<br />

• Useful wh<strong>en</strong> working with many items of the same type, for an example user name<br />

or constants<br />

• Arrays are 0-based and of fixed size<br />

• It’s possible to easily access elem<strong>en</strong>ts inside of the array. This makes it possible to<br />

loop through all elem<strong>en</strong>ts quickly


Collections<br />

Arrays<br />

• Loop through an array:


Collections<br />

List<br />

• The List object is a collection of a specific defined object type.<br />

• An array is always fixed size (it’s possible to resize but not very conv<strong>en</strong>i<strong>en</strong>t), the<br />

List object has functions for Add, Remove, Search etc. This makes life easier…


Debugging<br />

Debug an application<br />

• Wh<strong>en</strong> developing code it’s oft<strong>en</strong> necessary to debug and trouble shoot the code. There are<br />

many differ<strong>en</strong>t techniques, for an example:<br />

− Using Visual Studio’s built-in Debugger (makes it possible to Execute code ”row for row”, look at<br />

differ<strong>en</strong>t objects in the memory etc).<br />

− Printing debug messages (from the code)<br />

• This training will focus on Visual Studio’s debug capabilities<br />

• The first step is to start the Debug Session<br />

− F5<br />

− Gre<strong>en</strong> Play button<br />

− M<strong>en</strong>u (Debug -> Start Debug Session)


Debugging<br />

Debugging - Breakpoint<br />

• Wh<strong>en</strong> running the code it can be useful to add breakpoints. This way the Debugger halts<br />

wh<strong>en</strong> the selected row(s) is reached.<br />

• To add a breakpoint click on the desired row, wh<strong>en</strong> it has be<strong>en</strong> added the row changes color<br />

to red:<br />

• Wh<strong>en</strong> the code is reached Visual Studio will get focus and the color is changed to Yellow. By<br />

hoovering the cursor over an objects it’s possible to see it’s curr<strong>en</strong>t value:


Debugging<br />

Debugging – Step through code<br />

• It’s oft<strong>en</strong> necessary to execute code ”row by row”. There are three differ<strong>en</strong>t debug actions<br />

for stepping through the code:<br />

• Step Over (F10): Executes the curr<strong>en</strong>t row, never jumps into Functions.<br />

• Step Into (F11): Executes the curr<strong>en</strong>t row, if it’s a function call it will step into that<br />

Function and allow you to debug this as well.<br />

• Step Out (Shift + F11): This function can be used if you have stepped in to a Function but<br />

th<strong>en</strong> change your mind. Be executing this function you are returned to the previous row<br />

(calling the function).


Debugging<br />

Debugging – Locals/Watch window<br />

• The Locals window shows all local variables (wh<strong>en</strong> a breakpoint is<br />

<strong>en</strong>tered)<br />

• The Watch window allows the user to add any (local/global) object to<br />

the list (drag/drop or write name directly)<br />

• Both windows gives the user possibility to change object’s values


Debugging<br />

Debugging – Immediate window<br />

• The Immediate window allows the developer to test custom lines of<br />

code directly. For an example:


Debugging<br />

Debugging – Print Debug<br />

• If the code execution is time critical normal debugging might not be<br />

suffici<strong>en</strong>t. A quite common technique to use under such circumstances<br />

is ”Print debugging”<br />

• The System.Diagnostics.Debug object can be used to print debug<br />

messages to the output window:


OOP<br />

Developing our first Object<br />

• We are going to develop a small basic E-mail cli<strong>en</strong>t.<br />

• The first class that we will develop is an E-mail logic class, this object should have:<br />

− A field for the SMTP-server’s IP-address<br />

− A Property so that the IP-address can be changed<br />

− A function that s<strong>en</strong>ds the e-mail<br />

• The UI should look something like this:


Developing our first Object<br />

OOP


Exercise<br />

Exercise 8 – EmailLogic Object<br />

• Develop a UI similar to the one below, give all controls meaningful names (instead of<br />

standard TextBox1 etc.) .<br />

• Add a new Class to the application, name it EmailLogic. This Class shall contain a<br />

Constructor, a private Field for the IP, a Property so that the IP can be accessed and finally<br />

a function for s<strong>en</strong>ding an e-mail.<br />

• Test the application.


OOP<br />

Developing our second Object<br />

• In order to create a basic Address book we need to create a User object. It should have:<br />

− A field for the User name and E-mail address<br />

− A Constuctor<br />

− A read property for the E-mail address<br />

− A ToString method


Developing our second Object<br />

OOP


Exercise<br />

Exercise 8b – User Object<br />

• Add a new Class to the application<br />

• Name it User<br />

• Implem<strong>en</strong>t it according to the specification on the previous slide


OOP<br />

Developing our third Class/Object<br />

• The Users in the address book needs to be stored. We therefore need to develop a<br />

UserCollection object. It should have:<br />

− A field List, that will contain all Users.<br />

− A Property so that we can read/write to the List.<br />

− A Function that allows us to Add a user to the<br />

collection.


Exercise<br />

Exercise 8c – UserCollection Object<br />

• Add a new Class to the application<br />

• Name it UserCollection<br />

• Implem<strong>en</strong>t it according to the specification on the previous slide


Exercise<br />

Exercise 8d – Select/Add User UI<br />

• Develop a UI similar to the one below.<br />

• Create logic so that the application behaves like an E-mail cli<strong>en</strong>t with a basic Address book:


Day 2 – C# scripting in <strong>iX</strong> Developer<br />

The world's most graphic <strong>HMI</strong> solution. Truly op<strong>en</strong>.


<strong>Scripting</strong> in <strong>iX</strong><br />

C# scripting in <strong>iX</strong> Developer<br />

• Script language is C#, Full .NET framework is supported in<br />

PC/EPC-applications and Compact .Net framework in <strong>iX</strong> Panel<br />

applications<br />

• MSDN contains a lot of .NET related information<br />

− http://msdn.microsoft.com/<strong>en</strong>-us/library/67ef8sbd(VS.80).aspx<br />

• <strong>iX</strong> is ev<strong>en</strong>t driv<strong>en</strong>, objects fires ev<strong>en</strong>ts wh<strong>en</strong> certain conditions<br />

are met (for an example: ValueChange, Scre<strong>en</strong>Op<strong>en</strong>ed)<br />

• Scre<strong>en</strong> script<br />

• Controller script<br />

• Alarm server script<br />

• Script module<br />

− Global Script<br />

− Possible to execute from other scripts<br />

− Great tool in order to create Libraries with functions<br />

• The scripts can be debugged with Microsoft Visual Studio 2010.<br />

The express edition is free of charge!


Full vs compact framework<br />

• About 30 % of the full framework is supported by the compact framework<br />

• <strong>iX</strong> Developer supports the full framework wh<strong>en</strong> the target is PC and compact<br />

framework wh<strong>en</strong> the target system is <strong>iX</strong> Panels<br />

• <strong>iX</strong> Developer (2.0) will g<strong>en</strong>erate a compile error if the user attempts to use full<br />

framework functionality in a panel application:<br />

• A good overview of the biggest differ<strong>en</strong>ces are available at:<br />

− http://msdn.microsoft.com/<strong>en</strong>-us/library/2weec7k5(v=vs.90).aspx<br />

• Op<strong>en</strong>NetCF has made compact framework implem<strong>en</strong>tations that covers some of<br />

the gaps betwe<strong>en</strong> the full and compact framework:<br />

− http://www.op<strong>en</strong>netcf.com/Products/SmartDeviceFramework.aspx


<strong>Scripting</strong> in <strong>iX</strong><br />

Reuse code – Compon<strong>en</strong>t Library<br />

• Script code can be dragged/dropped betwe<strong>en</strong> the Compon<strong>en</strong>t library and the script editor.<br />

• This way you can build nice script libraries that can be re-used in other applications


<strong>Scripting</strong> in <strong>iX</strong><br />

Ev<strong>en</strong>t driv<strong>en</strong> programming<br />

• All scripts in <strong>iX</strong> are executed wh<strong>en</strong> a certain ev<strong>en</strong>t is fired, for an example<br />

− ValueChange<br />

− Scre<strong>en</strong>Op<strong>en</strong>ed<br />

− AlarmAcknowledge<br />

− Click<br />

− …<br />

• An ev<strong>en</strong>t can be fired wh<strong>en</strong> a user/operator executes an action (e.g Click on a button)<br />

• Ev<strong>en</strong>ts can also be fired wh<strong>en</strong> external ev<strong>en</strong>ts occurs. For an example wh<strong>en</strong> characters are<br />

received on the serial port


<strong>Scripting</strong> in <strong>iX</strong><br />

<strong>iX</strong> Ev<strong>en</strong>ts<br />

• Change view to Script<br />

• All objects/ev<strong>en</strong>ts are available in the list


<strong>Scripting</strong> in <strong>iX</strong><br />

Scripts – Code snippet<br />

• The Script Editor supports Code snippets. Press CTRL+K+X and select which function that<br />

should be added:<br />

• Use tab to jump betwe<strong>en</strong> the parameters in the statem<strong>en</strong>t


<strong>Scripting</strong> in <strong>iX</strong><br />

<strong>iX</strong> Ev<strong>en</strong>ts<br />

• A delegate method is added automatically wh<strong>en</strong> double clicking on an<br />

ev<strong>en</strong>t (wh<strong>en</strong> the text is bold a method is assigned to the ev<strong>en</strong>t)<br />

• The code inside of this method will be executed wh<strong>en</strong> the user clicks on<br />

the button


<strong>Scripting</strong> in <strong>iX</strong><br />

Access to <strong>iX</strong> objects<br />

• To access <strong>iX</strong> objects (e.g Tags, Recipe, Security) start with the keyword Globals<br />

• Example:


<strong>Scripting</strong> in <strong>iX</strong><br />

<strong>iX</strong> objects – Access to ev<strong>en</strong>t handlers<br />

• Detect a tag value change ev<strong>en</strong>t in one specific scre<strong>en</strong>


Exercise<br />

Exercise 1a – Ev<strong>en</strong>t<br />

• Create a new <strong>iX</strong>-application<br />

• Op<strong>en</strong> a MessageBox wh<strong>en</strong> a user clicks on a button<br />

• Add a script that op<strong>en</strong>s a MessageBox if the value of a tag exceeds 150


Exercise 1b – Ev<strong>en</strong>t via code<br />

• Add a Tag ValueChanged ev<strong>en</strong>t via code (in a Scre<strong>en</strong>).<br />

• Wh<strong>en</strong> the Tag changes it’s value, write it to an internal variable.


Script Module<br />

Script module<br />

• Script module<br />

− Global Script<br />

− Possible to execute from other scripts<br />

− Possible to re-use scripts<br />

− Easier to maintain


Script Module<br />

Script module<br />

• Why is it easier to maintain a function in the Script module compared to copy/paste<br />

code?<br />

Scre<strong>en</strong> 1<br />

Function1<br />

Scre<strong>en</strong> 2<br />

Function1<br />

Scre<strong>en</strong> 3<br />

Function1<br />

Scre<strong>en</strong> 4<br />

Function1<br />

Scre<strong>en</strong> 5<br />

Function1<br />

Scre<strong>en</strong> 6<br />

Function1<br />

• If the developer needs to modify the code he has to find all places where the code has<br />

be<strong>en</strong> duplicated, in this case 6 places<br />

• In a big application it’s likely that he will forget to modify the code in all places where<br />

it’s being used -> Unexpected behavior


Script Module<br />

Script module<br />

• Why is it easier to maintain a function in the Script module compared to copy/paste code?<br />

Scre<strong>en</strong> 1 Scre<strong>en</strong> 2 Scre<strong>en</strong> 3<br />

Scre<strong>en</strong> 4<br />

Script Module<br />

Function1<br />

Scre<strong>en</strong> 5<br />

Scre<strong>en</strong> 6<br />

• In this case the developer only needs to modify the function in the script module. This saves<br />

both time and reduces the likeliness of introducing bugs


Exercise<br />

Exercise - Script module<br />

• Why is it easier to maintain a function in the Script module compared to copy/paste code?<br />

Scre<strong>en</strong> 1 Scre<strong>en</strong> 2 Scre<strong>en</strong> 3<br />

Scre<strong>en</strong> 4<br />

Script Module<br />

Function1<br />

Scre<strong>en</strong> 5<br />

Scre<strong>en</strong> 6<br />

• In this case the developer only needs to modify the function in the script module. This saves<br />

both time and reduces the likeliness of introducing bugs


Read/Write File<br />

Write/read data to a text file<br />

• The .NET framework supports at least two differ<strong>en</strong>t ways to write/read data to/from a file,<br />

using either<br />

− StreamReader/StreamWriter objects<br />

− File object (System.IO)<br />

• System.IO.File contains several differ<strong>en</strong>t functions that allows you to handle files<br />

− Write<br />

− Read<br />

− Check if file exists<br />

− Move<br />

− …


Read/Write File<br />

Write data to a text file - Example<br />

• Write to file – tell the function where the file should be stored and the text that should be<br />

saved


Read/Write File<br />

Read data from a text file - Example<br />

• Read from file – tell the function where the file is located<br />

• Make sure that the file exists before attempting to op<strong>en</strong> it (File.Exists)


Exercise<br />

Exercise 2 – File handling<br />

• From now on all Functions should be placed in a script module.<br />

• Add two buttons to a scre<strong>en</strong>, one for saving text to a file and one for reading text from a file.<br />

• Don’t forget to add error handling (otherwise the application will crash if the file is removed,<br />

the path is faulty etc.).<br />

• Run the application, make sure that it works as expected


Serial Port<br />

Serial Port – Initialize port<br />

• The C# SerialPort object allows the application to op<strong>en</strong> a serial port and s<strong>en</strong>d/receive data.<br />

• S<strong>en</strong>ding data is easier than receiving data since all received data needs to be parsed and<br />

checked if it is correct (e.g checksum or <strong>en</strong>d character).<br />

• There are two differ<strong>en</strong>t ways of receiving data, “polled” mode (via a thread) or via a<br />

DataReceived ev<strong>en</strong>t.<br />

• The SerialPort class is part of the System.IO.Ports namespace.


Serial Port<br />

Serial Port – S<strong>en</strong>d data<br />

• The SerialPort class has two functions for writing data (Write and WriteLine).<br />

• In this example we will use the Write function, the in-parameter to this function is a string:


Serial Port<br />

Serial Port – Receive data<br />

• The easiest way to receive data from the SerialPort is to list<strong>en</strong> to it’s DataReceived ev<strong>en</strong>t.<br />

The problem with this ev<strong>en</strong>t is that it’s not easy to know wh<strong>en</strong> it’s fired (it could be fired<br />

wh<strong>en</strong> 8 characters have be<strong>en</strong> received and another time wh<strong>en</strong> 10 characters have be<strong>en</strong><br />

received).<br />

• To be sure that everything has be<strong>en</strong> received we need to know either how many bytes to<br />

expect in the reply or a checksum/<strong>en</strong>d character.<br />

• This basic sample just writes the received data to an internal string variable:


Exercise<br />

Exercise 3a – Serial Port<br />

• Write code that s<strong>en</strong>ds data from a TxA panel’s serial port to a PC (use HyperTerminal/LKA to<br />

s<strong>en</strong>d and receive strings)<br />

• Write code that can receive data from HyperTerminal. Store the received data in an internal<br />

variable and connect it to an analog numeric (don’t forget to change the pres<strong>en</strong>tation<br />

format to string).


Exercise<br />

Exercise 3b – Serial Port<br />

• Write code that receives data from the barcode reader<br />

• The barcode reader uses 9600 bps, 8 databits, None Parity and 1 stopbit


Exercise<br />

Exercise 3c – Serial Port<br />

• Reuse the code from 7a. The goal is to connect<br />

the panel to a GSM modem and s<strong>en</strong>d SMS via script.<br />

• The AT-command to s<strong>en</strong>d a SMS is:<br />

• Panel -> Modem: “AT+CMGS=+46703358477”<br />

• Modem -> Panel: “> “ (in total 4<br />

characters, the third is ‘>’<br />

• Panel -> Modem: “SMS Message”<br />

Pseudo code<br />

−Initialize Port (and hook up DataReceived ev<strong>en</strong>t)<br />

−Store the message in an instance variable<br />

−S<strong>en</strong>d first message<br />

−Wait for a data received ev<strong>en</strong>t<br />

−Evaluate the data received – is it a proper reply?<br />

−Yes? S<strong>en</strong>d the second part of the request<br />

Character<br />

<br />

<br />

Hex code<br />

0x0D<br />

0x1A


Ethernet<br />

TCP Cli<strong>en</strong>t - Init<br />

• The TcpCli<strong>en</strong>t object allows an application to connect to a TCP-server and exchange data.<br />

• TcpCli<strong>en</strong>t is part of the System.Net.Sockets framework.


Ethernet<br />

TCP Cli<strong>en</strong>t – S<strong>en</strong>d data<br />

• Data can be s<strong>en</strong>t to the server by using the Write function.<br />

• In this example a byte array is populated with a valid Modbus request and th<strong>en</strong> s<strong>en</strong>t to the<br />

Modbus TCP-server


Ethernet<br />

Ethernet – Receive data<br />

• The stream’s Read function can be used to receive a reply from the TCP-server.<br />

• Note! The Read function is blocking until a time out or data is received. Therefore this<br />

should typically be carried out in a Thread. This is not covered in this basic course.


Exercise<br />

Exercise 4 – Ethernet<br />

• Implem<strong>en</strong>t a basic Modbus request, s<strong>en</strong>d it to a Modbus Simulator<br />

• Receive the reply, make sure it’s a valid Modbus reply (l<strong>en</strong>gth). Parse the value from the<br />

reply and display it in an internal variable.


Timers<br />

Timers<br />

• A timer can be used wh<strong>en</strong> you want to execute some actions at a certain interval


Exercise<br />

Exercise 5 – Timers<br />

• We want to create a basic data logger<br />

• Every 5 seconds we should save a few tag values in a text file<br />

− Add a timer that executes every 5 seconds<br />

− App<strong>en</strong>d text to a text file (use the System.IO.File.App<strong>en</strong>dAllText function, a new line (a.k.a ) can<br />

be added with Environm<strong>en</strong>t.NewLine)


Exercise – Solution suggestion<br />

Exercise


Debug <strong>iX</strong> Application<br />

Debug application with Visual Studio 2010<br />

• Microsoft Visual Studio Express 2010 can be used to debug scripts. It’s available free of<br />

charge from microsoft’s website.<br />

• Add the path to visual studio. Th<strong>en</strong> you only need to click on the debug button, this means<br />

that Visual studio will start automatically preloaded with all source files.


Refer<strong>en</strong>ced Assembly<br />

Refer<strong>en</strong>ced Assemblies<br />

• Sometimes a customer might want to use a .NET class library in his/her application. A class<br />

library is compiled to a dll.<br />

• In <strong>iX</strong> Developer it’s possible to add refer<strong>en</strong>ced assemblies via the Project Tab.


Exercise<br />

Exercise 6 – Refer<strong>en</strong>ced assemblies<br />

• Create a Class library in Visual studio<br />

• Copy/paste the code from the E-mail sample (from yesterday’s exercises)<br />

• Compile the solution, a dll will be g<strong>en</strong>erated<br />

• Refer<strong>en</strong>ce and use this dll in an <strong>iX</strong> PC application


Samples<br />

Samples<br />

• Database<br />

• ISchedulerJob<br />

• Syncronize <strong>HMI</strong> with PLC clock<br />

Source: Scipting Mode [F1]


<strong>iX</strong> Objects – Properties/Functions<br />

• Mutiple Languages


<strong>iX</strong> Objects – Properties/Functions<br />

• Line object


<strong>iX</strong> Objects – Properties/Functions<br />

• Rectangle object


<strong>iX</strong> Objects – Properties/Functions<br />

• Ellipse object


<strong>iX</strong> Objects – Properties/Functions<br />

• Polyline object


<strong>iX</strong> Objects – Properties/Functions<br />

• Analog Numeric object


<strong>iX</strong> Objects – Properties/Functions<br />

• Button object


<strong>iX</strong> Objects – Properties/Functions<br />

• Picture object


<strong>iX</strong> Objects – Properties/Functions<br />

• MultiPicture object


<strong>iX</strong> Objects – Properties/Functions<br />

• AnimatedGIF object


<strong>iX</strong> Objects – Properties/Functions<br />

• Linear meter object


<strong>iX</strong> Objects – Properties/Functions<br />

• Slider object


<strong>iX</strong> Objects – Properties/Functions<br />

• CircularMeter object


<strong>iX</strong> Objects – Properties/Functions<br />

• Tr<strong>en</strong>dViewer object


<strong>iX</strong> Objects – Properties/Functions<br />

• Chart object


<strong>iX</strong> Objects – Properties/Functions<br />

• ActionM<strong>en</strong>u object


<strong>iX</strong> Objects – Properties/Functions<br />

• AnimatedLabel object


<strong>iX</strong> Objects – Properties/Functions<br />

• TouchComboBox object


<strong>iX</strong> Objects – Properties/Functions<br />

• TouchListBox object


<strong>iX</strong> Objects – Properties/Functions<br />

• RollerPanel object


<strong>iX</strong> Objects – Properties/Functions<br />

• DigitalClock object


<strong>iX</strong> Objects – Properties/Functions<br />

• AlarmViewer object


<strong>iX</strong> Objects – Properties/Functions<br />

• AuditTrailViewer object


<strong>iX</strong> Objects – Properties/Functions<br />

• MediaPlayer object


<strong>iX</strong> Objects – Properties/Functions<br />

• PDFViewer object


Develop a WPF-Control<br />

• Start Visual Studio 2010<br />

• Create a Class Library project, this means that the control will be embedded in a<br />

dll (that can be imported or refer<strong>en</strong>ced in <strong>iX</strong> Developer).


Develop a WPF-Control<br />

• Add a new Item to the application (Add -> New Item).<br />

• Select User Control (WPF), give the control a name.


Develop a WPF-Control - XAML<br />

• This control will only contain a TextBox<br />

• The TextBox’s Text property is bound to a property called Value, Elem<strong>en</strong>tName<br />

should be set to the name of the UserControl.


Develop a WPF-Control – C# Step 1/6<br />

• Add using System.Compon<strong>en</strong>tModel to the<br />

code.<br />

• Add [DefaultProperty("Value")] to the class,<br />

to define which property the tag should be<br />

connected to.


Develop a WPF-Control – C# Step 2/6<br />

• Add a dep<strong>en</strong>d<strong>en</strong>cy property with same name as the attribute in step 1 (Value)<br />

− static readonly Dep<strong>en</strong>d<strong>en</strong>cyProperty ValueProperty;


Develop a WPF-Control – C# Step 3/6<br />

• Add a static constructor and register the dep<strong>en</strong>d<strong>en</strong>cy property.


Develop a WPF-Control – C# Step 4/6<br />

• Create a Value property of type object.


Develop a WPF-Control – C# Step 5/6<br />

• Create a Value property of type object.


Develop a WPF-Control – C# Step 6/6<br />

• Compile the Visual studio solution<br />

• If the compilation is successful a dll will be g<strong>en</strong>erated<br />

• The dll can now be imported to <strong>iX</strong> Developer, it will be possible to connect a tag<br />

directly to the control (just as for normal <strong>iX</strong>-objects).


Pitfalls<br />

Pitfalls – Timers<br />

• For a timer it’s not <strong>en</strong>ough to unhook the ev<strong>en</strong>t handler<br />

• It’s very important that the timer is disabled (.Enabled = false)<br />

• Example:


Pitfalls<br />

Pitfalls – OPC<br />

• Let’s say you want to detect that the value of a tag/analog numeric is changed. Dep<strong>en</strong>ding on<br />

the value you want to execute differ<strong>en</strong>t actions<br />

• The problem is that the value in the analog numeric is changed but there is small delay before<br />

the OPC-server gets the new value<br />

• This means that the we compare the old value of tag1 with 10 (and not the value that was<br />

inserted in the analog numeric)<br />

• Solution: Use the tags ValueChange ev<strong>en</strong>t instead


Pitfalls<br />

Pitfalls – Ev<strong>en</strong>t handlers<br />

• Memory leak wh<strong>en</strong> using ev<strong>en</strong>ts is very common if an ev<strong>en</strong>thandler is not unhooked<br />

• Example:


Key Shortcuts<br />

<strong>Scripting</strong><br />

• [Ctrl] + [Space]<br />

− Intellis<strong>en</strong>se, drops the m<strong>en</strong>y<br />

• [Ctrl] + [K] + [L]<br />

− Listing Members<br />

• [Ctrl] + [Shift] + [Space]<br />

− Parameter/argum<strong>en</strong>t information<br />

• [Ctrl] + [K] + [X]<br />

• [Tab]<br />

− Displays Code Snippets<br />

− Completes word in intellis<strong>en</strong>se<br />

• [Ctrl] + [H]<br />

− Search and replace, op<strong>en</strong>s dialog<br />

Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works!<br />

Source: <strong>Scripting</strong> Mode Help [F1]


Key Shortcuts<br />

<strong>Scripting</strong><br />

• [Ctrl] + [F]<br />

− Find, op<strong>en</strong>s dialog<br />

• [Ctrl] + [F3]<br />

− Find next<br />

• [Ctrl] + [E] + [C]<br />

− Comm<strong>en</strong>t out the selected lines<br />

• [Ctrl] + [E] + [U]<br />

− Uncomm<strong>en</strong>t the selected lines<br />

• [Ctrl] + [G]<br />

− Go to line<br />

Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works!<br />

Source: <strong>Scripting</strong> Mode [F1]


Key Shortcuts<br />

Tables<br />

• [F4]<br />

− Expands a listbox<br />

• [Enter]<br />

• [Esc]<br />

− Enters a typed in value<br />

− Leaves the cell, and remains unchanged<br />

• [Space]<br />

− Checks or unchecks checkboxes<br />

• [Ctrl] + [Tab]<br />

− Shifts betwe<strong>en</strong> tabs<br />

Standard windows [Ctrl] + C(copy) / X(cut) / V(paste) always works!<br />

Source: Scipting Mode [F1]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!