Bits & Bytes

Posts Tagged ‘code’

Creating Timer Events in C#

If you want something to happen in a C# program at regular time intervals, the ideal way is to create a callback function that makes use of the Timer class. Below, I have created a class called CTimedObject that holds a Timer object. In the constructor, the Timer is allocated with a time interval of 2000 milliseconds or 2 seconds. Then OnTimedEvent() is set as a callback using the += operator and the Elapsed property. Finally, The Timer is started via a call to Start().

At this point, OnTimedEvent() will be called every 2 seconds. Inside the OnTimedEvent() function, the time is written to the console window via the passed in event object of type ElapsedEventArgs. The Object that is passed in is the Timer. Executing the program, the output looks like this

TimerEvent

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            CTimedObject qTimedObject = new CTimedObject();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }
    }
}

CTimedObject.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            Timer qTimer = new Timer(2000);
            qTimer.Elapsed += OnTimedEvent;
            qTimer.Start();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }

        static private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

The code above demonstrates how to use a Timer in an object. Alternatively, we could do the same thing more simply if we just want the event to fire with a static function. Below, we have code that does exacly the same thing without using a separate class.

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    public class CTimedObject {

        Timer mqTimer = null;

        public CTimedObject() {
            mqTimer = new Timer(2000);
            mqTimer.Elapsed += OnTimedEvent;
            mqTimer.Start();
        }

        private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

Using an External JavaScript File

Putting JavaScript into a separate file has many advantages over writing the code inline in an HTML file. First, it makes the JavaScript code much cleaner since the HTML code is in a separate file. Second, it helps to promote modularization, which is always a benefit in programming. Finally, it the eliminates the need for creating CDATA sections to encapsulate JavaScript code that contains XHTML characters; we will explain this more later

Beginning with the code from our earlier JavaScript post, we have a simple HTML file, which I have called “JavaScriptBasis.html” in this post. The original HTML code with the embedded JavaScript code looks like this:

Old JavaScriptBasis.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <title>XoaX.net</title>
</head>
<body>

<script type="text/javascript">
    document.write("Welcome to XoaX.net!");
</script>

</body>
</html>

What we want to do now is remove the JavaScript code, put it into a separate .js file, and call it via the script tag from the HTML file. To do this, use your favorite text editor to create a .js file called “BasicWrite.js” in the same directory as your HTML file and save it with this code pasted into it:

BasicWrite.js

document.write("Welcome to XoaX.net!");

Then open the file “JavaScriptBasis.html” and change code in the script tags to this:

<script type="text/javascript" src="BasicWrite.js"></script>

Now, your HTML file will call your JavaScript file. The code in the HTML file should look like this:

JavaScriptBasis.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <title>XoaX.net</title>
</head>
<body>

<script type="text/javascript" src="BasicWrite.js"></script>

</body>
</html>

After you have saved the new files, double-click the HTML file to open it and you should see the message “Welcome to XoaX.net!” printed just as you did before.

It may not feel like much has been accomplished yet. In fact, it might seem like we have made the code more complex. However, the advantages will become more apparent when we write bigger programs.

Finally, we remark that using .js files allows us to eliminate the need to use CDATA sections. When XHMTL characters, like <, are used inside of an embedded JavaScript section, they create validation problems. For example, in order to allow this code to validate, we need the CDATA section as shown here:

CDATA Section


<script type="text/javascript">
var iX = 10;
/*<![CDATA[*/
if (iX < 13) {
    document.write("Welcome to XoaX.net!");
}
]]>
/*]]>*/
</script>

When this code is put into an external JavaScript, this CDATA section is not needed for validation. Note that the CDATA section looks particularly horrific since it requires us to comment out both endpoints of the CDATA section so that it does not adversely affect the JavaScript code:
. . .
/*<![CDATA[*/
. . .
/*]]>*/
. . .

Arguments and Parameters

The terms argument and parameter are frequently used interchangeably, and there is often confusion about what these two terms mean. Arguments and parameters are two different things, but they are closely related. By definition, an argument is a value or variable that is passed into a function, and a parameter is value or variable that is used inside of a function. For illustration, look at the program below.

#include <iostream>

int Sum(int iP1, int iP2) {
    return iP1 + iP2;
}

int main () {
    int iA1 = 48;
    int iA2 = 24;

    std::cout << Sum(iA1, iA2) << std::endl;

    return 0;
}

The program contains takes in two int values and returns an int that is the sum of them. The two int values that the function takes in are called arguments, while the two values that are used inside the function are called parameters. To clarify this, we have named the variables that we used for the arguments, iA1 and iA2, and the two variables that we used for the parameters, iP1 and iP2. Correspondingly, "iA1, iA2" inside the function call is called the argument list and "int iP1, int iP2" inside the function definition is called the parameter list.

In the example above, the difference between the arguments and paramters is clear. The arguments and parameters refer to totally different memory locations because the arguments are both passed by value. In the program below, we have replaced the variables with the constant literals 48 and 24. In this program, these literals are the arguments.

#include <iostream>

int Sum(int iP1, int iP2) {
	return iP1 + iP2;
}

int main () {

    std::cout << Sum(48, 24) << std::endl;

    return 0;
}

In our last example below, we changed the function a bit; we pass the first argument by reference and use a default argument for the second. So, the arguments are iA and 45. The parameters are still iP1 and iP2. However, the first parameter is only a reference so changing its value changes the value of iA, as we would expect. Passing values by reference is probably one of the sources of confusion between arguments and parameters, but it is easy to understand if we remember that the parameter is only a reference; in fact, we could use any valid C++ data type as a parameter, including pointers, constants, etc.

#include <iostream>

void AddTo(int& iP1, int iP2 = 45) {
    iP1 += iP2;
}

int main () {
	int iA = 16;
	AddTo(iA);
	std::cout << iA << std::endl;

    return 0;
}
 

© 2007–2024 XoaX.net LLC. All rights reserved.