Conditional logic- if statements in Word Mail Merge

Donald,
Thanks for all your input. I just want to confirm that we did not work on field evaluation all this time because we always had a queue of no less critical tasks for the wider acceptance of the product.
What you are asking now is the most important part actually. It might be easy to replace/change what you want in a simple case, but more complex to code for more general cases.

Hi Donald,

Here is code example that shows how to evaluate simple IF statement in MS Word document:

public void Test181()
{
    // Open document
    Document doc = new Document(@"Test181\in.doc");
    // Execute mail merge
    doc.MailMerge.Execute(new string[] { "field1", "field2" }, new object[] { "test", "test1" });
    // Evaluate IF fields
    EvaluateIfContidions(doc);
    // Save output document
    doc.Save(@"Test181\out.doc");
}
private void EvaluateIfContidions(Document document)
{
    // Get collection of field starts
    NodeCollection starts = document.GetChildNodes(NodeType.FieldStart, true);
    // Loop through all field starts
    foreach (FieldStart start in starts)
    {
        // Check whether current FieldStart is start of IF field
        if (start.FieldType == FieldType.FieldIf)
        {
            // Field code is represented by content between Field Start and FieldSeparator
            string fieldCode = string.Empty;
            Node currentNode = start.NextSibling;
            while (currentNode.NodeType != NodeType.FieldSeparator)
            {
                Run fieldPart = currentNode as Run;
                if (fieldPart != null)
                    fieldCode += fieldPart.Text;
                // Move to next node
                currentNode = currentNode.NextSibling;
            }
            // Now we sould get Run that represents field value (displayed text)
            // Field values is located betwee FieldSeparator and FieldEnd values
            Run fieldValueRun = null;
            while (currentNode.NodeType != NodeType.FieldEnd)
            {
                fieldValueRun = currentNode as Run;
                if (fieldValueRun != null)
                    break;
                currentNode = currentNode.NextSibling;
            }
            // Now we shoule evaluate If condition
            // We will use regular expressions to achieve this
            if (fieldValueRun != null)
                fieldValueRun.Text = GetValueFromFieldCode(fieldCode);
        }
    }
}
private string GetValueFromFieldCode(string fieldCode)
{
    Console.WriteLine(fieldCode);
    // This method is just a demo, so we will evaluate only simple If condition
    // like IF "val1" = "val2" "True value" "False value"
    // Create regular expression that will help us to get all parts of condition
    Regex regex = new Regex("\\s*(?\\S+)\\s+" + // This is start of field. in our case it will be "IF"
    "((?[^\\s\"]+)|(\"(?[^\"]+)\"))" + // This is first option of condition
    "\\s+" + // Condition and operator must be separated by white space (of several white spaces)
    "(?\\S+)" + // This is condition operator (we will process only "=" operator)
    "\\s+" +
    "((?[^\\s\"]+)|(\"(?[^\"]+)\"))" + // The socond option
    "\\s+" +
    "((?[^\\s\"]+)|(\"(?[^\"]+)\"))" + // Text that will be displayed if condition is true
    "\\s+" +
    "((?[^\\s\"]+)|(\"(?[^\"]+)\"))" + // Text that will be displayed is condition is false
    "\\s+(?.+)");
    // Match our field code
    Match match = regex.Match(fieldCode);
    if (!match.Groups["operator"].Value.Equals("="))
        throw new InvalidOperationException("Unsupported operator. Only '=' operator is supported");
    // Return neccessary value
    if (match.Groups["option1"].Value == match.Groups["option2"].Value)
        return match.Groups["trueText"].Value;
    else
        return match.Groups["falseText"].Value;
}

Sample document are also attached.
Hope this helps.
Best regards.

The issues you have found earlier (filed as 126;37) have been fixed in this update.


This message was posted using Notification2Forum from Downloads module by aspose.notifier.

Great news. Do you have any examples of how to use this functionality? I looked in the help file and the demos folder and didn’t find anything. I’ve experimented some and haven’t had any luck as of yet getting it to work. What format is the IF MergeField supposed to be? Does it support IF fields inside of a Merge Region?

Thanks.

Hi

Thanks for your inquiry. Here is simple code example, which shows how you can use this feature:

// Open document.
Document doc = new Document(@"Test001\in.doc");
// Execute mail merge.
doc.MailMerge.Execute(new string[] {"test"}, new object[] {"true"});
// Update fields in the document.
doc.UpdateFields();
// Save output document
doc.Save(@"Test001\out.doc");

Also, I attached simple template. Hope this helps.
If you have problems, please attach your template here for testing.
Best regards.

It was the doc.UpdateFields(); statement that I was missing.Thanks.

Are you sure?
When you call MailMerge.Execute it actually updates all fields inside a mail merge region or in the whole document if there is no mail merge region. I wrote about this in the Field Update topic in the documentation and also in the documentation for the UpdateFields method.
We also have tests that confirm this is the case. If this does not work for you, please attach your document here and our support will try to reproduce, it will need to be fixed.
Aspose.Words must upate all fields during mail merge because MERGEFIELD could be nested inside IF and not only the inner MERGEFIELD but also the outer IF need to be evaluated and so on for all fields.

You are correct. I was mistaken. The UpdateFields method is not necessary. I had a deployment issue that happened to get fixed at the same time I added that method.