Task-based asynchronous MUC room configuration

The question on how to change the configuration of a Muc room, or how to make a room persistend comes up very often in our forums and support enquiries.

Here is a small example using MatriX and the task based asynchronous pattern.

In MatriX most of the Muc functionality can be accessed with the MucManager component. We assume that you are familiar with the MucManager and have joined or created Muc rooms already.

In this small example we want to make an existing room persistent.
Four steps are required to achieve this:

  1. Request the current room configuration.
  2. Parse the current room configuration in code or render it to a GUI.
  3. Create the xdata result, either in code or from the user input in the GUI.
  4. Submit the new room configuration.

Here is the code:

private async void MakeRoomPersitent(Jid roomJid)
{	
	// Step 1, request the room configuration
	var iq = await mm.RequestRoomConfigurationAsync(roomJid);
	if (iq.Type == IqType.result) // only proceed on result
	{
		// Step 2 and 3, parsing the current config and
		// creating the	result is done in the same loop here.
		var xdata = iq.Query.Element<Data>();
		var xDataResult = new Data
		{
			Type = FormType.submit
		};

		foreach (var field in xdata.GetFields())
		{
			var retField = new Field()
			{
				Type = field.Type, // keep the type
				Var = field.Var // keep the var
			};

			// we are changing the muc#roomconfig_persistentroom only
			// other fields get copied only with the existing values			
			if (field.Var == "muc#roomconfig_persistentroom")
				retField.AddValue(true);
			else
				retField.AddValues(field.GetValues().ToArray());

			xDataResult.AddField(retField);
		}

		// Step 4, submit the changed configuration back to the server (room)
		var submitIq = await mm.SubmitRoomConfigurationAsync(roomJid, xDataResult);
		if (submitIq.Type == IqType.result)
			Debug.WriteLine("success");
		else
			Debug.WriteLine("something went wrong");
	}
}

If you want to render Data froms to UI, and generate responses from the UI input, you can use the sources in the MatriX.Ui project which can we downloaded from here:
http://www.ag-software.net/download-directory/

Leave a Reply

Your email address will not be published. Required fields are marked *