Authoring a Component with Visual J#
The document is archived and information here might be outdated

Walkthrough: Authoring a Component with Visual J#

Visual Studio 2005

Components provide reusable code in the form of objects. An application that uses a component's code, by creating objects and calling their properties and methods, is referred to as a client. A client may or may not be in the same assembly as a component it uses.

The procedures build on each other, so the order in which you perform them is important.

To create the CDemoLib class library and the CDemo component

  1. From the File menu, select New and then Project to open the New Project dialog box. Select the Class Library project template from the list of Visual J# projects, and enter CDemoLib in the Name box.

    NoteNote

    Always specify the name of a new project when you create it. Doing so sets the root package, assembly name, and project name, and also ensures that the default component will be in the correct package.

  2. Click OK.

  3. On the Project menu, click Add Component.

  4. In the Add New Item dialog box, select Component Class, and in the Name box, type CDemo.jsl. Click Add.

    A component named CDemo.jsl is added to your class library.

  5. In Solution Explorer, right-click CDemo.jsl, and click View Code. The Code Editor opens.

    Notice the code extends System.ComponentModel.Component immediately after public class CDemo. This designates the class from which your class inherits. By default, a component inherits from the Component class provided by the system. The Component class provides many features for your component, including the ability to use designers.

  6. In Solution Explorer, right-click Class1.jsl and click Delete.

    This deletes the default class that is provided with the class library, as it will not be used in this walkthrough.

  7. On the File menu, click Save All to save the project. The Save Project dialog box opens. The dialog box shows the Name, Location, and New Solution Name. You can change any of these items when you save the project.

  8. Click Save.

Constructors control the way your component is initialized; the Finalize method controls the way it tears down. Code in the constructor and the Finalize method of the CDemo class maintains a running count of the number of CDemo objects in existence.

To add code for the constructor and Finalize method of the CDemo class

  1. In the Code Editor, add member variables to the CDemo class to keep a running total of instances of the CDemo class, and an ID number for each instance.

    // Visual J#
    private long InstanceID;
    private static long NextInstanceID = 0;
    private static long ClassInstanceCount = 0;
    

    Because the ClassInstanceCount and NextInstanceID member variables are declared static, they exist only at the class level. All instances of CDemo that access these members will use the same memory locations. Shared members will be initialized the first time the CDemo class is referred to in code. This could be the first time a CDemo object is created, or the first time one of the class's shared members is accessed.

  2. Locate the constructors public CDemo() and public CDemo(System.ComponentModel.IContainer container).

    These are the default constructors for the CDemo class. Your component can have several constructors, with different parameters, but they must all have the same name as the class

    NoteNote

    The access level of a class's constructors determines what clients will be able to create instances of the class.

  3. Add the following code to public CDemo(), to increment the instance count when a new CDemo is created, and to set the instance ID number.

    NoteNote

    Always add your code after the call to InitializeComponent. At that point, any constituent components have been initialized.

    // Visual J#
    InstanceID = NextInstanceID ++;
    ClassInstanceCount ++;
    
    NoteNote

    Users familiar with multithreading will see that assigning InstanceID and incrementing NextInstanceID should be an atomic operation.

  4. Add the following method after the end of the constructor:

    // Visual J#
    protected void Finalize()
    {
        ClassInstanceCount --;
    }
    

    The memory manager calls Finalize just before it finally reclaims memory occupied by the CDemo object. The Finalize method originates with Object, the root of all reference types in the .NET Framework. By overriding Finalize, you can perform cleanup just before your component is removed from memory. However, as you will see, there are good reasons to release resources earlier.

The CDemo class has a member that allows the client to find out how many CDemo objects there are in memory at any given time.

To create a method to retrieve the number of instances of CDemo

  • Add the following method declaration to the CDemo class, to allow clients to retrieve the number of instances of CDemo.

    // Visual J#
    public static long getInstanceCount()
    {
        return ClassInstanceCount;
    }
    

To build the component

  • On the Build menu, click Build Solution.

    The build should succeed with no compiler errors or warnings.

To test the component, you need a project that uses it. This project must be the first project that starts when you press the Run button.

To add the CDemoTest client project as the startup project for the solution

  1. From the File menu, point to Add Project, and click New Project. The Add New Project dialog box opens.

  2. Click the Windows Application project template from the list of Visual J# projects, and in the Name box, type CDemoTest, and then click OK.

    This adds the new project to the solution, and opens Form1.jsl in the Designer view.

  3. In Solution Explorer, right-click CDemoTest, and on the shortcut menu, click Set as Startup Project.

To use the CDemo component, the client test project must have a reference to the class library project. After adding the reference, it is a good idea to add an import statement to the test application to simplify the use of the component.

To add a reference to the class library project

  1. In Solution Explorer, right-click the References node immediately beneath CDemoTest, and on the shortcut menu, click Add Reference.

  2. In the Add Reference dialog box, click the Projects tab.

  3. Double-click the CDemoLib class library project, to add it to the Selected Components list. CDemoLib will appear under the References node for the CDemoTest project.

  4. In Solution Explorer, right-click Form1.jsl, and on the shortcut menu, click View Code.

Adding the reference to CDemoLib allows you to use the fully qualified name of the CDemo component in your code; that is, CDemoLib.CDemo.

To add an import statement

  • Add the following import statement to the list of import statements at the top of the Code Editor for Form1.

    // Visual J#
    import CDemoLib.*;
    

    Adding the import statement allows you to omit the library name, and refer to the component type as CDemo.

    You will now create and use a test program to test your component.

The CDemoTest program will illustrate object lifetime in the .NET Framework by creating and releasing large numbers of CDemo objects.

To add code to create and release CDemo objects

  1. Right-Click Form1.jsl, and click View Designer to open the Design view.

  2. Drag a button and a timer from the All Windows Forms tab of the Toolbox onto the Form1 design surface.

    The timer1 component icon appears on a separate design surface below the form.

  3. Double-click the icon for timer1 to create an event-handling method for the timer1 component's Tick event. Place the following code in the event-handling method.

    // Visual J#
    this.set_Text("CDemo instances: " + CDemo.getInstanceCount());
    

    On every tick of the timer, the form's caption will display the current instance count for the CDemo class. The class name is used as a qualifier for the shared InstanceCount property—there is no need to create an instance of CDemo to access a shared member.

  4. Locate the constructor for Form1 (public Form1()), and add the following code after the call to InitializeComponent().

    // Visual J#
    timer1.set_Enabled(true);
    

    This will start the timer as soon as the form is created.

  5. Click the Form1.jsl [Design] tab to return to the designer.

  6. Double-click the Button on Form1, to create an event-handling method for the button's Click event. Place the following code in the event-handling method.

    // Visual J#
    CDemo cd;
    int ct;
    for (ct = 0; ct < 1000; ct++)
    {
        cd = new CDemo();
    }
    

    This code might look strange to you. As each instance of CDemo is created, the previous instance is released. When the for loop is done, there will be only one instance of CDemo left. When the event-handling method exits, even that instance will be released, because the variable cd will go out of scope.

To run and debug the CDemoTest and CDemo projects

  1. Press F5 to start the solution.

    The client project will start, and Form1 will be displayed. Notice that the caption of the form displays "CDemo instances: 0".

  2. Click the button. The caption of the form should display "CDemo instances: 1000".

    The instances of CDemo were all released by the time the button's Click event-handling procedure finished. In brief, the memory manager finalizes objects in the background, at low priority. The priority is only increased if the system gets low on memory. This type of garbage collection scheme allows for very fast object allocation.

  3. Click the button several more times, watching the caption. At some point, the number of instances will suddenly drop. This means that the memory manager has reclaimed the memory of some of the objects.

    NoteNote

    If you have clicked more than 10 times, and the number of CDemo instances has not decreased, you may need to adjust the code so that it uses more memory. Close the form to return to the development environment, and increase the number of iterations in the for loop to 10000. Then run the project again.

  4. Repeat step 3. You will get farther this time before the memory manager finalizes more objects.

    In fact, each time you repeat step 3, you will probably be able to allocate more CDemo objects before the memory manager steps in. This is because more and more of Visual Studio is swapped out, leaving more space for instances of CDemo.

  5. Close the form to return to the development environment.

Show:
© 2016 Microsoft