Screen changes during customization disappearing after exiting and coming back in

Initially, the screen is similar to your screen shots, and i set the visibility to “False” for those control and then added the controls I wanted.

I didn’t know that Epicor could change the visibility on a fly, so I will try using the hide on loading of the screen.

It may have added issues with UDs over 100 that are parent child. I have only used the single table UDs to do this with.

Here is the code to hide the tree and main panel, if you need it.

		Epicor.Mfg.UI.FrameWork.EpiTreeViewPanel TreeViewPanel = (Epicor.Mfg.UI.FrameWork.EpiTreeViewPanel)csm.GetNativeControlReference("d3a4fa73-e037-484e-8c93-1f930be38abf");
		Epicor.Mfg.UI.App.UD04Entry.MainPanel MainPanel = (Epicor.Mfg.UI.App.UD04Entry.MainPanel)csm.GetNativeControlReference("1dff11bc-3024-4d17-acfc-b7af287e274b");
		TreeViewPanel.Dispose();
		MainPanel.Dispose();


Thanks, I will give that a try.

One more thing, in Epicor 9 this object Epicor.Mfg.UI.Rpt.ARInvForm.Transaction is used for invoice printing. What is the object should that is the replacement for this in Epicor 10?

I tried this Erp.UIRpt.ARInvForm.Transaction (making a reference to Erp.UIRpt.ARInvForm) but get error that UIRpt is not a part of Erp.

If the controls you’re talking about are Key fields, I believe you’ll find posts here that say the best way to “hide” them is to move them off screen with a really high or negative x,y values

1 Like

On EpicWeb for your version there will be ERP_BO_Ref_10.x.xxx file that will have the BOs. You should also be able to find doing a trace of the process. Use the BL Tester to figure out the call.

If this existed in E9 did it fail getting converted?

In E9, the object was Epicor.Mfg.UI.Rpt.ARInvForm.Transaction. What I would like to know, is what is the replacement for this object in E10, so that I can use it to do Batch Invoice Printing.

Okay, I will be trying the suggestion of @gpayne first and if that doesn’t work, then I will try your suggestion.
Thanks,

To find that you will need to run the mass print in AR Invoice entry with tracing on and then you can use the Trace Parser that @josecgomez made at the link below to find the object. Then use the BL Tester to work out the calls needed.

Thank you. Trying this today.

It was mentioned earlier that this is a UD form, and that the main controls can’t be made not visible.
Is that the extent of your issues?

Can you export the Customization then post it here?

Or at least show screen shots of what it looks like in developer mode, and what you see when launched in normally.

There are 2 issues:

  1. This is the UD form controls not showing my changes when I exit customization and go back in. The screen would go back to its original layout. I have been trying to use the visible property to hide the controls II do not need and @gpayne suggested using code to hide them instead. @Mark_Wonsil suggested moving the controls off screen. Will be trying @gpayne suggestion first and see how that works.

  2. This one is about reference object. As mentioned above, I am trying to find the E10 replacement for an E9 object ( Epicor.Mfg.UI.Rpt.ARInvForm.Transaction) and that is what @gpayne is referring to.

1 Like

This solution did work. As all of the controls returned to their original position.

Try this Roy

I will look into this.

So this has been resolve.
As a novice in Epicor, and thinking as a VS developer, I did not realize that if there are errors in the code when the screen loads, all screen changes revert back to default. Lesson learned, lesson not soon forgot.

Thank you everyone for your help.
Very much appreciated.

As mentioned before never remove UD key fields it will screw up the form interactions entirely. They must remain visible = true. How you deal with them otherwise as far as a user is concerned matters not (size, location)

Background on why the errors (unlike in VS stop the screen from loading), when you open a customization it compiles the code on the fly (exactly like build in VS) and saves the compiled customization to your local cache folder. This is one example of why a decent processor is required for client workstations, they are doing code compile builds on their actual machine. Imagine running VS builds on an Intel i3… it would be horribly slow, enter slow initial screen loads (when it says “Downloading from Database”). This is why if a change isn’t recognized, customizations can get “stuck” as an older version and you have to clear cache.

2 Likes

Thank you everyone, I was able to get pass the initial issues with help.

I continue to have other issues with the AR Batch Printing. I have been able to get a list of invoices however, it is not doing the filtering based on Customer selected, so I am getting the entire database list of invoices.

I have attached the entire code here. The issue I am having seems to start in function btnSearch_Click(). Thanks in advance for your help.

// **************************************************
// Custom code for UD110Form
// Created: 10/17/2014 2:43:06 PM
// **************************************************
using System;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using Ice.Lib;
using Erp.BO;
using Ice.BO;
using Ice.Proxy.BO;
using Ice.UI;
using Ice.Adapters;
using Erp.Adapters;
using Ice.Lib.Customization;
using Ice.Lib.ExtendedProps;
using Ice.UI.FormFunctions;
using Ice.Lib.Framework;
using Ice.Lib.Searches;

using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinProgressBar;
using System.Collections;
using System.Collections.Generic;
using System.Net.Mail;
using System.IO;
using System.Threading;
using System.Reflection;

public static class Script
{
// ** Wizard Insert Location - Do Not Remove ‘Begin/End Wizard Added Module Level Variables’ Comments! **
// Begin Wizard Added Module Level Variables **

// End Wizard Added Module Level Variables **

// Add Custom Module Level Variables Here **
private static Ice.Core.Session session;
static InvcPrinter invcPrinter;
static Hashtable custContacts;	// Contacts for each customer
//static Hashtable custInvoices;	// emailed invoices for each customer (table row's DataRow)
static UD110Adapter ud110adapter;
static CustCntAdapter custCntAdapter;
static UltraProgressBar progressBar;
static string dataDir, serverDir;
static object crystalRpt;	// ReportDocument
static string crystalRptFile;
static PrintDialog dialog;
static Thread thread;
static bool threadAborted = false;
static string action;	// PRINT, PDF or MAIL
static Assembly crystalEngine, crystalShared;
static bool KeepGeneratedFiles;
private static string lastCustID="";

public static void InitializeCustomCode()
{
	epiCheckEmailCopySelf.Checked=true;
	// ** Wizard Insert Location - Do not delete 'Begin/End Wizard Added Variable Initialization' lines **
	// Begin Wizard Added Variable Initialization
	baseToolbarsManager.ToolClick += new Infragistics.Win.UltraWinToolbars.ToolClickEventHandler(baseToolbarsManager_ToolClick);
	UD110Form.Closing += new System.ComponentModel.CancelEventHandler(UD110Form_Closing);
	// End Wizard Added Variable Initialization

	// Begin Wizard Added Custom Method Calls
	Script.buttonShipTo.Click += new System.EventHandler(Script.buttonShipTo_Click);
	Script.buttonCustomer.Click += new System.EventHandler(Script.buttonCustomer_Click);
	Script.txtCustID.LostFocus += new System.EventHandler(Script.txtCustID_LostFocus);
	Script.btnSearch.Click += new System.EventHandler(Script.btnSearch_Click);
	Script.buttonEmail.Click += new System.EventHandler(Script.buttonEmail_Click);
	Script.buttonPrint.Click += new System.EventHandler(Script.buttonPrint_Click);
	Script.buttonCloseContactList.Click += new System.EventHandler(Script.buttonCloseContactList_Click);
	Script.btnContinue.Click += new System.EventHandler(Script.btnContinue_Click);
	// End Wizard Added Custom Method Calls
	session = (Ice.Core.Session)oTrans.Session;
	// Hide tree
	((Infragistics.Win.UltraWinDock.WindowDockingArea)csm.PersonalizeCustomizeManager.ControlsHT["UD110Form.windowDockingArea1"]).Visible = false;
	//csm.GetNativeControlReference("46c8ee42-a6f1-468b-95ba-6dfc13223ee2").Parent.Parent.Visible = false;
	//csm.GetNativeControlReference("42ddcd10-9993-46f8-86e5-de797a96c3b8").Parent.Visible = false;
	
	KeepGeneratedFiles = false;
	invcPrinter = new InvcPrinter(oTrans);
	custContacts = new Hashtable();
	//custInvoices = new Hashtable();

	custCntAdapter = new CustCntAdapter(oTrans);
	custCntAdapter.BOConnect();
	ud110adapter = new UD110Adapter(oTrans);
	ud110adapter.BOConnect();
	DataRow row;
	try {
		ud110adapter.GetByID("INVOICE_MAILER","SUBJECT_BODY","","","");
		row = ud110adapter.UD110Data.UD110.Rows[0];
	} catch {
		ud110adapter.GetaNewUD110();
		row = ud110adapter.UD110Data.UD110.Rows[ud110adapter.UD110Data.UD110.Rows.Count-1];
		row["Key1"] = "INVOICE_MAILER";
		row["Key2"] = "SUBJECT_BODY";
		row["Character01"] = "CAToronto shipment invoices";
		row["Character02"] = "Good day. Attached you will find invoice(s) for shipments. "
			+ "Please email the sender OR your customer service rep with any discrepancies.";
		ud110adapter.Update();
	}
	//MessageBox.Show("loaded UD110");  //DEBUGGING CODE
	// Add Progress Bars to status panel
	progressBar = new UltraProgressBar();
	Control statusBar = oTrans.StatusPanel.UltraStatusBar;
	int w = statusBar.Width, h = statusBar.Height;
    progressBar.Location = new System.Drawing.Point(500,3);
    progressBar.Size = new System.Drawing.Size(200, h-6);
	//MessageBox.Show("Prepped progressBar");  //DEBUGGING CODE
	progressBar.Step = 1;
	progressBar.Text = "Files processed: "+UltraProgressBar.LABEL_VALUE;
	//progressBar.Visible = false;
	//MessageBox.Show("Set ProgressBar incrementals"); //DEBUGGING CODE
    statusBar.Controls.Add(progressBar);
	//MessageBox.Show("Added progressbar to astatus bar");  //DEBUGGING CODE
	//MessageBox.Show("Process to 'InitializeCustomCode' complete.");  //DEBUGGING CODE
}

public static void DestroyCustomCode()
{
	// ** Wizard Insert Location - Do not delete 'Begin/End Wizard Added Object Disposal' lines **
	// Begin Wizard Added Object Disposal
	baseToolbarsManager.ToolClick -= new Infragistics.Win.UltraWinToolbars.ToolClickEventHandler(baseToolbarsManager_ToolClick);
	UD110Form.Closing -= new System.ComponentModel.CancelEventHandler(UD110Form_Closing);
	Script.buttonShipTo.Click -= new System.EventHandler(Script.buttonShipTo_Click);
	Script.buttonCustomer.Click -= new System.EventHandler(Script.buttonCustomer_Click);
	Script.txtCustID.LostFocus -= new System.EventHandler(Script.txtCustID_LostFocus);
	Script.btnSearch.Click -= new System.EventHandler(Script.btnSearch_Click);
	Script.buttonEmail.Click -= new System.EventHandler(Script.buttonEmail_Click);
	Script.buttonPrint.Click -= new System.EventHandler(Script.buttonPrint_Click);
	Script.buttonCloseContactList.Click -= new System.EventHandler(Script.buttonCloseContactList_Click);
	Script.btnContinue.Click -= new System.EventHandler(Script.btnContinue_Click);
	// End Wizard Added Object Disposal

	// Begin Custom Code Disposal
	ud110adapter.Dispose();
	custCntAdapter.Dispose();
	// End Custom Code Disposal
}

private static void baseToolbarsManager_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs args)
{
	if (args.Tool.Key == "ClearTool") {
		//txtInvcStart.Value = txtInvcEnd.Value = dteStartDate.Value = dteEndDate.Value = txtCustomer.Value = null;
		
		txtCustID.Text = "";
		lastCustID = "";
		numericCustNum.Value = 0;
		txtShiptoNum.Text="";
		
		gridHeader.DataSource = new DataTable();
		gridHeader.Refresh();
		gridDetails.DataSource = new DataTable();
		gridDetails.Refresh();
		//gridDetails.Text = "";
		gridContacts.DataSource =new DataTable();
		groupContactSelector.Visible = false;
	}
}


private static void UD110Form_Closing(object sender, System.ComponentModel.CancelEventArgs args)
{
	if (thread != null && thread.IsAlive) {
		DialogResult res = EpiMessageBox.Show("A print job is running. Abort?", "", MessageBoxButtons.YesNo);
		args.Cancel = (res == DialogResult.No);
		if (args.Cancel) {
			threadAborted = true;
			thread.Abort();
		}
	}
}

private static void txtCustID_LostFocus(object sender, System.EventArgs args)
{
	if (string.Compare(lastCustID, txtCustID.Text.Trim(), true)==0)	return;	
	groupContactSelector.Visible=false;
	if (txtCustID.Text.Trim().Length<= 0)
	{
		numericCustNum.Value = 0;
		lastCustID = "";
		gridContacts.DataSource =new DataTable();
		groupContactSelector.Visible = false;
		return;
	}
	txtShiptoNum.Text="";
	bool recSelected;
	string whereClause = "CustId = '" + txtCustID.Text.Trim() + "'"; 
	SearchOnCustomerAdapterShowDialog(whereClause , false);
}

private static void buttonCustomer_Click(object sender, System.EventArgs args)
{

////////////DEBUGGING CODE … BELOW//////////////////
// string s=“”;
// foreach (System.Windows.Forms.Control c in UD110Form.Controls)
// {
// if (c.HasChildren) {
// s+= c.Name + " [ children? " + c.HasChildren.ToString() + " ] " + Environment.NewLine;
// foreach (System.Windows.Forms.Control c1 in c.Controls)
// {
// if (c1.HasChildren)
// {
// s+= " - "+ c1.Name + Environment.NewLine;
// foreach (System.Windows.Forms.Control c2 in c1.Controls)
// {
// if (c2.HasChildren)
// {
// s+= " >> "+ c2.Name + Environment.NewLine;
// }
// }
// }
// }
// }
// }
// MessageBox.Show(s);
// MessageBox.Show(
// ((System.Windows.Forms.Control)groupContactSelector).Parent.Name + Environment.NewLine +
// ((System.Windows.Forms.Control)groupContactSelector).Parent.Parent.Name + Environment.NewLine +
// ((System.Windows.Forms.Control)groupContactSelector).Parent.Parent.Parent.Name + Environment.NewLine
// );
////////////DEBUGGING CODE … ABOVE//////////////////
SearchOnCustomerAdapterShowDialog();
}

private static void SearchOnCustomerAdapterShowDialog()
{
	SearchOnCustomerAdapterShowDialog(string.Empty, true);
}		
private static void SearchOnCustomerAdapterShowDialog(string WhereClause, bool showSearchWindow)
{
	bool recSelected;
	string whereClause = WhereClause; //string.Empty;
	//SearchFunctions.listLookup Call belongs to : Ice.UI.FormFunctions.SearchFunctions.listLookup
	DataSet dsCustomerAdapter = SearchFunctions.listLookup(oTrans, "CustomerAdapter", out recSelected, showSearchWindow, whereClause);
	if (recSelected)
	{

		int custNum=0;

		System.Data.DataRow adapterRow = dsCustomerAdapter.Tables[0].Rows[0];

		// Map Search Fields to Application Fields
		try
		{
        	if (!int.TryParse(adapterRow["CustNum"].ToString(), out custNum)) custNum = 0;

			if (custNum>0) 
			{
				numericCustNum.Value = custNum;

// string str=“”; //DEBUGGING CODE
// for (int tc = 0; tc < dsCustomerAdapter.Tables[0].Columns.Count; tc++) //DEBUGGING CODE
// { //DEBUGGING CODE
// str +=dsCustomerAdapter.Tables[0].Columns[tc].ColumnName + " | "; //DEBUGGING CODE
// } //DEBUGGING CODE
// MessageBox.Show (str); //DEBUGGING CODE

// MessageBox.Show("EDVROW: " + adapterRow[“CustNum”].ToString());} //DEBUGGING CODE

				try{
					txtCustID.Text = adapterRow["CustId"].ToString();
					if (string.Compare(lastCustID, txtCustID.Text.Trim(), true)!=0)
					{
						txtShiptoNum.Text="";
						lastCustID = txtCustID.Text;
						btnSearch_Click(txtCustID, new System.EventArgs());
					}
				}
				catch{}
			}
			
		}
		catch{}
	}
}

private static void buttonShipTo_Click(object sender, System.EventArgs args)
{
	SearchOnShipToAdapterShowDialog();
}
private static void SearchOnShipToAdapterShowDialog()
{
	bool recSelected;
	string whereClause = string.Empty;
	if (txtCustID.Text.Trim().Length> 0)
	{ 
		whereClause = "CustNum = " + numericCustNum.Value.ToString() ;
	}
	System.Data.DataSet dsShipToAdapter = Ice.UI.FormFunctions.SearchFunctions.listLookup(oTrans, "ShipToAdapter", out recSelected, true, whereClause);
	if (recSelected)
	{
		System.Data.DataRow adapterRow = dsShipToAdapter.Tables[0].Rows[0];
		try{MessageBox.Show("EDVROW: " + adapterRow["ShipToNum"].ToString());}
		catch{}
        try{txtShiptoNum.Text = adapterRow["ShipToNum"].ToString();}
        catch{}
	}
}

private static void SearchOnCustContactsAdapterShowDialog(bool showSearchWindow)
{
	bool recSelected;
	string whereClause = string.Empty;

	if (txtCustID.Text.Trim().Length> 0)
	{
		whereClause = "CustNum = " + numericCustNum.Value.ToString() ; 
	}
	//SearchFunctions.listLookup Call belongs to : Ice.UI.FormFunctions.SearchFunctions.listLookup
	DataSet dsContactsAdapter = SearchFunctions.listLookup(oTrans, "CustCntAdapter", out recSelected, showSearchWindow, whereClause);
	if (recSelected)
	{

		int custNum=0;

		System.Data.DataRow adapterRow = dsContactsAdapter.Tables[0].Rows[0];
		// Map Search Fields to Application Fields
		try
		{
			MessageBox.Show("EDVROW: " + adapterRow["Name"].ToString());
		}
		catch{}
	}
}

private static void btnSearch_Click(object sender, System.EventArgs args)
{
	if (txtCustID.Text.Trim().Length == 0 && txtShiptoNum.Text.Trim().Length == 0)
	{
		MessageBox.Show("Please select a customer!");
		return;
	}

	gridHeader.DataSource = new DataTable();
	gridHeader.Refresh();
	gridDetails.DataSource = new DataTable();
	gridDetails.Refresh();
	gridDetails.Text = "";
	SetStatusText("Retrieving data...");
	groupContactSelector.Visible = false;
	gridContacts.DataSource =new DataTable();
	string BAQ = session.CompanyID + "-ARInvoice_Mailer_Head";

	try 
	{
	DynamicQueryAdapter queryAdapter = new DynamicQueryAdapter(oTrans);
	queryAdapter.BOConnect();
    queryAdapter.GetDashboardQuery(BAQ);
    //DataView dv = new DataView(queryAdapter.RuntimeQuery.Tables["QueryTable"]);
	DataView dv = new DataView(queryAdapter.QueryResults.Tables["QueryTable"]);	// by Roy
	//DataView dv = new DataView(queryAdapter.QueryResults.Tables["Results"]);  // by ROY
	string filter ="";
	//filter = AddFilter("", "InvcHead.InvoiceNum>=", txtInvcStart.Text, false);
	//filter = AddFilter(filter, "InvcHead.InvoiceNum<=", txtInvcEnd.Text, false);
	//filter = AddFilter(filter, "InvcHead.InvoiceDate>=", dteStartDate.Value, true);
	//filter = AddFilter(filter, "InvcHead.InvoiceDate<=", dteEndDate.Value, true);

// if (!cbxNotPosted.Checked)
// filter = AddFilter(filter, “InvcHead.Posted=”, true, false);
// if (!cbxNotReadyToCalc.Checked)
// filter = AddFilter(filter, “InvcHead.ReadyToCalc=”, true, false);
// dv.RowFilter = “DataTableName=‘InvcHead’”;
// dv[0][“WhereClause”] = filter;

	if (txtCustID.Text.Trim().Length > 0)
	{
		//MessageBox.Show (dv.Count.ToString());
		//dv.RowFilter = String.Format("Customer_CustID = '{0}'", txtCustID.Text.Trim());

		filter = AddFilter("", "Customer_CustID=", txtCustID.Text.Trim(), true); //txtCustomer.Text, true);
		//dv.RowFilter = String.Format("Customer_CustID = '{0}'", txtCustID.Text.Trim());
		//MessageBox.Show (filter);

// dv.RowFilter = “DataTableName=‘Customer’”;
//dv[0][“WhereClause”] = filter;
dv.RowFilter = filter;
}

// if (txtShiptoNum.Text.Trim().Length > 0)
// {
// filter = AddFilter(“”, “InvcDtl.ShipToNum=”, txtShiptoNum.Text.Trim(), true);
// dv.RowFilter = “DataTableName=‘InvcDtl’”;
// dv[0][“WhereClause”] = filter;
// }

    queryAdapter.ExecuteBAQDataViewQuery(queryAdapter.RuntimeQuery);            
    DataTable dt = queryAdapter.QueryResults.Tables["Results"];
	//dt.Columns["Mailed"].Caption = "PDF";
	gridHeader.DataSource = dt;
	
	// Disable updating on the entire grid except first column
	for (int i=1; i < gridHeader.DisplayLayout.Bands[0].Columns.Count; i++) {
    	gridHeader.DisplayLayout.Bands[0].Columns[i].CellActivation = Activation.ActivateOnly;
	}
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_InvoiceSuffix"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_Company"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_CustNum"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_ReadyToCalc"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_Posted"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_CheckRef"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["Customer_CustID"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_DocInvoiceAmt"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_InvoiceBal"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_InvoiceHeld"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_CurrencyCode"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_ApplyDate"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_DepositAmt"].Hidden = true;
	gridHeader.DisplayLayout.Bands[0].Columns["InvcHead_InvoiceRef"].Hidden = true;
	queryAdapter.Dispose();
	SetStatusText("Ready. " + dt.Rows.Count + " records found.");

////////// LOAD Customer Contacts! //////////////////
SearchOptions opts = new SearchOptions(SearchMode.AutoSearch);
opts.SelectMode= SelectMode.MultiSelect; //Ice.Lib.Searches.
opts.DataSetMode = DataSetMode.ListDataSet; //Ice.Lib.Searches.
bool more;
opts.NamedSearch.WhereClauses[“CustCnt”] = “CustNum=” + numericCustNum.Value.ToString();//+invoice[“InvcHead.CustNum”]; //[“Customer.CustNum”];
custCntAdapter.ClearData();
// DataRow[] contacts = custCntAdapter.GetRows(opts, out more).Tables[0].Select(“PrimaryBilling=true”);
// if (contacts.Length == 0) {
// MessageBox.Show(“Invoice “+invoice[“InvcHead.InvoiceNum”]+”, Customer “+custID+”: No Billing contact.”);
// return null;
// }
// if ((string)contacts[0][“EmailAddress”] == “”) {
// MessageBox.Show(“Invoice “+invoice[“InvcHead.InvoiceNum”]+”, Customer “+custID+”: No Email address for Billing contact.”);
// return null;
// }
// custContacts[custID] = new Contact((int)invoice[“InvcHead.InvoiceNum”], custID, (string)contacts[0][“Name”], (string)contacts[0][“EmailAddress”]);

	DataTable conTable=new DataTable();
	conTable.Columns.Add("Selected", typeof(bool));
	conTable.Columns.Add("CustNum",typeof(string)); // typeof(int));
	conTable.Columns.Add("CustNumCustID",typeof(string)); // typeof(int));
	conTable.Columns.Add("ShipToNum",typeof(string)); // typeof(int));
	conTable.Columns.Add("Name",typeof(string)); // typeof(string));
	conTable.Columns.Add("EMailAddress",typeof(string)); // typeof(string));
	conTable.Columns.Add("PrimaryBilling",typeof(bool));
	conTable.Columns.Add("PrimaryPurchasing", typeof(bool));
	conTable.Columns.Add("PrimaryShipping", typeof(bool));
	//MessageBox.Show ("Columns added to Con Table!!"); // DEBUGGING CODE
	for (int c = 0; c < conTable.Columns.Count; c++) {conTable.Columns[c].AllowDBNull = true;}
	//MessageBox.Show ("Contacts Table columns set to nullable!!"); // DEBUGGING CODE

	DataTable t = custCntAdapter.GetRows(opts, out more).Tables[0];				
	//MessageBox.Show ("Got Rows from ContactsAdapter!!!!"); // DEBUGGING CODE


	try 
	{
		using (CustomerAdapter custAdapter = new CustomerAdapter(oTrans))
		{
			custAdapter.BOConnect();
			opts.NamedSearch.WhereClauses["Customer"] = "CustNum=" + numericCustNum.Value.ToString();//+invoice["InvcHead.CustNum"]; //["Customer.CustNum"];
			using (DataTable custTable = custAdapter.GetRows(opts, out more).Tables[0])
			{
				if (custTable.Rows.Count > 0)
				{

// string strCust =“”; //DEBUGGING CODE
// for (int ct = 0; ct < custTable.Columns.Count;ct++) //DEBUGGING CODE
// { //DEBUGGING CODE
// strCust +=custTable.Columns[ct].ColumnName + " | "; //DEBUGGING CODE
// } //DEBUGGING CODE
// MessageBox.Show (strCust); //DEBUGGING CODE
conTable.Rows.Add(new object[] {
false,
numericCustNum.Value,
txtCustID.Text,
“** default **”,
custTable.Rows[0][“Name”].ToString(),
custTable.Rows[0][“EMailAddress”].ToString(),
false,
false,
false
});

				}
			}
		}
	} catch{}

	try
	{
		for (int r = 0; r < t.Rows.Count; r++)
		{
			conTable.Rows.Add(new object[] { 
					false, 
					t.Rows[r]["CustNum"].ToString(),  
					t.Rows[r]["CustNumCustID"].ToString(),  
					t.Rows[r]["ShipToNum"].ToString(),  
					t.Rows[r]["Name"].ToString(),
					t.Rows[r]["EMailAddress"].ToString(),
					t.Rows[r]["PrimaryBilling"],
					t.Rows[r]["PrimaryPurchasing"],
					t.Rows[r]["PrimaryShipping"]
			});
		}
	} catch (Exception excep)  {
		MessageBox.Show ("Exception Adding rows to new table!!!" + Environment.NewLine + excep.Message); }

	//MessageBox.Show ("Columns added to Con Table!! or were they??"); // DEBUGGING CODE

// gridContacts.DataSource = custCntAdapter.GetRows(opts, out more).Tables[0]; //custCntAdapter.GetList(opts, out more).Tables[0];
//custCntAdapter.GetList(opts, out more).Tables[0];
// string str=“”; //DEBUGGING CODE
// for (int tc = 0; tc < t.Columns.Count; tc++) //DEBUGGING CODE
// { //DEBUGGING CODE
// str +=t.Columns[tc].ColumnName + " | "; //DEBUGGING CODE
// } //DEBUGGING CODE
// MessageBox.Show (str); //DEBUGGING CODE
gridContacts.DataSource =conTable;

// // SET FONT for Default row to True
// if(e.Row.Cells.FromKey(“ShipToNum”).Value == “** default **”)
// e.Row.Style.Font.Bold = true;

	try{
		//Disable all columns except first ("Selected")
		for (int i=1; i < gridContacts.DisplayLayout.Bands[0].Columns.Count; i++) {
        	gridContacts.DisplayLayout.Bands[0].Columns[i].CellActivation = Activation.ActivateOnly;
		}
		//Disable all lontacts who don't have email so they cannot be selected
		DisableContactsWithoutEmail(conTable.Rows.Count);

		//Hide the 2 columns needed for behind teh scenes data access...
		gridContacts.DisplayLayout.Bands[0].Columns["CustNum"].Hidden = true;
		gridContacts.DisplayLayout.Bands[0].Columns["CustNumCustID"].Hidden = true;

	} catch{}
	//try{SearchOnCustContactsAdapterShowDialog(true);} catch{}


	} catch (Exception excep)  {
		MessageBox.Show ("ERROR!!" + Environment.NewLine + excep.Message); }
}

private static void DisableContactsWithoutEmail(int _rowcount)
{
    for (int i = 0; i < _rowcount; i++)
    {         
		// SET FONT for Default row to True
   	 if (gridContacts.Rows[i].Cells["ShipToNum"].Value.ToString()== "** default **")
			gridContacts.Rows[i].Appearance.ForeColor = System.Drawing.Color.Blue; // System.Windows.Media.Color.Blue; //.Bold = true;
        //Disable all rows with "blank" email addresses...
		if (gridContacts.Rows[i].Cells["EMailAddress"].Value.ToString().Length <=0)
        {                    
            gridContacts.Rows[i].Activation = Infragistics.Win.UltraWinGrid.Activation.Disabled;
        }
    }
}

private static void buttonCloseContactList_Click(object sender, System.EventArgs args)
{
	groupContactSelector.Visible = false;		
}

private static void btnContinue_Click(object sender, System.EventArgs args)
{
	try
	{
		if (gridHeader.DataSource != null) {
			gridHeader.ReadOnly = false; 
		} else { return; }
		
		ProcessSelectedInvoices("MAIL");
		if (gridHeader.DataSource != null) { gridHeader.ReadOnly = true; }
	} 
	catch (Exception exception)
	{
		MessageBox.Show("Exception encountered while attempting to e-mail invoices! " + Environment.NewLine + exception.Message);
		if (gridHeader.DataSource != null) { gridHeader.ReadOnly = true;}
	}
}

private static void buttonEmail_Click(object sender, System.EventArgs args)
{
	groupContactSelector.Width = 536;
	groupContactSelector.Height = 214;
	groupContactSelector.Visible = true;
	((System.Windows.Forms.Control)groupContactSelector).BringToFront();
	//((System.Windows.Forms.Control)groupPrintOptions).SendToBack();
	((System.Windows.Forms.Control)gridHeader).SendToBack();
}

private static void buttonPrint_Click(object sender, System.EventArgs args)
{
	ProcessSelectedInvoices("PRINT");
}

private static void ProcessSelectedInvoices(string _action)
{
	try 
	{
		string recipients = "";
		if (gridHeader.DataSource == null)
			return;
		if (session.UserEmail == null)
		{
			MessageBox.Show("Please update your email address using Epicor User Maintenance and then login to Epicor before continuing.");
			return;
		}

		if (session.UserEmail.Trim() =="")
		{
			MessageBox.Show("Please update your email address using Epicor User Maintenance and then login to Epicor before continuing.");
			return;
		}

		DataRow[] invoiceList = ((DataTable)gridHeader.DataSource).Select("Calculated_Selected=true");
		if (invoiceList.Length == 0) {
			MessageBox.Show("No invoices have been selected.");
			return;
		}

		DataRow[] recipientList = ((DataTable)gridContacts.DataSource).Select("Selected=true");
		//MessageBox.Show("Copy Self? " + epiCheckEmailCopySelf.Checked.ToString() + Environment.NewLine  + "Action: " + _action  +  Environment.NewLine + "Recipients " + recipientList.Length.ToString());
		if (recipientList.Length <= 0 && (!epiCheckEmailCopySelf.Checked) && _action == "MAIL") {
			MessageBox.Show("No recipients have been selected.");
			return;
		}
		else
		{
			if (recipientList.Length>0)
			{
				foreach (DataRow contact in recipientList)
				{
					recipients+=contact["EmailAddress"].ToString() + ", ";
				}
				if (recipients.Length > 2)
					recipients = recipients.Substring(0, recipients.Length - 2);
				MessageBox.Show ("RecipientList Compiled - " + recipients); //DEBUGING CODE
			}
		}

		action = _action;
		custContacts = new Hashtable();
		
		Hashtable custInvoices = FindInvoices(invoiceList);
		if (custInvoices == null) {
			return;
		}
		//MessageBox.Show("Found Invoices");  //DEBUGGING CODE
		Worker w = new Worker(custInvoices, invoiceList, recipients, epiCheckEmailCopySelf.Checked); // ( _action == "PRINT"?recipientList:null) );
		//MessageBox.Show("Worker Instantiated");   //DEBUGGING CODE
		thread = new Thread(new ThreadStart(w.Update));
		thread.Start();
	}
	catch (Exception excep)  {
		MessageBox.Show ("ERROR!!" + Environment.NewLine + excep.Message); }

}

static Hashtable FindInvoices(DataRow[] invoiceList)
{
	Hashtable custInvoices = new Hashtable();
	// Find invoices for each customer
	foreach (DataRow row in invoiceList) {

// string custID = (string)row[“Customer.CustID”];
string custID = (string)row[“Customer_CustID”];

		List<DataRow> invoices = custInvoices.Contains(custID) ? (List<DataRow>)custInvoices[custID] : new List<DataRow>();
		invoices.Add(row);
		custInvoices[custID] = invoices;
	}
	
	// Find contacts for each customer
	SearchOptions opts = new SearchOptions(SearchMode.AutoSearch);
	foreach (string custID in custInvoices.Keys) {
		DataRow invoice = ((List<DataRow>)custInvoices[custID])[0];
		if (action != "MAIL") {
			custContacts[custID] = new Contact((int)invoice["InvcHead_InvoiceNum"], custID, "", "");
			continue;
		}
		custCntAdapter.ClearData();
		opts.NamedSearch.WhereClauses["CustCnt"] = "CustNum="+invoice["InvcHead_CustNum"]; //["Customer.CustNum"];
		bool more;

// DataRow[] contacts = custCntAdapter.GetRows(opts, out more).Tables[0].Select(“PrimaryBilling=true”);
// if (contacts.Length == 0) {
// MessageBox.Show(“Invoice “+invoice[“InvcHead.InvoiceNum”]+”, Customer “+custID+”: No Billing contact.”);
// return null;
// }
// if ((string)contacts[0][“EmailAddress”] == “”) {
// MessageBox.Show(“Invoice “+invoice[“InvcHead.InvoiceNum”]+”, Customer “+custID+”: No Email address for Billing contact.”);
// return null;
// }
// custContacts[custID] = new Contact((int)invoice[“InvcHead.InvoiceNum”], custID, (string)contacts[0][“Name”], (string)contacts[0][“EmailAddress”]);
custContacts[custID] = new Contact((int)invoice[“InvcHead_InvoiceNum”], custID, custID + “_” + session.UserName, session.UserEmail);
}

	// Display confirmation message
	string msg = "";
	foreach (string custID in custContacts.Keys) {
		Contact contact = (Contact)custContacts[custID];
		if (msg != "") msg += "\n";
		msg += custID+" "+contact.Name+" "+contact.EmailAddress+":\n  ";
		foreach (DataRow invoice in (List<DataRow>)custInvoices[custID]) {
			msg += invoice["InvcHead_InvoiceNum"] + ",";
		}
		msg = msg.Substring(0,msg.Length-1);
	}
	string a = (action == "MAIL") ? "Email" : ((action == "PRINT") ? "Print" : "Create PDF");
    DialogResult res = EpiMessageBox.Show(msg, a+" invoices?", MessageBoxButtons.YesNo);
    return (res == DialogResult.Yes) ? custInvoices : null;
}

private static string AddFilter(string filter, string expr, object v, bool quoted)
{
	if (v == null || Convert.IsDBNull(v) || v.ToString() == "")
		return filter;
	if (filter != "") filter += " AND ";
	return filter + expr + (quoted ? "'" : "") + v + (quoted ? "'" : "");
}

// Sets status text and cursor to busy
private static void SetStatusText(string msg)
{
	try {oTrans.PushDisposableStatusText(msg, !msg.StartsWith("Ready"));} catch {}
}

private static bool SendEmail(string toAddr, bool CCSelf, string subject, string body, List<string> files)
{
	bool ret = true;
	CompanyAdapter companyAdapter = new CompanyAdapter(oTrans);
	companyAdapter.BOConnect();
	companyAdapter.GetByID(session.CompanyID);
	string fromAddr = session.UserEmail; //"ar@CAToronto.ca";
	//string fromAddr = (string) companyAdapter.CompanyData.Company.Rows[0]["EmailFromAddr"];
	string smtpServer = (string) companyAdapter.CompanyData.Company.Rows[0]["SMTPServer"];
	int smtpPort = (int) companyAdapter.CompanyData.Company.Rows[0]["SMTPPort"];
	companyAdapter.Dispose();
	if (fromAddr == "" || smtpServer == "" || smtpPort == 0) {
		MessageBox.Show("1 or more values are not set in Company Configuration:\nGlobal Alert Email From, SMTP server or SMTP port");
		return false;
	}
	//MessageBox.Show("from="+fromAddr+" smtp="+smtpServer+" port="+smtpPort); //debugging code 
	
	// Send the notification
	SmtpClient client = new SmtpClient(smtpServer, smtpPort);
	//client.Credentials = new NetworkCredential("account-name", "password");
    //MailAddress from = new MailAddress(fromAddr, session.UserName + "_CATorontoAR", System.Text.Encoding.UTF8);
   //MessageBox.Show (toAddr);  //Debugging code
	//MailAddress to = new MailAddress(toAddr);
	//MailAddress to = new MailAddress("Shanna@CAToronto.ca"); //("Bdalal@CAToronto.ca"); 
    //MailMessage message = new MailMessage(from, to);
	MailMessage message = new MailMessage();
	//message.Sender = new System.Net.Mail.MailAddress(fromAddr, session.UserName + "_CATorontoAR", System.Text.Encoding.UTF8);
	message.From= new System.Net.Mail.MailAddress(fromAddr, session.UserName + "_CATorontoAR", System.Text.Encoding.UTF8);
	if (toAddr.Length>0) message.To.Add(toAddr);
	if (CCSelf) message.CC.Add(fromAddr);
    message.Subject = subject;
    message.Body = body;

	foreach (string file in files) {
		Attachment attach = new Attachment(file, System.Net.Mime.MediaTypeNames.Application.Pdf);
   		message.Attachments.Add(attach);
	}

	try {
   		client.Send(message);
	} catch (Exception e) { 
		MessageBox.Show("SendEmail error: "+e.Message);
		ret = false;
	}
	message.Dispose();
	return ret;
}

static bool InitPrintData()
{
	if (action == "PRINT" && dialog == null) {
		dialog = new PrintDialog();
		if (dialog.ShowDialog() != DialogResult.OK) {
			dialog = null;
			return false;
		}
	}
	if (serverDir != null && crystalRptFile != null)
		return true;
	SetStatusText("Finding server directories.");
	// Get server and client data directories
	SysAgentAdapter agentAdapter = new SysAgentAdapter(oTrans);
	agentAdapter.BOConnect();
	string agentID;
	agentAdapter.GetDefaultTaskAgentID(out agentID);
	agentAdapter.GetByID(agentID);
	dataDir = (string)agentAdapter.SysAgentData.SysAgent.Rows[0]["ClientFileRootDir"];
	serverDir = (string)agentAdapter.SysAgentData.SysAgent.Rows[0]["ClientProgRootDir"];
	agentAdapter.Dispose();

	// Find default or 1st Crystal Report file
	SetStatusText("Finding AR Inventory style.");
	ReportAdapter reportAdapter = new ReportAdapter(oTrans);
	reportAdapter.BOConnect();
	reportAdapter.GetByID("ARForm");
	string filter = "Company='"+session.CompanyID+"' AND ValidStyle=true";
	DataRow[] companyList = reportAdapter.ReportData.ReportComp.Select(filter+" AND IsDefault=true");
	if (companyList.Length == 0) {
		companyList = reportAdapter.ReportData.ReportComp.Select(filter);
	}
	foreach (DataRow compRow in companyList) {
		DataRow reportStyle = reportAdapter.ReportData.ReportStyle.Select(" StyleDescription LIKE '%PDF%'")[0]; // ("StyleNum="+compRow["StyleNum"])[0];
		if (((string)reportStyle["PrintProgram"]).EndsWith(".rpt")) {
			crystalRptFile = ((string)reportStyle["PrintProgram"]).Replace('/', '\\');;
			break;
		}
	}
	reportAdapter.Dispose();
	if (crystalRptFile == null) {
		MessageBox.Show("Could not find a Crystal Report style for the 'ARForm' report.");
		//btnEmail.Enabled = btnPrint.Enabled = btnPDF.Enabled = false;
		return false;
	}
	
	// Crystal DLLs
	SetStatusText("Loading Crystal DLLs");
	//string[] dir = Directory.GetFiles(@"C:\Program Files\Business Objects\Common", "CrystalDecisions.CrystalReports.Engine.dll", SearchOption.AllDirectories);
	string[] dir = Directory.GetFiles(@"C:\Windows\assembly", "CrystalDecisions.CrystalReports.Engine.dll", SearchOption.AllDirectories); 
    if (dir.Length == 0) {
        MessageBox.Show("Could not find Crystal Report DLLs");
		//btnEmail.Enabled = btnPrint.Enabled = btnPDF.Enabled = false;
		return false;
    }
	else {
        crystalEngine = Assembly.LoadFrom(dir[0]);
		dir = Directory.GetFiles(@"C:\Windows\assembly", "CrystalDecisions.Shared.dll", SearchOption.AllDirectories); 
        //string shared = dir[0].Substring(0,dir[0].LastIndexOf(@"\\")) + "\\CrystalDecisions.Shared.dll";
        //crystalShared = Assembly.LoadFrom(shared);
        if (dir.Length > 0)
        {
           crystalShared = Assembly.LoadFrom(dir[0]);
           //MessageBox.Show("All Good!!");   //DEBUGGING CODE
        }
        else
            MessageBox.Show("Could not find Crystal Report shared DLL");

	}
	SetStatusText("Ready.");
	return true;
} 

private static void Process(Hashtable custInvoices, DataRow[] invoiceList, string recipientEmails, bool emailCopySelf)
{
	if (!InitPrintData())
		return;
	// Save subject and body if changed
	if (action == "MAIL") 
	{ /*Check if subject / body need to be changed /.. */ }
	progressBar.Value = 0;
	progressBar.Maximum = invoiceList.Length;

	foreach (string custID in custInvoices.Keys) {
		List<string> pdfFileList = new List<string>();
		foreach (DataRow invoice in ((List<DataRow>)custInvoices[custID])) {
			int invcNum = (int)invoice["InvcHead_InvoiceNum"];
			string type = (string)invoice["InvcHead_InvoiceSuffix"];
			if (type == "") type = "IN";
			SetStatusText(((action == "MAIL" || action == "PDF") ? "Creating PDF for " : "Printing ")+invcNum);
			progressBar.PerformStep();
			if (action == "MAIL") {
				//MessageBox.Show("Preparing to PDF Invoice: " + invcNum.ToString() + ".");   //DEBUGGING CODE
				pdfFileList.Add(invcPrinter.PrintPDF(invcNum, type));
				//MessageBox.Show("Invoice: " + invcNum.ToString() + " form created.");   //DEBUGGING CODE
			}
			else if (action == "PDF") {
				invcPrinter.PrintPDF(invcNum, type);
			}
			else if (!invcPrinter.PrintPaper(invcNum)) {
				goto exit;
			}
		}
		if (action == "MAIL") {
			//MessageBox.Show("Preparing Email");   //DEBUGGING CODE
			//Contact contact = (Contact)custContacts[custID];
			//MessageBox.Show ("DEBUG: " + Environment.NewLine + "RecipientList Compiled - " + recipientEmails); //DEBUGING CODE

			SetStatusText("Sending "+pdfFileList.Count+" invoices to "+ recipientEmails) ; //contact.EmailAddress);

			//if (!SendEmail(contact.EmailAddress, txtSubject.Text, txtBody.Text, pdfFileList)) 
			//if (!SendEmail(contact.EmailAddress, "CAToronto AR Invoices (" + custID + ")" , "Good Day. " + Environment.NewLine + " Attached find invoice(s). If you notice any descrepancies, please contact the sender of this email. ", pdfFileList)) 
			if (!SendEmail(recipientEmails, emailCopySelf, "CAToronto AR Invoices (" + custID + ")" , "Good Day. " + Environment.NewLine + 
														   " Attached find invoice(s). If you notice any descrepancies, please contact the sender of this email. ", pdfFileList)) 
			{
				goto exit;
			}
			groupContactSelector.Visible = false;
			if (!KeepGeneratedFiles)//(!cbxKeepFiles.Checked) 
			{
				foreach (string file in pdfFileList) {
					File.Delete(file);
				}
			}
		}
		
		// Set Processed flag for each invoice
		foreach (DataRow invoice in ((List<DataRow>)custInvoices[custID])) {
			int invcNum = (int)invoice["InvcHead_InvoiceNum"];
			//MessageBox.Show("Preparing adapter UD110 for logging");    //DEBUGGING CODE
			ud110adapter.ClearData();
			string field = (action == "MAIL" || action == "PDF") ? "CheckBox01" : "CheckBox02";
			try {
				ud110adapter.GetByID("INVOICE_MAILER", "PROCESSED", invcNum.ToString(),"","");
				if  ((bool)ud110adapter.UD110Data.UD110.Rows[0][field])
					continue;
			} catch {
				ud110adapter.GetaNewUD110();
			}
			//MessageBox.Show("Logging to UD110");   //DEBUGGING CODE
			DataRow row = ud110adapter.UD110Data.UD110.Rows[0];
			row["Key1"] = "INVOICE_MAILER";
			row["Key2"] = "PROCESSED";
			row["Key3"] = invcNum.ToString();
			row["Number01"] = invcNum;
			row[field] = true;
			ud110adapter.Update();
			//MessageBox.Show("UD110 adapter updated");   //DEBUGGING CODE
			DataRow gridRow = ((DataTable)gridHeader.DataSource).Select("InvcHead_InvoiceNum="+invcNum)[0];
			//gridRow[(action == "MAIL" || action == "PDF") ? "Mailed" : "Printed"] = true; //BD Throws errors FIX THIS 
		}
	}

exit:
string msg = "Ready. ";
if (action == “PDF” || (action == “MAIL” && KeepGeneratedFiles)) //cbxKeepFiles.Checked))
msg += "Files created in "+@"C:\Temp" + Environment.GetEnvironmentVariable(“USERNAME”);
SetStatusText(msg);
}

class Contact {
	public int InvcNum;
	public string CustID, Name, EmailAddress;
	public Contact(int invcNum, string custID, string name, string emailAddress) 
	{
		this.InvcNum = invcNum; this.CustID = custID; this.Name = name; this.EmailAddress = emailAddress;
	}
}  //END OF CONTACT class

class InvcPrinter : Erp.UI.Rpt.ARInvForm.Transaction {
	public InvcPrinter(object sender) : base(sender) {
	}

	// Returns create PDF filename
	string GenerateXML(int invcNum)
	{
		SetStatusText("Generating data for "+invcNum);
		Invoice = invcNum.ToString();
		setInvoice();
		RunDirect("GenerateDirect");
		string[] files = Directory.GetFiles(dataDir + @"\Reports\"+ session.UserID, "AR Invoice Form*.xml");
		string xmlFile = files[files.Length-1];
		SetStatusText("XML file: "+xmlFile);

		crystalRpt = crystalEngine.CreateInstance("CrystalDecisions.CrystalReports.Engine.ReportDocument");
        Type ReportDoc = crystalEngine.GetType("CrystalDecisions.CrystalReports.Engine.ReportDocument");
		//MessageBox.Show("instantiated CR");   //DEBUGGING CODE
		// OpenReportMethod.OpenReportByDefault
        Type OpenReportMethod = crystalShared.GetType("CrystalDecisions.Shared.OpenReportMethod");
        FieldInfo openReportByDefaultInfo = OpenReportMethod.GetField("OpenReportByDefault");
        object OPEN_BY_DEFAULT = openReportByDefaultInfo.GetValue(null);
		//MessageBox.Show("SET OPEN BY DEFAULT");   //DEBUGGING CODE

        // crystalRpt.Load()
		//MessageBox.Show("preparing to 'load' CR object " + serverDir+@"\"+crystalRptFile);   //DEBUGGING CODE
        MethodInfo load = ReportDoc.GetMethod("Load", new Type[] { typeof(string) }); //, OpenReportMethod });
        load.Invoke(crystalRpt, new object[] { serverDir+@"\"+crystalRptFile}); //, OPEN_BY_DEFAULT });
		//MessageBox.Show("'Loaded' CR " + serverDir+@"\"+crystalRptFile);   //DEBUGGING CODE

        // crystalRpt.SetDataSource()
        DataSet ds = new DataSet();
        ds.ReadXml(xmlFile);
        MethodInfo setDataSource = ReportDoc.GetMethod("SetDataSource", new Type[]{typeof(DataSet)});
        setDataSource.Invoke(crystalRpt, new object[] { ds });

        // crystalRpt.ReportDefinition
        Type ReportDefinition = crystalEngine.GetType("CrystalDecisions.CrystalReports.Engine.ReportDefinition");
        PropertyInfo reportDefinitionInfo = ReportDoc.GetProperty("ReportDefinition");
        object reportDefinition = reportDefinitionInfo.GetValue(crystalRpt, null);
		//MessageBox.Show("instantiated RD");   //DEBUGGING CODE

        // crystalRpt.ReportDefinition.ReportObjects
        Type ReportObjects = crystalEngine.GetType("CrystalDecisions.CrystalReports.Engine.ReportObjects");
        PropertyInfo reportObjectsInfo = ReportDefinition.GetProperty("ReportObjects");
        object reportObjects = reportObjectsInfo.GetValue(reportDefinition, null);
		//MessageBox.Show("instantiated RD Objects");   //DEBUGGING CODE

        Type SubreportObject = crystalEngine.GetType("CrystalDecisions.CrystalReports.Engine.SubreportObject");
        PropertyInfo subreportNameInfo = SubreportObject.GetProperty("SubreportName");
		//MessageBox.Show("instantiated SubReport infrastructure");   //DEBUGGING CODE

        // Set datasource of each subreport
        foreach (object reportObj in ((System.Collections.ICollection)reportObjects)) {
            if (reportObj.GetType() != SubreportObject)
                continue;
			//MessageBox.Show("Set datasource for subreport(s)");   //DEBUGGING CODE
            string name = (string)subreportNameInfo.GetValue(reportObj, null);
            MethodInfo openSubreport = ReportDoc.GetMethod("OpenSubreport", new Type[] { typeof(string) });
	        object subRpt = openSubreport.Invoke(crystalRpt, new object[] { name });
            setDataSource.Invoke(subRpt, new object[] { ds });
        }
		//MessageBox.Show("xml file prepared");   //DEBUGGING CODE
		return xmlFile;
	}

	public string PrintPDF(int invcNum, string type) {
		string xmlFile = GenerateXML(invcNum);
		string pdfDirectory = @"C:\Temp\" + Environment.GetEnvironmentVariable("USERNAME");
		string pdfFile = pdfDirectory + "\\" + type + " " + invcNum + ".pdf";
		try{Directory.CreateDirectory(pdfDirectory);}
		catch (Exception exception) {MessageBox.Show("Exception creating Directory! " + exception.Message);}

        Type ReportDoc = crystalEngine.GetType("CrystalDecisions.CrystalReports.Engine.ReportDocument");

    	// ExportDestinationType.DiskFile
        Type ExportDestinationType = crystalShared.GetType("CrystalDecisions.Shared.ExportDestinationType");
        FieldInfo diskFileInfo = ExportDestinationType.GetField("DiskFile");
        object DISKFILE = diskFileInfo.GetValue(null);
		//MessageBox.Show("set destination .. diskfile " );   //DEBUGGING CODE

        // crystalRpt.ExportOptions
		PropertyInfo exportOptionsInfo = ReportDoc.GetProperty("ExportOptions");
		object exportOptions = exportOptionsInfo.GetValue(crystalRpt, null);
		Type ExportOptions = crystalShared.GetType("CrystalDecisions.Shared.ExportOptions");
		//MessageBox.Show("set and instantiated Export Options" );   //DEBUGGING CODE
		
		// crystalRpt.ExportOptions.ExportDestinationType
		PropertyInfo exportDestinationTypeInfo = ExportOptions.GetProperty("ExportDestinationType");
		exportDestinationTypeInfo.SetValue(exportOptions, DISKFILE, null);
		//MessageBox.Show("Set export destination type" );   //DEBUGGING CODE

		// ExportFormatType.PortableDocFormat
		Type ExportFormatType = crystalShared.GetType("CrystalDecisions.Shared.ExportFormatType");
		FieldInfo portableDocFormatInfo = ExportFormatType.GetField("PortableDocFormat");
		object PORTABLE_DOC_FORMAT = portableDocFormatInfo.GetValue(null);
		//MessageBox.Show("Set CRW portable Doc Format" );   //DEBUGGING CODE
		
		// crystalRpt.ExportOptions.ExportFormatType
		PropertyInfo exportFormatTypeInfo = ExportOptions.GetProperty("ExportFormatType");
		exportFormatTypeInfo.SetValue(exportOptions, PORTABLE_DOC_FORMAT, null);
		
		// DiskFileDestinationOptions.DiskFileName
		Type DiskFileDestOptions = crystalShared.GetType("CrystalDecisions.Shared.DiskFileDestinationOptions");
		PropertyInfo diskFileNameInfo = DiskFileDestOptions.GetProperty("DiskFileName");
		object diskOptions = crystalShared.CreateInstance("CrystalDecisions.Shared.DiskFileDestinationOptions");
		diskFileNameInfo.SetValue(diskOptions, pdfFile, null);
		//MessageBox.Show("Set Diskfile Destination options" );   //DEBUGGING CODE

		// crystalRpt.ExportOptions.DestinationOptions
		PropertyInfo destinationOptionsInfo = ExportOptions.GetProperty("DestinationOptions");
		destinationOptionsInfo.SetValue(exportOptions, diskOptions, null);
		
		// crystalRpt.ExportOptions.FormatOptions
		PropertyInfo formatOptionsInfo = ExportOptions.GetProperty("FormatOptions");
		object formatOptions = crystalShared.CreateInstance("CrystalDecisions.Shared.PdfRtfWordFormatOptions");
		formatOptionsInfo.SetValue(exportOptions, formatOptions, null);
		
		// crystalRpt.Export()
		MethodInfo export = ReportDoc.GetMethod("Export", new Type[]{});
		export.Invoke(crystalRpt, null);
		//MessageBox.Show("Invoking Export!" );   //DEBUGGING CODE
		
		// crystalRpt.Close()
		MethodInfo close = ReportDoc.GetMethod("Close", new Type[] {});
		close.Invoke(crystalRpt, null);

		File.Delete(xmlFile);
		return pdfFile;
	}

	public bool PrintPaper(int invcNum) {
		string xmlFile = GenerateXML(invcNum);

		SetStatusText("Printing");
        Type ReportDoc = crystalEngine.GetType("CrystalDecisions.CrystalReports.Engine.ReportDocument");
        // crystalRpt.PrintOptions
        PropertyInfo printOptionsInfo = ReportDoc.GetProperty("PrintOptions");
        object printOptions = printOptionsInfo.GetValue(crystalRpt, null);
        Type PrintOptions = crystalEngine.GetType("CrystalDecisions.CrystalReports.Engine.PrintOptions");

        // crystalRpt.PrintOptions.PrinterName
        PropertyInfo printerNameInfo = PrintOptions.GetProperty("PrinterName");
        printerNameInfo.SetValue(printOptions, dialog.PrinterSettings.PrinterName, null);
            
        //crystalRpt.PrintToPrinter(1, false, 0, 0);
        MethodInfo printToPrinter = ReportDoc.GetMethod("PrintToPrinter", new Type[] { typeof(int), typeof(bool), typeof(int), typeof(int) });
        printToPrinter.Invoke(crystalRpt, new object[] { 1, false, 0, 0 });

        // crystalRpt.Close()
        MethodInfo close = ReportDoc.GetMethod("Close", new Type[] {});
        close.Invoke(crystalRpt, null);

		File.Delete(xmlFile);
		return true;
	}
} // END OF INVCPRINTER class

class Worker {
	Hashtable custInvoices;
	DataRow[] invoiceList;
	string recipientsEmails;
	bool emailSelf;
	public Worker(Hashtable custInvoices, DataRow[] invoiceList) 
	{
		this.custInvoices = custInvoices;
		this.invoiceList = invoiceList;
		this.recipientsEmails = null;
		this.emailSelf = false;
	}
	
	public Worker(Hashtable custInvoices, DataRow[] invoiceList, string recipients) 
	{
		this.custInvoices = custInvoices;
		this.invoiceList = invoiceList;
		this.recipientsEmails = recipients;
		this.emailSelf = false;
	}

	public Worker(Hashtable custInvoices, DataRow[] invoiceList, string recipients, bool sendEmailToSelf) 
	{
		this.custInvoices = custInvoices;
		this.invoiceList = invoiceList;
		this.recipientsEmails = recipients;
		this.emailSelf = sendEmailToSelf;
	}

	public void Update() 
	{
		//btnEmail.Enabled = btnPrint.Enabled = btnPDF.Enabled = false;
		try {
			Process(custInvoices, invoiceList, recipientsEmails, emailSelf);
			//btnEmail.Enabled = btnPrint.Enabled = btnPDF.Enabled = true;
			progressBar.Value = 0;
		} catch (Exception e) {
			if (!threadAborted && Thread.CurrentThread.ThreadState == System.Threading.ThreadState.Running) {
				ExceptionBox.Show(e);
			}
		}
	}
} //END OF WORKER class

}

Greg,
I am using this code to hide a tree panel but it is saying I’m missing an assembly reference. Do you know which one is needed?

@skearney Here are the Infragistics usings I have always added.

using Infragistics.Shared;
using Infragistics.Win;
using Infragistics.Win.UltraWinToolbars;
using Infragistics.Win.UltraWinDock;