Main Content

Create Windows Communications Foundation Component

The following example shows you how to implement a Windows® Communications Foundation (WCF) component using a type-safe interface and integrate it into a client-server .NET application.

For an additional example and data conversion rules regarding type-safe interfaces, see Implement Type-Safe Interface and Integrate into .NET Application.

For up-to-date information regarding WCF, see What Is Windows Communication Foundation in the Microsoft® documentation.

Write and Test Your MATLAB Code

Create your MATLAB® program and then test the code before implementing a type-safe interface. The functions in your MATLAB program must match the declarations in your native .NET interface.

For this example, save the following code as addOne.m.

function y = addOne(x)
% Input must be either a scalar or a matrix of single or multiple dimensions

    if ~isnumeric(x)
        error('Input must be numeric. Input was %s.', class(x));
    end
    y = x + 1;

end

At the MATLAB command prompt, enter addOne([1,2,3]).

The output is:

     2     3     4

Implement WCF Interface

After you write and test your MATLAB code, develop an interface in either C# or Visual Basic® that supports the native types through the API.

  1. Open Microsoft Visual Studio® and create a new Class Library (.NET Framework) project named IAddOne.

  2. In the Solution Explorer window within Visual Studio, rename the Class1.cs file to IAddOne.cs. In this file, write source code for the WCF interface that accesses the component.

    In this example, the IAddOne interface is written in C# and specifies six overloads of addOne:

     IAddOne.cs

    Note that in the WCF implementation of addOne, you decorate the methods with the OperationContract property. You give each method a unique operation name, which you specify with the Name property of OperationContract

    Note

    When using WCF, your overloaded functions must have unique names.

    Each method in the interface must exactly match a deployed MATLAB function. All methods have one input and one output (to match the MATLAB addOne function), though the type and position of these parameters varies.

  3. Go to Build > Configuration Manager and change the platform from Any CPU to x64.

  4. Build the project with Microsoft Visual Studio. The file IAddOne.dll is generated in the build folder.

    Note

    This example assumes your assembly contains only IAddOne. Realistically, it is more likely that IAddOne will already be part of a compiled assembly. The assembly may be complete even before the MATLAB function is written.

Create .NET Assembly Using Library Compiler App

The Library Compiler app generates the type-safe API when you build your component, if the following options are selected.

  1. Create a Library Compiler project and select .NET Assembly from the Type list.

  2. Use the following values:

    Library NameAddOneComp
    Class NameMechanism
    File to CompileaddOne.m

  3. Expand the Additional Runtime Settings section.

    In the Type-Safe API section, do the following:

    1. Select Enable Type-Safe API.

    2. In the Interface assembly field, specify the location of the type-safe/WCF interface assembly IAddOne.dll that you built.

    3. Select the IAddOne interface from the .NET interface drop-down box.

      Tip

      If the drop-down is blank, the Library Compiler may have been unable to find any .NET interfaces in the assembly you selected.

    4. Leave the Namespace and MEF metadata fields blank.

    5. Specify the Mechanism class in the Wrapped Class field.

  4. Click the Package button to build the project.

    The file AddOneCompNative.dll is generated in the for_redistribution_files_only folder.

Create .NET Assembly Using compiler.build.dotNETAssembly

Note

If you have already created a .NET assembly using the Library Compiler app, you can skip this section. However, if you want to know how to create a .NET assembly from the MATLAB command window using a programmatic approach, follow these instructions.

To generate the type-safe API with your component build using the compiler.build.dotNETAssembly function, complete the following steps:

  1. Build the .NET assembly using compiler.build.dotNETAssembly. Use name-value arguments to specify the assembly name and class name.

    compiler.build.dotNETAssembly('addOne.m', ...
        'AssemblyName','AddOneComp', ...
        'ClassName','Mechanism');
    
  2. Navigate to the generated AddOneCompdotNETAssembly directory.

  3. Generate the type-safe API by using the ntswrap command from MATLAB:

    ntswrap('-c','AddOneComp.Mechanism', ...
            '-a','IAddOne.dll', ...
            '-i','IAddOne');

    Not all arguments are compatible with each other. See ntswrap for details on all command options.

    Tip

    If the IAddOne.dll assembly is not in the current folder, specify the full path.

    This command generates the assembly MechanismIAddOne.dll that contains a type-safe API for the MATLAB Compiler SDK™ class Mechanism in the namespace AddOneCompNative.

Develop Server Program Using WCF Interface

Develop a server program that provides access (via the WCFServiceContract) to the overloads of addOne defined by the WCF IAddOne interface. The program references an App.config XML configuration file.

The WCF server program loads the WCF-based addOne.Mechanism component and makes it available to SOAP clients via the type-safe mechanismIAddOne interface.

Tip

When writing your interface, you will be coding to handle jagged arrays, as opposed to rectangular arrays. For more information, see Jagged Array Processing.

Compile the server program using Microsoft Visual Studio by doing the following steps:

  1. Open Microsoft Visual Studio and create a C# Console App (.NET Framework) called AddOneApp.

  2. Copy the following source code into the generated Program.cs in your project:

     WCF Server Program

  3. Add the following configuration file App.config to your project. You may need to modify the listed .NET Framework version.

     App.config XML file

  4. Add references in the project to the following files:

    This reference:Defines:
    IAddOne.dllThe .NET native type interface IAddOne
    MechanismIAddOne.dllThe generated type-safe API
    AddOneCompNative.dllThe generated .NET assembly

    Note

    Unlike other .NET deployment scenarios, you do not need to reference MWArray.dll in the server program source code. The MWArray data types are hidden behind the type-safe API in MechanismIAddOne.

  5. Add a reference to System.ServiceModel, which is listed under Assemblies.

  6. Go to Build > Configuration Manager and change the platform from Any CPU to x64.

  7. Compile and run the server program with Microsoft Visual Studio.

    The program displays the following output:

    Addition Server is up running......
    Press any key to close the service.
    

    Pressing a key results in the following.

    Closing service....

Generate Proxy Code for Clients

Configure your clients to communicate with the server by running the automatic proxy generation tool svcutil.exe. Most versions of Microsoft Visual Studio can automatically generate client proxy code from server metadata.

Caution

Before you generate your client proxy code using this step, the server must be available and running. Otherwise, the client will not find the server.

  1. Create a client project in Microsoft Visual Studio.

  2. Add references by using either of these two methods.

    Method 1Method 2
    1. In the Solutions Explorer pane, right-click References.

    2. Select Add Service Reference. The Add Service Reference dialog box appears.

    3. In the Address field, enter: http://localhost:8001/Addition/

      Note

      Be sure to include the / following Addition.

    4. In the Namespace field, enter AdditionProxy.

    5. Click OK.

    1. Enter the following command from your client application directory to generate AdditionProxy.cs, which contains client proxy code. This command also generates the configuration file App.config.

      svcutil.exe /t:code http://localhost:8001/Addition//out:AdditionProxy.cs /config:App.config

      Note

      Enter the above command on one line, without breaks.

    2. Add AdditionProxy.cs and App.config to your client project

Note

When running a self-hosted application, you may encounter issues with port reservations. Use the tool netsh to modify your port configurations, as necessary.

Develop Client Program Using WCF Interface

At start-up, the client program connects to the AdditionService provided by the Addition WCF service. Instead of directly invoking the methods of the type-safe mechanism IAddOne interface, the WCF client uses the method names defined in the OperationContract attributes of IAddOne.

Compile the client program using Microsoft Visual Studio by doing the following:

  1. Open Microsoft Visual Studio and create a C# Console App (.NET Framework) called AdditionClient.

  2. Copy the following source code into the generated Program.cs in your project:

     WCF Client Program

  3. If you are not already referencing System.ServiceModel, add it to your Visual Studio project.

  4. Go to Build > Configuration Manager and change the platform from Any CPU to x64.

  5. Compile the WCF client program with Microsoft Visual Studio.

  6. Run the program from the command line with administrator access.

    The program displays the following output:

    Conntecting to Addition Service through Http connection...
    Conntected to Addition Service...
    addOne(1) = 2
    addOne(16) = 17
    addOne(2) = 3
    addOne(495) = 496
    addOne([30 60 88]) = [31 61 89]
    addOne([0 2; 3 1]) = [1 3; 4 2]
    Press any key to close the client application.
    

    Pressing a key results in the following:

    Closing client....

Tips

  • If you want to use WCF, the easiest way to do so is through the type-safe API.

  • WCF and .NET remoting are not compatible in the same deployment project or component.

  • This example requires both client and server to use message sizes larger than the WCF defaults. For information about changing the default message size, see the MSDN article regarding the maxreceivedmessagesize property.

See Also

| | |

Related Topics