Untitled

 avatar
unknown
plain_text
2 years ago
93 kB
0
Indexable
using Exact.SystemLayer.TypeExtension;
using Exact.Win.UI.Form;
using Microsoft.VisualBasic;
using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Windows.Forms;
using UpgradeHelpers.Gui;
using UpgradeHelpers.Helpers;

namespace Exact.Crm.DocumentBrowser
{
	[Exact.Win.UI.Form.FormLayout(ShowExactMenu=false, ShowActionBar=true, ShowStatusBar=true)]
	internal partial class frmBrowseDocuments
		: Exact.Win.UI.Form.ExactFormBase, Exact.SystemLayer.Interfaces.IExactConnection2
	{

		public frmBrowseDocuments()
			: base()
		{
			if (m_vb6FormDefInstance is null)
			{
				if (m_InitializingDefInstance)
				{
					m_vb6FormDefInstance = this;
				}
				else
				{
					try
					{
						//For the start-up form, the first instance created is the default instance.
						if (!(System.Reflection.Assembly.GetExecutingAssembly().EntryPoint is null) && System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType == this.GetType())
						{
							m_vb6FormDefInstance = this;
						}
					}
					catch
					{
					}
				}
			}
			//This call is required by the Windows Form Designer.
			InitializeComponent();
		}

		//-- Interfaces

		//-- Private vars
		private Exact.SystemLayer.Interfaces.IApplication m_App = null;
		private Exact.SystemLayer.Interfaces.ICompany m_Comp = null;
		private Exact.SystemLayer.Interfaces.ITranslator m_Term = null;
		private Exact.DataLayer.IEdlConnection m_conn = null;
		private Exact.DataLayer.IEdlRef m_EdlRef = null; //Chan31941 07-Jun-2005 [FC 15.246.455]

		private int m_JobLevel = 0;
		private byte[] m_AttachedDocument = null;
		private byte[] m_DocumentBody = null;
		private string m_FileName = "";
		private string m_TempFile = "";

		private bool m_busy = false;

		//Start CBR 80.967.458
		private GlobalInterfaces.GI_Exact.Cmdm.Tools.IclsGeneral m_oCMDMTools = null;
		private const string gsCMDMTopicAccount = "ACCOUNT";
		private bool m_bUseCentralData = false;
		//End CBR 80.967.458

		//-- Public vars: Contains the params
		//-- For query - view
		public string OrderNumber = "";
		public string OurRef = "";
		public string YourRef = "";
		public object AttachmentId = null;
		public object Account = null;
		public object Resource = null;
		public object ProjectNumber = null;
		public object Item = null;
		public object PaymentReference = null;
		public object ItemSerialNumber = null;
		//chan221476 (10-02-2009) [BR29.584.764] - New variable to store table name
		public string TableSourceInvoice = "";
		////New feature, add existing documents:
		private System.Collections.Generic.IList<int> m_alngExisting = new System.Collections.Generic.List<int>();
		private System.Collections.Generic.IList<string> m_astrFilterDocType = new System.Collections.Generic.List<string>();

		//-- Used when adding new
		public int DocType = 0;
		public string DefaultOrderNumber = "";
		public string DefaultOurRef = "";
		public string DefaultYourRef = "";
		public string DefaultAccount = "";
		public string DefaultResource = "";
		public string DefaultProjectNumber = "";
		public string DefaultItem = "";
		public string DefaultPaymentReference = "";
		public string DefaultItemSerialNumber = "";
		public string DefaultEntryKey = "";

		public string NewDocumentID = "";
		public bool ReadOnly = false;
		public bool ReturnIDWhenEmpty = false;
		public bool UseExistConnection = false;

		private bool bShouldReturnID = false;
		private bool bAllowAddNew = false;
		private bool bAllowAddExisting = false;
		private bool bEnableButtons = false;

		private const string cUnsafeFileExtensions = ".ade.adp.bas.bat.chm.cmd.com.cpl.crt.exe.hlp.hta.inf.ins.isp.js.jse.lnk.mdb.mde.msc.msi.msp.mst.pcd.pif.reg.scr.sct.shs.shb.url.vb.vbe.vbs.wsc.wsf.wsh";
		private const short cFileThresholdSize = 4000; //Chan31941, 12-Oct-04 [12.654.658]

		//''Private Enum WhereClause
		//''    eAll
		//''    eOrderNumberAccount
		//''    eOrderNumberYourRefAccount
		//''    eOrderNumberOurRefAccount
		//''    eOurRefYourRefAccount
		//''    eOurRefAccount
		//''    eYourRefAccount
		//''    eOrderNumber
		//''    eOrderNumberYourRef
		//''    eOrderNumberOurRef
		//''    eOurRefYourRef
		//''    eAccount
		//''    eOurRef
		//''    eYourRef
		//''    eItem
		//''    eProject
		//''    eResource
		//''    eNone
		//''End Enum

		//-- Holds reference to maintenance object
		private Exact.SystemLayer.Interfaces.IExactMaintenance m_Maint = null;

		//-- Observers
        private Exact.SystemLayer.SubjectRx.SubjectFactory m_Factory = null;
		private Exact.SystemLayer.SubjectRx.Subject m_Subject = null;
		private Exact.SystemLayer.Interfaces.IObserver m_Observer = null;

		//-- Constants
		private enum aBarButtons
		{
			CMD_CLOSE = 1,
			CMD_EDIT = 2,
			CMD_NEW = 3,
			CMD_OPEN = 4,
			CMD_NOTE = 5,
			CMD_DOWNLOAD = 6,
			CMD_EXISTING = 7
		}

		//[limh109866][FC21.820.527]16 MAR 2007
		public string StateCode = "";
		public string CountryCode = "";

		public Exact.SystemLayer.Interfaces.ISettings iSet = null;
		public bool m_bUseTaxExemptedCert = false; //BR 28.356.242
		private Exact.SystemLayer.SetAppTitle.Titles _m_oTitle = null;
		private Exact.SystemLayer.SetAppTitle.Titles m_oTitle
		{
			get
			{
				if (_m_oTitle is null)
				{
					_m_oTitle = new Exact.SystemLayer.SetAppTitle.Titles();
				}
				return _m_oTitle;
			}
			set
			{
				_m_oTitle = value;
			}
		}
		 //PBI 112801: Applocale Set application title

		public void AddExistingType(int lngType)
		{
			////---------------------------------------------------------------------------------------
			//// Procedure: AddExistingType
			//// DateTime : 30-07-2003 / 11:14
			//// Author   : Rick Langevoort
			//// Purpose  : Add a type ID to the array of types to be displayed.
			////
			//// Returns  : -
			////
			//// Revision :
			////---------------------------------------------------------------------------------------

			Globals.Add2Array_Long(  m_alngExisting, lngType, true);
		}

		//Option to filter on document type
		public void FilterDocType(int lngType)
		{
			Globals.Add2Array(  m_astrFilterDocType, lngType.ToString().Trim(), true);
		}

		//-- Connetion interface
		public Exact.SystemLayer.Interfaces.IApplication Application
		{
			get
			{
				return m_App;
			}
			set
			{
				m_App = value;
			}
		}


		public Exact.SystemLayer.Interfaces.ICompany Company
		{
			get
			{
				return m_Comp;
			}
			set
			{
				m_Comp = value;
			}
		}


		public Exact.SystemLayer.Interfaces.ITranslator Translator
		{
			get
			{
				return m_Term;
			}
			set
			{
				m_Term = value;
			}
		}


		public void Connect()
		{
			Initialize(m_App, m_Comp, m_Term);
			m_App.ConnectObject(brwDocuments, m_Comp, m_Term);
			m_App.ConnectObject(ActionBar, m_Comp, m_Term);
			//Chan31941 07-Jun-2005 [FC 15.246.455]
			m_EdlRef = m_conn.CreateRef("orkrg", "ID", "*", Exact.DataLayer.LockModes.edlLockUpdate);
		}

		//-- Public functions and subs
		//UPGRADE-WARNING: Parameter Term was changed from byref to byval.
		//UPGRADE-WARNING: Parameter Comp was changed from byref to byval.
		//UPGRADE-WARNING: Parameter App was changed from byref to byval.
		public void Initialize(Exact.SystemLayer.Interfaces.IApplication App, Exact.SystemLayer.Interfaces.ICompany Comp, Exact.SystemLayer.Interfaces.ITranslator Term)
		{
			//-- Create objects
			if (m_App is null)
			{
				m_App = App;
			}
			if (m_Comp is null)
			{
				m_Comp = Comp;
			}
			if (m_Term is null)
			{
				m_Term = Term;
			}
			if (m_conn is null)
			{
				m_conn = m_Comp.EDLConnection;
			}

			//-- Get the joblevel of the user
			m_JobLevel = GetJobLevel();
		}

		public void ShowForm()
		{
			this.ShowDialog();
		}

		private void ActionBar_ButtonClick(object eventSender, Exact.Win.UI.Controls.Interfaces.ButtonClickEventArgs eventArgs)
		{
			int nID = eventArgs.nID;

			try
			{
				Exact.DataLayer.EdlObject vAccount = null;
				frmExisting objEx = null;
				//UPGRADE_WARNING: (6021) Casting 'int' to Enum may cause different behaviour. More Information: https://www.mobilize.net/vbtonet/ewis/ewi6021
				switch((aBarButtons) nID)
				{
					case aBarButtons.CMD_EXISTING : 
						//Chan31941, [06-Sep-2006] [20.078.294] 
						if (IsRecordLocked())
						{
							return;
						} 
						 
						 
						objEx = new frmExisting(); 
						 
						//UPGRADE_ISSUE: (2064) Void method Global.Load was not upgraded. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2064 
						//VB.Global.Load(objEx); 
						 
						////Set types to be shown: 
						foreach (int m_alngExisting_item in m_alngExisting)
						{
							objEx.AddExistingType(m_alngExisting_item);
						} 
						 
						//BR 09.188.353: Document browser should try to prefill the account number 
						//Apply only for single type document 
						objEx.DefaultAccount = DefaultAccount; 
						if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultAccount) || Exact.SystemLayer.Common.ConvertHelper.IsNull(DefaultAccount) || DefaultAccount.TrimNullAndSpaces() == "")
						{
							if (m_alngExisting.Count == 1)
							{
								switch(m_alngExisting[0])
								{
									case GlobalInterfaces.GI_Exact.Crm.DocumentBrowser.Globals.cTypePurchaseQuotation : 
										vAccount = m_conn.Query("SELECT cicmpy.cmp_wwn FROM orkrg INNER JOIN cicmpy ON cicmpy.crdnr = orkrg.crdnr WHERE orkrg.ordernr = ?", OrderNumber, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls); 
										break;
									case GlobalInterfaces.GI_Exact.Crm.DocumentBrowser.Globals.cTypeSalesOrder : case GlobalInterfaces.GI_Exact.Crm.DocumentBrowser.Globals.cTypeRequestForProposal : 
										vAccount = m_conn.Query("SELECT cicmpy.cmp_wwn FROM orkrg INNER JOIN cicmpy ON cicmpy.debnr = orkrg.debnr WHERE orkrg.ordernr = ?", OrderNumber, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls); 
										break;
									case GlobalInterfaces.GI_Exact.Crm.DocumentBrowser.Globals.cTypePurchaseInvoice : 
										//Chan31941, [08-Nov-2006] [20.781.920]-Adjustment on performance for SQL2005 
										vAccount = m_conn.Query("SELECT cicmpy.cmp_wwn FROM cicmpy WHERE cicmpy.crdnr = (SELECT DISTINCT gbkmut.crdnr " + 
										           "FROM gbkmut " + 
										           "LEFT OUTER JOIN btwtrs b1 ON gbkmut.reknr = b1.reknr AND gbkmut.reknr IS NOT NULL AND b1.reknr IS NOT NULL " + 
										           "LEFT OUTER JOIN btwtrs b2 ON gbkmut.crdnr = b2.creditor AND gbkmut.crdnr IS NOT NULL AND b2.creditor IS NOT NULL " + 
										           "WHERE gbkmut.faktuurnr = ? AND gbkmut.crdnr IS NOT NULL " + 
										           "AND (b1.ID IS NULL AND b2.ID IS NULL))", OurRef, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls); 
										break;
								}

								if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vAccount))
								{
									objEx.DefaultAccount = vAccount;
								}
							}
						} 
						 
						////Set order data: 
						objEx.DefaultOrderNumber = DefaultOrderNumber; 
						objEx.DefaultOurRef = DefaultOurRef; 
						objEx.DefaultYourRef = DefaultYourRef; 
						objEx.DefaultResource = DefaultResource; 
						objEx.DefaultProjectNumber = DefaultProjectNumber; 
						objEx.DefaultItem = DefaultItem; 
						objEx.DefaultPaymentReference = DefaultPaymentReference; 
						objEx.DefaultItemSerialNumber = DefaultItemSerialNumber; 
						objEx.DefaultEntryKey = DefaultEntryKey; 
						objEx.ReadOnly = ReadOnly; 
						 
						////Start browsing: 
						objEx.BrowseExisting(m_App, m_conn, m_Comp, m_Term, this); 
						 
						if (objEx.DocMatched)
						{
							RefreshBrowser();
						} 
						 
						objEx.Close(); 
						objEx = null; 
						 
						break;
					case aBarButtons.CMD_EDIT : 
						//Chan31941, [27-Jul-2006] [19.759.784] 
						if (IsDocumentExists())
						{
							return;
						} 
						 
						if (HasRights())
						{
							//Chan31941, [06-Sep-2006] [20.078.294]
							if (IsRecordLocked())
							{
								return;
							}
							OpenAttachment();
						}
						else
						{
							//PBI 112801: Applocale Set application title
							m_App.Message(this.Handle, m_Term.String(15469, "No rights"), m_oTitle.GetTitle(this));
						} 
						break;
					case aBarButtons.CMD_CLOSE : 
						//-- Try to delete the current temp file 
						DeleteTempFile(); 
						//UPGRADE_WARNING: (1049) Use of Null/IsNull() detected. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1049 
						if (Exact.SystemLayer.Common.ConvertHelper.IsNull((Exact.SystemLayer.Common.ConvertHelper.IsEmpty(AttachmentId)) ? DBNull.Value : AttachmentId))
						{
							if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(NewDocumentID))
							{
								if (brwDocuments.NumRows > 0)
								{
									brwDocuments.CurrentRow = 1;
									if (bShouldReturnID)
									{
										//UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
										NewDocumentID = Convert.ToString(brwDocuments.get_value("ID"));
									}
								}
							}
							else if (brwDocuments.NumRows == 0)
							{ 
								NewDocumentID = ""; //br30.701.256 chon32144 30/05/2009
							}
						} 
						//[limh109866][05 JUN 2006]br19.275.758 
						//Me.Hide 
						this.Close(); 
						break;
					case aBarButtons.CMD_NEW : 
						//Chan31941, [06-Sep-2006] [20.078.294] 
						if (IsRecordLocked())
						{
							return;
						} 
						NewDocument(); 
						break;
					case aBarButtons.CMD_OPEN : 
						//Chan31941, [27-Jul-2006] [19.759.784] 
						if (IsDocumentExists())
						{
							return;
						} 
						 
						if (HasRights())
						{
							DisplayAttachment(false);
						}
						else
						{
							//PBI 112801: Applocale Set application title
							m_App.Message(this.Handle, m_Term.String(15469, "No rights"), m_oTitle.GetTitle(this));
						} 
						break;
					case aBarButtons.CMD_NOTE : 
						if (HasRights())
						{
							DisplayNotes();
						}
						else
						{
							//PBI 112801: Applocale Set application title
							m_App.Message(this.Handle, m_Term.String(15469, "No rights"), m_oTitle.GetTitle(this));
						} 
						break;
					case aBarButtons.CMD_DOWNLOAD : 
						//Chan31941, [27-Jul-2006] [19.759.784] 
						if (IsDocumentExists())
						{
							return;
						} 
						 
						if (HasRights())
						{
							DisplayAttachment(true);
						}
						else
						{
							//PBI 112801: Applocale Set application title
							m_App.Message(this.Handle, m_Term.String(15469, "No rights"), m_oTitle.GetTitle(this));
						} 
						break;
				}
			}
			finally
			{
				eventArgs.nID = nID;
			}
		}

		private bool bLoaded = false;
		private void brwDocuments_RowChanged(Object eventSender, EventArgs eventArgs)
		{
			if (bLoaded) EnableButtons(true);
		}

		private void brwDocuments_Selected(Object eventSender, EventArgs eventArgs)
		{
			if (ActionBar[(int) aBarButtons.CMD_EDIT].Enabled)
			{
				ActionBar_ButtonClick(ActionBar, new Exact.Win.UI.Controls.Interfaces.ButtonClickEventArgs((int) aBarButtons.CMD_EDIT));
			}
		}

        protected override void FormLoad()
        {
			//-- Set the caption
			//PBI 112801: Applocale Set application title
			m_oTitle.SetFormTitle(this, m_Term.String(31261, "Attachments"), true);

			//-- Init observer
			System.Threading.Tasks.Task.Run(() => { InitObserver(); });

			//Read settings
			ReadSettings();
		}

		private void Form_Load(object sender, System.EventArgs e)
		{
			//>>BR: 14.556.042-Locking error during adding attachment
			bEnableButtons = true;
			if (IsOrkrgLocked())
			{
				bEnableButtons = false;
			}

			NewDocumentID = "";

			if (Exact.SystemLayer.Common.ConvertHelper.IsNull((Exact.SystemLayer.Common.ConvertHelper.IsEmpty(AttachmentId)) ? DBNull.Value : AttachmentId))
			{
				bShouldReturnID = ReturnIDWhenEmpty;
			}

			////New feature: show existing, non-matched, documents of specified type(s):
			////Add the default type (Miscellaneous) if not exist
			if (!Globals.TestArray_Long(m_alngExisting))
			{
				if (DocType != 0)
				{
					AddExistingType(DocType);
				}
				else
				{
					AddExistingType(GlobalInterfaces.GI_Exact.Crm.DocumentBrowser.Globals.cTypeMiscellaneous);
				}
			}
			ActionBar.ToggleVisibility(false);
			ActionBar.ShowButton((int)aBarButtons.CMD_EXISTING, Globals.TestArray_Long(m_alngExisting));
			ActionBar.ToggleVisibility(true);
		}

		private void Form_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
		{
			// Do not remove, allow form UI to render first
			System.Windows.Forms.Application.DoEvents();
			// Run browser query and rendering in separate Task
			System.Threading.Tasks.Task.Run(()=> { RefreshBrowser(); bLoaded = true; }); 			
		}

		private void Form_Closed(Object eventSender, CancelEventArgs eventArgs)
		{
			int Cancel = (eventArgs.Cancel) ? 1 : 0;
			try
			{
				if (IsRunning(false))
				{
					//-- Don't allow unload
					Cancel = 1;
					return;
				}

				//-- Try to delete the current temp file
				DeleteTempFile();
				//UPGRADE_WARNING: (1049) Use of Null/IsNull() detected. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1049
				if (Exact.SystemLayer.Common.ConvertHelper.IsNull((Exact.SystemLayer.Common.ConvertHelper.IsEmpty(AttachmentId)) ? DBNull.Value : AttachmentId))
				{
					if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(NewDocumentID))
					{
						if (brwDocuments.NumRows > 0)
						{
							brwDocuments.CurrentRow = 1;
							if (bShouldReturnID)
							{
								//UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
								NewDocumentID = Convert.ToString(brwDocuments.get_value("ID"));
							}
						}
					}
					else if (brwDocuments.NumRows == 0)
					{ 
						NewDocumentID = ""; //br30.701.256 chon32144 30/05/2009
					}
				}

				//-- Terminate observer
				TerminateObserver();
				//chan221476 (10-02-2009) [BR29.584.764] - Set it back to empty when form close
				if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(TableSourceInvoice))
				{
					TableSourceInvoice = "";
				}
				//-- Kill objects
				m_Maint = null;
				m_App = null;
				m_Comp = null;
				m_Term = null;
				m_conn = null;

				//>>BR: 14.556.042-Locking error during adding attachment
				//Chan31941, 07-Jun-2005 [FC 15.246.455]
				m_EdlRef?.Dispose();
				m_EdlRef = null;
				m_oTitle = null; //PBI 112801: Applocale Set application title
			}
			finally
			{
				eventArgs.Cancel = Cancel != 0;
			}

		}

		//''Private Function GetClause() As WhereClause
		//''    '-- Resource is always filled!
		//''
		//''    '-- Browse only for item?
		//''    If Not IsEmpty(Item) Then
		//''        If IsEmpty(ProjectNumber) And IsEmpty(Account) And IsEmpty(OrderNumber) And IsEmpty(OurRef) And IsEmpty(YourRef) Then
		//''            GetClause = eItem
		//''            Exit Function
		//''        End If
		//''    End If
		//''
		//''    '-- Browse only for resource?
		//''    If Not IsEmpty(Resource) Then
		//''        If IsEmpty(ProjectNumber) And IsEmpty(Account) And IsEmpty(OrderNumber) And IsEmpty(OurRef) And IsEmpty(YourRef) And IsEmpty(Item) Then
		//''            GetClause = eResource
		//''            Exit Function
		//''        End If
		//''    End If
		//''
		//''    '-- Browse only for project?
		//''    If Not IsEmpty(ProjectNumber) Then
		//''        If IsEmpty(Item) And IsEmpty(Account) And IsEmpty(OrderNumber) And IsEmpty(OurRef) And IsEmpty(YourRef) Then
		//''            GetClause = eProject
		//''            Exit Function
		//''        End If
		//''    End If
		//''
		//''    '-- Evaluate fither
		//''    If Not IsEmpty(OrderNumber) And Not IsEmpty(OurRef) And Not IsEmpty(YourRef) Then
		//''        GetClause = eAll
		//''    Else
		//''        If Not IsEmpty(OrderNumber) And Not IsEmpty(OurRef) And Not IsEmpty(Account) Then
		//''            GetClause = eOrderNumberOurRefAccount
		//''        Else
		//''            If Not IsEmpty(OrderNumber) And Not IsEmpty(YourRef) And Not IsEmpty(Account) Then
		//''                GetClause = eOrderNumberYourRefAccount
		//''            Else
		//''                If Not IsEmpty(YourRef) And Not IsEmpty(OurRef) And Not IsEmpty(Account) Then
		//''                    GetClause = eOurRefYourRefAccount
		//''                Else
		//''                    If Not IsEmpty(OrderNumber) And Not IsEmpty(OurRef) Then
		//''                        GetClause = eOrderNumberOurRef
		//''                    Else
		//''                        If Not IsEmpty(OrderNumber) And Not IsEmpty(YourRef) Then
		//''                            GetClause = eOrderNumberYourRef
		//''                        Else
		//''                            If Not IsEmpty(YourRef) And Not IsEmpty(OurRef) Then
		//''                                GetClause = eOurRefYourRefAccount
		//''                            Else
		//''                                If Not IsEmpty(YourRef) And Not IsEmpty(Account) Then
		//''                                    GetClause = eYourRefAccount
		//''                                Else
		//''                                    If Not IsEmpty(OurRef) And Not IsEmpty(Account) Then
		//''                                        GetClause = eOurRefAccount
		//''                                    Else
		//''                                        If Not IsEmpty(OrderNumber) And Not IsEmpty(Account) Then
		//''                                            GetClause = eOrderNumberAccount
		//''                                        Else
		//''                                            If Not IsEmpty(Account) Then
		//''                                                GetClause = eAccount
		//''                                            Else
		//''                                                If Not IsEmpty(YourRef) Then
		//''                                                    GetClause = eYourRef
		//''                                                Else
		//''                                                    If Not IsEmpty(OurRef) Then
		//''                                                        GetClause = eOurRef
		//''                                                    Else
		//''                                                        If Not IsEmpty(OrderNumber) Then
		//''                                                            GetClause = eOrderNumber
		//''                                                        Else
		//''                                                            GetClause = eNone
		//''                                                        End If
		//''                                                    End If
		//''                                                End If
		//''                                            End If
		//''                                        End If
		//''                                    End If
		//''                                End If
		//''                            End If
		//''                        End If
		//''                    End If
		//''                End If
		//''            End If
		//''        End If
		//''    End If
		//''End Function

		//UPGRADE-WARNING: Parameter AttachGuid was changed from byref to byval.
		private void UpdateBacoDiscussions(string AttachGuid)
		{
			//'tanj42445 - 20101125 - FC 37.043.210 - Trigger notification when update document
			Exact.SystemLayer.Interfaces.IConnectivity oESF = new Exact.Entity.Notification.Connectivity();
			m_App.ConnectObject(oESF, m_Comp, m_Term);

			//UPGRADE_WARNING: (2081) Array has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
			m_conn.Exec("UPDATE BacoDiscussions SET OrderNumber=?,OurRef=?,YourRef=?,Cmpwwn=?,Type=?,HumResId=?,EntryKey=? WHERE ID=?", new Exact.DataLayer.EdlObject[]{DefaultOrderNumber, DefaultOurRef, DefaultYourRef, DefaultAccount, DocType, DefaultResource, DefaultEntryKey, AttachGuid});
			oESF.NotifyProcessWithBCEdit("BDDocument", "ID", AttachGuid, Exact.SystemLayer.Interfaces.NotifyAction.naUpdate);
			m_conn.Commit();

			//'End FC 36.946.408
		}

		private void NewDocument()
		{
			string DocumentId = "";

			Exact.SystemLayer.Interfaces.IExactMaintenance oMaint = null;
			Exact.SystemLayer.Interfaces.IExtensionDlg b = null;
			Exact.SystemLayer.Utils.MaintenanceHelper maintHelper = null;
			Exact.SystemLayer.Interfaces.IValueSet vs = null;
			if (!StartNewDocumentApp())
			{

				//UPGRADE_WARNING: (7008) The ProgId could not be found on computer where this application was migrated More Information: https://www.mobilize.net/vbtonet/ewis/ewi7008
				b = (Exact.SystemLayer.Interfaces.IExtensionDlg) new Exact.Win.UI.FipAttachment();

				m_App.ConnectObject(b, m_Comp, m_Term);
				b.Title = m_Term.String(7226, "Document");
				//UPGRADE_WARNING: (1068) tempRefParam of type object is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
				object tempRefParam = DocumentId;
				b.Show(this.Handle, 0, ref tempRefParam);
				DocumentId = Convert.ToString(tempRefParam);

				if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DocumentId))
				{
					UpdateBacoDiscussions(DocumentId);

					if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(NewDocumentID))
					{
						NewDocumentID = DocumentId;
					}
				}
			}
			else
			{
				//-- Use new document applications
				//If m_Maint Is Nothing Then
				//    Set m_Maint = CreateObject("MDocuments.Document", "")
				//    m_App.ConnectObject m_Maint, m_Comp, m_Term
				//End If

				//CBR78.032.704
				maintHelper = new Exact.SystemLayer.Utils.MaintenanceHelper();
				m_App.ConnectObject(maintHelper, m_Comp, m_Term);
				oMaint = maintHelper.CreateMaintObj("MDocuments.Document", "");

				vs = new Exact.SystemLayer.Common.ValueSet();

				//-- Create value set with values
				vs.Add("OrderNumber", DefaultOrderNumber);
				vs.Add("OurRef", DefaultOurRef);
				vs.Add("YourRef", DefaultYourRef);
				vs.Add("Person", DefaultResource);
				vs.Add("Associate", DefaultAccount);
				vs.Add("Type", DocType);
				vs.Add("ProjectNr", DefaultProjectNumber);
				if ((((DefaultItem) is null) ? 0 : Convert.ToString(DefaultItem).Trim().Length) > 0)
				{
					vs.Add("Item", DefaultItem);
				}
				vs.Add("PaymentReference", DefaultPaymentReference);
				if ((((DefaultItem) is null) ? 0 : Convert.ToString(DefaultItem).Trim().Length) > 0 && (((DefaultItemSerialNumber) is null) ? 0 : Convert.ToString(DefaultItemSerialNumber).Trim().Length) > 0)
				{
					//NGOB24429: [09.150.093] 23/12/2003 (Wrongly set property name, caused invalid validation in repository.)
					//.Add "ItemSerialNumberCode", DefaultItemSerialNumber
					vs.Add("ItemSerialNumber", DefaultItemSerialNumber);
				}
				vs.Add("EntryKey", DefaultEntryKey);

				//[limh109866][FC21.820.527]16 MAR 2007
				//BR 28.356.242 - Check on the setting
				if (m_bUseTaxExemptedCert && !System.String.IsNullOrWhiteSpace(StateCode) && !System.String.IsNullOrWhiteSpace(CountryCode))
				{
					vs.Add("StateCode", StateCode);
					vs.Add("CountryCode", CountryCode);
				}

				if (UseExistConnection)
                {
					vs.Add("UseExistConnection", UseExistConnection);
                }
				
				oMaint.Add(this.Handle, vs, Exact.SystemLayer.Interfaces.MaintenanceFlags.mntModal, "U");
				oMaint = null;

				//[limh109866][05 JUN 2006]br19.275.758
				if (m_App is null)
				{
					return;
				}
				bShouldReturnID = true;
				//tanc30792 [BR 12.312.774] [10 Sep 2004]
				//Always refresh to refresh the calculated field
				brwDocuments.Refresh();
				vs = null;
			}

			EnableButtons(true);
		}

		private void OpenAttachment()
		{
			string DocumentId = "";

			Exact.SystemLayer.Interfaces.IExactMaintenance oMaint = null;
			Exact.SystemLayer.Interfaces.IExtensionDlg b = null;
			Exact.SystemLayer.Utils.MaintenanceHelper maintHelper = null;
			if (!StartNewDocumentApp())
			{

				//UPGRADE_WARNING: (7008) The ProgId could not be found on computer where this application was migrated More Information: https://www.mobilize.net/vbtonet/ewis/ewi7008
				b = (Exact.SystemLayer.Interfaces.IExtensionDlg) new Exact.Win.UI.FipAttachment();
				m_App.ConnectObject(b, m_Comp, m_Term);

				b.Title = m_Term.String(31617, "Attachement");

				//Open the document
				if (brwDocuments.NumRows != 0)
				{
					//UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
					DocumentId = Convert.ToString(brwDocuments.get_value("BacoDiscussions.ID"));
					if (ReadOnly)
					{
						//UPGRADE_WARNING: (1068) tempRefParam of type object is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
						object tempRefParam = DocumentId;
						b.Show(this.Handle, 1, ref tempRefParam);
						DocumentId = Convert.ToString(tempRefParam);
					}
					else
					{
						//UPGRADE_WARNING: (1068) tempRefParam2 of type object is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
						object tempRefParam2 = DocumentId;
						b.Show(this.Handle, 0, ref tempRefParam2);
						DocumentId = Convert.ToString(tempRefParam2);
					}
				}

				b = null;
			}
			else
			{
				//-- Use new document applications
				//If m_Maint Is Nothing Then
				//    Set m_Maint = CreateObject("MDocuments.Document")
				//    m_App.ConnectObject m_Maint, m_Comp, m_Term
				//End If

				//CBR78.032.704
				maintHelper = new Exact.SystemLayer.Utils.MaintenanceHelper();
				m_App.ConnectObject(maintHelper, m_Comp, m_Term);
				oMaint = maintHelper.CreateMaintObj("MDocuments.Document", "");

				//UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to int. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
				oMaint.Edit(this.Handle, Convert.ToInt32(brwDocuments.get_value("BacoDiscussions.HID")), Exact.SystemLayer.Interfaces.MaintenanceFlags.mntModal, (ReadOnly) ? "UR" : "UA");
				oMaint = null;

				//[limh109866][05 JUN 2006]br19.275.758
				if (m_App is null)
				{
					return;
				}
				//tanc30792 [BR 12.312.774] [10 Sep 2004]
				//Always refresh to refresh the calculated field
				brwDocuments.Refresh();
			}
		}

		private bool StartNewDocumentApp()
		{
			//-- Use new document app when crm present in license or when Compact
			//BR 10.316.682: No checking on CRM and Compact option
			//If m_Comp.GetOpt(OPT_E_CIS) Or m_Comp.GetOpt(OPT_COMPACT) Then
			return true;
			//Else
			//    StartNewDocumentApp = False
			//End If
		}

		private string GetSelectCol()
		{
			return "HID, (LEFT(RIGHT(RTRIM('00000000' + CAST(HID AS char(8))), 8), 2) + '.' + SUBSTRING(RIGHT(RTRIM('00000000' + CAST(HID AS char(8))), 8), 3, 3) + '.' + RIGHT(RTRIM('00000000' + CAST(HID AS char(8))), 3)) AS HIDFormatted, " + 
			"BacoDiscussionFixedTypes.Description, BacoDiscussions.JobLevel, BacoDiscussions.Subject, BacoDiscussions.FileName, (RTRIM(Cast(DataLength(BacoDiscussions.Document)/1000 AS char(12))) + ' KB') AS Size, BacoDiscussions.OrderNumber, BacoDiscussions.OurRef, BacoDiscussions.YourRef, (CASE WHEN ISNULL(BacoDiscussions.Source,'S') = 'I' THEN 1 ELSE 0 END) AS Input, (CASE WHEN NOT ISNULL(BacoDiscussions.Source,'S') = 'I' THEN 1 ELSE 0 END) AS Output, (CASE WHEN BacoDiscussions.Note IS NULL THEN 0 ELSE 1 END) as Notes," + 
			"BacoDiscussions.CreatedByFullName, BacoDiscussions.CreatedDate, BacoDiscussions.ModifiedDate," + 
			"BacoDiscussions.ID";
		}

		private string GetColumnInfo()
		{
			//tanc30792 [BR 14.674.387] [12 Apr 2005] Term Size
			return "HIDFormatted,7226,Document,,,2048;BacoDiscussionFixedTypes.Description,4243,Description,15;" + 
			"Input,8644,Input;Output,8888,Output;Notes,8873,Notes;BacoDiscussions.OrderNumber,404,Order Number;BacoDiscussions.OurRef,119,Our Ref;BacoDiscussions.YourRef,78,Your Ref;BacoDiscussions.Subject,213,Subject,25;BacoDiscussions.JobLevel,209,Security level,10,64;BacoDiscussions.CreatedDate,2468,Created,20;" + 
			"BacoDiscussions.CreatedByFullName,10696,Created by,20;BacoDiscussions.FileName,31617,File name,25;BacoDiscussions.ModifiedDate,32118,Modified,20;" + 
			"BacoDiscussions.ModifiedByFullName,24774,Modified by,20;Size,5810,Size,12,64";
		}

		private string GetFrom()
		{
			//BR 08.910.344: Optimize query by reducing number of "inner join"
			//GetFrom = "BacoDiscussions " & _
			//    '    "INNER JOIN BacoDiscussionFixedTypes ON BacoDiscussions.Type = BacoDiscussionFixedTypes.TypeID " & _
			//    '    "INNER JOIN (" & _
			//    '    "SELECT ID " & _
			//    '        "FROM BacoDiscussions " & _
			//    '        "INNER JOIN BacoDiscussionFixedTypes ON BacoDiscussions.Type = BacoDiscussionFixedTypes.TypeID WHERE [WHERE]" & _
			//    '        " UNION " & _
			//    '        "SELECT ID " & _
			//    '        "FROM BacoDiscussions " & _
			//    '        "LEFT JOIN BacoDiscussionFixedTypes ON BacoDiscussions.Type = BacoDiscussionFixedTypes.TypeID WHERE BacoDiscussions.ID=" & m_conn.Literal(IIf(IsEmpty(AttachmentId), Null, AttachmentId)) & _
			//    '        ") AS X ON X.Id=BacoDiscussions.ID "


			string result = "";
			result = "BacoDiscussions " + 
			         "INNER JOIN BacoDiscussionFixedTypes ON BacoDiscussions.Type = BacoDiscussionFixedTypes.TypeID WHERE [WHERE]";

			//[limh109866][FC21.820.527]16 MAR 2007
			//BR 28.356.242 - Check on the setting
			if (m_bUseTaxExemptedCert && !System.String.IsNullOrWhiteSpace(StateCode) && !System.String.IsNullOrWhiteSpace(CountryCode))
			{
				result = "BacoDiscussions " + 
				         "INNER JOIN BacoDiscussionFixedTypes ON BacoDiscussions.Type = BacoDiscussionFixedTypes.TypeID " + 
				         "INNER JOIN TaxExemptStateCertificates ON BacoDiscussions.ID = TaxExemptStateCertificates.DocumentID WHERE [WHERE]";
			}
			return result;
		}

		//-- Does the user have rights to open the document?
		private bool HasRights()
		{

			//Get information on the document
			Exact.DataLayer.EdlObject vDocument = m_conn.Query("SELECT Owner, CreatedBy, JobLevel, HumresID FROM BacoDiscussions WHERE ID=?", new Exact.DataLayer.EdlObject(brwDocuments.get_value("ID")), Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

			bool bHasRights = true;
			Exact.SystemLayer.Interfaces.IUser withVar = null;
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vDocument))
			{
				withVar = m_Comp.User;
				bHasRights = (withVar.ID == ((double) vDocument[0]));
				bHasRights = bHasRights || withVar.ID == ((double) vDocument[1]);
				bHasRights = bHasRights || m_JobLevel >= ((double) vDocument[2]);
				bHasRights = bHasRights || (withVar.ID == ((double) vDocument[3]) && ((double) vDocument[2]) == 100);
				bHasRights = bHasRights || withVar.Administrator;
				//BR 45.464.594 Check project specific document rights
				bHasRights = bHasRights || (((double) vDocument[2]) == 101 && IsProjectMember());
			}

			return bHasRights;
		}

		private bool IsProjectMember()
		{

			//UPGRADE_WARNING: (2081) Array has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
			return (bool) m_conn.Query("SELECT 1 FROM prmember WHERE ProjectNr = (SELECT ProjectNr FROM BacoDiscussions WHERE ID = ?) AND res_id = ?", new Exact.DataLayer.EdlObject[]{new Exact.DataLayer.EdlObject(brwDocuments.get_value("ID")), m_Comp.User.ID}, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

		}

		private int GetJobLevel()
		{

			Exact.DataLayer.EdlObject vResult = m_conn.Query("SELECT job_level" + 
			                                    "  FROM humres " + 
			                                    "    WHERE res_id=?", m_Comp.User.ID, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult))
			{
				return (int) vResult;
			}
			else
			{
				return 0;
			}
		}

		// --- showing attached document ---
		//UPGRADE-WARNING: Parameter bDownLoad was changed from byref to byval.
		private void DisplayAttachment(bool bDownLoad)
		{

			string sTempFileName = "";
			int nFileHandle = 0;
			bool bYesDownload = false;
			Exact.SystemLayer.General.Filer oFiler = new Exact.SystemLayer.General.Filer();
			try
			{
				//-- Get Current document
				StartProcess();
				//UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
				ReadAttachedDocument(Convert.ToString(brwDocuments.get_value("ID")));

				//-- Try to delete the current temp file
				DeleteTempFile();

				// --- generate temporary file to be able to show attachment ---
				if (m_AttachedDocument.GetUpperBound(0) > 0 || m_DocumentBody.GetUpperBound(0) > 0)
				{
					// --- generate temporary file name and path ---
				
					sTempFileName = Path.GetFileName(Path.GetTempFileName());
					if ((((m_FileName) is null) ? 0 : Convert.ToString(m_FileName).Trim().Length) > 0)
					{
						sTempFileName = Path.GetFileNameWithoutExtension(sTempFileName) + "." + Path.GetExtension(m_FileName).Substring(1);
					}
					else
					{
						sTempFileName = Path.GetFileNameWithoutExtension(sTempFileName) + ".htm";
					}
					sTempFileName = (new DirectoryInfo(Path.GetTempPath())).FullName + "\\" + sTempFileName;

					using (FileStream fs = File.Create(sTempFileName))
					{
						//Chan31941, 12-Oct-04 [12.654.658]-validate with UBound instead of IsEmpty
						//If Not IsEmpty(m_AttachedDocument) Then
						if (m_AttachedDocument.GetUpperBound(0) > 0)
						{
							//UPGRADE_WARNING: (2080) Put was upgraded to FilePutObject and has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2080
							fs.Write(m_AttachedDocument, 0, m_AttachedDocument.Length);
						}
						else
						{
							//Chan31941, 12-Oct-04 [12.654.658]-call function to download images.
							DownloadInsertedImages();
							//UPGRADE_WARNING: (2080) Put was upgraded to FilePutObject and has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2080
							fs.Write(m_DocumentBody, 0, m_DocumentBody.Length);
						}
					}

					//Special Cater for htm chinese character
					oFiler.ConvertFileFormat(sTempFileName, sTempFileName); //ASL for applocale
					oFiler = null;
					//Chan31941, 12-Oct-04 [12.654.658]
					//do not check UBound(m_AttachedDocument) cus this preventing document without attachment to launch
					//If UBound(m_AttachedDocument) > 0 Then
					if (bDownLoad || cUnsafeFileExtensions.ToUpper().IndexOf(Path.GetExtension(sTempFileName).Substring(1).ToUpper()) >= 0)
					{
						if (!bDownLoad)
						{
							//PBI 112801: Applocale Set application title
							bYesDownload = m_App.Query(this.Handle, m_Term.String(15839, "Unsafe") + ": " + m_Term.String(16165, "file") + Environment.NewLine + m_Term.String(20307, "Save?"), m_oTitle.GetTitle(this));
						}
						else
						{
							bYesDownload = true;
						}
                        
						//-- Download?
						if (bYesDownload)
						{
							if (CommonDialog == null)
								this.CommonDialog = new Exact.Win.UI.UniCommonDialog.CommonDialogW();
							CommonDialog.DefaultExt = Path.GetExtension(sTempFileName).Substring(1);
							//PBI 112801: Applocale Set application title
							CommonDialog.DialogTitle = m_oTitle.GetTitle(this);
							CommonDialog.CancelError = true;
							CommonDialog.Flags = (int) (Exact.Win.UI.UniEnums.FileOpenConstantsW.cdlOFNHideReadOnly | Exact.Win.UI.UniEnums.FileOpenConstantsW.cdlOFNOverwritePrompt);
							//UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
							CommonDialog.FileName = Convert.ToString(brwDocuments.get_value("FileName"));
							//UPGRADE_TODO: (1069) Error handling statement (On Error Resume Next) was converted to a pattern that might have a different behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1069
							try
							{
								CommonDialog.ShowSave();

                                if (CommonDialog.FileName.TrimNullAndSpaces() != "") 
								{
									//BR37.628.906 File not replaced if already exists. Since user already selected <replace file> option, so just delete if file exists
									if (File.Exists(CommonDialog.FileName))
									{
										File.Delete(CommonDialog.FileName);
									}
									File.Move(sTempFileName, CommonDialog.FileName);
								}
							}
							catch (Exception catchedException)
							{
								Exact.Exceptions.Globe.BaseGlobeException exc = Exact.Exceptions.Utils.ExceptionBuilder.Build(catchedException);
							}

						}
						ProgressTerm();
						EndProcess();
						return;
					}

					////chan31941, 16-Sep-04 [12.369.914]
					////set the document to ReadOnly mode.
					//UPGRADE_WARNING: (6021) Casting 'bool' to Enum may cause different behaviour. More Information: https://www.mobilize.net/vbtonet/ewis/ewi6021
					//UPGRADE_ISSUE: (2064) Scripting.IFile property GetFile.Attributes was not upgraded. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2064
                    File.SetAttributes(sTempFileName, FileAttributes.ReadOnly);

					ProgressTerm();

					// --- open attachment using associated application ---
					string tempRefParam = null;
					string tempRefParam2 = null;
					string tempRefParam3 = null;
					if (32 > Exact.SystemLayer.Common.PInvoke.SafeNative.shell32.ShellExecute(this.Handle ,   tempRefParam,   sTempFileName,   tempRefParam2,   tempRefParam3, 5).ToInt32())
					{
						string tempRefParam4 = null;
						string tempRefParam5 = "notepad.exe";
						string tempRefParam6 = null;
						if (32 > Exact.SystemLayer.Common.PInvoke.SafeNative.shell32.ShellExecute(this.Handle ,   tempRefParam4,   tempRefParam5,   sTempFileName,   tempRefParam6, 5).ToInt32())
						{
							//PBI 112801: Applocale Set application title
							m_App.Message(this.Handle, "No application associated with this file type.", m_oTitle.GetTitle(this));
						}
					}
					//End If

					//-- the current temp file in memory
					m_TempFile = sTempFileName;
				}

				EndProcess();
			}
			catch (System.Exception catchedException)
			{
				Exact.Exceptions.Globe.BaseGlobeException excep = Exact.Exceptions.Utils.ExceptionBuilder.Build(catchedException);

				//PBI 112801: Applocale Set application title
				//UPGRADE_WARNING: (2081) Err.Number has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
				m_App.Message(this.Handle, m_Term.String(8335, "Unknown error") + ": (" + ") - " + excep.Message, m_oTitle.GetTitle(this));
				ProgressTerm();
				EndProcess();
			}
		}

		private void ReadAttachedDocument(string ID)
		{

			Exact.DataLayer.EdlObject vResult = null;
			int lngSize = 0;
			Exact.DataLayer.EdlObject Piece = null;

			try
			{

				//*** Chan31941, 12-Oct-04 [12.654.658] - codes to read attachment, replacing the commented old codes below ***'
				vResult = m_conn.Query("SELECT DataLength(Document), Body, FileName FROM BacoDiscussions WHERE ID=? ", ID, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

				if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult))
				{
					lngSize = (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult[0])) ? 0 : ((int) vResult[0]);
					m_DocumentBody = (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult[1])) ? (UnicodeEncoding.Unicode.GetBytes("")) : ((byte[]) vResult[1]);
					m_FileName = (string) vResult[2];
				}
				else
				{
					//UPGRADE_WARNING: (1059) Code was upgraded to use System.Text.UnicodeEncoding.Unicode.GetBytes() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
					m_AttachedDocument = UnicodeEncoding.Unicode.GetBytes("");
					//UPGRADE_WARNING: (1059) Code was upgraded to use System.Text.UnicodeEncoding.Unicode.GetBytes() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
					m_DocumentBody = UnicodeEncoding.Unicode.GetBytes("");
					m_FileName = "";
				}

				//check if document datalength is greater then predefined thresholdsize.
				if (lngSize > cFileThresholdSize)
				{

					ProgressInit(Convert.ToDouble(lngSize), m_Term.String(6473, "Retrieving info"));

					m_AttachedDocument = new byte[lngSize];
					int tempForEndVar = lngSize;
					for (int lngI = 1; (cFileThresholdSize < 0) ? lngI >= tempForEndVar : lngI <= tempForEndVar; lngI += cFileThresholdSize)
					{
						ProgressValue(Convert.ToDouble(lngI));
						//UPGRADE_WARNING: (2081) Array has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
						Piece = m_conn.Query("SELECT TOP 1 SUBSTRING(Document,?,?) FROM BacoDiscussions WHERE ID=?", new Exact.DataLayer.EdlObject[]{lngI, cFileThresholdSize, ID});
						int tempForEndVar2 = Piece.GetUpperBound(0);
						for (int lngJ = 0; lngJ <= tempForEndVar2; lngJ++)
						{
							if (lngI - 1 + lngJ <= m_AttachedDocument.GetUpperBound(0))
							{
								m_AttachedDocument[lngI - 1 + lngJ] = ((byte[]) Piece.Data)[lngJ];
							}
							else
							{
								break;
							}
						}
					}
					ProgressTerm();
				}
				else
				{

					vResult = m_conn.Query("SELECT Document, Body, FileName FROM BacoDiscussions WHERE ID = ?", ID, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

					if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult))
					{
						m_AttachedDocument = (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult[0])) ? (UnicodeEncoding.Unicode.GetBytes("")) : ((byte[]) vResult[0]);
						m_DocumentBody = (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult[1])) ? (UnicodeEncoding.Unicode.GetBytes("")) : ((byte[]) vResult[1]);
						m_FileName = (string) vResult[2];
					}
					else
					{
						//UPGRADE_WARNING: (1059) Code was upgraded to use System.Text.UnicodeEncoding.Unicode.GetBytes() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
						m_AttachedDocument = UnicodeEncoding.Unicode.GetBytes("");
						//UPGRADE_WARNING: (1059) Code was upgraded to use System.Text.UnicodeEncoding.Unicode.GetBytes() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
						m_DocumentBody = UnicodeEncoding.Unicode.GetBytes("");
						m_FileName = "";
					}
				}
			}
			catch (System.Exception catchedException)
			{
				Exact.Exceptions.Globe.BaseGlobeException excep = Exact.Exceptions.Utils.ExceptionBuilder.Build(catchedException);

				//PBI 112801: Applocale Set application title
				m_App.Message(this.Handle, m_Term.String(8335, "Unknown error") + ": (" + ") - " + excep.Message, m_oTitle.GetTitle(this));
				ProgressTerm();
			}
		}

		//-- Progress indication procedures
		private void ProgressInit(double Max, string sMessage)
		{
			StatusBar.Progress = sMessage;
			StatusBar.Max = Convert.ToInt32(Max);
			StatusBar.Value = 0;
		}

		private void ProgressValue(double dValue)
		{
			StatusBar.Value = Convert.ToInt32(dValue);
			System.Windows.Forms.Application.DoEvents();
		}

		private void ProgressTerm()
		{
			StatusBar.Value = 0;
			StatusBar.Progress = "";
		}

		public void StartProcess()
		{
			m_busy = true;
			EnableButtons(false);
			brwDocuments.Enabled = false;
			System.Windows.Forms.Application.DoEvents();
		}

		public void EndProcess()
		{
			m_busy = false;
			EnableButtons(true);
			brwDocuments.Enabled = true;
			System.Windows.Forms.Application.DoEvents();
		}

		private void EnableButtons(bool bEnabled)
		{
			//>>BR: 14.556.042-Locking error during adding attachment
			ActionBar[(int) aBarButtons.CMD_NEW].Enabled = bEnabled && !ReadOnly && bAllowAddNew && bEnableButtons;
			ActionBar[(int) aBarButtons.CMD_EDIT].Enabled = bEnabled && brwDocuments.CurrentRow > 0 && bEnableButtons;

			ActionBar[(int) aBarButtons.CMD_DOWNLOAD].Enabled = bEnabled && brwDocuments.CurrentRow > 0;
			ActionBar[(int) aBarButtons.CMD_OPEN].Enabled = bEnabled && brwDocuments.CurrentRow > 0;
			ActionBar[(int) aBarButtons.CMD_NOTE].Enabled = bEnabled && brwDocuments.CurrentRow > 0 && bEnableButtons;
			ActionBar[(int) aBarButtons.CMD_CLOSE].Enabled = bEnabled;
			if (ReadOnly)
			{
				ActionBar[(int) aBarButtons.CMD_EDIT].SetCaptionTermID(8549, "Display", false);
			}
			else
			{
				ActionBar[(int) aBarButtons.CMD_EDIT].SetCaptionTermID(25319, "Edit", false);
			}

			//Chan31941, [06-Sep-2006] [20.078.294]
			ActionBar[(int) aBarButtons.CMD_EXISTING].Enabled = bAllowAddNew && !ReadOnly && bAllowAddExisting && bEnableButtons;

			//Start CBR 80.967.458
			if (m_Comp.GetOpt(GlobalInterfaces.GI_Exact.Crm.DocumentBrowser.Options.OPT_CENTRAL_MASTER_DATA))
			{
				LoadObjCMDMToolsGeneral();
				if (m_bUseCentralData)
				{
					ActionBar[(int) aBarButtons.CMD_NEW].Enabled = true;
				}
			}
			//End CBR 80.967.458

		}

		//Chan31941, [06-Sep-2006] [20.078.294]
		//Check if record is locked. If true, then disable <New>,<Edit> and <Add existing> buttons
		private bool IsRecordLocked()
		{
			bool result = false;
			if (IsOrkrgLocked())
			{
				//Display message
				//PBI 112801: Applocale Set application title
				m_App.Message(this.Handle, m_Term.String(18839, "Data in use"), m_oTitle.GetTitle(this));
				bEnableButtons = false;
				EnableButtons(true);
				result = true;
			}
			return result;
		}

		//>>BR: 14.556.042-Locking error during adding attachment
		private bool IsOrkrgLocked()
		{
			bool result = false;
			Exact.DataLayer.EdlObject vRes = null;
			string sSQL = "";

			try
			{

				result = false;

				sSQL = "SELECT ID FROM orkrg WITH (NOLOCK) WHERE ordernr = ?";

				vRes = m_conn.Query(sSQL, OrderNumber, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);
				//BR 21.862.123 [27-06-2007]: add in additional condition to check OrderNumber,
				//               if it is empty, then no need check for locking since is new record
				if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vRes) && !Exact.SystemLayer.Common.ConvertHelper.IsEmpty(OrderNumber))
				{
					//Chan31941, 07-Jun-2005 [FC 15.246.455]
					m_EdlRef.Find1(vRes);
					m_conn.Commit();
					result = false;
				}
			}
			catch
			{

				//Chan31941, [11-Sep-2006] [20.107.535]
				m_conn.Commit();

				//Chan31941, 07-Jun-2005 [FC 15.246.455]
				result = true;
			}

			return result;
		}

		//UPGRADE-WARNING: Parameter bSilent was changed from byref to byval.
		private bool IsRunning(bool bSilent = false)
		{
			if (!bSilent)
			{
				if (m_busy)
				{
					//PBI 112801: Applocale Set application title
					m_App.Message(this.Handle, m_Term.String(10333, "Can't close"), m_oTitle.GetTitle(this));
				}
			}
			return m_busy;
		}

		private void RefreshBrowser()
		{
			Exact.DataLayer.EdlObject vIsCreditor = null;
			Exact.DataLayer.EdlObject vDocID = null;
			Exact.DataLayer.EdlObject vResult = null;

			this.Cursor = Cursors.WaitCursor;

			// --- Set browser props
			//Chan31941, 05-Jan-2005 [13.521.061]-do not display error.
			//.DisplayErrors = True
			brwDocuments.ResetColInfo();
			brwDocuments.ColInfo = GetColumnInfo();
			brwDocuments.CheckmarkCols = "Input,Output,Notes";
			brwDocuments.InvisibleCols = "HID,BacoDiscussions.ID";
			brwDocuments.Tables = "BacoDiscussions,BacoDiscussionFixedTypes";
			brwDocuments.SelectColumnsMode = 1;
			brwDocuments.StorageKey = "CRMDocumentBrowser";
			// -- Build Select statement
			string sSQL = "SELECT [SELECT] FROM [FROM] [ORDER BY]";
			sSQL = StringsHelper.Replace(sSQL, "[SELECT]", GetSelectCol(), 1, -1, CompareMethod.Binary);
			sSQL = StringsHelper.Replace(sSQL, "[ORDER BY]", " ORDER BY BacoDiscussions.HID DESC", 1, -1, CompareMethod.Binary);

			string sWhere = "";
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(Account))
			{
				sWhere = "BacoDiscussions.cmpwwn=" + m_conn.Literal(Account);
			}
			//08.910.344: Turn this filter option off
			//BR 09.371.219: RTE on search for related trough document
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(Resource) && (((Resource) is null) ? 0 : Convert.ToString(Resource).Length) > 0)
			{
				if (!System.String.IsNullOrWhiteSpace(sWhere))
				{
					sWhere = sWhere + " AND ";
				}
				sWhere = sWhere + "BacoDiscussions.HumresID=" + m_conn.Literal(Resource);
			}
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(OrderNumber) && (((OrderNumber) is null) ? 0 : Convert.ToString(OrderNumber).Length) > 0)
			{
				if (!System.String.IsNullOrWhiteSpace(sWhere))
				{
					sWhere = sWhere + " AND ";
				}
				sWhere = sWhere + "BacoDiscussions.OrderNumber=" + m_conn.Literal(OrderNumber);
			}
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(OurRef) && (((OurRef) is null) ? 0 : Convert.ToString(OurRef).Length) > 0)
			{
				if (!System.String.IsNullOrWhiteSpace(sWhere))
				{
					sWhere = sWhere + " AND ";
				}
				sWhere = sWhere + "BacoDiscussions.OurRef=" + m_conn.Literal(OurRef);
			}
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(YourRef))
			{ //BR 15.445.947 - kohw108768 - 22 June 2005 - need to use this searching criteria when users do not fill in anything in field Your Ref

				//br34.058.775(simc178002)[29/03/2010] validation need to cater for GIU. GIU used docnumber to group lines together.
				//Pass in docnumber to YourRef in BacoDiscussions line
				if (GetFromGIU(YourRef, OurRef))
				{
					if (!System.String.IsNullOrWhiteSpace(sWhere))
					{
						sWhere = sWhere + " OR ";
					}
					if (System.String.IsNullOrWhiteSpace(YourRef))
					{
						sWhere = sWhere + "BacoDiscussions.YourRef IS NULL";
					}
					else
					{
						sWhere = sWhere + "BacoDiscussions.YourRef=" + m_conn.Literal(YourRef);
					}
				}
				else
				{
					//Original
					if (!System.String.IsNullOrWhiteSpace(sWhere))
					{
						sWhere = sWhere + " AND ";
					}
					if (System.String.IsNullOrWhiteSpace(YourRef))
					{
						sWhere = sWhere + "BacoDiscussions.YourRef IS NULL";
					}
					else
					{
						sWhere = sWhere + "BacoDiscussions.YourRef=" + m_conn.Literal(YourRef);
					}
				}

				//'        If sWhere <> "" Then sWhere = sWhere & " AND "
				//'        If YourRef = "" Then
				//'            sWhere = sWhere & "BacoDiscussions.YourRef IS NULL"
				//'        Else
				//'            sWhere = sWhere & "BacoDiscussions.YourRef=" & m_conn.Literal(YourRef)
				//'        End If
			}
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(ProjectNumber) && (((ProjectNumber) is null) ? 0 : Convert.ToString(ProjectNumber).Length) > 0)
			{
				if (!System.String.IsNullOrWhiteSpace(sWhere))
				{
					sWhere = sWhere + " AND ";
				}
				sWhere = sWhere + "BacoDiscussions.ProjectNr=" + m_conn.Literal(ProjectNumber);
			}
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(Item) && (((Item) is null) ? 0 : Convert.ToString(Item).Length) > 0)
			{
				if (!System.String.IsNullOrWhiteSpace(sWhere))
				{
					sWhere = sWhere + " AND ";
				}
				sWhere = sWhere + "BacoDiscussions.ItemCode=" + m_conn.Literal(Item);
			}
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(PaymentReference) && (((PaymentReference) is null) ? 0 : Convert.ToString(PaymentReference).Length) > 0)
			{
				if (!System.String.IsNullOrWhiteSpace(sWhere))
				{
					sWhere = sWhere + " AND ";
				}
				sWhere = sWhere + "BacoDiscussions.PaymentReference LIKE " + m_conn.Literal(PaymentReference);
			}
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(ItemSerialNumber) && (((ItemSerialNumber) is null) ? 0 : Convert.ToString(ItemSerialNumber).Length) > 0)
			{
				vResult = m_conn.Query("SELECT TOP 1 ID FROM ItemNumbers WHERE Number=?", new Exact.DataLayer.EdlObject(ItemSerialNumber), Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);
				if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult))
				{
					if (!System.String.IsNullOrWhiteSpace(sWhere))
					{
						sWhere = sWhere + " AND ";
					}
					sWhere = sWhere + "BacoDiscussions.ItemNumberID=" + m_conn.Literal(vResult.Data);
				}
			}

			bool bMatchedFields = true;
			if (System.String.IsNullOrWhiteSpace(sWhere))
			{
				bMatchedFields = false;
			}

			if (Globals.TestArray(m_astrFilterDocType))
			{
				if (!System.String.IsNullOrWhiteSpace(sWhere))
				{
					sWhere = sWhere + " AND ";
				}
				//BR48.097.773 - For Item card -> Attachment, the document type filtering should check again the output of each transaction only
				if (TableSourceInvoice == "I")
				{
					sWhere = sWhere + "((BacoDiscussions.Type IN (" + String.Join(",", m_astrFilterDocType) + ") AND Source = 'S') OR Source <> 'S')";
				}
				else
				{
					sWhere = sWhere + "BacoDiscussions.Type IN (" + String.Join(",", m_astrFilterDocType) + ")";
				}
			}

			//Not allow add existing if no matched fields
			bAllowAddExisting = false;
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultOrderNumber) && (((DefaultOrderNumber) is null) ? 0 : Convert.ToString(DefaultOrderNumber).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultOurRef) && (((DefaultOurRef) is null) ? 0 : Convert.ToString(DefaultOurRef).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultYourRef) && (((DefaultYourRef) is null) ? 0 : Convert.ToString(DefaultYourRef).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultResource) && (((DefaultResource) is null) ? 0 : Convert.ToString(DefaultResource).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultProjectNumber) && (((DefaultProjectNumber) is null) ? 0 : Convert.ToString(DefaultProjectNumber).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultItem) && (((DefaultItem) is null) ? 0 : Convert.ToString(DefaultItem).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultItemSerialNumber) && (((DefaultItemSerialNumber) is null) ? 0 : Convert.ToString(DefaultItemSerialNumber).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultPaymentReference) && (((DefaultPaymentReference) is null) ? 0 : Convert.ToString(DefaultPaymentReference).Length) > 0);
			bAllowAddExisting = bAllowAddExisting || (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(DefaultEntryKey) && (((DefaultEntryKey) is null) ? 0 : Convert.ToString(DefaultEntryKey).Length) > 0);

			//BR 09.233.667: Use AttachmentID if no matched fields or account
			string sSql2 = "";
			string sCondition = "";
			if (!bMatchedFields)
			{
				bAllowAddNew = false;

				//UPGRADE_WARNING: (1049) Use of Null/IsNull() detected. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1049
				if (!Exact.SystemLayer.Common.ConvertHelper.IsNull((Exact.SystemLayer.Common.ConvertHelper.IsEmpty(AttachmentId)) ? DBNull.Value : AttachmentId))
				{
					sWhere = "ID=" + m_conn.Literal(AttachmentId);
				}
				else
				{
					throw new Exact.Exceptions.Globe.ApplicationException2(m_Term.String(20006, "Invalid") + ": " + m_Term.String(26031, "Parameters"));
				}
			}
			else
			{
				bAllowAddNew = true;

				//UPGRADE_WARNING: (1049) Use of Null/IsNull() detected. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1049
				if (!Exact.SystemLayer.Common.ConvertHelper.IsNull((Exact.SystemLayer.Common.ConvertHelper.IsEmpty(AttachmentId)) ? DBNull.Value : AttachmentId))
				{
					//[limh109866][29 JUN 2006]br18.971.461
					if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(Account))
					{
						if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(OrderNumber) && (((OrderNumber) is null) ? 0 : Convert.ToString(OrderNumber).Length) > 0)
						{ //br30.701.256 chon32144 03/06/2009
							sWhere = sWhere + " OR (BacoDiscussions.ID=" + m_conn.Literal(AttachmentId) + " AND BacoDiscussions.OrderNumber IS NOT NULL) ";
						}
						else
						{
							sWhere = sWhere + " OR BacoDiscussions.ID=" + m_conn.Literal(AttachmentId);
						}
					}
					else
					{

						//BR 22.857.239 - Tighten the filter WHERE clause, if not unrelated documents will be shown
						//UPGRADE_WARNING: (1068) Account of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
						vIsCreditor = m_conn.Query("SELECT cicmpy.crdnr, cicmpy.debnr FROM cicmpy WHERE cicmpy.cmp_wwn ='" + Convert.ToString(Account) + "'", null, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);
						if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vIsCreditor[0]))
						{
							sWhere = sWhere + " OR BacoDiscussions.ID=" + m_conn.Literal(AttachmentId);
						}
						else
						{
							//DEBTOR for Delivery Notes, Confirmation Letters etc
							//BR 22.857.239 - Tighten the filter WHERE clause: Added gbkmut.debnr AND gbkmut.bkstnr_sub
							//br 25.116.900 - edited the query to put m_Conn.litstring for docnumber to avoid rte becoz of extra" ' "
							//BR 39.599.717 - Wrong attachment shown due to same your ref & debnr. Added oorsprong 'A' since following logic only applicable to Delivery Notes, Confirmation
							//                Exclude all entries created from Financial module.
							if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(OrderNumber))
							{
								sSql2 = "SELECT TOP 1 gbkmut.DocAttachmentID FROM gbkmut WHERE gbkmut.oorsprong NOT IN ('F','R','A') AND gbkmut.docnumber =" + m_conn.LitString(DefaultYourRef) + " AND gbkmut.DocAttachmentID <>" + m_conn.Literal(AttachmentId) + " AND gbkmut.debnr=? AND gbkmut.bkstnr_sub=?";
								//UPGRADE_WARNING: (2081) Array has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
								vDocID = m_conn.Query(sSql2, new Exact.DataLayer.EdlObject[]{vIsCreditor[1], OrderNumber}, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);
							}
							else
							{
								sSql2 = "SELECT TOP 1 gbkmut.DocAttachmentID FROM gbkmut WHERE gbkmut.oorsprong NOT IN ('X','F','R','A') AND gbkmut.docnumber = " + m_conn.LitString(DefaultYourRef) + " AND gbkmut.DocAttachmentID <>" + m_conn.Literal(AttachmentId) + " AND gbkmut.debnr=? ";
								vDocID = m_conn.Query(sSql2, vIsCreditor[1], Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);
							}

							if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vDocID))
							{
								sWhere = sWhere + " OR BacoDiscussions.ID=" + m_conn.Literal(AttachmentId);
							}
							else
							{
								//leey267218 CBR78.722.349 - Attached documents to invoice: Not all show up in the screen
								//CBR48.811.229 - Wrong delivery note is attached to the sales invoice
								sCondition = " OR BacoDiscussions.ID= (CASE BacoDiscussionFixedTypes.TypeID WHEN 12 THEN " + Environment.NewLine + 
								             "(SELECT TOP 1 orhk.DocAttachmentID FROM orhkrg orhk" + Environment.NewLine + 
								             " INNER JOIN frhkrg frhk on frhk.pakbon_nr = orhk.pakbon_nr WHERE frhk.faknr = " + m_conn.Literal(OurRef) + ")" + Environment.NewLine + 
								             " ELSE '" + ((string) vDocID) + "'" + Environment.NewLine + 
								             " END)";

								sWhere = sWhere + " OR BacoDiscussions.ID=" + m_conn.Literal(AttachmentId) + sCondition;
								//CBR48.811.229 - old code replace by above
								//sWhere = sWhere & " OR BacoDiscussions.ID=" & m_conn.Literal(AttachmentId) & " OR BacoDiscussions.ID='" & vDocID & "'"



							}
						}
					}
				}
			}

			//chan221476 (10-02-2009) [BR29.584.764] - Variable is not empty when pass in from invoice/invoice history so as to show attachment link in case group invoice
			string sGroupOrder = "";
			if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(TableSourceInvoice) && (((TableSourceInvoice) is null) ? 0 : Convert.ToString(TableSourceInvoice).Length) > 0)
			{
				//BR47.303.798 - Performance tuning : seperate group order from sub query (40% improvement)
				//If LCase(Trim(TableSourceInvoice)) = "frkrg" Then
				//    sWhere = sWhere & " OR (BacoDiscussions.OrderNumber IN ("
				//    sWhere = sWhere & " SELECT fsg.ordernr FROM frsrg fsg INNER JOIN frkrg fkg ON fkg.fakt_code=fsg.fakt_code AND fkg.volgnr5=fsg.volgnr5"
				//    sWhere = sWhere & " WHERE fkg.ordernr=" & m_conn.Literal(OrderNumber)
				//    sWhere = sWhere & " GROUP BY fsg.ordernr"
				//    sWhere = sWhere & " ) AND BacoDiscussions.OrderNumber<>" & m_conn.Literal(OrderNumber) & ")"
				//ElseIf LCase(Trim(TableSourceInvoice)) = "frhkrg" Then
				//    sWhere = sWhere & " OR (BacoDiscussions.OrderNumber IN ("
				//    sWhere = sWhere & " SELECT fsg.ordernr FROM frhsrg fsg INNER JOIN frhkrg fkg ON fkg.faknr=fsg.faknr AND fkg.dagbknr=fsg.dagbknr"
				//    sWhere = sWhere & " WHERE fkg.ordernr=" & m_conn.Literal(OrderNumber)
				//    sWhere = sWhere & " GROUP BY fsg.ordernr"
				//    sWhere = sWhere & " ) AND BacoDiscussions.OrderNumber<>" & m_conn.Literal(OrderNumber) & ")"
				//End If

				if (GetGroupInvoiceOrderNo(TableSourceInvoice, OrderNumber, ref sGroupOrder))
				{
					sWhere = sWhere + " OR (BacoDiscussions.OrderNumber IN (" + sGroupOrder + ")) ";
				}

			}
			//[limh109866][FC21.820.527]16 MAR 2007
			//BR 28.356.242 - Read Setting
			if (m_bUseTaxExemptedCert && !System.String.IsNullOrWhiteSpace(StateCode) && !System.String.IsNullOrWhiteSpace(CountryCode))
			{
				sWhere = sWhere + " AND (TaxExemptStateCertificates.Account = " + m_conn.Literal(Account) + 
				         " AND TaxExemptStateCertificates.StateCode = '" + StateCode + "'" + 
				         " AND TaxExemptStateCertificates.CountryCode = '" + CountryCode + "')";
			}

			string sFrom = StringsHelper.Replace(GetFrom(), "[WHERE]", sWhere, 1, -1, CompareMethod.Binary);
			sSQL = StringsHelper.Replace(sSQL, "[FROM]", sFrom, 1, -1, CompareMethod.Binary);

			brwDocuments.SQL = sSQL;
			brwDocuments.Refresh();

			//''    '-- Construct Query and refresh browser
			//''    Select Case GetClause()
			//''        Case eAll
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OrderNumber=? AND BacoDiscussions.OurRef=? AND BacoDiscussions.YourRef=? AND BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OrderNumber,BacoDiscussions.OurRef,BacoDiscussions.YourRef,BacoDiscussions.cmpwwn"
			//''                .Refresh OrderNumber, OurRef, YourRef, Account
			//''            End With
			//''
			//''        Case eProject
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.ProjectNr=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.ProjectNr"
			//''                .Refresh ProjectNumber
			//''            End With
			//''
			//''        Case eResource
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.HumresID=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.HumresID"
			//''                .Refresh Resource
			//''            End With
			//''
			//''        Case eItem
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.ItemCode=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.ItemCode"
			//''                .Refresh Item
			//''            End With
			//''
			//''        Case eOrderNumberAccount
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OrderNumber=? AND BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OrderNumber,BacoDiscussions.cmpwwn"
			//''                .Refresh OrderNumber, Account
			//''            End With
			//''
			//''        Case eOrderNumberYourRefAccount
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OrderNumber=? AND BacoDiscussions.YourRef=? AND BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OrderNumber, BacoDiscussions.YourRef, BacoDiscussions.cmpwwn"
			//''                .Refresh OrderNumber, YourRef, Account
			//''            End With
			//''
			//''        Case eOrderNumberOurRefAccount
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OrderNumber=? AND BacoDiscussions.OurRef=? AND BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OrderNumber, BacoDiscussions.OurRef,BacoDiscussions.cmpwwn"
			//''                .Refresh OrderNumber, OurRef, Account
			//''            End With
			//''
			//''        Case eOurRefYourRefAccount
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OurRef=? AND BacoDiscussions.YourRef=? AND BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.YourRef, BacoDiscussions.OurRef,BacoDiscussions.cmpwwn"
			//''                .Refresh YourRef, OurRef, Account
			//''            End With
			//''
			//''        Case eOurRefAccount
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OurRef=? AND BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OurRef,BacoDiscussions.cmpwwn"
			//''                .Refresh OurRef, Account
			//''            End With
			//''
			//''        Case eYourRefAccount
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.YourRef=? AND BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.YourRef,BacoDiscussions.cmpwwn"
			//''                .Refresh YourRef, Account
			//''            End With
			//''
			//''        Case eAccount
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.cmpwwn=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.cmpwwn"
			//''                .Refresh Account
			//''            End With
			//''
			//''        Case eOrderNumber
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OrderNumber=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OrderNumber"
			//''                .Refresh OrderNumber
			//''            End With
			//''
			//''        Case eOrderNumberYourRef
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OrderNumber=? AND BacoDiscussions.YourRef=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OrderNumber, BacoDiscussions.YourRef"
			//''                .Refresh OrderNumber, YourRef
			//''            End With
			//''
			//''        Case eOrderNumberOurRef
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OrderNumber=? AND BacoDiscussions.OurRef=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OrderNumber, BacoDiscussions.OurRef"
			//''                .Refresh OrderNumber, OurRef
			//''            End With
			//''
			//''        Case eOurRefYourRef
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OurRef=? AND BacoDiscussions.YourRef=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.YourRef, BacoDiscussions.OurRef"
			//''                .Refresh YourRef, OurRef
			//''            End With
			//''
			//''        Case eOurRef
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.OurRef=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.OurRef"
			//''                .Refresh OurRef
			//''            End With
			//''
			//''        Case eYourRef
			//''            sFrom = Replace(GetFrom(), "[WHERE]", "BacoDiscussions.YourRef=?")
			//''            sSQL = Replace(sSQL, "[FROM]", sFrom)
			//''
			//''            With brwDocuments
			//''                .Sql = sSQL
			//''                .Params = "BacoDiscussions.YourRef"
			//''                .Refresh YourRef
			//''            End With
			//''
			//''        Case eNone
			//''            '-- No clue what to do
			//''            Err.Raise vbObjectError + 2, App.EXEName, m_Term.String(20006, "Invalid") & ": " & m_Term.String(26031, "Parameters")
			//''    End Select

			//-- Do we have results?
			if (bLoaded && brwDocuments.NumRows > 0)
			{
				brwDocuments.SelectRow(1, true);
				brwDocuments.CurrentRow = 1;
				//>>BR: 14.556.042-Locking error during adding attachment
				ActionBar[(int) aBarButtons.CMD_EDIT].Enabled = true && bEnableButtons;
				ActionBar[(int) aBarButtons.CMD_OPEN].Enabled = true;
				ActionBar[(int) aBarButtons.CMD_NOTE].Enabled = true && bEnableButtons;
				ActionBar[(int) aBarButtons.CMD_DOWNLOAD].Enabled = true;
				if (brwDocuments.NumRows == 1)
				{
					if (bShouldReturnID)
					{
						//UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
						NewDocumentID = Convert.ToString(brwDocuments.get_value("BacoDiscussions.ID"));
					}
				}
			}
			else
			{
				ActionBar[(int) aBarButtons.CMD_EDIT].Enabled = false;
				ActionBar[(int) aBarButtons.CMD_OPEN].Enabled = false;
				ActionBar[(int) aBarButtons.CMD_NOTE].Enabled = false;
				ActionBar[(int) aBarButtons.CMD_DOWNLOAD].Enabled = false;
				//UPGRADE_WARNING: (1049) Use of Null/IsNull() detected. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1049
				if (Exact.SystemLayer.Common.ConvertHelper.IsNull((Exact.SystemLayer.Common.ConvertHelper.IsEmpty(AttachmentId)) ? DBNull.Value : AttachmentId))
				{
					bShouldReturnID = ReturnIDWhenEmpty;
				}
			}
			
			ActionBar[(int) aBarButtons.CMD_NEW].Enabled = !ReadOnly;

			//BR 09.233.667: Not allow add new if no account or matched fields pass in
			//>>BR: 14.556.042-Locking error during adding attachment
			ActionBar[(int) aBarButtons.CMD_NEW].Enabled = bAllowAddNew && !ReadOnly && bEnableButtons;
			ActionBar[(int) aBarButtons.CMD_EXISTING].Enabled = bAllowAddNew && !ReadOnly && bAllowAddExisting && bEnableButtons;

			this.Cursor = Cursors.Default;

			//Start CBR 80.967.458
			if (m_Comp.GetOpt(GlobalInterfaces.GI_Exact.Crm.DocumentBrowser.Options.OPT_CENTRAL_MASTER_DATA))
			{
				LoadObjCMDMToolsGeneral();
				if (m_bUseCentralData)
				{
					ActionBar[(int) aBarButtons.CMD_NEW].Enabled = true;
				}
			}
			//End CBR 80.967.458

		}
		//br34.058.775(simc178002)[29/03/2010]to check if faktuurnr and docnumber pass in are Group Intenal Use (GIU)
		private bool GetFromGIU(string sYourRef, string sOurRef)
		{
			Exact.DataLayer.EdlObject v = null;

			if (!System.String.IsNullOrWhiteSpace(sYourRef) && !System.String.IsNullOrWhiteSpace(sOurRef))
			{
				//UPGRADE_WARNING: (2081) Array has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
				v = m_conn.Query("SELECT ID FROM gbkmut WHERE faktuurnr=? AND docnumber=? AND transtype='B' AND transsubtype='B' AND freefield1='I'", new Exact.DataLayer.EdlObject[]{sOurRef, sYourRef}, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

				if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(v))
				{
					return false;
				}
				else
				{
					return true;
				}
			}
			else
			{
				return false;
			}

		}

		private void DisplayNotes()
		{
			//'tanj42445 - 20101125 - FC 37.043.210 - Trigger notification when update document
			Exact.SystemLayer.Interfaces.IConnectivity oESF = new Exact.Entity.Notification.Connectivity();
			m_App.ConnectObject(oESF, m_Comp, m_Term);
			//'End FC 36.946.408

			//UPGRADE_WARNING: (7008) The ProgId could not be found on computer where this application was migrated More Information: https://www.mobilize.net/vbtonet/ewis/ewi7008
			Exact.SystemLayer.Interfaces.IExtensionDlg eDlg = (Exact.SystemLayer.Interfaces.IExtensionDlg) new Exact.Win.UI.FipExtNote();
			m_App.ConnectObject(eDlg, m_Comp, m_Term);
			eDlg.Title = m_Term.String(19582, "Notes");

			Exact.DataLayer.EdlObject vntValue = m_conn.Query("SELECT Note FROM BacoDiscussions WHERE ID=?", new Exact.DataLayer.EdlObject(brwDocuments.get_value("ID")), Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);
			object vntValueOld = vntValue.Data;
			if (ReadOnly)
			{
				object tempRefParam = vntValue.Data;
				eDlg.Show(this.Handle, 1, ref tempRefParam);
				vntValue = new Exact.DataLayer.EdlObject(tempRefParam);
			}
			else
			{
				object tempRefParam2 = vntValue.Data;
				eDlg.Show(this.Handle, 0, ref tempRefParam2);
				vntValue = new Exact.DataLayer.EdlObject(tempRefParam2);
				if (vntValueOld != vntValue)
                {
                    //UPGRADE_TODO: (1069) Error handling statement (On Error Resume Next) was converted to a pattern that might have a different behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1069
                    
                    //UPGRADE_WARNING: (2081) Array has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
						m_conn.Exec("UPDATE BacoDiscussions SET Note=?,ModifiedDate=?,ModifiedBy=? WHERE ID=?", new Exact.DataLayer.EdlObject[]{vntValue, DateTime.Now, m_Comp.User.ID, new Exact.DataLayer.EdlObject(brwDocuments.get_value("ID"))});
                    //UPGRADE_WARNING: (1068) brwDocuments.Value() of type Variant is being forced to string. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
						oESF.NotifyProcessWithBCEdit("BDDocument", "ID", Convert.ToString(brwDocuments.get_value("ID")), Exact.SystemLayer.Interfaces.NotifyAction.naUpdate); //'tanj42445 - 20101125 - FC 37.043.210
                    m_conn.Commit();
                  
                }
				brwDocuments.Refresh(); //DBR : 80.088.676
			} //'tanj42445 - 20101125 - FC 37.043.210
		}

		private object DeleteTempFile()
		{
			

			if ((((m_TempFile) is null) ? 0 : Convert.ToString(m_TempFile).Length) > 0)
			{
				try
				{
					//UPGRADE_WARNING: (2081) DeleteFile has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
					File.Delete(m_TempFile);
				}
				catch
				{
				}
			}
			return null;
		}

		private void InitObserver()
		{
			//-- Set up observer
			if (m_Factory is null)
			{
                m_Factory = Exact.SystemLayer.SubjectRx.SubjectFactory.Instance;
				m_Observer = (Exact.SystemLayer.Interfaces.IObserver) brwDocuments;
				m_Subject = (Exact.SystemLayer.SubjectRx.Subject) m_Factory.CreateDatabaseSubject(m_Comp.ServerName, m_Comp.DatabaseName, "BacoDiscussions");
				m_Subject.Attach(m_Observer);
			}
		}

		private void TerminateObserver()
		{
			//-- Detach observer
			m_Subject.Detach(m_Observer);
			(m_Observer as IDisposable)?.Dispose();
			m_Observer = null;
			(m_Subject as IDisposable)?.Dispose();
			m_Subject = null;
			m_Factory = null;
		}

		//Chan31941, 12-Oct-04 [12.654.658]
		//method which prepares standard e-Synergy document to be shown including standard inserted pictures
		////modified from method DownloadInsertedImages (MDocuments.dll)
		private void DownloadInsertedImages()
		{

			int intFileHandle = 0;
			int lngStartPosition = 0;
			int lngGUIDPosition = 0;
			int lngEndPosition = 0;
			string vTempFileName = "";
			string vGUID = "";
			Exact.DataLayer.EdlObject vFilename = null;
			Exact.DataLayer.EdlObject vImage = null;
			bool bImage = false;
			Object clsFileSystem = null;
			byte[] aByte = null;

			try
			{

				//check if any images
				//UPGRADE_WARNING: (1059) Code was upgraded to use UpgradeHelpers.Helpers.StringsHelper.ByteArrayToString() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
				lngStartPosition = (StringsHelper.ByteArrayToString(m_DocumentBody).IndexOf("BacoDiscussionsBlob.asp?") + 1);

				//start getting images (if found any)
				while (lngStartPosition > 0)
				{

					//find GUID position
					//UPGRADE_WARNING: (2065) Long method Strings.InStr has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2065
					//UPGRADE_WARNING: (1059) Code was upgraded to use UpgradeHelpers.Helpers.StringsHelper.ByteArrayToString() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
					lngGUIDPosition = StringsHelper.ByteArrayToString(m_DocumentBody).IndexOf("{");

					//if ok then find end position
					if (lngGUIDPosition > 0)
					{

						lngGUIDPosition++;
						//UPGRADE_WARNING: (2065) Long method Strings.InStr has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2065
						//UPGRADE_WARNING: (1059) Code was upgraded to use UpgradeHelpers.Helpers.StringsHelper.ByteArrayToString() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
						lngEndPosition = StringsHelper.ByteArrayToString(m_DocumentBody).IndexOf("}");

						//if ok then continue with action
						if (lngEndPosition > 0)
						{

							//extract GUID first
							//UPGRADE_WARNING: (1059) Code was upgraded to use UpgradeHelpers.Helpers.StringsHelper.ByteArrayToString() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
							vGUID = StringsHelper.ByteArrayToString(m_DocumentBody).Substring(lngGUIDPosition - 1, Math.Min(lngEndPosition - lngGUIDPosition, StringsHelper.ByteArrayToString(m_DocumentBody).Length - (lngGUIDPosition - 1)));

							//get picture from database
							vImage = m_conn.Query("SELECT Picture FROM BacoDiscussionPictures WHERE ID = ?", vGUID, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

							//get image type from database
							vFilename = m_conn.Query("SELECT Filename FROM BacoDiscussionPictures WHERE ID = ?", vGUID, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);

							bImage = true;
							if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vImage) || Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vFilename))
							{
								bImage = false;
							}

							if (bImage)
							{
								//generate tempfile name
								clsFileSystem = new Object();
								vTempFileName = Path.GetFileNameWithoutExtension(Path.GetFileName(Path.GetTempFileName())) + "." + Path.GetExtension((string) vFilename).Substring(1);
								vTempFileName = (new DirectoryInfo(Path.GetTempPath())).FullName + "\\" + vTempFileName;

								//save image to temporary file
								aByte = (byte[]) ArraysHelper.DeepCopy(vImage);
								intFileHandle = FileSystem.FreeFile();
								FileSystem.FileOpen(intFileHandle, vTempFileName, OpenMode.Binary, OpenAccess.Default, OpenShare.Default, -1);
								//UPGRADE_WARNING: (2080) Put was upgraded to FilePutObject and has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2080
								FileSystem.FilePutObject(intFileHandle, aByte, 0);
								FileSystem.FileClose(intFileHandle);

								//replace hyperlink in original document
								//UPGRADE_WARNING: (1059) Code was upgraded to use UpgradeHelpers.Helpers.StringsHelper.ByteArrayToString() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
								//UPGRADE_WARNING: (1059) Code was upgraded to use System.Text.UnicodeEncoding.Unicode.GetBytes() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
								m_DocumentBody = UnicodeEncoding.Unicode.GetBytes(StringsHelper.Replace(StringsHelper.ByteArrayToString(m_DocumentBody), StringsHelper.ByteArrayToString(m_DocumentBody).Substring(lngStartPosition - 1, Math.Min(lngEndPosition - lngStartPosition + 1, StringsHelper.ByteArrayToString(m_DocumentBody).Length - (lngStartPosition - 1))), "\"" + vTempFileName + "\"", 1, -1, CompareMethod.Binary));

								//go for next image
								//UPGRADE_WARNING: (1059) Code was upgraded to use UpgradeHelpers.Helpers.StringsHelper.ByteArrayToString() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
								lngStartPosition = (StringsHelper.ByteArrayToString(m_DocumentBody).IndexOf("BacoDiscussionsBlob.asp?") + 1);
							}
							else
							{
								//UPGRADE_WARNING: (2065) Long method Strings.InStr has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2065
								//UPGRADE_WARNING: (1059) Code was upgraded to use UpgradeHelpers.Helpers.StringsHelper.ByteArrayToString() which may not have the same behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1059
								lngStartPosition = StringsHelper.ByteArrayToString(m_DocumentBody).IndexOf("BacoDiscussionsBlob.asp?");
							}
						}
						else
						{
							lngStartPosition = 0;
						}
					}
					else
					{
						lngStartPosition = 0;
					}
				}
			}
			catch (System.Exception catchedException)
			{
				Exact.Exceptions.Globe.BaseGlobeException excep = Exact.Exceptions.Utils.ExceptionBuilder.Build(catchedException);

				//PBI 112801: Applocale Set application title
				//UPGRADE_WARNING: (2081) Err.Number has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
				m_App.Message(this.Handle, m_Term.String(8335, "Unknown error") + ": (" + ") - " + excep.Message, m_oTitle.GetTitle(this));
			}

		}

		//Chan31941, [27-Jul-2006] [19.759.784]
		private bool IsDocumentExists()
		{

			bool result = false;
			Exact.DataLayer.EdlObject vResult = m_conn.Query("SELECT 1 FROM BacoDiscussions WHERE ID =?", new Exact.DataLayer.EdlObject(brwDocuments.get_value("BacoDiscussions.ID")), Exact.DataLayer.EdlQueryValueOptions.edlNoNulls);
			if (Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vResult))
			{
				result = true;
			}

			string sMessage = m_App.get_Term().String(11337, "Not found") + ": " + m_App.get_Term().String(7226, "Document") + Environment.NewLine + 
			                  m_App.get_Term().String(13449, "The data on screen has been deleted by another user.");

			//Display message
			if (result)
			{
				//PBI 112801: Applocale Set application title
				m_App.Message(this.Handle, sMessage, m_oTitle.GetTitle(this));
				brwDocuments.Refresh();
			}

			return result;
		}

		private void ReadSettings()
		{

			iSet = (Exact.SystemLayer.Interfaces.ISettings) m_App.DefaultCompany;
			//UPGRADE_WARNING: (1068) iSet.Setting() of type Variant is being forced to bool. More Information: https://www.mobilize.net/vbtonet/ewis/ewi1068
			m_bUseTaxExemptedCert = Convert.ToBoolean(iSet.Setting("eaccount\\UseTaxExemptedCert,b", false));
			iSet = null;
		}

		//Start CBR 80.967.458
		private void LoadObjCMDMToolsGeneral()
		{
			if (m_oCMDMTools is null)
			{
				m_oCMDMTools = GlobalInterfaces.Factory.CreateInstance<GlobalInterfaces.GI_Exact.Cmdm.Tools.IclsGeneral>();

				m_App.ConnectObject(m_oCMDMTools, m_Comp, m_Term);
				m_oCMDMTools.Topic = gsCMDMTopicAccount;
			}
			m_bUseCentralData = m_oCMDMTools.UseCentralMasterData;
			m_oCMDMTools = null;
		}
		//End CBR 80.967.458

		//BR47.303.798 - Performance tuning : seperate group order from sub query (40% improvement)
		private bool GetGroupInvoiceOrderNo(string sTable, string sOrderNr, ref string sGroupOrder)
		{
			bool result = false;
			string sSQL = "";
			Exact.DataLayer.EdlObject vData = null;

			try
			{
				if (TableSourceInvoice.Trim().ToLower() == "frkrg")
				{
					sSQL = "SELECT DISTINCT fsg.ordernr FROM frsrg fsg INNER JOIN frkrg fkg ON fkg.fakt_code=fsg.fakt_code AND fkg.volgnr5=fsg.volgnr5" + Environment.NewLine;
					sSQL = sSQL + " WHERE fkg.ordernr= ? AND fsg.ordernr <> ? AND fsg.ordernr IS NOT NULL";

				}
				else if (TableSourceInvoice.Trim().ToLower() == "frhkrg")
				{ 
					sSQL = "SELECT DISTINCT fsg.ordernr FROM frhsrg fsg INNER JOIN frhkrg fkg ON fkg.faknr=fsg.faknr AND fkg.dagbknr=fsg.dagbknr" + Environment.NewLine;
					sSQL = sSQL + " WHERE fkg.ordernr= ? AND fsg.ordernr <> ? AND fsg.ordernr IS NOT NULL";
				}

				//UPGRADE_WARNING: (2081) Array has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2081
				vData = m_conn.Query(sSQL, new Exact.DataLayer.EdlObject[]{sOrderNr, sOrderNr}, Exact.DataLayer.EdlQueryValueOptions.edlNoNulls | Exact.DataLayer.EdlQueryValueOptions.edlForce2dim);

				if (!Exact.SystemLayer.Common.ConvertHelper.IsEmpty(vData))
				{
					int tempForEndVar = vData.GetUpperBound(0) + 1;
					for (int l = vData.GetLowerBound(0) + 1; l <= tempForEndVar; l++)
					{
						if ((((((string) vData[l - 1]).Trim()) is null) ? 0 : Convert.ToString(((string) vData[l - 1]).Trim()).Length) > 0)
						{
							if ((((sGroupOrder) is null) ? 0 : Convert.ToString(sGroupOrder).Length) > 0)
							{
								sGroupOrder = sGroupOrder + ",";
							}
							sGroupOrder = sGroupOrder + m_conn.LitString((string) vData[l - 1]);
						}
					}
				}

				if ((((sGroupOrder) is null) ? 0 : Convert.ToString(sGroupOrder).Trim().Length) > 0)
				{
					result = true;
				}
			}
			catch
			{

				result = false;
			}

			return result;
		}
	}
}