C# quickstart

View as Markdown

In about 10 minutes you build a .NET console app that connects to an M-Files vault over native gRPC, logs in, lists the 10 most recently modified documents and logs out. The app uses the M-Files gRPC client package MFiles.Grpc, which builds on the official Grpc.Net.Client and Google.Protobuf packages.

Prerequisites

Cloud and on-premises and Connecting to the server explain the endpoints in detail.

Create the project

dotnet new console -o MFilesQuickstart
cd MFilesQuickstart
dotnet add package MFiles.Grpc

The package MFiles.Grpc contains the client code generated from the M-Files protos and the helpers that the guides use, all in the namespace MFiles.Grpc:

Versions. There is one package version per M-Files release: 26.11.0 has the API of M-Files 26.11, and 26.11.1 is a revision of it. A version works with its release and later ones; with an older server, the methods that the server does not have fail with Unimplemented. To get the version of a release, pin it: dotnet add package MFiles.Grpc --version 26.11.*. The package is a preview: its helpers can still change between releases.

Write the program

Replace the content of Program.cs with this:

using MFiles.Grpc;
using static MFiles.Grpc.MFilesValues;

// Connect and log in with the MFILES_* settings. Disposing the connection logs out.
await using var connection = await MFilesConnection.ConnectAsync(
    MFilesSettings.FromEnvironment(), clientName: "M-Files gRPC quickstart");

// Search for the 10 most recently modified documents.
var request = new SearchObjectsRequest
{
    // Documents (object type 0) that are not deleted.
    Conditions = { new SearchConditionArray { Value = { IsObjectType(0), IsNotDeleted() } } },
    // Newest first by property 21, "Last modified". The server sorts, then takes 10.
    Sorting = new SearchResultsSorting
    {
        Rules = new SortRuleValueArray
        {
            Values = { new SortRule { Key = 21, Options = new SortRuleFlags { SortDescending = true } } },
        },
    },
    Limit = 10,
};

// Service clients run on the connection's call invoker, which adds the session to each call.
var search = new IRPCSearch.IRPCSearchClient(connection.CallInvoker);
var response = await search.SearchObjectsAsync(request);

// One line per document: title, ID, version and when it was last modified.
foreach (var item in response.Results)
{
    var version = item.Object.VersionInfo;
    Console.WriteLine($"{version.Title} (ID {item.Object.ObjectInfo.ObjId.ItemId.InternalId}, " +
        $"version {version.Version.InternalVersion}, " +
        $"modified {version.LastModifiedAtUtc.ToDateTime():yyyy-MM-dd HH:mm:ss} UTC)");
}

Full source: mfiles-grpc-dotnet/examples/Quickstart/Program.cs

Configure

The helper reads its settings from environment variables:

Variable Value
MFILES_ADDRESS host:port, for example contoso.cloudvault.m-files.com:443 or mfserver:7766
MFILES_TLS true (default), or false for a server without TLS
MFILES_CA_CERT Optional: a PEM file of the root certificate to trust, for a server whose certificate comes from a private CA
MFILES_VAULT The vault GUID, with braces
MFILES_AUTH browser for single sign-on in the browser; then MFILES_VAULT is optional
MFILES_REMEMBER_SIGN_IN Optional, with MFILES_AUTH=browser: true keeps the sign-in in Windows Credential Manager
MFILES_USERNAME, MFILES_PASSWORD An M-Files user account
MFILES_TOKEN Instead of a password, for single sign-on: an access token from the vault's identity provider
MFILES_AUTH_PLUGIN, MFILES_AUTH_SCOPE Optional, with MFILES_TOKEN: the authentication plugin and its configuration scope. Without them the helper asks the vault and uses its plugin, if the vault has one or one marked as the default

M-Files Cloud with single sign-on:

$env:MFILES_ADDRESS = 'contoso.cloudvault.m-files.com:443'
$env:MFILES_AUTH = 'browser'

On-premises without TLS, with a user name and password:

$env:MFILES_ADDRESS = 'mfserver:7766'
$env:MFILES_TLS = 'false'
$env:MFILES_VAULT = '{7BBEA0BC-40D8-4BCB-A67D-8A3ACFBDB575}'
$env:MFILES_USERNAME = 'alice'
$env:MFILES_PASSWORD = Read-Host -Prompt 'Password'

Single sign-on. A vault that signs users in through M-Files Login Service, as is typical on M-Files Cloud, refuses a password login with "Authentication failed.". With MFILES_AUTH=browser the helper signs you in through the browser, as M-Files' own clients do, and logs in with the token (see M-Files Login Service). The vault comes from the sign-in configuration, so MFILES_VAULT is not needed. With MFILES_REMEMBER_SIGN_IN=true, the next run signs in without the browser. A token that you get elsewhere goes into MFILES_TOKEN.

Run

dotnet run

The output lists the documents, newest first. In the M-Files Sample Vault it starts like this:

Project Plan (template) (ID 445, version 1, modified 2012-06-07 12:01:57 UTC)
Project Tasks - CRM Development (ID 444, version 1, modified 2012-06-07 11:54:29 UTC)
Corporate Presentation (ID 443, version 1, modified 2012-06-07 11:40:14 UTC)
...

The code

IsObjectType and IsNotDeleted are small builders from the helper. They show the message shapes of the two conditions:

/// <summary>A condition on a property value, e.g. property 100 (Class) equals a lookup.</summary>
/// <param name="propertyDef">The property definition.</param>
/// <param name="type">How to compare, e.g. Equal or GreaterThanOrEqual.</param>
/// <param name="value">The value to compare with.</param>
public static SearchCondition PropertyCondition(
    int propertyDef, ConditionType type, TypedValue value) => new()
{
    Expression = new Expression
    {
        Type = ExpressionType.PropertyValue,
        Data = new ExpressionUnion
        {
            PropertyValue = new ExpressionUnion.Types.PropertyValueData
            {
                PropertyDef = propertyDef,
            },
        },
    },
    Type = type,
    Value = value,
};

/// <summary>A condition on a status value, e.g. the object type or the deleted flag.</summary>
/// <param name="status">The status value, e.g. ObjectType or IsDeleted.</param>
/// <param name="type">How to compare, e.g. Equal.</param>
/// <param name="value">The value to compare with.</param>
public static SearchCondition StatusCondition(
    StatusType status, ConditionType type, TypedValue value) => new()
{
    Expression = new Expression
    {
        Type = ExpressionType.StatusValue,
        Data = new ExpressionUnion
        {
            StatusValue = new ExpressionUnion.Types.StatusValueData { Type = status },
        },
    },
    Type = type,
    Value = value,
};

/// <summary>Objects of one object type. Value list -11 lists the object types.</summary>
/// <param name="objectType">The object type, e.g. 0 for documents.</param>
public static SearchCondition IsObjectType(int objectType) =>
    StatusCondition(StatusType.ObjectType, ConditionType.Equal, Lookup(-11, objectType));

/// <summary>Objects that are not deleted.</summary>
public static SearchCondition IsNotDeleted() =>
    StatusCondition(StatusType.IsDeleted, ConditionType.Equal, Boolean(false));

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesValues.cs

What the helper does

gRPC alone is not enough to talk to M-Files: part of the contract travels in call metadata, and errors arrive in trailers. MFilesConnection takes care of that.

The channel. TLS or plain HTTP/2, an optional private root certificate, and the message size limits that M-Files' own client uses: responses of any size, requests up to 48 MiB. With an http:// address, .NET makes an unencrypted HTTP/2 connection; no extra switch is needed on .NET 10. SocketsHttpHandler keeps cookies, so the affinity cookie that M-Files Cloud sets (mfilesmsm) goes back on later calls, as Call metadata requires:

// The HTTP handler: the cookie and connection settings M-Files needs, and keep-alive pings
// that detect a dropped connection.
var handler = new SocketsHttpHandler
{
    // M-Files Cloud answers with a server affinity cookie (mfilesmsm); the handler's
    // cookie container sends it back on later calls.
    UseCookies = true,
    // Open another HTTP/2 connection when the calls in progress reach the server's limit of
    // concurrent calls on one connection, instead of making further calls wait.
    EnableMultipleHttp2Connections = true,
    KeepAlivePingDelay = TimeSpan.FromSeconds(60),
    KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
};

// With a CA certificate: trust this root (e.g. an on-premises server's own CA) instead of
// the system's roots.
if (settings.CaCertificatePath is { } caPath)
{
    var roots = new X509Certificate2Collection();
    roots.ImportFromPemFile(caPath);
    handler.SslOptions.CertificateChainPolicy = new X509ChainPolicy
    {
        TrustMode = X509ChainTrustMode.CustomRootTrust,
        // A private CA usually publishes no revocation list.
        RevocationMode = X509RevocationMode.NoCheck,
    };
    handler.SslOptions.CertificateChainPolicy.CustomTrustStore.AddRange(roots);
}

// Create the channel on the handler. "http://" makes an unencrypted HTTP/2 connection
// (lab servers only).
string scheme = settings.UseTls ? "https" : "http";
var channel = GrpcChannel.ForAddress($"{scheme}://{settings.Address}", new GrpcChannelOptions
{
    HttpHandler = handler,
    // No limit (null) on received messages: responses can be much larger than gRPC's
    // default of 4 MiB.
    MaxReceiveMessageSize = null,
    MaxSendMessageSize = MaxSendMessageSize,
});

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

Call metadata. A call invoker adds the M-Files metadata to every call, and after login the session ID:

/// <summary>
/// The metadata M-Files expects on every call. gRPC base64-encodes "-bin" values itself.
/// </summary>
/// <param name="options">The caller's call options.</param>
/// <returns>The options with the caller's headers and the M-Files metadata.</returns>
private CallOptions WithMFilesMetadata(CallOptions options)
{
    // Keep the headers the caller set.
    var headers = new Metadata();
    foreach (var entry in options.Headers ?? [])
        headers.Add(entry);

    // The caller is not one of the server's own local processes.
    headers.Add("mfiles-is-remote-call", "true");

    // A new 16-byte ID per call; it identifies the call in the server's logs.
    headers.Add("mfiles-activity-id-bin", Guid.NewGuid().ToByteArray());

    // After LogIn: the session ID, unchanged.
    if (connection.SessionId is { } sessionId)
        headers.Add("mfiles-session-id-bin", sessionId.ToByteArray());

    // The caller's other options stay as they are.
    return options.WithHeaders(headers);
}

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesCallInvoker.cs

Login. LogIn with M-Files credentials returns a session; its session_id goes into mfiles-session-id-bin from then on:

// The authentication data: an M-Files user name and password.
var authentication = new AuthDataClient
{
    Type = AuthDataType.Credentials,
    Data = new AuthDataClientUnion
    {
        Credentials = new Credentials
        {
            Username = username,
            Password = password,
            Type = CredentialsType.Mfiles,  // M-Files authentication
        },
    },
};

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

// Log in: who the client is, which vault it opens and how it authenticates.
var request = new LogInRequest
{
    EnvironmentData = new EnvironmentData { ClientName = clientName, HostPlatform = ".NET" },
    ClientData = new ClientData
    {
        Type = ClientType.ServerApi,
        Language = "en",
        // Needed for the 32-byte attempt ID of a token login.
        Capabilities = new ClientCapabilities { LongAuthenticationAttemptIdentifier = true },
    },
    LoginData = new LoginData { ServerHostname = _host, VaultGuid = vault },
    AuthenticationData = authentication,
};
var login = new IRPCLogin.IRPCLoginClient(CallInvoker);
var response = await login.LogInAsync(request, cancellationToken: cancellationToken);

// A one-step login returns the session in the response.
if (response.SessionData is not { SessionId.IsEmpty: false } session)
    throw new InvalidOperationException(
        "LogIn returned no session; this helper supports one-step logins only.");

// Every later call sends this session ID in mfiles-session-id-bin (see MFilesCallInvoker).
Session = session;

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

Errors. A failed call throws MFilesException, decoded from the mfiles-error-serialized-bin and mfiles-error-text-bin trailers: the gRPC status (StatusCode), the message, the M-Files error code of the top-level error (ErrorCode, an HRESULT such as 0x8004000B "Not found."; the last entry of the error stack that is not the generic 0x80040001), every code of the stack (ErrorCodes) and Has(code):

/// <summary>The generic code of an error that is only passed up the stack.</summary>
private const int PassThrough = unchecked((int)0x80040001);

/// <summary>
/// Decodes the M-Files error from the trailers of a failed call.
/// </summary>
/// <param name="e">The exception of the failed call.</param>
public static MFilesException FromRpcException(RpcException e)
{
    // The error stack: a serialized MFiles.RPCErrorInfoArray, the original error first.
    var errors = e.Trailers.GetValueBytes("mfiles-error-serialized-bin") is { } stack
        ? RPCErrorInfoArray.Parser.ParseFrom(stack).Value.ToList()
        : [];

    // The long error message: UTF-8 text in a binary header.
    string? details = e.Trailers.GetValueBytes("mfiles-error-text-bin") is { } text
        ? System.Text.Encoding.UTF8.GetString(text)
        : null;

    // The call failed with the top-level error, the last entry; the status detail is its
    // message. Skip entries that only pass the error on.
    int? errorCode = errors.Count > 0 ? errors[^1].ErrorCode : null;
    if (errors.LastOrDefault(error => error.ErrorCode != PassThrough) is { } topLevel)
        errorCode = topLevel.ErrorCode;
    return new MFilesException(e, errorCode, details, errors);
}

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesException.cs

Catch it like this:

try
{
    await objects.GetObjectInfoAndPropertiesAsync(request);
}
catch (MFilesException e) when (e.Has(0x8004000B))  // not found
{
    Console.WriteLine($"{e.ErrorCodeHex}: {e.Message}");
}

Errors lists the common codes and what to do about each.

Troubleshooting

Symptom Cause
Status Unavailable, "Error connecting to subchannel" Wrong host or port, or a firewall in between.
Status Internal, "The SSL connection could not be established" ... UntrustedRoot The server's certificate comes from a CA your machine does not trust. Set MFILES_CA_CERT to its root certificate (PEM).
Status Internal, "The SSL connection could not be established" ... "corrupted frame" TLS against a server without TLS: set MFILES_TLS=false, only for a lab server on a trusted network.
Status Unimplemented, "HTTP status code: 404", against M-Files Cloud MFILES_TLS=false; M-Files Cloud needs TLS.
Status Unimplemented for one method, other calls work The server is older than the package and does not have the method.
M-Files error 0x8004001A, "Authentication failed." Wrong user name or password, or the vault uses single sign-on (see Configure).

The connect recipe (see the next steps) calls QueryVersion before it logs in, so it tells connection problems from login problems.

Next steps

Generate the client code yourself

The package is the easiest way to the client code. To generate it yourself, for example into a namespace of your own, use the proto files of the gRPC API bundle and the packages that MFiles.Grpc itself uses; Grpc.Tools is needed only at build time:

<ItemGroup>
  <PackageReference Include="Google.Protobuf" Version="3.36.2" />
  <PackageReference Include="Grpc.Net.Client" Version="2.85.0" />
  <PackageReference Include="Grpc.Tools" Version="2.85.0" PrivateAssets="All" />
</ItemGroup>

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFiles.Grpc.csproj

Grpc.Tools generates the code on every build. MFilesProtoDir stands for the bundle's proto folder; ProtoRoot must be the folder that contains mfiles/, because the files import each other by that path:

<!-- Generate client classes for every service of the bundle. ProtoRoot must be the folder that
     contains mfiles/, because the protos import each other as "mfiles/structs.proto". -->
<ItemGroup>
  <Protobuf Include="$(MFilesProtoDir)/mfiles/**/*.proto" ProtoRoot="$(MFilesProtoDir)"
            GrpcServices="Client" Access="Public" />
</ItemGroup>

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFiles.Grpc.csproj

An M-Files Server installation also has the API definition, in <installation folder>\Common\Web\GRPC\proto, as one combined file without documentation. It describes the same wire contract, but its generated C# namespace is MFiles rather than MFiles.Grpc. Prefer the bundle.