Documente Academic
Documente Profesional
Documente Cultură
.Net
Managed Code
Garbage Collection
C#
.Net
.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)
.Net
Managed Code
Garbage Collection
C#
Managed Code
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
System Runtime
.Net CLR
.Net
Managed Code
Garbage Collection
C#
Garbage Collection
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
.Net
Managed Code
Garbage Collection
C#
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
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
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
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):
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.
Variables
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
It’s possible to access characters in the string with the following syntax:
Variables
Build a string (e.g one string variable and one constant string)
Variables
Uppercase/Lowercase:
Replace
Contains
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
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:
Exercise
Message box
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
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.
Coding Style
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
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
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:
Exercise
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
Flow Control
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
If you want to execute the same code a specific number of times then a for-loop can be used
Flow Control
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
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
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)
Exercise
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
Collections
Arrays
It’s possible to easily access elements inside of the array. This makes it possible to
loop through all elements quickly
Collections
Arrays
List
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
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
The Watch window allows the user to add any (local/global) object to
the list (drag/drop or write name directly)
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.
OOP
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
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.
Exercise
C# scripting in iX Developer
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
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
The Script Editor supports Code snippets. Press CTRL+K+X and select which function that
should be added:
iX Events
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
Exercise 1a – Event
Script module
Script module
− Global Script
− Possible to execute from other scripts
− Possible to re-use scripts
− Easier to maintain
Script Module
Script module
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
Script Module
Script module
Why is it easier to maintain a function in the Script module compared to copy/paste code?
Screen 6
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
Exercise
Why is it easier to maintain a function in the Script module compared to copy/paste code?
Screen 6
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
Read/Write 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 to file – tell the function where the file should be stored and the text that should be
saved
Read/Write File
Read from file – tell the function where the file is located
Make sure that the file exists before attempting to open it (File.Exists)
Exercise
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
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
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:
Exercise
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
Pseudo code
−Initialize Port (and hook up DataReceived event)
−Store the message in an instance variable Character Hex code
−Send first message
−Wait for a data received event <CR> 0x0D
−Evaluate the data received – is it a proper reply?
−Yes? Send the second part of the request
<ctrl-z> 0x1A
Ethernet
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
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.
Exercise
Exercise 4 – Ethernet
Timers
A timer can be used when you want to execute some actions at a certain interval
Exercise
Exercise 5 – Timers
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.
Referenced Assembly
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.
Exercise
Samples
Database
ISchedulerJob
Syncronize HMI with PLC clock
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
Button object
iX Objects – Properties/Functions
Picture object
iX Objects – Properties/Functions
MultiPicture object
iX Objects – Properties/Functions
AnimatedGIF 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
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
Pitfalls – Timers
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)
Memory leak when using events is very common if an eventhandler is not unhooked
Example:
Key Shortcuts
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
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
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