Bits & Bytes

Posts Tagged ‘program’

Creating Multicast Delegates in C#

As stated in my prior post on C# delegates, a C# delegate is similar to a function pointer in C++. There, I gave a couple of examples of how to use delegates and said that I would cover multicast delagates later.

So, what is a multicast delegate? A multicast delegate is a function pointer that can be set to point to multiple functions at the same time. It calls each of them in order when it is called. Since a function can only return one value, multicast delegates must return a void type; that is, they must not have a return type.

The program below demonstrates how to use a multicast delegate. First, the delegate type DPrintMultipleOfNumber is declared. Then, inside the Main() function, we declare an instance of the delegate called pfnMulticast and initialize it with function OneTimes() that is defined below the Main() function. The next two lines add the functions TwoTimes() and ThreeTimes() to it via the =+ operator. Finally, we call all three of the functions via the delegate with the argument 13.

The output of the program looks like this:

UsingMulticast

Program.cs

using System;

namespace UsingMulticastDelegates {
    class Program {

        delegate void DPrintMultipleOfNumber(double dX);

        static void Main(string[] args) {
            DPrintMultipleOfNumber pfnMulticast = OneTimes;
            pfnMulticast += TwoTimes;
            pfnMulticast += ThreeTimes;
            pfnMulticast(13);
        }

        static void OneTimes(double dX) {
            Console.WriteLine("One times {0} is {1}", dX, dX);
        }

        static void TwoTimes(double dX) {
            Console.WriteLine("Two times {0} is {1}", dX, 2.0*dX);
        }

        static void ThreeTimes(double dX) {
            Console.WriteLine("Three times {0} is {1}", dX, 3.0*dX);
        }
    }
}

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[*/
. . .
/*]]>*/
. . .