Duplicate Region not working

Hello,
So earlier I tried to change the code as per your documentation and as per your reply I tried to modify.
I think now its not working and I have attached template again as well. When I try to use same table twice it does not work 2nd time.
Following is the code: -
A CH61 APPROVAL (KL) (8).docx (87.9 KB)

System.IO.MemoryStream objstream = new MemoryStream(LetterTemplateEntity.CRSC_LETTER_TEMPLATE);
doc = TemplateEngine.ExecuteDocumentMerge(objstream, dS);
doc.MailMerge.TrimWhitespaces = true;

doc.MailMerge.MergeDuplicateRegions = true;

@vlbuch23 It looks like you are setting MergeDuplicateRegions options after executing mail merge. You should specify the options before executing mail merge.

So should be like this?

Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "Low", "", "Data in table for notification");
doc.MailMerge.MergeDuplicateRegions = true;
System.IO.MemoryStream objstream = new MemoryStream(LetterTemplateEntity.CRSC_LETTER_TEMPLATE);
                   
doc = TemplateEngine.ExecuteDocumentMerge(objstream, dS);

Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Document Merge Successful");

string doctype = LookupService.Instance.RetrieveLookupTableDescription(LookupTables.LK_DOCUMENT_TYPE,
                                        Util.ConvertToInt(LetterTemplateEntity.DOCUMENT_TYPE_ID.ToString()));

Issue with duplicate merge still a problem. Unable to use fields twice. Please if you can go through this code and let me know …


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

using SCORB.Common;
using SCORB.Common.Constants;
using SCORB.BusinessLogic;
using SCORB.BusinessLogic.Templates;
using SCORB.Entity;
using SCORB.Data.EntityClasses;
using SCORB.Data.HelperClasses;
using SCORB.Common.DTO;
using SCROB;
using Aspose.Words;
using SCORB.DAL;
using Aspose.Words.Saving;
using Aspose.Words.MailMerging;
using Aspose.Words.Replacing;
using System.Text.RegularExpressions;
using Aspose.Words.Tables;

public partial class CRSC_Notifications_GenerateNotificationLetters : System.Web.UI.Page
{
    private bool IsSysAdminUser = ((SCORB.Common.Security.SCORBPrincipal)HttpContext.Current.User).IsInAnyRole(UserRoles.System_Adminstrator, UserRoles.CRSC_System_Administrator, UserRoles.CRSC_Analyst);
    private bool IsEditableUser = ((SCORB.Common.Security.SCORBPrincipal)HttpContext.Current.User).IsInAnyRole(UserRoles.CRSC_Supervisor);
    private bool IsReadOnlyUser = ((SCORB.Common.Security.SCORBPrincipal)HttpContext.Current.User).IsInAnyRole(UserRoles.CRSC_Liasion, UserRoles.CRSC_Legal_Counsel);

    protected void Page_Load(object sender, EventArgs e)
    {
        //start ddn
        this.ValidationSummary.Enabled = true;
        //end ddn
        if (!Page.IsPostBack)
        {
            if (IsSysAdminUser || IsEditableUser || IsReadOnlyUser)
            {
                
                Master.SelectedValue = (int)CRSCCaseSubNavs.GenerateNotificationLetters;
                Master.CurrentSubNav = SubNavs.CRSCCaseDetails;
                BindLookupList();
                BindGridView();
                ConfigureScreen();
                if (!IsSysAdminUser)
                {
                    this.gridLetterView.Columns[5].Visible = false;
                    if (!IsEditableUser)
                    {
                        this.generatePanel.Visible = false;
                        this.AddNotification.Visible = false;
                    }
                }
            }
            else
            {
				Response.Redirect("/NotAuthorized.aspx", false);
            }
        }

    }

    protected void BindLookupList()
    {
        //Binding the DropDownList values to the values from the database
        //Populate the Template Drop Down List
        DataTable lkLetterTemplate = LookupService.GetLookup(LookupTables.LK_CRSC_LETTER_TEMPLATE.ToString());

        DataRow[] rows = lkLetterTemplate.Select("CRSC_LETTER_TEMPLATE_ID <>'" + Util.Config(ConfigKeys.DFASTLTemplateId).ToString() + "'");
        DataTable dt = lkLetterTemplate.Clone();

        foreach (DataRow myRow in rows)
        {
            dt.ImportRow(myRow);
        }

        DataView dv = dt.DefaultView;
        dv.Sort = "CRSC_LETTER_TEMPLATE_DESC";
        dt = dv.Table;

        Util.SetDropDown(dt, lkLetterTemplate.Columns[1].ToString(), lkLetterTemplate.Columns[0].ToString(),
        NotificationTypeDropDown, "");

        DataTable tailoredResponseTable = LookupService.GetLookup(LookupTables.LK_CRSC_TAILORED_RESPONSE.ToString());
        dt = tailoredResponseTable.Clone();
        // columns[8] is IS_DIAGNOSIS
        rows = tailoredResponseTable.Select(dt.Columns[8].ToString() + " = 0");
        foreach (DataRow myRow in rows)
        {
            dt.ImportRow(myRow);
        }

        dv = dt.DefaultView;
        dv.Sort = tailoredResponseTable.Columns[1].ToString();
        dt = dv.Table;

        SituationTailoredResponseListBox.DataSource = dt;
        SituationTailoredResponseListBox.DataTextField = dt.Columns[1].ToString();
        SituationTailoredResponseListBox.DataValueField = dt.Columns[0].ToString();
        SituationTailoredResponseListBox.DataBind();
        SituationTailoredResponseListBox.Items.Insert(0, "");

        // diagnosis listbox 

        dt.Clear();
        // columns[8] is IS_DIAGNOSIS
        rows = tailoredResponseTable.Select(dt.Columns[8].ToString() + " = 1");
        foreach (DataRow myRow in rows)
        {
            dt.ImportRow(myRow);
        }

        dv = dt.DefaultView;
        dv.Sort = tailoredResponseTable.Columns[1].ToString();
        dt = dv.Table;

        DiagnosisTailoredResponseListBox.DataSource = dt;
        DiagnosisTailoredResponseListBox.DataTextField = dt.Columns[1].ToString();
        DiagnosisTailoredResponseListBox.DataValueField = dt.Columns[0].ToString();
        DiagnosisTailoredResponseListBox.DataBind();
        DiagnosisTailoredResponseListBox.Items.Insert(0, "");
    }

    protected void GenerateNotificationLetter_Click(object sender, EventArgs e)
    {
        Logger.Instance.LogToDb(this.ToString(), "low", "", "Entering Generate Notification Block Level 0");
        if (Page.IsValid && Util.RetrieveQuerystringOrSessionId(QueryStrings.CASE_ID, Request) != 0)
        {
            Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Entering Generate Notification Block Level 1");

            try
            {
                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Entering Generate Notification Block Level 2 -- Try Block");

                int TemplateId = Int32.Parse(NotificationTypeDropDown.SelectedValue);

                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Parsed templateID Successfully -- Try Block");

				//Generate the notification history
                TBL_NOTIFICATION_HISTORY NotificationHistory = new TBL_NOTIFICATION_HISTORY();//start ddn

                NotificationHistory.CRSC_LETTER_TEMPLATE_ID = TemplateId;
                NotificationHistory.CREATED_BY = ((SCORB.Common.Security.SCORBIdentity)HttpContext.Current.User.Identity).UserID;
                NotificationHistory.CREATED_DATE = DateTime.Now;
                NotificationHistory.CRSC_CASE_ID = Util.RetrieveQuerystringOrSessionId(QueryStrings.CASE_ID, Request);

                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Generated Notification History Successfully");

				NotificationLetterController notifController = new NotificationLetterController();
                notifController.SaveNotificationHistory(NotificationHistory);


                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Saved Notification History Successfully");

                string tailoredResponseList = "";
                foreach (ListItem item in SituationTailoredResponseListBox.Items)
                {
                    if (item.Selected)
                        tailoredResponseList += item.Value + ",";
                }
                foreach (ListItem item in DiagnosisTailoredResponseListBox.Items)
                {
                    if (item.Selected)
                        tailoredResponseList += item.Value + ",";
                }

                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "tailoredResponseListGenerated Successfully");

                if (TemplateId == Int32.Parse(Util.Config(ConfigKeys.DDFORM149)) ||
                    TemplateId == Int32.Parse(Util.Config(ConfigKeys.DDFORM2860)))
                {
                    Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Parsed TemplateId Successfully");
                    GeneratePdfLetter(TemplateId);
                }

                NotificationLetterController notificationController = new NotificationLetterController();
                LK_CRSC_LETTER_TEMPLATE LetterTemplateEntity = notificationController.GetLetterTemplate(TemplateId);
                SessionManager session = new SessionManager();

                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Retrieved notification letter template successfully");

                TemplateController templateController = new TemplateController();
                DataSet dS = templateController.RetrieveFormData(int.Parse(session.GetSessionValue(SessionKeys.CaseId)), tailoredResponseList);
                Document doc = null;
              
                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Retrieved dataset of template controller successfully");

                if (dS.Tables.Count > 0)
                {
                    Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "Low", "", "Data in table for notification");

                    System.IO.MemoryStream objstream = new MemoryStream(LetterTemplateEntity.CRSC_LETTER_TEMPLATE);
                    doc = TemplateEngine.ExecuteDocumentMerge(objstream, dS);
                    doc.MailMerge.TrimWhitespaces = true;

                    doc.MailMerge.MergeDuplicateRegions = true;





                    Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Document Merge Successful");

                    string doctype = LookupService.Instance.RetrieveLookupTableDescription(LookupTables.LK_DOCUMENT_TYPE,
                                        Util.ConvertToInt(LetterTemplateEntity.DOCUMENT_TYPE_ID.ToString()));

                    Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Successfully converted to int");

                    if (SCORB.BusinessLogic.Controllers.FileUploadChecker.isValidFileExtension(doctype))
                    {
                        Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "File type correct");
                        //doc.Save(LetterTemplateEntity.CRSC_LETTER_TEMPLATE_DESC + doctype,
                        //    SaveFormat.FormatDocument, SaveType.OpenInWord, this.Response);
                        //doc.Save(LetterTemplateEntity.CRSC_LETTER_TEMPLATE_DESC + doctype,
                        //    SaveFormat.FormatDocument, SaveType.OpenInWord, this.Response);
                        //  doc.Save(this.Response, LetterTemplateEntity.CRSC_LETTER_TEMPLATE + doctype, ContentDisposition.Inline, new OoxmlSaveOptions());
                        //    doc.MailMerge.RemoveEmptyParagraphs = true;


                        
                        Regex regex = new Regex(" ");
                        FindReplaceOptions options = new FindReplaceOptions();
                        options.IgnoreFields = true;
                        
                        // Replace 'e' in document while ignoring deleted text.
                        options.IgnoreDeleted = true;
                        // doc.Range.Replace(regex, "", options);
                        doc.UpdateFields();
                        doc.Range.Replace(new Regex(@" <MiddleInitial>"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <PartyMiddleName>"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <MiddleName>"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <Vasrd>,"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <crsceffdates>,"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <Vasrd1>,"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <Vasrd2>,"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <Vasrd3>,"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <LatestDisabilityPercentage>,"), string.Empty, options);
                        doc.Range.Replace(new Regex(@" <VADiagnosticDesc>,"), string.Empty, options);
                        doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyTableRows | MailMergeCleanupOptions.RemoveUnusedFields | MailMergeCleanupOptions.RemoveEmptyParagraphs | MailMergeCleanupOptions.RemoveContainingFields;
                        doc.MailMerge.DeleteFields();
                        CleanupOptions cleanupOptions = new CleanupOptions();
                        cleanupOptions.UnusedBuiltinStyles = true;
                        doc.Cleanup(cleanupOptions);
                       
                       
                        //  doc.MailMerge.Execute(dS.Tables["DateRanges"]);
                        doc.Save(this.Response, LetterTemplateEntity.CRSC_LETTER_TEMPLATE_DESC.ToString() + ".docx", Aspose.Words.ContentDisposition.Inline, new OoxmlSaveOptions());
                     
                        Response.End();
                        Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "low", "", "Save was successful, exiting function");
                    }
                    else
                    {
                        throw new Exception("Error: not valid file format");
                    }
                }
                else
                {
                    Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "medium", "", "No rows in table for tailored response");
                }
            }
            catch (Exception ex)
            {
                string error = Util.LogApplicationError(ex);
                this.statusMessageLabel.Visible = true;
                this.statusMessageLabel.CssClass = "errormsg";
                this.statusMessageLabel.Text = "Document is incorrectly formatted. Please check the document or contact your Systems Administrator. Error Number: " + error; 
                Logger.Instance.LogToDb(this.ToString() + "/GenerateNotificationLetter_Click", "High", "",
                    " Exception=" + ex.Message +
                    (ex.InnerException != null ? "|InnerException=" + ex.InnerException : string.Empty) +
                    (ex.StackTrace != null ? "|StackTrace=" + ex.StackTrace : string.Empty));
            }
        }
    }

    private void BindGridView()
    {
        NotificationLetterController notificationLetter = new NotificationLetterController();

        int caseId = Util.RetrieveQuerystringOrSessionId(QueryStrings.CASE_ID, Request);
        gridLetterView.DataSource = notificationLetter.GetAllCaseNotifications(caseId);
        gridLetterView.DataBind();

		GeneratedNotificationHistory.DataSource = notificationLetter.GetNotificationHistoryList(caseId);
		GeneratedNotificationHistory.DataBind();
    }
	
    protected void gridLetterView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int NotificationLetterId = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName.Equals("ViewNotification"))
        {
            Response.Redirect(string.Format("NotificationLetterDetail.aspx?" + QueryStrings.NOTIFICATION_LETTER_ID
			+ "={0}", NotificationLetterId), false);
        }

        if (e.CommandName.Equals("DeleteNotification"))
        {
            //start ddn
            this.ValidationSummary.Enabled = false;
            //end ddn
            NotificationLetterController notificationcontroller = new NotificationLetterController();
            notificationcontroller.DeleteNotification(NotificationLetterId);
            BindGridView();

        }

        if (e.CommandName.Equals("DownloadNotification"))
        {
            DownloadNotification(NotificationLetterId);
        }
    }
	protected void GeneratedNotificationHistory_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		int NotificationHistoryId = Convert.ToInt32(e.CommandArgument);	
		if (e.CommandName.Equals("DeleteNotificationHistory"))
		{
			NotificationLetterController notificationcontroller = new NotificationLetterController();
			notificationcontroller.DeleteNotificationHistory(NotificationHistoryId);
			BindGridView();

		}
	}

    protected void GeneratedNotificationHistory_OnPageIndexChanging(Object sender, GridViewPageEventArgs e)
    {
        GeneratedNotificationHistory.PageIndex = e.NewPageIndex;
        BindGridView();
        //GeneratedNotificationHistory.DataBind();
       
    }

    protected void GeneratedNotificationHistory_PageIndexChanged(Object sender, EventArgs e)
    {

    }
    protected void gridLetterView_OnPageIndexChanging(Object sender, GridViewPageEventArgs e)
    {
        gridLetterView.PageIndex = e.NewPageIndex;
        gridLetterView.DataBind();
    }

    protected void gridLetterView_PageIndexChanged(Object sender, EventArgs e)
    {
    }

    protected void AddNotificationLetter_Click(object sender, EventArgs e)
    {
        SessionManager session = new SessionManager();
        session.RemoveSessionValue(SessionKeys.NotificationLetterId);

        Response.Redirect(string.Format("NotificationLetterForm.aspx?" + QueryStrings.CASE_ID + "={0}",
		  Util.RetrieveQuerystringOrSessionId(QueryStrings.CASE_ID, Request)), false);
    }

    private void ConfigureScreen()
    {
        this.statusMessageLabel.Visible = true;
        this.statusMessageLabel.CssClass = "confirmmsg";
        this.statusMessageLabel.Text = GetStatusMessage();
    }

    private string GetStatusMessage()
    {
        SessionManager sessionManager = new SessionManager();
        string statusmessage;

        statusmessage = sessionManager.GetSessionValue(SessionKeys.ConfirmationMessage);
        sessionManager.RemoveSessionValue(SessionKeys.ConfirmationMessage);

        return statusmessage;
    }

    protected void DownloadNotification(int NotificationLetterId)
    {
        using (SCORBEntities context = new SCORBEntities())
        {

            NotificationLetterController notificationController = new NotificationLetterController();
            TBL_NOTIFICATION_LETTER notificationEntity = notificationController.GetNotification(NotificationLetterId);

            //clear the current output contents from the buffer
            Response.Clear();

            //add the header that specifies the default filename for the Download/SaveAs dialog
            Response.AddHeader("Content-Disposition", "attachment; filename=" +
                notificationEntity.NOTIFICATION_LETTER_DESC);

            //add the header that specifies the file size, so that the browser can show
            //the download progress.
            Response.AddHeader("Content-Length", notificationEntity.LETTER.Length.ToString());

            //specify that the response is a stream that cannot be read by the 
            //client and must be downloaded
            Response.ContentType = "application/octet-stream";

            //Write the binary file to the output word document
            Response.BinaryWrite(notificationEntity.LETTER);

            //stop the execution of the page
            Response.End();
        }
    }

    protected void GeneratePdfLetter(int templateId)
    {
        NotificationLetterController notificationletterController = new NotificationLetterController();
        LK_CRSC_LETTER_TEMPLATE letterTemplateEntity = notificationletterController.GetLetterTemplate(templateId);

        if (letterTemplateEntity.DOCUMENT_TYPE_ID == Int32.Parse(Util.Config(ConfigKeys.TemplateDocTypeWord)))
        {
            return;
        }

        string doctype = LookupService.Instance.RetrieveLookupTableDescription(LookupTables.LK_DOCUMENT_TYPE,
                            Util.ConvertToInt(letterTemplateEntity.DOCUMENT_TYPE_ID.ToString()));

        //clear the current output contents from the buffer
        Response.Clear();

        //add the header that specifies the default filename for the Download/SaveAs dialog
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
                        letterTemplateEntity.CRSC_LETTER_TEMPLATE_DESC + doctype);

        //add the header that specifies the file size, so that the browser can show
        //the download progress.
        Response.AddHeader("Content-Length", letterTemplateEntity.CRSC_LETTER_TEMPLATE.Length.ToString());

        //specify that the response is a stream that cannot be read by the 
        //client and must be downloaded
        Response.ContentType = "application/octet-stream";

        //Write the binary file to the output pdf document
        Response.BinaryWrite(letterTemplateEntity.CRSC_LETTER_TEMPLATE);

        //stop the execution of the page
        Response.End();
    }
}

@vlbuch23 In your code I do not see that you execute mail merge. I see you set mail merge options and remove merge fields, but there is no MailMerge.Execute or MailMerge.ExecuteWithRegions calls in your code. The options I have suggested works only upon executing mail merge. For example see the following code:

// Create some dummy data
DataTable dt = new DataTable("DateRanges");
dt.Columns.Add("crsceffdates");
dt.Columns.Add("VaEffStartDt");
dt.Rows.Add("val1_1", "val1_2");
dt.Rows.Add("val2_1", "val2_2");
dt.Rows.Add("val3_1", "val3_2");

// Open template.
Document doc = new Document(@"C:\Temp\in.docx");

// Set mail merge options.
doc.MailMerge.MergeDuplicateRegions = true;

// Execute mail merge.
doc.MailMerge.ExecuteWithRegions(dt);

doc.Save(@"C:\Temp\out.docx");

So I would suggest you to move setting MailMerge.MergeDuplicateRegions to the place before executing mail merge with regions.

Hi, Thank you for the reply, There is if you look closely.

System.IO.MemoryStream objstream = new MemoryStream(LetterTemplateEntity.CRSC_LETTER_TEMPLATE);
doc = TemplateEngine.ExecuteDocumentMerge(objstream, dS);
doc.MailMerge.TrimWhitespaces = true;

doc.MailMerge.MergeDuplicateRegions = true;

@vlbuch23 I suspect template is opened and mail merge is executed in TemplateEngine.ExecuteDocumentMerge method. So setting mail merge options should be moved into this method too. Just set the required mail merge options right before calling MailMerge.ExecuteWithRegions or MailMerge.Execute methods call.

So you are saying do it like this?

System.IO.MemoryStream objstream = new MemoryStream(LetterTemplateEntity.CRSC_LETTER_TEMPLATE);
doc.MailMerge.MergeDuplicateRegions = true;
doc.MailMerge.ExecuteWithRegions(dS);
doc = TemplateEngine.ExecuteDocumentMerge(objstream, dS);
//doc.MailMerge.TrimWhitespaces = true;

@vlbuch23 No, you do not have doc before TemplateEngine.ExecuteDocumentMerge method is called. I suspect, Document is created from objstream inside TemplateEngine.ExecuteDocumentMerge. So you should modify this method.

Like this order? Can you please show me.

 doc.MailMerge.MergeDuplicateRegions = true;
doc.MailMerge.ExecuteWithRegions(dS);
System.IO.MemoryStream objstream = new MemoryStream(LetterTemplateEntity.CRSC_LETTER_TEMPLATE);
                    
doc = TemplateEngine.ExecuteDocumentMerge(objstream, dS);
//doc.MailMerge.TrimWhitespaces = true;

@vlbuch23 Order must be like this:

// Open template.
Document doc = new Document(@"C:\Temp\in.docx");
// Set mail merge options.
doc.MailMerge.MergeDuplicateRegions = true;
// Execute mail merge.
doc.MailMerge.ExecuteWithRegions(dt);

You are trying to change the order of calls in wrong place. You should go to sources of TemplateEngine.ExecuteDocumentMerge method and modify it.

So write. TemplateEngine is doing this part I have included the code below.

private static void BindRegionFields(Document doc, DataSet ds)
{

    TemplateMapping[] fields = TemplateMappings.GetByFieldType(MergeFieldType.Region);

    string[] mergeFields = doc.MailMerge.GetFieldNames();

    // Sort mergeFields array, otherwise BinarySearch will not work
    Array.Sort(mergeFields);
    TemplateMapping mapping = null;
    for (int i = 0; i < fields.Length; i++)
    {
        mapping = fields[i];

        int searchResult = Array.BinarySearch(mergeFields, mapping.MergeField);
        if (searchResult >= 0)
        {
            switch (mapping.MappingName)
            {
                case "DisabilityTable":
                    DataTable crDisaDT = ds.Tables[mapping.DataField]; //DM
                    doc.MailMerge.MergeDuplicateRegions = true;
                    doc.MailMerge.ExecuteWithRegions(crDisaDT);
                    break;
                case "NonCombatRelatedDisabilityTable":
                    DataTable noncrDisaDT = ds.Tables[mapping.DataField];
                    doc.MailMerge.MergeDuplicateRegions = true;
                    doc.MailMerge.ExecuteWithRegions(noncrDisaDT);
                    break;
                case "TailoredResponseListTable":
                    if (ds.Tables[mapping.DataField] != null)
                        doc.MailMerge.MergeDuplicateRegions = true;
                    doc.MailMerge.ExecuteWithRegions(ds.Tables[mapping.DataField]);
                    break;
                case "DFASTLTable":
                    DataTable dfasTLDT = ds.Tables[mapping.DataField];
                    if (dfasTLDT != null)
                        doc.MailMerge.MergeDuplicateRegions = true;
                    doc.MailMerge.ExecuteWithRegions(dfasTLDT);
                    break;
                case "SecondaryParty":
                    DataTable secPartyDT = ds.Tables[mapping.DataField];
                    doc.MailMerge.MergeDuplicateRegions = true;
                    doc.MailMerge.ExecuteWithRegions(secPartyDT);
                    break;
                case "CombinedCRSCPercentages":
                    DataTable combCrscPctDT = ds.Tables[mapping.DataField];
                    //DataTable dt = ds.Tables[mapping.DataField];
                    doc.MailMerge.MergeDuplicateRegions = true;
                    doc.MailMerge.ExecuteWithRegions(combCrscPctDT);
                    // doc.MailMerge.ExecuteWithRegions(dt);
                    break;
                case "NonCombatRelatedVasrd":
                    DataTable noncrVasrdDT = ds.Tables[mapping.DataField];
                    doc.MailMerge.MergeDuplicateRegions = true;
                    doc.MailMerge.ExecuteWithRegions(noncrVasrdDT);
                    break;
                default:
                    break;
            }
        }
    }
}

@vlbuch23 I see in some cases MergeDuplicateRegions option is set conditionally. Maybe this causes the problem. I think, you can simply set the option at the beginning of this method.

So like this below should work?

TemplateMapping[] fields = TemplateMappings.GetByFieldType(MergeFieldType.Region);
doc.MailMerge.MergeDuplicateRegions = true;
string[] mergeFields = doc.MailMerge.GetFieldNames();

// Sort mergeFields array, otherwise BinarySearch will not work
Array.Sort(mergeFields);
TemplateMapping mapping = null;
for (int i = 0; i < fields.Length; i++)
{
    mapping = fields[i];

    int searchResult = Array.BinarySearch(mergeFields, mapping.MergeField);


    if (searchResult >= 0)
    {
        switch (mapping.MappingName)
        {
            case "DisabilityTable":
                DataTable crDisaDT = ds.Tables[mapping.DataField]; //DM
                doc.MailMerge.ExecuteWithRegions(crDisaDT);
                break;
            case "NonCombatRelatedDisabilityTable":
                DataTable noncrDisaDT = ds.Tables[mapping.DataField];

                doc.MailMerge.ExecuteWithRegions(noncrDisaDT);
                break;
            case "TailoredResponseListTable":
                if (ds.Tables[mapping.DataField] != null)

                    doc.MailMerge.ExecuteWithRegions(ds.Tables[mapping.DataField]);
                break;
            case "DFASTLTable":
                DataTable dfasTLDT = ds.Tables[mapping.DataField];
                if (dfasTLDT != null)

                    doc.MailMerge.ExecuteWithRegions(dfasTLDT);
                break;
            case "SecondaryParty":
                DataTable secPartyDT = ds.Tables[mapping.DataField];

                doc.MailMerge.ExecuteWithRegions(secPartyDT);
                break;
            case "CombinedCRSCPercentages":
                DataTable combCrscPctDT = ds.Tables[mapping.DataField];
                //DataTable dt = ds.Tables[mapping.DataField];

                doc.MailMerge.ExecuteWithRegions(combCrscPctDT);
                // doc.MailMerge.ExecuteWithRegions(dt);
                break;
            case "NonCombatRelatedVasrd":
                DataTable noncrVasrdDT = ds.Tables[mapping.DataField];

                doc.MailMerge.ExecuteWithRegions(noncrVasrdDT);
                break;
            default:
                break;
        }
    }
}
}

My above modification did the trick and this solves a lot of issues I was having. It was blocking me to print fields twice.

1 Like