Exemplo n.º 1
0
        private static bool IsDBAlive()
        {
            Event clsEvent = new Event();

            try
            {
                clsEvent.AddEvent("Checking connections to server.");
                if (IPAddress.IsOpen(AceSoft.RetailPlus.DBConnection.ServerIP(), DBConnection.DBPort()) == false)
                {
                    clsEvent.AddEvent("Cannot connect to server please check.");
                    return(false);
                }

                clsEvent.AddEvent("Checking connections to database.");

                Data.Database clsDatabase = new Data.Database();
                bool          boIsDBAlive = clsDatabase.IsAlive();
                clsEvent.AddEventLn("Done! Connected to " + clsDatabase.Connection.ConnectionString, false);

                clsEvent.AddEventLn("Updating version to " + Application.ProductVersion, true);
                Data.Terminal clsTerminal = new Data.Terminal(clsDatabase.Connection, clsDatabase.Transaction);
                clsTerminal.UpdateFEVersion(Constants.TerminalBranchID, CompanyDetails.TerminalNo, Application.ProductVersion);

                clsDatabase.CommitAndDispose();

                return(boIsDBAlive);
            }
            catch (Exception ex)
            {
                clsEvent.AddErrorEventLn(ex);
                return(false);
            }
        }
Exemplo n.º 2
0
        private static bool IsDateLastInitializationOK()
        {
            Event clsEvent = new Event();

            try
            {
                clsEvent.AddEvent("Checking last initialization date");

                Data.Database clsDatabase           = new Data.Database();
                DateTime      dtDateLastInitialized = clsDatabase.DateLastInitialized(Constants.TerminalBranchID, CompanyDetails.TerminalNo);
                clsDatabase.CommitAndDispose();

                bool boReturn = false;

                if (DateTime.Now > dtDateLastInitialized)
                {
                    boReturn = true;
                    clsEvent.AddEventLn("OK: Last initialization is smaller than system date. DateLastInitialized=" + dtDateLastInitialized.ToString("yyyy-MM-dd hh:mm") + " SystemDate=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm"));
                }
                else
                {
                    clsEvent.AddEventLn("Error: Last initialization is greater than system date. DateLastInitialized=" + dtDateLastInitialized.ToString("yyyy-MM-dd hh:mm") + " SystemDate=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm"));
                }

                return(boReturn);
            }
            catch (Exception ex)
            {
                clsEvent.AddErrorEventLn(ex);
                return(false);
            }
        }
Exemplo n.º 3
0
        private void SaveToDB()
        {
            AceSoft.RetailPlus.Client.MasterDB clsMasterConnection;
			Data.Products clsProducts;
            Data.Inventory clsInventory;
            Data.Database clsDatabase;

            Data.ERPConfig clsERPConfig = new Data.ERPConfig();
            Data.ERPConfigDetails clsERPConfigDetails = clsERPConfig.Details();
            string strReferenceNo = Constants.CLOSE_INVENTORY_CODE + CompanyDetails.BECompanyCode + DateTime.Now.Year.ToString() + clsERPConfig.get_LastClosingNo();
            clsERPConfig.CommitAndDispose();

            Data.ProductDetails clsProductDetails;
            Data.InventoryDetails clsInventoryDetails;

            DateTime dtePostingDate = DateTime.Now;

            if (!Directory.Exists("invfiles/backups/")) Directory.CreateDirectory("invfiles/backups/");
            if (File.Exists("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + ".inv"))
            {
                if (MessageBox.Show("You have already loaded the inventory for this branch today. Please verify the file you are loading. Would you like to continue?", "RetailPlus", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    bgwSavetoDB.ReportProgress(100);
                    return;
                }
            }
            else
            {
                System.IO.File.Copy("invfiles/" + mclsBranchDetails.BranchCode + ".inv", "invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + ".inv");
            }

            InvExLog clsInvExLog = new InvExLog();
            clsInvExLog.BranchDetails = mclsBranchDetails;
            if (File.Exists("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv"))
            {
                System.IO.File.Copy("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv", "invfiles/backups/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv" + "_" + DateTime.Now.ToString("yyyyddMMhhmmss"));
                System.IO.File.Delete("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv");
            }

            InvLoadedLog clsInvLoadedLog = new InvLoadedLog();
            clsInvLoadedLog.BranchDetails = mclsBranchDetails;
            if (File.Exists("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv"))
            {
                System.IO.File.Copy("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv", "invfiles/backups/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv" + "_" + DateTime.Now.ToString("yyyyddMMhhmmss"));
                System.IO.File.Delete("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv");
            }

            decimal iCtr = 1, iRows = Decimal.Parse(mdtItems.Rows.Count.ToString());
            foreach (System.Data.DataRow dr in mdtItems.Rows)
			{
                string strBarCode = dr["BarCode"].ToString();
                decimal decQuantity = decimal.Parse(dr["Quantity"].ToString());

                string strUnit = dr["Unit"].ToString();
                string strDescription = dr["Description"].ToString();

                mstStatus = "[" + iCtr.ToString() + "/" + iRows + "]Saving " + strBarCode + strDescription;
                bgwSavetoDB.ReportProgress(int.Parse(Math.Ceiling(iCtr / iRows * 100).ToString()));
                iCtr++;

        back:
                clsMasterConnection = new AceSoft.RetailPlus.Client.MasterDB();
                try
                {
                    clsMasterConnection.GetConnection();

                    clsProducts = new Data.Products(clsMasterConnection.Connection, clsMasterConnection.Transaction);
                    clsInventory = new Data.Inventory(clsMasterConnection.Connection, clsMasterConnection.Transaction);

                    clsProductDetails = clsProducts.Details(mclsBranchDetails.BranchID, strBarCode);
                    if (clsProductDetails.ProductID == 0)
                    {
                        clsInvExLog.AddItem(strBarCode, decQuantity, strUnit, strDescription);
                    }
                    else
                    {
                        clsInvLoadedLog.AddItem(strBarCode, decQuantity, strUnit, strDescription);

                        /*******************************************
                        * Add to Inventory
                        * ****************************************/
                        //clsProduct.AddQuantity(lngProductID, decQuantity);
                        //if (lngVariationMatrixID != 0) { clsProductVariationsMatrix.AddQuantity(lngVariationMatrixID, decQuantity); }
                        // July 26, 2011: change the above codes to the following
                        clsProducts.AddQuantity(mclsBranchDetails.BranchID, clsProductDetails.ProductID, 0, decQuantity, Data.Products.getPRODUCT_INVENTORY_MOVEMENT_VALUE(Data.PRODUCT_INVENTORY_MOVEMENT.ADD_INVENTORY_BY_BRANCH) + " /" + clsProductDetails.BaseUnitCode, DateTime.Now, strReferenceNo, "System");


                        //-- STEP 1: Insert to tblInventory for reporting purposes
                        /*******************************************
                            * Add to Inventory Analysis
                            * ****************************************/
                        clsInventoryDetails = new Data.InventoryDetails();
                        clsInventoryDetails.BranchID = mclsBranchDetails.BranchID;
                        clsInventoryDetails.PostingDateFrom = clsERPConfigDetails.PostingDateFrom;
                        clsInventoryDetails.PostingDateTo = clsERPConfigDetails.PostingDateTo;
                        clsInventoryDetails.PostingDate = dtePostingDate;
                        clsInventoryDetails.ReferenceNo = strReferenceNo;
                        clsInventoryDetails.ContactID = clsProductDetails.SupplierID;
                        clsInventoryDetails.ContactCode = clsProductDetails.SupplierCode;
                        clsInventoryDetails.ProductID = clsProductDetails.ProductID;
                        clsInventoryDetails.ProductCode = clsProductDetails.ProductCode;
                        clsInventoryDetails.VariationMatrixID = 0;
                        clsInventoryDetails.MatrixDescription = "";
                        clsInventoryDetails.ClosingQuantity = clsProductDetails.Quantity;
                        clsInventoryDetails.ClosingActualQuantity = decQuantity + clsProductDetails.Quantity;
                        clsInventoryDetails.ClosingCost = (decQuantity + clsProductDetails.Quantity) * clsProductDetails.PurchasePrice;
                        clsInventoryDetails.ClosingVAT = (decQuantity + clsProductDetails.Quantity) * clsProductDetails.PurchasePrice * decimal.Parse("0.12");	// Purchase Cost with VAT
                        clsInventoryDetails.PurchasePrice = clsProductDetails.PurchasePrice;

                        clsInventory.Insert(clsInventoryDetails);
                    }
                    
                    clsMasterConnection.CommitAndDispose();
                }
                catch (Exception ex) 
                {
                    if (ex.Message.Contains("Deadlock found when trying to get lock; try restarting transaction"))
                    { try { clsMasterConnection.ThrowException(ex); } catch { } clsDatabase = new Data.Database(); clsDatabase.FlushHosts(); clsDatabase.CommitAndDispose(); goto back; }
                    else if (ex.InnerException.Message.Contains("Deadlock found when trying to get lock; try restarting transaction"))
                    { try { clsMasterConnection.ThrowException(ex); } catch { } clsDatabase = new Data.Database(); clsDatabase.FlushHosts(); clsDatabase.CommitAndDispose(); goto back; }
                }
			}
            
            bgwSavetoDB.ReportProgress(100);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            WriteProcessToMonitor("Starting RetailPlus Credit Biller tool...");

            // check if it's already running
            if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
            {
                WriteProcessToMonitor("   already running. Press any key to continue...");
                Console.ReadLine();
                return;
            }

            WriteProcessToMonitor("   ok");
        back:

            try
            {
                WriteProcessToMonitor("Checking process start time...");
                DateTime _CreditBillerProcessStartTime = DateTime.TryParse(DateTime.Now.ToString("yyyy-MM-dd") + " " + System.Configuration.ConfigurationManager.AppSettings["ProcessStartTime"].ToString(), out _CreditBillerProcessStartTime) ? _CreditBillerProcessStartTime : DateTime.MinValue;
                if (DateTime.Now < _CreditBillerProcessStartTime)
                {
                    WriteProcessToMonitor("   cannot process will process next day-starttime:" + _CreditBillerProcessStartTime.ToString("hh:mm tt"));
                    Wait();
                    goto back;
                }

                WriteProcessToMonitor("Checking process end time...");
                DateTime _CreditBillerProcessEndTime = DateTime.TryParse(DateTime.Now.ToString("yyyy-MM-dd") + " " + System.Configuration.ConfigurationManager.AppSettings["ProcessEndTime"].ToString(), out _CreditBillerProcessEndTime) ? _CreditBillerProcessEndTime : DateTime.MinValue;
                if (DateTime.Now > _CreditBillerProcessEndTime)
                {
                    WriteProcessToMonitor("   cannot process will process next day-endtime:" + _CreditBillerProcessEndTime.ToString("hh:mm tt"));
                    Wait();
                    goto back;
                }

                WriteProcessToMonitor("Checking connections to server.");
                if (IPAddress.IsOpen(AceSoft.RetailPlus.DBConnection.ServerIP(), DBConnection.DBPort()) == false)
                {
                    WriteProcessToMonitor("   cannot connect to server please check.");
                    Wait();
                    goto exit;
                }
                WriteProcessToMonitor("   ok");
                WriteProcessToMonitor("Checking connections to database.");
                Data.Database clsDatabase = new Data.Database();
                mConnection = clsDatabase.Connection; mTransaction = clsDatabase.Transaction;

                try
                {
                    bool boIsDBAlive = clsDatabase.IsAlive();
                    WriteProcessToMonitor("   connected to '" + clsDatabase.Connection.ConnectionString.Split(';')[0].ToString().Replace("Data Source=", "") + "'");
                }
                catch (Exception ex)
                {
                    WriteProcessToMonitor("   ERROR connecting to database. Exception: " + ex.ToString());
                    clsDatabase.CommitAndDispose();
                    return;
                }
                
                WriteProcessToMonitor("Checking credit billings with guarantor to process...");
                WriteProcessToMonitor("   done checking...");

                Data.CardType clsCardType = new Data.CardType(mConnection, mTransaction);
                mConnection = clsCardType.Connection; mTransaction = clsCardType.Transaction;
                System.Data.DataTable dt = clsCardType.ListAsDataTable(new Data.CardTypeDetails() { CreditCardType = CreditCardTypes.Internal, CheckGuarantor = true, WithGuarantor = true });
                clsCardType.CommitAndDispose();
                clsDatabase.CommitAndDispose();

                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    WriteProcessToMonitor("Processing " + dr["CardTypeName"].ToString() + "...");
                    ProcessCreditBillWG(dr["CardTypeName"].ToString());
                }

                WriteProcessToMonitor("Checking credit billings to process...");
                WriteProcessToMonitor("   done checking...");


                // processing of Internal WithOutGuarantor
                clsCardType = new Data.CardType(mConnection, mTransaction);
                mConnection = clsCardType.Connection; mTransaction = clsCardType.Transaction;
                dt = clsCardType.ListAsDataTable(new Data.CardTypeDetails() { CreditCardType = CreditCardTypes.Internal, CheckGuarantor = true, WithGuarantor = false });
                clsCardType.CommitAndDispose();
                clsDatabase.CommitAndDispose();

                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    WriteProcessToMonitor("Processing " + dr["CardTypeName"].ToString() + "...");
                    ProcessCreditBill(dr["CardTypeName"].ToString());
                }

                // redo this checking before processing creditbill with Guarantor
                WriteProcessToMonitor("Checking process start time...");
                if (DateTime.Now < _CreditBillerProcessStartTime)
                {
                    WriteProcessToMonitor("   cannot process will process next day-starttime:" + _CreditBillerProcessStartTime.ToString("hh:mm tt"));
                    goto exit;
                }

                WriteProcessToMonitor("Checking process end time...");
                if (DateTime.Now > _CreditBillerProcessEndTime)
                {
                    WriteProcessToMonitor("   cannot process will process next day-endtime:" + _CreditBillerProcessEndTime.ToString("hh:mm tt"));
                    goto exit;
                }
                // end-redo this checking before processing creditbill with Guarantor

                Wait();
                goto back;
            exit:
                WriteProcessToMonitor("Sytem terminated.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                WriteProcessToMonitor("PLEASE CALL RETAILPLUS IMMEDIATELY... error:" + ex.ToString());
                goto back;
            }
        }
Exemplo n.º 5
0
		private bool IsDateLastInitializationOK(bool ShowMessageBox = true)
		{
			try
			{
				clsEvent.AddEvent("Checking last initialization date");

				Data.Database clsDatabase = new Data.Database(mConnection, mTransaction);
                mConnection = clsDatabase.Connection; mTransaction = clsDatabase.Transaction;

				DateTime dtDateLastInitialized = clsDatabase.DateLastInitialized(mclsTerminalDetails.BranchDetails.BranchID, mclsTerminalDetails.TerminalNo);

				bool boRetValue = false;

				if (DateTime.Now > dtDateLastInitialized)
				{
					clsEvent.AddEventLn("OK: Last initialization is smaller than system date. DateLastInitialized=" + dtDateLastInitialized.ToString("yyyy-MM-dd hh:mm") + " SystemDate=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm"));
				}
				else
				{
					clsEvent.AddEventLn("Error: Last initialization is greater than system date. DateLastInitialized=" + dtDateLastInitialized.ToString("yyyy-MM-dd hh:mm") + " SystemDate=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm"));
					clsDatabase.CommitAndDispose();
					MessageBox.Show("FATAL ERROR Level 2.!!! System date is behind ZREAD last initialization date. Please adjust SYSTEM DATE!!!", "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return boRetValue;
				}

				Data.TerminalReport clsTerminalReport = new Data.TerminalReport(mConnection, mTransaction);
                mConnection = clsTerminalReport.Connection; mTransaction = clsTerminalReport.Transaction;

				DateTime dteTransactionDate = Convert.ToDateTime(lblTransDate.Text);

				DateTime dteStartCutOffTime = Convert.ToDateTime(Convert.ToDateTime(lblTransDate.Text).ToString("yyyy-MM-dd") + " " + mclsTerminalDetails.StartCutOffTime);
				DateTime dteEndCutOffTime = Convert.ToDateTime(Convert.ToDateTime(lblTransDate.Text).ToString("yyyy-MM-dd") + " " + mclsTerminalDetails.EndCutOffTime);

				// if StartCutOffTime is greater than EndCutOffTime
				// this means that EndCutOffTime is in the morning.
				// Add 1 more day.
				if (dteStartCutOffTime >= dteEndCutOffTime)
					dteEndCutOffTime = dteEndCutOffTime.AddDays(1);

				DateTime dteAllowedStartDateTime; DateTime dteAllowedEndDateTime;
				if (dteTransactionDate < dteEndCutOffTime)
				{
					dteAllowedStartDateTime = Convert.ToDateTime(Convert.ToDateTime(lblTransDate.Text).ToString("yyyy-MM-dd") + " " + mclsTerminalDetails.EndCutOffTime).AddDays(-1).AddMilliseconds(1);
					dteAllowedEndDateTime = Convert.ToDateTime(Convert.ToDateTime(lblTransDate.Text).ToString("yyyy-MM-dd") + " " + mclsTerminalDetails.StartCutOffTime);
				}
				else
				{
					dteAllowedStartDateTime = Convert.ToDateTime(Convert.ToDateTime(lblTransDate.Text).ToString("yyyy-MM-dd") + " " + mclsTerminalDetails.EndCutOffTime).AddMilliseconds(1);
					dteAllowedEndDateTime = Convert.ToDateTime(Convert.ToDateTime(lblTransDate.Text).ToString("yyyy-MM-dd") + " " + mclsTerminalDetails.StartCutOffTime).AddDays(1);
				}
				if (dteTransactionDate < dteAllowedEndDateTime)
				{
					dteStartCutOffTime = dteStartCutOffTime.AddDays(1);
					dteEndCutOffTime = dteEndCutOffTime.AddDays(1);
				}

				DateTime dtePreviousStartCutOffTime = dteStartCutOffTime.AddDays(-1);
				DateTime dtePreviousEndCutOffTime = dteEndCutOffTime.AddDays(-1);
				DateTime dtePreviousAllowedStartDateTime = dteAllowedStartDateTime.AddDays(-1);
				DateTime dtePreviousAllowedEndDateTime = dteAllowedEndDateTime.AddDays(-1);

                DateTime dteMAXDateLastInitialized = clsTerminalReport.MAXDateLastInitialized(mclsTerminalDetails.BranchDetails.BranchID, mclsTerminalDetails.TerminalNo, Constants.C_DATE_MIN_VALUE);

				clsEvent.AddEventLn("Checking if MAXDateLastInitialized: " + dteMAXDateLastInitialized.ToString("yyyy-MM-dd HH:mm") + " is already initialized.", true);
				if (dteMAXDateLastInitialized >= dteAllowedStartDateTime && dteMAXDateLastInitialized <= dteAllowedEndDateTime)
				{
					clsDatabase.CommitAndDispose();
					clsEvent.AddEventLn("Transaction is not allowed, ZRead is already initialized for this date.", true);
					MessageBox.Show("Sorry initialization is not permitted this time, ZRead is already initialized for this date.", "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Information);
					txtBarCode.Text = "";
					return boRetValue;
				}
				clsEvent.AddEventLn("OK. MAXDateLastInitialized: " + dteMAXDateLastInitialized.ToString("yyyy-MM-dd HH:mm") + " is for previous zreading.", true);

				if (dteMAXDateLastInitialized < dteAllowedStartDateTime)
				{
					if (dteMAXDateLastInitialized >= dtePreviousAllowedStartDateTime && dteMAXDateLastInitialized <= dtePreviousEndCutOffTime)
					{
						clsEvent.AddEventLn("OK: AllowedStartDateTime [" + dteAllowedStartDateTime.ToString("yyyy-MM-dd HH:mm:ss") + "] is now less than MAXDateLastInitialized [" + dteMAXDateLastInitialized.ToString("yyyy-MM-dd HH:mm:ss") + "].", true);
					}
					else if(mclsTerminalDetails.CheckCutOffTime == true)
					{
						clsEvent.AddEventLn("Transaction is not allowed, transaction date is 2-Days delayed. Please restart FE.", true);
						MessageBox.Show("Transaction is not allowed, transaction date is 2Days delayed. Please restart FE." +
							Environment.NewLine + "Sorry selling is not permitted this time, Please consult for the Selling time.", "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Information);
						txtBarCode.Text = "";
						return false;
					}
				}
				if (dteMAXDateLastInitialized > dteTransactionDate)
				{
					clsDatabase.CommitAndDispose();
					clsEvent.AddEventLn("Transaction is not allowed, transaction date is delayed. Please restart FE.", true);

                    // 22Jun2015 : ShowMessageBox = false if its from ZRead
                    if (ShowMessageBox) MessageBox.Show("Transaction is not allowed, transaction date is delayed. Please restart FE.", "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Information);

					txtBarCode.Text = "";
					return boRetValue;
				}
				clsEvent.AddEventLn("OK to initialize...", true);
                clsDatabase.CommitAndDispose();

				boRetValue = true;

				return boRetValue;
			}
			catch (Exception ex)
			{
				InsertErrorLogToFile(ex);
				return false;
			}
		}
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            try
            {
                WriteProcessToMonitor("Starting RetailPlus monitoring tool...");

                // check if it's already running
                if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
                {
                    WriteProcessToMonitor("   already running. not ok");
                    return;
                }

                WriteProcessToMonitor("   ok");

                Data.Database clsDatabase = new Data.Database();
            back:
                WriteProcessToMonitor("Checking connections to server.");
                if (IPAddress.IsOpen(AceSoft.RetailPlus.DBConnection.ServerIP(), DBConnection.DBPort()) == false)
                {
                    WriteProcessToMonitor("   cannot connect to server please check.");
                    goto exit;
                }
                WriteProcessToMonitor("   ok");
                WriteProcessToMonitor("Checking connections to database.");
                
                clsDatabase.GetConnection(username: "******", password: "******");
                try
                {
                    bool boIsDBAlive = clsDatabase.IsAlive();
                    WriteProcessToMonitor("   connected to '" + clsDatabase.Connection.ConnectionString.Split(';')[0].ToString().Replace("Data Source=", "") + "'");
                }
                catch (Exception ex)
                {
                    WriteProcessToMonitor("   ERROR connecting to database. Exception: " + ex.ToString());
                }

                #region Timed-Out Process
                WriteProcessToMonitor("Checking timed-out process.");
                System.Data.DataTable dtProcessList = clsDatabase.getProcessList();
                foreach (DataRow dr in dtProcessList.Rows)
                {
                    int iID = int.Parse(dr["ID"].ToString());
                    string strHost = dr["Host"].ToString();
                    string strDB = dr["db"].ToString();
                    int iTime = int.Parse(dr["Time"].ToString());
                    string strInfo = dr["Info"].ToString();
                    if (strInfo.ToUpper() != "SHOW PROCESSLIST" || strDB == "pos")
                    {
                        WriteProcessToMonitor("      id:" + iID.ToString() + "  host:" + strHost + "  Time:" + iTime.ToString() + "  Info:" + strInfo);
                        if (iTime > Constants.C_DEFAULT_MYSQL_PROCESS_TIMEOUT && strDB == "pos")
                        {
                            WriteProcessToMonitor("          status not ok... killing process id: " + iID.ToString());
                            clsDatabase.killProcess(iID);
                            WriteProcessToMonitor("      done.");
                        }
                        else if (iTime > 16 && string.IsNullOrEmpty(strInfo))
                        {
                            WriteProcessToMonitor("          status idle... killing process id: " + iID.ToString());
                            clsDatabase.killProcess(iID);
                            WriteProcessToMonitor("      done.");
                        }
                        else if (strInfo.Contains("INSERT INTO tblTransactions") && iTime >= 8)
                        {
                            WriteProcessToMonitor("          status not ok...  flushing table tblTransactions...process id: " + iID.ToString());
                            clsDatabase.FlushTable("tblTransactions");
                            WriteProcessToMonitor("      done.");
                        }
                        else if (strInfo.Contains("UPDATE tblTerminalReport") && iTime >= 8)
                        {
                            WriteProcessToMonitor("          status not ok... flushing table tblTerminalReport...process id: " + iID.ToString());
                            clsDatabase.FlushTable("tblTerminalReport");
                            WriteProcessToMonitor("      done.");
                        }
                        else { WriteProcessToMonitor("          status ok"); }
                    }
                }
                clsDatabase.CommitAndDispose();

                // audit
                //clsDatabase = new Data.Database(clsDatabase.Connection, clsDatabase.Transaction);
                clsDatabase.GetConnection(username: "******", password: "******");
                try
                {
                    bool boIsDBAlive = clsDatabase.IsAlive();
                    WriteProcessToMonitor("   connected to '" + clsDatabase.Connection.ConnectionString.Split(';')[0].ToString().Replace("Data Source=", "") + "'");
                }
                catch (Exception ex)
                {
                    WriteProcessToMonitor("   ERROR connecting to database. Exception: " + ex.ToString());
                }
                WriteProcessToMonitor("Checking Audit timed-out process.");
                dtProcessList = clsDatabase.getProcessList();
                foreach (DataRow dr in dtProcessList.Rows)
                {
                    int iID = int.Parse(dr["ID"].ToString());
                    string strHost = dr["Host"].ToString();
                    string strDB = dr["db"].ToString();
                    int iTime = int.Parse(dr["Time"].ToString());
                    string strInfo = dr["Info"].ToString();
                    if (strInfo.ToUpper() != "SHOW PROCESSLIST" || strDB == "pos")
                    {
                        WriteProcessToMonitor("      audit id:" + iID.ToString() + "  host:" + strHost + "  Time:" + iTime.ToString() + "  Info:" + strInfo);
                        if (iTime > Constants.C_DEFAULT_MYSQL_PROCESS_TIMEOUT && strDB == "pos")
                        {
                            WriteProcessToMonitor("          status not ok... killing process id: " + iID.ToString());
                            clsDatabase.killProcess(iID);
                            WriteProcessToMonitor("      done.");
                        }
                        else { WriteProcessToMonitor("          status ok"); }
                    }
                }
                clsDatabase.CommitAndDispose();
                WriteProcessToMonitor("   done checking...");
                #endregion

                string strSyncFunction = ""; 
                try { strSyncFunction = System.Configuration.ConfigurationManager.AppSettings["SyncFunction"].ToString(); }
                catch { }

                if (strSyncFunction.ToLower().Trim() == "export")
                {
                    #region Export Products
                
                    //clsDatabase = new Data.Database(clsDatabase.Connection, clsDatabase.Transaction);
                    clsDatabase.GetConnection(username: "******", password: "******");

                    Data.SysConfig clsSysConfig = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                    DateTime dteLastSyncDateTime = clsSysConfig.get_ProdLastSyncDateTime();
                    DateTime dteLastSyncDateTimeTo = dteLastSyncDateTime.AddMinutes(clsSysConfig.get_ProdSyncInterval());

                    if (dteLastSyncDateTimeTo <= DateTime.Now)
                    {
                        Data.DBSync clsDBSync = new Data.DBSync(clsDatabase.Connection, clsDatabase.Transaction);
                        System.Data.DataTable stSyncItems = clsDBSync.ListAsDataTable("tblProducts", dteLastSyncDateTime, dteLastSyncDateTimeTo);

                        if (stSyncItems.Rows.Count > 0)
                        {
                            string xmlFileName = @"C:\RetailPlus\RetailPlus\RetailPlus\temp\uploaded\prodsync\prod_" + dteLastSyncDateTime.ToString("yyyyMMddHHmmss") + ".xml";

                            if (!System.IO.File.Exists(xmlFileName))
                            {
                                XmlTextWriter writer = new XmlTextWriter(xmlFileName, System.Text.Encoding.UTF8);

                                writer.Formatting = Formatting.Indented;
                                writer.WriteStartDocument();
                                writer.WriteComment("This file represents the updated products.");
                                writer.WriteStartElement("Header");
                                writer.WriteAttributeString("TableName", stSyncItems.TableName);
                                writer.WriteAttributeString("LastSyncDateTime", dteLastSyncDateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                                writer.WriteAttributeString("LastSyncDateTimeTo", dteLastSyncDateTimeTo.ToString("yyyy-MM-dd HH:mm:ss"));

                                foreach (DataRow dr in stSyncItems.Rows)
                                {
                                    writer.WriteStartElement("Details");

                                    foreach (DataColumn dc in dr.Table.Columns)
                                    {
                                        if (dc.DataType ==  System.Type.GetType("System.DateTime"))
                                            writer.WriteAttributeString(dc.ColumnName, DateTime.Parse(dr[dc.ColumnName].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                                        else 
                                            writer.WriteAttributeString(dc.ColumnName, dr[dc.ColumnName].ToString());
                                    }
                                    writer.WriteEndElement();
                                }
                                writer.WriteEndElement();

                                //Write the XML to file and close the writer
                                writer.Flush();
                                writer.Close();
                            }
                        }

                        clsSysConfig = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                        clsSysConfig.Save(new Data.SysConfigDetails()
                        {
                            ConfigName = "ProdLastSyncDateTime",
                            ConfigValue = dteLastSyncDateTimeTo.ToString("yyyy-MM-dd HH:mm:ss"),
                            Category = "Sync"
                        });
                    }
                    clsDatabase.CommitAndDispose();
                
                    #endregion
                }
                else if (strSyncFunction.ToLower().Trim() == "import")
                {
                    #region Import Products

                    XmlTextReader xmlReader = new XmlTextReader(@"C:\RetailPlus\RetailPlus\RetailPlus\temp\uploaded\prodsync\prod_20150629183000.xml");
                    xmlReader.WhitespaceHandling = WhitespaceHandling.None;

                    ////clsDatabase = new Data.Database(clsDatabase.Connection, clsDatabase.Transaction);
                    clsDatabase.GetConnection(DBName: "poseamirror", username: "******", password: "******");
                    clsDatabase.SetForeignKey(false);

                    Data.SysConfig clsSysConfig = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                    DateTime dteLastSyncDateTime = clsSysConfig.get_ProdLastSyncDateTime();
                    DateTime dteLastSyncDateTimeTo = dteLastSyncDateTime.AddMinutes(clsSysConfig.get_ProdSyncInterval());

                    Data.Products clsProducts = new Data.Products(clsDatabase.Connection, clsDatabase.Transaction);
                    Data.ProductDetails clsProductDetails = new Data.ProductDetails();

                    string strTableName = "";
                    DateTime dteXmlLastSyncDateTime = Constants.C_DATE_MIN_VALUE;
                    DateTime dteXmlLastSyncDateTimeTo = Constants.C_DATE_MIN_VALUE;

                    while (xmlReader.Read())
                    {
                        switch (xmlReader.NodeType)
                        {
                            case XmlNodeType.Element:
                                if (xmlReader.Name == "Header")
                                {
                                    strTableName = xmlReader.GetAttribute("TableName").ToString();
                                    dteXmlLastSyncDateTime = DateTime.TryParse(xmlReader.GetAttribute("LastSyncDateTime").ToString(), out dteXmlLastSyncDateTime) ? dteXmlLastSyncDateTime : Constants.C_DATE_MIN_VALUE;
                                    dteXmlLastSyncDateTimeTo = DateTime.TryParse(xmlReader.GetAttribute("LastSyncDateTimeTo").ToString(), out dteXmlLastSyncDateTimeTo) ? dteXmlLastSyncDateTimeTo : Constants.C_DATE_MIN_VALUE;

                                    if (dteLastSyncDateTime >= dteXmlLastSyncDateTime) break;
                                }
                                else if (strTableName == "tblProducts" && xmlReader.Name == "Details")
                                {
                                    clsProductDetails = Data.DBSync.setSyncProductDetails(xmlReader);
                                    clsProducts.Save(clsProductDetails);
                                }
                                break;
                        }
                    }

                    if (dteLastSyncDateTime < dteXmlLastSyncDateTime)
                    {
                        clsSysConfig = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                        clsSysConfig.Save(new Data.SysConfigDetails()
                        {
                            ConfigName = "ProdLastSyncDateTime",
                            ConfigValue = dteXmlLastSyncDateTimeTo.ToString("yyyy-MM-dd HH:mm:ss"),
                            Category = "Sync"
                        });
                    }

                    clsDatabase.SetForeignKey(true);
                    clsDatabase.CommitAndDispose();

                    #endregion
                }

                WriteProcessToMonitor("Waiting for next process...");

                System.Threading.Thread.Sleep(20000);
                goto back;
            exit:
                WriteProcessToMonitor("Sytem terminated.");
            }
            catch (Exception ex) 
            {
                WriteProcessToMonitor("PLEASE CALL RETAILPLUS IMMEDIATELY... error:" + ex.ToString());
            }
        }
Exemplo n.º 7
0
        private static bool IsDateLastInitializationOK()
        {
            Event clsEvent = new Event();
            try
            {
                clsEvent.AddEvent("Checking last initialization date");

                Data.Database clsDatabase = new Data.Database();
                DateTime dtDateLastInitialized = clsDatabase.DateLastInitialized(Constants.TerminalBranchID, CompanyDetails.TerminalNo);
                clsDatabase.CommitAndDispose();

                bool boReturn = false;

                if (DateTime.Now > dtDateLastInitialized)
                {
                    boReturn = true;
                    clsEvent.AddEventLn("OK: Last initialization is smaller than system date. DateLastInitialized=" + dtDateLastInitialized.ToString("yyyy-MM-dd hh:mm") + " SystemDate=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm"));
                }
                else
                {
                    clsEvent.AddEventLn("Error: Last initialization is greater than system date. DateLastInitialized=" + dtDateLastInitialized.ToString("yyyy-MM-dd hh:mm") + " SystemDate=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm"));
                }

                return boReturn;
            }
            catch (Exception ex)
            {

                clsEvent.AddErrorEventLn(ex);
                return false;
            }
        }
Exemplo n.º 8
0
        private static bool IsDBAlive()
        {
            Event clsEvent = new Event();
            try
            {
                clsEvent.AddEvent("Checking connections to server.");
                if (IPAddress.IsOpen(AceSoft.RetailPlus.DBConnection.ServerIP(), DBConnection.DBPort()) == false)
                {
                    clsEvent.AddEvent("Cannot connect to server please check.");
                    return false;
                }

                clsEvent.AddEvent("Checking connections to database.");

                Data.Database clsDatabase = new Data.Database();
                bool boIsDBAlive = clsDatabase.IsAlive();
                clsEvent.AddEventLn("Done! Connected to " + clsDatabase.Connection.ConnectionString, false);

                clsEvent.AddEventLn("Updating version to " + Application.ProductVersion, true);
                Data.Terminal clsTerminal = new Data.Terminal(clsDatabase.Connection, clsDatabase.Transaction);
                clsTerminal.UpdateFEVersion(Constants.TerminalBranchID, CompanyDetails.TerminalNo, Application.ProductVersion);

                clsDatabase.CommitAndDispose();

                return boIsDBAlive;
            }
            catch (Exception ex)
            {

                clsEvent.AddErrorEventLn(ex);
                return false;
            }
        }
Exemplo n.º 9
0
        private void SaveToDB()
        {
            AceSoft.RetailPlus.Client.MasterDB clsMasterConnection;
            Data.Products  clsProducts;
            Data.Inventory clsInventory;
            Data.Database  clsDatabase;

            Data.ERPConfig        clsERPConfig        = new Data.ERPConfig();
            Data.ERPConfigDetails clsERPConfigDetails = clsERPConfig.Details();
            string strReferenceNo = Constants.CLOSE_INVENTORY_CODE + CompanyDetails.BECompanyCode + DateTime.Now.Year.ToString() + clsERPConfig.get_LastClosingNo();

            clsERPConfig.CommitAndDispose();

            Data.ProductDetails   clsProductDetails;
            Data.InventoryDetails clsInventoryDetails;

            DateTime dtePostingDate = DateTime.Now;

            if (!Directory.Exists("invfiles/backups/"))
            {
                Directory.CreateDirectory("invfiles/backups/");
            }
            if (File.Exists("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + ".inv"))
            {
                if (MessageBox.Show("You have already loaded the inventory for this branch today. Please verify the file you are loading. Would you like to continue?", "RetailPlus", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    bgwSavetoDB.ReportProgress(100);
                    return;
                }
            }
            else
            {
                System.IO.File.Copy("invfiles/" + mclsBranchDetails.BranchCode + ".inv", "invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + ".inv");
            }

            InvExLog clsInvExLog = new InvExLog();

            clsInvExLog.BranchDetails = mclsBranchDetails;
            if (File.Exists("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv"))
            {
                System.IO.File.Copy("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv", "invfiles/backups/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv" + "_" + DateTime.Now.ToString("yyyyddMMhhmmss"));
                System.IO.File.Delete("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_exc.inv");
            }

            InvLoadedLog clsInvLoadedLog = new InvLoadedLog();

            clsInvLoadedLog.BranchDetails = mclsBranchDetails;
            if (File.Exists("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv"))
            {
                System.IO.File.Copy("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv", "invfiles/backups/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv" + "_" + DateTime.Now.ToString("yyyyddMMhhmmss"));
                System.IO.File.Delete("invfiles/" + mclsBranchDetails.BranchCode + DateTime.Now.ToString("yyyyMMdd") + "_saved.inv");
            }

            decimal iCtr = 1, iRows = Decimal.Parse(mdtItems.Rows.Count.ToString());

            foreach (System.Data.DataRow dr in mdtItems.Rows)
            {
                string  strBarCode  = dr["BarCode"].ToString();
                decimal decQuantity = decimal.Parse(dr["Quantity"].ToString());

                string strUnit        = dr["Unit"].ToString();
                string strDescription = dr["Description"].ToString();

                mstStatus = "[" + iCtr.ToString() + "/" + iRows + "]Saving " + strBarCode + strDescription;
                bgwSavetoDB.ReportProgress(int.Parse(Math.Ceiling(iCtr / iRows * 100).ToString()));
                iCtr++;

back:
                clsMasterConnection = new AceSoft.RetailPlus.Client.MasterDB();
                try
                {
                    clsMasterConnection.GetConnection();

                    clsProducts  = new Data.Products(clsMasterConnection.Connection, clsMasterConnection.Transaction);
                    clsInventory = new Data.Inventory(clsMasterConnection.Connection, clsMasterConnection.Transaction);

                    clsProductDetails = clsProducts.Details(mclsBranchDetails.BranchID, strBarCode);
                    if (clsProductDetails.ProductID == 0)
                    {
                        clsInvExLog.AddItem(strBarCode, decQuantity, strUnit, strDescription);
                    }
                    else
                    {
                        clsInvLoadedLog.AddItem(strBarCode, decQuantity, strUnit, strDescription);

                        /*******************************************
                         * Add to Inventory
                         * ****************************************/
                        //clsProduct.AddQuantity(lngProductID, decQuantity);
                        //if (lngVariationMatrixID != 0) { clsProductVariationsMatrix.AddQuantity(lngVariationMatrixID, decQuantity); }
                        // July 26, 2011: change the above codes to the following
                        clsProducts.AddQuantity(mclsBranchDetails.BranchID, clsProductDetails.ProductID, 0, decQuantity, Data.Products.getPRODUCT_INVENTORY_MOVEMENT_VALUE(Data.PRODUCT_INVENTORY_MOVEMENT.ADD_INVENTORY_BY_BRANCH) + " /" + clsProductDetails.BaseUnitCode, DateTime.Now, strReferenceNo, "System");


                        //-- STEP 1: Insert to tblInventory for reporting purposes

                        /*******************************************
                         * Add to Inventory Analysis
                         * ****************************************/
                        clsInventoryDetails                       = new Data.InventoryDetails();
                        clsInventoryDetails.BranchID              = mclsBranchDetails.BranchID;
                        clsInventoryDetails.PostingDateFrom       = clsERPConfigDetails.PostingDateFrom;
                        clsInventoryDetails.PostingDateTo         = clsERPConfigDetails.PostingDateTo;
                        clsInventoryDetails.PostingDate           = dtePostingDate;
                        clsInventoryDetails.ReferenceNo           = strReferenceNo;
                        clsInventoryDetails.ContactID             = clsProductDetails.SupplierID;
                        clsInventoryDetails.ContactCode           = clsProductDetails.SupplierCode;
                        clsInventoryDetails.ProductID             = clsProductDetails.ProductID;
                        clsInventoryDetails.ProductCode           = clsProductDetails.ProductCode;
                        clsInventoryDetails.VariationMatrixID     = 0;
                        clsInventoryDetails.MatrixDescription     = "";
                        clsInventoryDetails.ClosingQuantity       = clsProductDetails.Quantity;
                        clsInventoryDetails.ClosingActualQuantity = decQuantity + clsProductDetails.Quantity;
                        clsInventoryDetails.ClosingCost           = (decQuantity + clsProductDetails.Quantity) * clsProductDetails.PurchasePrice;
                        clsInventoryDetails.ClosingVAT            = (decQuantity + clsProductDetails.Quantity) * clsProductDetails.PurchasePrice * decimal.Parse("0.12"); // Purchase Cost with VAT
                        clsInventoryDetails.PurchasePrice         = clsProductDetails.PurchasePrice;

                        clsInventory.Insert(clsInventoryDetails);
                    }

                    clsMasterConnection.CommitAndDispose();
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("Deadlock found when trying to get lock; try restarting transaction"))
                    {
                        try { clsMasterConnection.ThrowException(ex); } catch { } clsDatabase = new Data.Database(); clsDatabase.FlushHosts(); clsDatabase.CommitAndDispose(); goto back;
                    }
                    else if (ex.InnerException.Message.Contains("Deadlock found when trying to get lock; try restarting transaction"))
                    {
                        try { clsMasterConnection.ThrowException(ex); } catch { } clsDatabase = new Data.Database(); clsDatabase.FlushHosts(); clsDatabase.CommitAndDispose(); goto back;
                    }
                }
            }

            bgwSavetoDB.ReportProgress(100);
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            try
            {
                WriteProcessToMonitor("Starting RetailPlus monitoring tool...");

                // check if it's already running
                if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
                {
                    WriteProcessToMonitor("   already running. not ok");
                    return;
                }

                WriteProcessToMonitor("   ok");

                Data.Database clsDatabase = new Data.Database();
back:
                WriteProcessToMonitor("Checking connections to server.");
                if (IPAddress.IsOpen(AceSoft.RetailPlus.DBConnection.ServerIP(), DBConnection.DBPort()) == false)
                {
                    WriteProcessToMonitor("   cannot connect to server please check.");
                    goto exit;
                }
                WriteProcessToMonitor("   ok");
                WriteProcessToMonitor("Checking connections to database.");

                clsDatabase.GetConnection(username: "******", password: "******");
                try
                {
                    bool boIsDBAlive = clsDatabase.IsAlive();
                    WriteProcessToMonitor("   connected to '" + clsDatabase.Connection.ConnectionString.Split(';')[0].ToString().Replace("Data Source=", "") + "'");
                }
                catch (Exception ex)
                {
                    WriteProcessToMonitor("   ERROR connecting to database. Exception: " + ex.ToString());
                }

                #region Timed-Out Process
                WriteProcessToMonitor("Checking timed-out process.");
                System.Data.DataTable dtProcessList = clsDatabase.getProcessList();
                foreach (DataRow dr in dtProcessList.Rows)
                {
                    int    iID     = int.Parse(dr["ID"].ToString());
                    string strHost = dr["Host"].ToString();
                    string strDB   = dr["db"].ToString();
                    int    iTime   = int.Parse(dr["Time"].ToString());
                    string strInfo = dr["Info"].ToString();
                    if (strInfo.ToUpper() != "SHOW PROCESSLIST" || strDB == "pos")
                    {
                        WriteProcessToMonitor("      id:" + iID.ToString() + "  host:" + strHost + "  Time:" + iTime.ToString() + "  Info:" + strInfo);
                        if (iTime > Constants.C_DEFAULT_MYSQL_PROCESS_TIMEOUT && strDB == "pos")
                        {
                            WriteProcessToMonitor("          status not ok... killing process id: " + iID.ToString());
                            clsDatabase.killProcess(iID);
                            WriteProcessToMonitor("      done.");
                        }
                        else if (iTime > 16 && string.IsNullOrEmpty(strInfo))
                        {
                            WriteProcessToMonitor("          status idle... killing process id: " + iID.ToString());
                            clsDatabase.killProcess(iID);
                            WriteProcessToMonitor("      done.");
                        }
                        else if (strInfo.Contains("INSERT INTO tblTransactions") && iTime >= 8)
                        {
                            WriteProcessToMonitor("          status not ok...  flushing table tblTransactions...process id: " + iID.ToString());
                            clsDatabase.FlushTable("tblTransactions");
                            WriteProcessToMonitor("      done.");
                        }
                        else if (strInfo.Contains("UPDATE tblTerminalReport") && iTime >= 8)
                        {
                            WriteProcessToMonitor("          status not ok... flushing table tblTerminalReport...process id: " + iID.ToString());
                            clsDatabase.FlushTable("tblTerminalReport");
                            WriteProcessToMonitor("      done.");
                        }
                        else
                        {
                            WriteProcessToMonitor("          status ok");
                        }
                    }
                }
                clsDatabase.CommitAndDispose();

                // audit
                //clsDatabase = new Data.Database(clsDatabase.Connection, clsDatabase.Transaction);
                clsDatabase.GetConnection(username: "******", password: "******");
                try
                {
                    bool boIsDBAlive = clsDatabase.IsAlive();
                    WriteProcessToMonitor("   connected to '" + clsDatabase.Connection.ConnectionString.Split(';')[0].ToString().Replace("Data Source=", "") + "'");
                }
                catch (Exception ex)
                {
                    WriteProcessToMonitor("   ERROR connecting to database. Exception: " + ex.ToString());
                }
                WriteProcessToMonitor("Checking Audit timed-out process.");
                dtProcessList = clsDatabase.getProcessList();
                foreach (DataRow dr in dtProcessList.Rows)
                {
                    int    iID     = int.Parse(dr["ID"].ToString());
                    string strHost = dr["Host"].ToString();
                    string strDB   = dr["db"].ToString();
                    int    iTime   = int.Parse(dr["Time"].ToString());
                    string strInfo = dr["Info"].ToString();
                    if (strInfo.ToUpper() != "SHOW PROCESSLIST" || strDB == "pos")
                    {
                        WriteProcessToMonitor("      audit id:" + iID.ToString() + "  host:" + strHost + "  Time:" + iTime.ToString() + "  Info:" + strInfo);
                        if (iTime > Constants.C_DEFAULT_MYSQL_PROCESS_TIMEOUT && strDB == "pos")
                        {
                            WriteProcessToMonitor("          status not ok... killing process id: " + iID.ToString());
                            clsDatabase.killProcess(iID);
                            WriteProcessToMonitor("      done.");
                        }
                        else
                        {
                            WriteProcessToMonitor("          status ok");
                        }
                    }
                }
                clsDatabase.CommitAndDispose();
                WriteProcessToMonitor("   done checking...");
                #endregion

                string strSyncFunction = "";
                try { strSyncFunction = System.Configuration.ConfigurationManager.AppSettings["SyncFunction"].ToString(); }
                catch { }

                if (strSyncFunction.ToLower().Trim() == "export")
                {
                    #region Export Products

                    //clsDatabase = new Data.Database(clsDatabase.Connection, clsDatabase.Transaction);
                    clsDatabase.GetConnection(username: "******", password: "******");

                    Data.SysConfig clsSysConfig          = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                    DateTime       dteLastSyncDateTime   = clsSysConfig.get_ProdLastSyncDateTime();
                    DateTime       dteLastSyncDateTimeTo = dteLastSyncDateTime.AddMinutes(clsSysConfig.get_ProdSyncInterval());

                    if (dteLastSyncDateTimeTo <= DateTime.Now)
                    {
                        Data.DBSync           clsDBSync   = new Data.DBSync(clsDatabase.Connection, clsDatabase.Transaction);
                        System.Data.DataTable stSyncItems = clsDBSync.ListAsDataTable("tblProducts", dteLastSyncDateTime, dteLastSyncDateTimeTo);

                        if (stSyncItems.Rows.Count > 0)
                        {
                            string xmlFileName = @"C:\RetailPlus\RetailPlus\RetailPlus\temp\uploaded\prodsync\prod_" + dteLastSyncDateTime.ToString("yyyyMMddHHmmss") + ".xml";

                            if (!System.IO.File.Exists(xmlFileName))
                            {
                                XmlTextWriter writer = new XmlTextWriter(xmlFileName, System.Text.Encoding.UTF8);

                                writer.Formatting = Formatting.Indented;
                                writer.WriteStartDocument();
                                writer.WriteComment("This file represents the updated products.");
                                writer.WriteStartElement("Header");
                                writer.WriteAttributeString("TableName", stSyncItems.TableName);
                                writer.WriteAttributeString("LastSyncDateTime", dteLastSyncDateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                                writer.WriteAttributeString("LastSyncDateTimeTo", dteLastSyncDateTimeTo.ToString("yyyy-MM-dd HH:mm:ss"));

                                foreach (DataRow dr in stSyncItems.Rows)
                                {
                                    writer.WriteStartElement("Details");

                                    foreach (DataColumn dc in dr.Table.Columns)
                                    {
                                        if (dc.DataType == System.Type.GetType("System.DateTime"))
                                        {
                                            writer.WriteAttributeString(dc.ColumnName, DateTime.Parse(dr[dc.ColumnName].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                                        }
                                        else
                                        {
                                            writer.WriteAttributeString(dc.ColumnName, dr[dc.ColumnName].ToString());
                                        }
                                    }
                                    writer.WriteEndElement();
                                }
                                writer.WriteEndElement();

                                //Write the XML to file and close the writer
                                writer.Flush();
                                writer.Close();
                            }
                        }

                        clsSysConfig = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                        clsSysConfig.Save(new Data.SysConfigDetails()
                        {
                            ConfigName  = "ProdLastSyncDateTime",
                            ConfigValue = dteLastSyncDateTimeTo.ToString("yyyy-MM-dd HH:mm:ss"),
                            Category    = "Sync"
                        });
                    }
                    clsDatabase.CommitAndDispose();

                    #endregion
                }
                else if (strSyncFunction.ToLower().Trim() == "import")
                {
                    #region Import Products

                    XmlTextReader xmlReader = new XmlTextReader(@"C:\RetailPlus\RetailPlus\RetailPlus\temp\uploaded\prodsync\prod_20150629183000.xml");
                    xmlReader.WhitespaceHandling = WhitespaceHandling.None;

                    ////clsDatabase = new Data.Database(clsDatabase.Connection, clsDatabase.Transaction);
                    clsDatabase.GetConnection(DBName: "poseamirror", username: "******", password: "******");
                    clsDatabase.SetForeignKey(false);

                    Data.SysConfig clsSysConfig          = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                    DateTime       dteLastSyncDateTime   = clsSysConfig.get_ProdLastSyncDateTime();
                    DateTime       dteLastSyncDateTimeTo = dteLastSyncDateTime.AddMinutes(clsSysConfig.get_ProdSyncInterval());

                    Data.Products       clsProducts       = new Data.Products(clsDatabase.Connection, clsDatabase.Transaction);
                    Data.ProductDetails clsProductDetails = new Data.ProductDetails();

                    string   strTableName             = "";
                    DateTime dteXmlLastSyncDateTime   = Constants.C_DATE_MIN_VALUE;
                    DateTime dteXmlLastSyncDateTimeTo = Constants.C_DATE_MIN_VALUE;

                    while (xmlReader.Read())
                    {
                        switch (xmlReader.NodeType)
                        {
                        case XmlNodeType.Element:
                            if (xmlReader.Name == "Header")
                            {
                                strTableName             = xmlReader.GetAttribute("TableName").ToString();
                                dteXmlLastSyncDateTime   = DateTime.TryParse(xmlReader.GetAttribute("LastSyncDateTime").ToString(), out dteXmlLastSyncDateTime) ? dteXmlLastSyncDateTime : Constants.C_DATE_MIN_VALUE;
                                dteXmlLastSyncDateTimeTo = DateTime.TryParse(xmlReader.GetAttribute("LastSyncDateTimeTo").ToString(), out dteXmlLastSyncDateTimeTo) ? dteXmlLastSyncDateTimeTo : Constants.C_DATE_MIN_VALUE;

                                if (dteLastSyncDateTime >= dteXmlLastSyncDateTime)
                                {
                                    break;
                                }
                            }
                            else if (strTableName == "tblProducts" && xmlReader.Name == "Details")
                            {
                                clsProductDetails = Data.DBSync.setSyncProductDetails(xmlReader);
                                clsProducts.Save(clsProductDetails);
                            }
                            break;
                        }
                    }

                    if (dteLastSyncDateTime < dteXmlLastSyncDateTime)
                    {
                        clsSysConfig = new Data.SysConfig(clsDatabase.Connection, clsDatabase.Transaction);
                        clsSysConfig.Save(new Data.SysConfigDetails()
                        {
                            ConfigName  = "ProdLastSyncDateTime",
                            ConfigValue = dteXmlLastSyncDateTimeTo.ToString("yyyy-MM-dd HH:mm:ss"),
                            Category    = "Sync"
                        });
                    }

                    clsDatabase.SetForeignKey(true);
                    clsDatabase.CommitAndDispose();

                    #endregion
                }

                WriteProcessToMonitor("Waiting for next process...");

                System.Threading.Thread.Sleep(20000);
                goto back;
exit:
                WriteProcessToMonitor("Sytem terminated.");
            }
            catch (Exception ex)
            {
                WriteProcessToMonitor("PLEASE CALL RETAILPLUS IMMEDIATELY... error:" + ex.ToString());
            }
        }