Getting Started

This section demonstrates the use of M-Files Web Service by using low level HTTP requests. The information below should be applicale to most programming languages. See Sample Code section for sample M-Files Web Service C# client. The Sample Code package also contains the struct definitions used in the samples below.

Prerequisities

There are three prerequisities for using MFWS: A HTTP client, MFWS URL and M-Files credentials. While the last item isn’t strictly required, most of the M-Files operations require authentication and access to a document vault.

The HTTP client depends on the programming platform and doesn’t necessarily mean a web browser. WebClient is available for .NET framework and HttpURLConnection can be used in Java. Browser applications can perform the HTTP requests using the raw XMLHttpRequest or a wrapper around this such as jQuery’s $.ajax. If such HTTP API isn’t available a raw network socket API will do as well.

The MFWS URL and the credentials are M-Files installation specific. The easiest way to acquire the URL is to configure M-Files Classic Web, which comes with the web service. If M-Files Classic Web is configured at http://example.org/m-files, the MFWS URL is http://example.org/m-files/REST. For the credentials please contact your M-Files administrator.

Authenticating

MFWS provides three ways to authenticate the requests: Credentials in HTTP headers, cookie-based session and authentication tokens. Passing the credentials in the HTTP headers is the easiest way but sacrifices some security as the plain text credentials are passed in each request. Authentication tokens improve upon this by encrypting the credentials using asymmetric encryption. Cookie-based sessions offer some benefits in browser environments where the browser can manage the cookies. The choice of authentication mechanism has no effect on the actual use of the web service. The examples will mostly use the token based authentication.

Example: Acquiring the authentication token

An authentication token request is one of the requests that can be made unauthenticated. It is made by POSTing the authentication credentials to the /server/authenticationtokens resource as shown in the example below.

using System;
using System.Net;

// Requires reference to Systme.Runtime.Serialization assembly.
using System.Runtime.Serialization.Json;

// See the 'Sample code' for a package containing the struct definitions.
using MFiles.Mfws.Structs;

public class AuthenticationSample
{
	public static string Authenticate( string username, string password, string vaultGuid )
	{
		// Create the authentication details.
		var auth = new Authentication
		{
			Username = username,
			Password = password,
			VaultGuid = vaultGuid  // Use GUID format with {braces}.
		};

		// Create the web request.
		var request = WebRequest.Create( "http://example.org/REST/server/authenticationtokens" );
		request.Method = "POST";

		// Serialize the authentication details into the request.
		var serializer = new DataContractJsonSerializer( typeof( Authentication ) );
		serializer.WriteObject( request.GetRequestStream(), auth );

		// Get the response.
		var response = request.GetResponse();

		// Deserialize the authentication token.
		var deserializer = new DataContractJsonSerializer( typeof( PrimitiveType<string> ) );
		var token = (PrimitiveType<string>) deserializer.ReadObject( response.GetResponseStream() );

		// Return the token to the caller for future requests.
		Console.WriteLine( token.Value );
		return token.Value;
	}
}
var getToken = function (username, password, vault) {
	
		// Request an encrypted token with the login information.
		$.ajax({
			url: "http://example.org/REST/server/authenticationtokens.aspx",
			type: "POST",
			dataType: "json",
			contentType: "application/json",
			data: JSON.stringify({ Username: username, Password: password, VaultGuid: vault }),
			success: processToken
		});
	};
	
	var processToken = function (token) {
		// Set the header.
		$.ajaxSetup({ headers: { "X-Authentication" : token.Value } });
	};
Example 1: Requesting the authentication token.

Once the authentication token has been acquired it can be used in the requests by passing it in the X-Authentication header. Note authentication can be done with or without the vault GUID. Authenticating without the vault GUID allows access to the server-level resources such as the document vault collection. A vault-level authentication is required to access the information within a document vault.

Reading the resources

Once the authentication has been performed it is possible to access information within a document vault. This information is made available in terms of [resources/. Save for few exceptions all of these resources support the HTTP GET method which allows an application to request the current representation of the resource. The example below uses a GET request on the document vault root view resource found at /views/items to list all the views in the document vault root.

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using MFiles.Mfws.Structs;

public class RootViewSample
{
	public static void GetRootView( string authToken )
	{
		// Create the web request.
		var request = WebRequest.Create( "http://example.org/REST/views/items" );
		request.Headers[ "X-Authentication" ] = authToken;

		// Get the response.
		var response = request.GetResponse();

		// Deserialize the view.
		var deserializer = new DataContractJsonSerializer( typeof( FolderContentItems ) );
		var result = (FolderContentItems) deserializer.ReadObject( response.GetResponseStream() );

		foreach( var folderItem in result.Items )
		{
			if( folderItem.FolderContentItemType == MFFolderContentItemType.ViewFolder )
				Console.WriteLine( folderItem.View.Name );
		}
	}
}
var getRootItems = function () {

    // Post the object data.
    $.ajax({
        url: "http://example.org/REST/views/items.aspx",
        type: "GET",
        dataType: "json",
        success: processView
    });
};

var processView = function (folderContents) {
    $.each( folderContents, function (i, item) {

        // Ignore this if the item is not a view.
        if( item.FolderContentItemType !== 1 ) return;

        alert( item.View.Name );
    });
};
Example 2: Requesting the contents of the document vault root view.

Testing resource reading is easy with the browser itself. You can log in to M-Files Classic Web to establish the session. After this the GET-resources can be read with normal HTTP requests. However some browsers demand XML representation which MFWS is currently unable to provide for all resources. At least Internet Explorer 9 is able to read the resources in JSON format.

Writing the resources

Just like reading resources, modifying them by deleting or editing existing ones or creating new ones is done with basic HTTP requests as well. Each of these different operations has its own HTTP verb: POST for creating, PUT for editing and DELETE for deleting. However unlike GET, these other verbs are not available for all resources. The resource reference contains information on the resources and the methods available for them. The example example below below uses POST request on the documents collection resource found at /objects/0 to create a new document in the document vault.

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using MFiles.Mfws.Structs;

public class CreationSample
{
	public static ObjectVersion CreateObject( string authToken )
	{
		// Create the object creation info.
		var creationInfo = new ObjectCreationInfo
		{
			PropertyValues = new[]
			{
				new PropertyValue
				{
					PropertyDef = 0,
					TypedValue = new TypedValue { DataType = MFDataType.Text, Value = "Invoice" }
				},
				new PropertyValue
				{
					PropertyDef = 22,
					TypedValue = new TypedValue { DataType = MFDataType.Boolean, Value = false }
				},
				new PropertyValue
				{
					PropertyDef = 100,
					TypedValue = new TypedValue
					{
						DataType = MFDataType.Lookup,
						Lookup = new Lookup { Item = 0 }
					}
				}
			}
		};

		// Create the web request.
		var request = WebRequest.Create("http://example.org/REST/objects/0");
		request.Headers[ "X-Authentication" ] = authToken;
		request.Method = "POST";

		// Serialize the authentication details into the request.
		var serializer = new DataContractJsonSerializer(typeof (ObjectCreationInfo));
		serializer.WriteObject(request.GetRequestStream(), creationInfo);

		// Get the response.
		var response = request.GetResponse();

		// Deserialize the information on the created object.
		var deserializer = new DataContractJsonSerializer(typeof (ObjectVersion));
		var createdObject = (ObjectVersion) deserializer.ReadObject( response.GetResponseStream() );

		// Return the created object.
		Console.WriteLine(createdObject.Title);
		return createdObject;
	}
}
var createObject = function () {

    // Post the object data.
    $.ajax({
        url: "http://example.org/REST/objects/0.aspx",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            PropertyValues: [{
                    // Document name
                    PropertyDef: 0,
                    TypedValue: { DataType: 1, Value: "Invoice" }
                }, {
                    // "Single File" property
                    PropertyDef: 22,
                    TypedValue: { DataType: 8, Value: false }
                }, {
                    // Class.
                    PropertyDef: 100,
                    TypedValue: { DataType: 9, Lookup: { Item: 0 } }
                }],
            Files: []
        }),
        success: processDocument
    });
};

var processDocument = function (objectVersion) {
    alert( objectversion.Title + " created successfully." );
};
Example 3: Creating a new document.

Especially older IIS versions (5.1, 6.0) make it harder to use non GET or POST verbs with ASP.Net applications. While M-Files Web Service supports pure PUT and DELETE requests, the default IIS configuration for M-Files Classic Web doesn’t enable PUT and DELETE requests for IIS. For this reason M-Files Web Service supports a ?\_method=VERB query parameter which is the recommended way to communicate the PUT and DELETE intents. See compatibility for more information on this. Example below shows a PUT request on the check-out state resource.

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using MFiles.Mfws.Structs;

public class CheckOutSample
{
	public static void CheckOut( string authToken, int type, int id, int version )
	{
		// Create the web request.
		// Use the _method parameter to tunnel PUT through POST.
		var url = string.Format(
			"http://example.org/REST/objects/{0}/{1}/{2}/checkedout?_method=PUT",
			type, id, version );

		var request = WebRequest.Create( url );
		request.Headers[ "X-Authentication" ] = authToken;
		request.Method = "POST";

		// Serialize the authentication details into the request.
		var status = new PrimitiveType<MFCheckOutStatus> { Value = MFCheckOutStatus.CheckedOutToMe };
		var serializer = new DataContractJsonSerializer( status.GetType() );
		serializer.WriteObject( request.GetRequestStream(), status );

		var response = request.GetResponse();

		var deserializer = new DataContractJsonSerializer( typeof( ObjectVersion ) );
		var result = (ObjectVersion) deserializer.ReadObject( response.GetResponseStream() );

		Console.WriteLine( result.Title );
	}
}
var checkOut = function (type, id, version) {

    // Construct the URL.
    // .../REST/objects/(type)/(id)/(version)/checkedout?_method=PUT
    var url = "http://example.org/REST/objects/" +
              [type, id, version].join("/") +
              "/checkedout.aspx?_method=PUT";

    // Request an encrypted token with the login information.
    $.ajax({
        url: url, type: "POST", dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({ Value: 2 /* Checked out to me */ }),
        success: modifyObject
    });
};

var modifyObject = function (objectVersion) {
    // Object is checked out.
};
Example 4: Performing a check out.