Component Sample

We will write our first component in C# and not in PerlNET, as you would expect. This choice is not casual, as the C# language was written especially for .NET, while considering all the tiniest details of this environment, and that is why the structure of programs written in C# is much closer to the structure of .NET assemblies. Therefore, it is rather natural to start advanced programming learning of any .NET-compliant language with C#, as we gain an additional insight into the .NET Framework. We will continue this approach of using C# to delve more deeply into .NET in Chapter 13.

C# Sample

Our example provides simple functionality of a stock item. The code resides in StockCs. Our class defines a constructor, two properties, and one method. The code is quite simple and intuitive. First, just read the code and try to understand it. Then, read our explanations following the listing. These explanations are brief, as C# is out of the scope of this book, but this is enough to understand the concept. You may refer to Appendix B for a more detailed discussion of C# and its syntax. Here is the code in C# for our sample.


//
// StockItem.cs
using System;

// Define namespace for class
namespace OI.Samples
{
   public class StockItem
   {
      // Member variables (fields) for storing
      // properties
      private int m_id;           // Item ID
      private string m_name;      // Item Name

      // Constructor
      public StockItem(int id, string name)
      {
         this.m_id = id;          // Initialize ID
         this.m_name = name;      // Initialize Name
      }
      // Definition of read-only ID property
      public int ID
      {
         // Only "get" function
         get
         {
            return m_id;
         }
      }
      // Definition of read-write Name property
      public string Name
      {
         // "get" and "set" functions
         get
         {
            return m_name;
         }
         set
         {
            m_name = value;
         }
      }
      // Output Item Information
      public void OutputItem(bool lines)
      {
         if (lines)
            Console.WriteLine("---------------------");

         Console.WriteLine("{0}	{1}",this.m_id,
                                      this.m_name);

         if (lines)
            Console.WriteLine("---------------------");
      }
   }
}

The StockItem.cs file defines the StockItem class in the OI.Samples namespace. We declared two private member variables for the class: m_id and m_name. The private modifier makes these variables inaccessible from outside, which means that they are visible only for the methods of the StockItem class. Every class must have a constructor.[2] In C#, a constructor must have the same name as the class. In our case, the constructor has the following prototype:

[2] If you do not define a constructor, then the C# compiler will generate the default constructor that accepts no arguments and has an empty body. As we will see later, this is true for PerlNET as well.

StockItem(int id, string name);

As you can see, the constructor expects two parameters, id and name, whose values are assigned to m_id and m_name respectively.

Next, we have the read-only ID property defined. In programs that use the StockItem class, we would not be able to set this property. In addition, we defined the Name property, which is read-write. This means that we would be able to get and set it using all known ways to do it.

Finally, we defined the public method for performing output of stock item details:

public OutputItem(bool lines);

This method expects one boolean parameter, lines. If lines is true, then lines are printed before and after the stock item details; otherwise, only stock item details are displayed.

As you probably noticed, the above class does not have Main function that we mention in Chapter 9 when we describe .NET program structure. It is not a mistake, as we will build the StockItem class as a library and not as an executable. This means that we cannot use StockItem as a standalone program, because we intend it to be referenced and used in other .NET programs.

First, let us build the StockItem library. This can be easily done with the C# command line compiler csc.exe:[3]

[3] Optionally, you may double-click the solution file in the sample directory and open it in Visual Studio.NET, where you can build your applications or components with F7. In Appendix A, we explain how to use Visual Perl. In case of C# projects, the keyboard shortcuts are the same as in Visual Perl.

csc /target:library StockItem.cs

As a result of running the above command, StockItem.dll will be created. Other .NET programs can use this library now in order to work with the StockItem class.

PerlNET Client Program

To make our demonstration complete, we present a program in which we reference the StockItem class and illustrate its usage. Such a program may be referred to as a client program, as it makes use of the StockItem component-provided functionality. All the principles of using .NET components in the PerlNET programs we learned in the previous chapter remain in force when we work with custom components (ones that are not part of .NET Framework). Therefore, the code we write in PerlNET for our client program of the StockItem component will look familiar and comprehensible to you.

We wrote the PerlNET client program, which reflects the common way of custom .NET components usage. You may find it in the StockStockItemCli directory under the chapter samples directory. Here is the code for this program.


#
# StockItemCli.pl
#
use strict;
use namespace "System.Collections";
use namespace "OI.Samples";
use PerlNET qw(AUTOCALL in);

$| = 1;
my $items = ArrayList->new();

# Create 5 items and add them to collection
for(my $i = 0; $i < 5; $i++)
{
   my $item = StockItem->new(int($i), "item " . $i);
   $items->Add($item);
}

# Output second item
$items->[1]->OutputItem(PerlNET::true);

# Output all 5 items
print "-------------------------
";
foreach my $item(in $items)
{
   $item->OutputItem(PerlNET::false);
}
print "-------------------------
";

# Access read-only property
print "ID of Second Item: ";
print $items->[1]->{ID}, "
";

# Access read-write property
print "Name of Second Item: ";
print $items->[1]->{Name}, "
";
# Alter read-write property
$items->[1]->{Name} = "Pencil";
print "New Name of Second Item: ";
print $items->[1]->{Name}, "
";

Before running and examining the output of this program, we should clarify several important points. Recall the C# code for the StockItem component where we defined the OI.Samples namespace. This namespace exposes the StockItem class. Hence, in order to be able to use the unqualified name StockItem, we write

use namespace "OI.Samples";

We construct the StockItem class objects by calling the new method, as for every other .NET class.

my $item = StockItem->new(int($i), "item " . $i);

Now, after the code is ready, let us try to compile it with the usual plc command that we learned to use in Chapter 10.

plc StockItemCli.pl

Run this command in the sample directory and examine the output. Despite that we did not make any syntax errors, the compilation was not successful. The error message will be similar to this:

D:DOCUME~1ADMINI~1LOCALS~1Temp432.cs(7,7): error CS0246: The type or namespace name
 'OI' could not be found (are you missing a using directive or an assembly reference?)
Stopped with exit code 1

So, what did we do wrong? Well, we forgot to tell the compiler where to look for the OI.Samples namespace, which exposes the StockItem class. As you remember, prior to writing our client program, we built a library for the StockItem component, StockItem.dll, and now we should reference it by modifying our command line as follows:

plc StockItemCli.pl -reference=StockItem.dll

Referenced Components

The referenced component should reside in the same directory as the client program. Otherwise, we have to write the path to the DLL (dynamic-link library) when referencing it. In any case, when running the client exe-program, our DLL should be in the same directory as our executable. In order to assure the correct functioning of the sample programs, please compile the component first and then copy the resulting DLL to the client program folder. Refer to the readme.txt file in the chapter's samples directory for more details.


Now, as StockItemCli.exe was built successfully, we may run it and get the following output:

-------------------------
1     item 1
-------------------------
-------------------------
0     item 0
1     item 1
2     item 2
3     item 3
4     item 4
-------------------------
ID of Second Item: 1
Name of Second Item: item 1
New Name of Second Item: Pencil

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.111.33