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();
}
}