Monday 19 December 2011

Word Automation Services: Asynchronous

What that Means


That has two important consequences for solutions:

  • First, it means that you don't know immediately when a conversion has completed – the Start() call for a ConversionJob returns as soon as the job is submitted into the queue. You must monitor the job's status (via the ConversionJobStatus object) or use list-level events if you want to know when the conversion is complete and/or perform actions post-conversion.

  • Second, it means that maximum throughput is defined by the frequency with which the queue is polled for work, and the amount of new work requested on each polling interval.


Dissecting those consequences a little further:

Asynchronous


The asynchronous nature of the service means you need to set up your solutions to use either list events or the job status API to find out when a conversion is complete. For example, if I wanted to delete the original file once the converted one was written, as commenter Flynn suggested, I would need to do something like this:
public void ConvertAndDelete(string[] inputFiles, string[] outputFiles)
{
    //start the conversion
    ConversionJob job = new ConversionJob("Word Automation Services");
    job.UserToken = SPContext.Site.UserToken;
    for (int i = 0; i < inputFiles.Count; i++)
        job.AddFile(inputfiles[i], outputFiles[i]);
    job.Start();

    bool done = false;
    while(!done)
    {
        Thread.Sleep(5000);
        ConversionJobStatus status = new ConversionJobStatus("Word Automation Services", jobId, null);
        
        if(status.Count == (status.Succeeded + status.Failed + status.Canceled)) //everything done
        {
            done = true;
            
            //only delete successful conversions
            ConversionItemInfo[] items = status.GetItems(ItemType.Succeeded);
            foreach(ConversionItemInfo item in items)
                SPContext.Web.Files.Delete(item);
        }
    }
}

Now, clearly using Thread.Sleep isn't something you'd want to do if this is going to happen on many threads simultaneously on the server, but you get the idea – a workflow with a Delay activity is another example of a solution to this situation.

No comments:

Post a Comment