Main Content

Synchronous RESTful Requests Using Protocol Buffers in .NET Client

This example shows how to make synchronous RESTful requests using the .NET client API, MATLAB® Production Server™ RESTful API for MATLAB Function Execution, and protocol buffers (protobuf). The example provides and explains a sample C# client, MagicSync.cs, for evaluating a MATLAB function deployed on the server.

To use protobuf when making a request to the server, set the HTTP Content-Type request header to application/x-google-protobuf in the client code. The MathWorks.MATLAB.ProductionServer.Client.REST namespace in the .NET client library provides helper classes to internally create protobuf messages based on a proto format and returns the corresponding byte array. Use this byte array in the HTTP request body. The .NET client library provides methods and classes to deserialize the protobuf responses.

In synchronous request execution, after a client posts a request, the server blocks all further requests until it has completed processing the original request. After processing is complete, the server automatically returns a response to the client. For more information, see Synchronous Execution.

To use the .NET client API, you must add a reference to the MathWorks.MATLAB.ProductionServer.Client.dll file in your C# project. For more information on preparing your Microsoft® Visual Studio® environment for your project, see Prepare Your Microsoft Visual Studio Environment.

In an on-premises MATLAB Production Server installation, the client APIs are located in $MPS_INSTALL/client, where $MPS_INSTALL is the MATLAB Production Server installation location. The client APIs are also available for download at MATLAB Production Server Client Libraries. The Java® client API is also hosted in a Maven™ repository at https://mvnrepository.com/artifact/com.mathworks.prodserver/mps_java_client.

Deploy MATLAB Function to Server

Write a MATLAB function mymagic that uses the magic (MATLAB) function to create a magic square, then deploy it on the server. The function mymagic takes a single int32 input and returns a magic square as a 2-D double array. The example assumes that the server instance is running at http://localhost:9910.

For information on how to deploy, see Create Deployable Archive for MATLAB Production Server.

function m = mymagic(in)

  m = magic(in);
end

Make Synchronous Request to Server

In the C# client code, use the POST Synchronous Request to make the initial request to the server. For more information about synchronous request execution in MATLAB Production Server, see Synchronous Execution.

  1. Create the request.

    Create a request to the POST Synchronous Request RESTful API using the .NET WebRequest.Create method.

    The request URL comprises the address of the server instance (http://localhost:9910), the name of the deployed archive (mymagic), and the name of the MATLAB function to evaluate (mymagic). Set the HTTP request method to POST. Set the HTTP Content-Type request header to application/x-google-protobuf, as the API returns a byte array of protocol buffer messages.

    String mpsBaseUrl = "http://localhost:9910";
    var firstRequest = (HttpWebRequest)WebRequest.Create(mpsBaseUrl + "/mymagic/mymagic");
    firstRequest.Method = "POST";
    firstRequest.ContentType = "application/x-google-protobuf";

  2. Send the request to the server.

    Send the request to the server using the .NET WebRequest.getResponse method.

    Use the Create(arg1, arg2, arg3) method defined in the MATLABParams class present in MathWorks.MATLAB.ProductionServer.Client.REST namespace of the MATLAB Production Server .NET client API to build the protocol buffer message. The Create method takes as input the expected number of output arguments for the deployed function, the expected output type, and an array of objects representing the inputs to the deployed function. Since the deployed mymagic function returns a single 2-D array, set arg1 to 1 and arg2 to new List<Type> { typeof(double[,]) }. Specify an integer value for arg3, which is the input to the mymagic function.

    MATLABParams mlParams = MATLABParams.Create(1, new List<Type> { typeof(double[,]) }, 2);
    mlParams.WriteTo(firstRequest.GetRequestStream());
    var response = (HttpWebResponse)firstRequest.GetResponse();

For more information on the WebRequest class, see Microsoft documentation.

Receive and Interpret Server Response

On successful execution of the POST Synchronous Request, the server responds with a protocol buffer message. Parse the protocol buffer message using methods from the MATLABResult class to get the result of the request. To create a MATLABResult object, use the Create method. Pass the MATLABParams mlParams object and the response body of the POST Synchronous Request to the Create method.

If an error occurs when the deployed MATLAB function executes, the call to the Result method throws a MATLABException that contains the error message from MATLAB.

MATLABResult mlResult;
mlResult = MATLABResult.Create(mlParams, response.GetResponseStream());
try
{
    double[,] result = mlResult.Result<double[,]>();
    Console.WriteLine("Printing the 2-D array...\n");
    PrintMagic(result);
}
catch (MATLABException e)
{
    Console.WriteLine(e.ToString());
}

The example uses a helper method PrintMagic that takes as input the response body of the POST Synchronous Request and prints the corresponding 2-D magic square array.

static void PrintMagic(double[,] magic)
{
    int numDims = magic.Rank;
    int[] dims = new int[numDims];

    for (int i = 0; i < numDims; i++)
    {
        dims[i] = magic.GetLength(i);
    }
    
    for (int j = 0; j < dims[0]; j++)
    {    
        for (int k = 0; k < dims[1]; k++)
        {
            Console.Write(magic[j, k]);
            if (k < dims[1] - 1)
            {
                Console.Write(",");
            }
        }
        Console.WriteLine();
    }
}

Running the C# application generates the following output.

Printing the 2-D array...

1,3
4,2

Sample code for the MagicSync.cs C# client follows.

Code:

 MagicSync.cs

See Also

Related Topics