Skip to Main Content Skip to Search
Product Documentation

Magic Square Example: Integrating Your .NET Component In a C# Application

The following tasks are usually performed by the .NET developer.

.NET Developer

RoleKnowledge BaseResponsibilities

.NET Developer
  • Little to no MATLAB experience

  • Moderate IT experience

  • .NET expert

  • Minimal access to IT systems

  • Integrates deployed component with the rest of the .NET application

Key Tasks for the .NET Developer

TaskReference
Ensure you have the needed files from the MATLAB programmer.Gathering Files Needed for Deployment
Install your application on target computers without MATLAB (installing the MCR).Installing the MATLAB Compiler Runtime (MCR)
Integrate classes generated by the MATLAB Builder NE product into existing .NET applications.Integrating Your Component into a .NET Class Using Microsoft Visual Studio
Verify your .NET application works as expected in your end user's deployment environment.Building and Testing the .NET Application with Microsoft Visual Studio

Gathering Files Needed for Deployment

Before beginning, verify you have the files the MATLAB programmer packaged, listed in Packaging Your Component (Optional).

The package is a self-extracting executable. Paste it in a folder on the development machine and run it. If you are using a .zip file bundled with WinZip, unzip and extract the contents to the development machine.

Installing the MATLAB Compiler Runtime (MCR)

On target computers without MATLAB, install the MCR, if it is not already present on the deployment machine.

MATLAB Compiler Runtime (MCR) and the MCR Installer

The MATLAB Compiler Runtime (MCR) is an execution engine made up of the same shared libraries MATLAB uses to enable the execution of MATLAB files on systems without an installed version of MATLAB.

In order to deploy a component, you package the MCR along with it. Before you utilize the MCR on a system without MATLAB, run the MCR Installer.

The installer does the following:

  1. Installs the MCR (if not already installed on the target machine)

  2. Installs the component assembly in the folder from which the installer is run

  3. Copies the MWArray assembly to the Global Assembly Cache (GAC), as part of installing the MCR

MCR Prerequisites

  1. Since installing the MCR requires write access to the system registry, ensure you have administrator privileges to run the MCR Installer.

  2. The version of the MCR that runs your application on the target computer must be compatible with the version of MATLAB Compiler that built the component.

  3. Avoid installing the MCR in MATLAB installation directories.

Adding the MCR Installer To Your Deployment Package

Include the MCR in your deployment by using the Deployment Tool.

On the Package tab of the deploytool interface, click Add MCR.

Testing with the MCR

When you test with the MCR, keep in mind that the MCR is an instance of MATLAB. Given this, it is not possible to load the MCR into MATLAB.

For example, if you build a generic COM component with the Deployment Tool from MATLAB Builder NE, you generate a DLL.

If you then try to test the component with an application such as actxserver, which loads its process into MATLAB, you are effectively loading the MCR into MATLAB, producing an error such as this:

mwsamp.mymagic(3,[],[]) 
??? Invoke Error, Dispatch Exception: 
Source: tmw1.Class1.1_0 
Description: MCR instance is not available 

Therefore, understand the behaviors of third-party processes before attempting to test them with the MCR.

If you are uncertain about the behavior of these processes, contact your developer or systems administrator.

MCR Installation and Setting System Paths

To install the MCR, perform the following tasks on the target machines:

  1. If you added the MCR during packaging, open the package to locate the installer. Otherwise, run the command mcrinstaller to display the locations where you can download the installer.

  2. If you are running on a platform other than Windows, set the system paths on the target machine. Setting the paths enables your application to find the MCR.

    Windows paths are set automatically. On Linux and Mac, you can use the run script to set paths. See Using Run Script to Set MCR Paths in the appendix Using MATLAB Compiler on UNIX in the MATLAB Compiler User's Guide for more information.

Where to find the MWArray API.  The MCR also includes MWArray.dll, which contains an API for exchanging data between your applications and the MCR. You can find documentation for this API in the Help folder of the installation.

On target machines where the MCR Installer is run, the MCR Installer puts the MWArray assembly in installation_folder\toolbox\dotnetbuilder\
bin\architecture\framework_version
.

See Supported Microsoft .NET Framework Versions for a list of supported framework versions.

Sample Directory Structure of the MCR Including MWArray.dll

Integrating Your Component into a .NET Class Using Microsoft Visual Studio

Creating a Microsoft Visual Studio Project

To create a Microsoft Visual Studio project:

  1. Open Microsoft Visual Studio

  2. Click File > New > Project.

  3. In the New Project dialog, select the project type and template you want to use.

    For example, if you want to create a C# Console Application, select Windows in the Visual C# branch of the Project Type pane, and select the Console Application template from the Templates pane.

  4. Type the name of the project in the Name field (MainApp, for example).

Creating a Reference to Your Component

Create a reference in your code to the component that you just built.

To do so, in Microsoft Visual Studio, perform the following steps:

  1. In the Solution Explorer pane within Microsoft Visual Studio (usually on the right side), select the name of your project, highlighting it.

  2. Right-click and select Add Reference.

  3. In the Add Reference dialog box, select the Browse tab. Locate the distrib folder using this dialog box. When you are finished the path to your distrib folder should be in the File Name: field. Click OK when done to open the distrib folder.

  4. After you access the folder, select your component's executable file (in the case of the standalone example, a .dll file). Click OK.

Creating a Reference to the MWArray API

You also need to reference MWArray.dll, which has already been registered with the Global Assembly Cache (GAC) (if you installed the MCR). The GAC is a machine-wide .NET assembly cache for Microsoft's CLR platform.

To create the reference, in Microsoft Visual Studio, perform the following steps:

  1. In the Solution Explorer pane within Microsoft Visual Studio (usually on the right side), select the name of your project, and highlight it.

  2. Right-click and select Add Reference.

  3. Add a reference as follows, based on the version of Visual Studio you are running:

    • Microsoft Visual Studio 2005 or 2008: In the Add Reference dialog box, select the .NET tab. Locate MathWorks, .NET MWArray API, and select it. Click OK

    • Microsoft Visual Studio 2010: Browse for MWArray in this location: matlabroot\toolbox\dotnetbuilder\bin\arch\version\ and click Open.

    .

Making .NET Namespaces Available for Your Generated Component and MWArray Libraries

Make pertinent namespaces available to your application by adding the following using statements to your C#/.NET code:

using com.component_name;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;

Specifying Component Assembly and Namespace.  To use the component assembly generated using the MATLAB Builder NE product from the client application, you must

Suppose you named the component you created MyComponentName and you want to use it in a program named MyApp.cs. Here are the statements to use at the beginning of MyApp.cs:

using System;
using MathWorks.MATLAB.NET.Arrays;
using MyComponentName;

Initializing Your Classes

As a best practice, initialize your classes before you use them.

For example, you start by initializing an abstract class, MLTestClass, and then writing the code as follows.

Initializing Classes

In this example, you perform the following initializations:

Instantiating Your Classes

After your classes have been initialized, you write code to create objects (instances of the class) using instantiation (creating an instance of a class). Instantiating a class requires use of the new keyword.

In this example, you instantiate MLTestClass with obj = new MLTestClass();:

Instantiating a Class

Creating an Instance of a Class.  As with any .NET class, you need to create an instance of the classes you create with the MATLAB Builder NE product before you can use them in your program.

Suppose you build a component with a class named MyComponentClass. Here is an example of creating an instance of that class:

MyComponentClass classInstance = new MyComponentClass();

See How the MCR Is Shared Among Classes for additional information about what happens when you instantiate classes.

Invoking the Component

After you complete the tasks of initializing and instantiating the classes you are working with, invoke the makeSqr component you built with MATLAB Builder NE in Deployable Component Creation.

Invoke the component method using a signature containing both the number of output arguments expected and the number of input arguments the MATLAB function requires. In this example, using makeSqr, the number of input arguments is 1 and the number of output arguments is 5:

obj.makeSqr(1, 5);

Using Implicit Conversion.  Make use of implicit conversion, from .NET types to MATLAB types, by passing the native C# value directly to makeSqr using the input argument, as follows:

input = new MWNumericArray(5);
obj.makeSqr(1, input);

Using Implicit Constructors.  You can exploit implicit constructors supplied with MWArray classes to save writing code.

For example, in this example, you can directly define your input as 5 (input being identified previously as MATLAB numeric type MWNumericArray).

Defining Input Using an Implicit Constructor

Handling Output from MWArray.  The makeSqr method returns an array of MWArrays

Extract the Magic Square you created from the first indice of result and print the output, as follows:

output = (MWNumericArray)result[0];
Console.WriteLine(output);

Handling Errors Using Try-Catch Blocks

Because class instantiation and method invocation make their exceptions at run-time, you enclose your code in a try-catch block to handle errors.

Using a Try-Catch Block

For More Information

If you want to...See...
Perform advanced integration tasksComponent Integration
Convert native data types to MATLAB data typesManual Data Conversion from Native Types to MATLAB Types
Learn about creating type-safe interfaces, in order to avoid data conversion tasks with MWArray.Type-Safe Interfaces, WCF, and MEF
Automatic casting to MATLAB data typesAutomatic Casting to MATLAB Types
Learn more about building your componentComponent Building
  • Perform basic MATLAB Programmer tasks

  • Understand how the deployment products process your MATLAB functions

  • Understand how the deployment products work together

  • Explore guidelines about writing deployable MATLAB code

MATLAB Code Deployment

Building and Testing the .NET Application with Microsoft Visual Studio

After you finish writing your code, you build and run it with Microsoft Visual Studio:

  1. To build the application, select Build > Build Solution.

  2. To run the application, select Debug > Start Without Debugging.

For More Information

If you want to...See...
Perform advanced integration tasksComponent Integration
Convert native data types to MATLAB data typesManual Data Conversion from Native Types to MATLAB Types
Learn about creating type-safe interfaces, in order to avoid data conversion tasks with MWArray.Type-Safe Interfaces, WCF, and MEF
Automatic casting to MATLAB data typesAutomatic Casting to MATLAB Types
Learn more about building your componentComponent Building
  • Perform basic MATLAB Programmer tasks

  • Understand how the deployment products process your MATLAB functions

  • Understand how the deployment products work together

  • Explore guidelines about writing deployable MATLAB code

MATLAB Code Deployment

The Magic Square Component in an Enterprise C# Application

  1. Write source code for an application that uses the .NET component created in Deployable Component Creation.

    The C# source code for the sample application for this example is in MagicSquareExample\MagicSquareCSApp\MagicSquareApp.cs.

      Tip   Although MATLAB Builder NE generates C# code for the MagicSquare component and the sample application is in C#, applications that use the component do not need to be coded in C#. You can access the component from any CLS-compliant .NET language. For C#, as well as Microsoft® Visual Basic® examples, see Component Integration.

  2. Build the application using Visual Studio® .NET.

      Note   In the project file for this example, the MWArray assembly and the magic square component assembly have been prereferenced. Any references preceded by an exclamation point require you to remove the reference and rereference the affected assembly.

      Note   Microsoft .NET Framework version 2.0 is not supported by Visual Studio 2003.

    1. Open the project file for the Magic Square example (MagicSquareCSApp.csproj) in Visual Studio .NET.

    2. Add a reference to the MWArray component in matlabroot\toolbox\dotnetbuilder\bin\
      architecture\framework_version.

      See Supported Microsoft .NET Framework Versions for a list of supported framework versions.

    3. If necessary, add a reference to the Magic Square component (MagicSquareComp), which is in the distrib subfolder.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS