コード例 #1
0
ファイル: DebugForm.cs プロジェクト: fhoner/Kasse
 public DebugForm(Printer printer, VirtualComPort lockPort)
     : this()
 {
     this.printer = printer;
     this.printer.PrintOccured += printer_PrintOccured;
     this.lockPort = lockPort;
 }
コード例 #2
0
ファイル: AdministrationForm.cs プロジェクト: fhoner/Kasse
        public AdministrationForm(ObservableCollection<Profile> profiles, ObservableCollection<User> userList, User loggedInUser, Printer printer)
        {
            InitializeComponent();

            this.Activated += (s, e) => { StatusUpdater.Instance.Update(loggedInUser.Username, CashpointAction.ACTION_ADMIN); };

            this.loggedInUser = loggedInUser;
            this.profiles = profiles;
            this.users = userList;
            this.printer = printer;
            this.primaryProfile = (from p in profiles where p.IsPrimary select p as Profile).FirstOrDefault();

            this.Load += (sender, args) => 
            {
                if (printer.PrintStatus == PrintStatus.Printing) btnPrintResult.Enabled = false;
                printer.PrintStatusChanged += printer_PrintStatusChanged;

                lblProfile.Text = primaryProfile.Name;
                lblVersion.Text = Kasse.Properties.Resources.Version;
                lblDbVersion.Text = DatabaseHandler.GetDbVersion();
                lblUsername.Text = loggedInUser.Username;
                if (loggedInUser.CurrentSession == null)
                    loggedInUser.Login();
                TimeSpan ts = DateTime.Now - loggedInUser.CurrentSession.LoginTime;
                lblSessionTime.Text = ts.ToString("hh") + ":" + ts.ToString("mm") + ":" + ts.ToString("ss");
                Timer t = new Timer() { Interval = 1000 };
                t.Tick += (s, a) => {
                    try
                    {
                        if (loggedInUser != null && loggedInUser.CurrentSession != null)
                        {
                            TimeSpan span = DateTime.Now - loggedInUser.CurrentSession.LoginTime;
                            lblSessionTime.Text = span.ToString("hh") + ":" + span.ToString("mm") + ":" + span.ToString("ss");
                        }
                        else
                            lblSessionTime.Text = "- Fehler -";
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Write(ex, LOGFILE_NAME);
                    }
                    
                };
                t.Enabled = true;

                lblRefreshEnabled.Text = LoginForm.CashpointSettings["AutoRefresh"].ToLower() == "auto" ? "Automatisch" : "Manuell";
                lblRefreshInterval.Text = LoginForm.CashpointSettings["AutoRefreshInterval"];
                btnToggleAutorefresh.Text = LoginForm.CashpointSettings["AutoRefresh"].ToLower() == "auto" ? "Aktualisierung (Ein)" : "Aktualisierung (Aus)";
                ConfigurationReader configReader = new ConfigurationReader(ConfigurationReader.CONFIGURATION_FILE_NAME);
                lblHost.Text = configReader.GetValue("server");
                lblLiveview.Text = LoginForm.CashpointSettings["LiveViewEndpoint"] + " (" + (StatusUpdater.Instance.IsInitialized ? "online" : "offline") + ")";

                cmbUsers.DataSource = userList;
                cmbArticles.DataSource = primaryProfile.Articles;
                cmbResultProfile.DataSource = profiles;
                cmbResultUser.DataSource = userList;
            };
        }
コード例 #3
0
ファイル: DebugForm.cs プロジェクト: fhoner/Kasse
        internal DebugForm(Printer printer, VirtualComPort lockPort, IList<User> users)
        {
            InitializeComponent();

            this.printer = printer;
            this.printer.PrintOccured += printer_PrintOccured;
            this.lockPort = lockPort;
            this.users = users;
            lbKeyUsers.DataSource = users;
        }
コード例 #4
0
ファイル: PurchaseSummaryForm.cs プロジェクト: fhoner/Kasse
        public PurchaseSummaryForm(Printer printDevice)
        {
            InitializeComponent();

            this.Activated += (s, e) => { StatusUpdater.Instance.Update(StatusUpdater.Instance.LastUser, CashpointAction.ACTION_SUMMARY); };

            this.autoPrint = true;
            this.printDevice = printDevice;

            dgvCartTable.Font = new Font(dgvCartTable.Font.FontFamily, 9.0F, FontStyle.Regular);
        }
コード例 #5
0
ファイル: RegisterForm.cs プロジェクト: fhoner/Kasse
        public DepositRegisterForm(ObservableCollection<Profile> profiles, ObservableCollection<User> users, Printer printDevice)
        {
            InitializeComponent();

            this.Activated += (s, e) => 
            {
                StatusUpdater.Instance.Update(userLoggedIn.Username, CashpointAction.ACTION_REGISTER);
                Invoke(new Action(() => { btnExit.Enabled = userLoggedIn.IsAdministrator; }));
            };

            // remove articles without deposit
            foreach (Profile p in profiles)
            {
                p.Articles =
                    new ObservableCollection<Article>(
                    (from a in p.Articles where a.Deposit != Deposit.NullDeposit select a).ToList()
                );
            }

            this.printDevice = printDevice;
            this.profiles = profiles;
            this.users = users;
            primaryProfile = (from p in profiles where p.IsPrimary == true select p as Profile).First();
            printDevice.Profile = primaryProfile;

            List<int> addedDeposits = new List<int>();
            foreach (Article a in primaryProfile.Articles)
            {
                if(!addedDeposits.Contains(a.Deposit.DepositID))
                {
                    DepositButton btn = a.Button.ToDepositButton();
                    btn.Cart = this.cart;
                    this.Controls.Add(btn);
                    addedDeposits.Add(a.Deposit.DepositID);
                }
            }

            this.cart.CartChanged += RefreshCartGUI;
            dgvCartTable.Font = new Font(dgvCartTable.Font.FontFamily, 11.0F, FontStyle.Regular);

            // add eventhandler for successed sales to trigger printer
            this.SaleSuccessed += RegisterForm_SaleSuccessed;

            // reset refresh pending
            this.Shown += (a, b) =>
            {
                this.RefreshNeeded = false;
            };

            // log user off when form hides
            this.FormClosing += (e, args) =>
            {
                try
                {
                    cart.Clear();
                    userLoggedIn.Logout();
                }
                catch (Exception ex)
                {
                    LogWriter.Write(ex, LOGFILE_NAME);
                    MessageBox.Show("Programmfehler: " + ex.ToString());
                }
            };

            // create dialogs
            confirmationDialog = new PurchaseSummaryForm(printDevice);

            // bottom labels
            lblProfile.Text = primaryProfile.Name;
            lblTime.Text = DateTime.Now.ToString("HH:mm:ss");
            time = new Timer();
            time.Interval = 1000;
            time.Tick += (sender, e) => { lblTime.Text = DateTime.Now.ToString("HH:mm:ss"); };

            // logout timer
            logoutHoldTimer = new Timer();
            int duration = Convert.ToInt32(LoginForm.CashpointSettings["HoldLogoutDuration"]);
            logoutHoldTimer.Interval = duration > 0 ? duration * 1000 : 1;
            logoutHoldTimer.Tick += delegate(object sender, EventArgs e)
            {
                logoutHoldTimer.Stop();
                if (cart.Count > 0 && loginMode == LoginForm.LoginMode.Key)
                {
                    if (discardForm.ShowDialog(userLoggedIn.Username) == DialogResult.OK)
                    {
                        cart.Clear();
                        if (refreshNeeded) this.Close();
                        this.Hide();
                    }
                }
                else
                    this.Hide();
            };
            btnLogout.MouseDown += delegate(object sender, MouseEventArgs mea)
            {
                logoutHoldTimer.Start();
            };
            btnLogout.MouseUp += delegate(object sender, MouseEventArgs mea)
            {
                logoutHoldTimer.Stop();
            };

            // printer status subscription
            printDevice.PrintStatusChanged += (sender, e) =>
            {
                try
                {
                    if (e.NewStatus == PrintStatus.Printing)
                        btnPrint.Invoke(new Action(() => btnPrint.Enabled = false));
                    else
                    {
                        if (cart.Count > 0)
                            btnPrint.Invoke(new Action(() => { btnPrint.Enabled = true; btnReset.Enabled = true; }));
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Write(ex, LOGFILE_NAME);
                    MessageBox.Show(ex.Message);
                }
            };

            // set picture boxes
            pctRefreshPending.Image = Resources.Get(Resources.Images.RefreshPending);
            pctPaperNearOut.Image = Resources.Get(Resources.Images.PrinterIconSmall);
            if (printDevice.DeviceStatusCode == 25) pctPaperNearOut.Visible = true;

            // create discard form
            discardForm = new DiscardCartForm();

            // create popups
            Popups = new Dictionary<Popup, Form>();
            Popups = new Dictionary<Popup, Form>();
            Popups.Add(Popup.RefreshInvoked, new InformRefreshInvokedForm());
            Popups.Add(Popup.RefreshNow, new InformRefreshPopupForm());
            Popups.Add(Popup.ShowMessage, new ShowMessageForm());

        }
コード例 #6
0
ファイル: LoginForm.cs プロジェクト: fhoner/Kasse
        /// <summary>
        /// Backgroundworker DoWork method: represents the routine for the startup of the cashpoint.
        /// Step 1: check completeness of config file
        /// Step 2: check database connectivity
        /// Step 3: connect to printer device
        /// Step 4: connect to addimat lock
        /// Step 5: load profiles (including articles), users, config
        /// Step 6: initialize status update sender object
        /// Step 7: create forms, e.g. RegisterForm() + draw articles, popup(), submit cashpoint state
        /// Step 8: debug options
        /// </summary>
        void InitializeCashpoint(object sender, DoWorkEventArgs e)
        {
            bgwInitialize.ReportProgress(2, "StartupRoutine");

            bool configCorrect = false, databaseCorrect = false, printerFound = false, lockFound = false, dataLoaded = false;
            int currentStep = 0;
            int goToStep;
            try
            {
                goToStep = Convert.ToInt32(e.Argument);
            }
            catch (Exception)
            {
                goToStep = 0;
            }

            #region step 1
            currentStep++;
            bgwInitialize.ReportProgress(0, currentStep);
            if (goToStep <= 1)
                do
                {
                    try
                    {
                        bgwInitialize.ReportProgress(1, "");
                        ConfigReader = new ConfigurationReader(ConfigurationReader.CONFIGURATION_FILE_NAME);
                        ConfigReader.Check();
                        configCorrect = true;
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Write(ex, LOGFILE_NAME);
                        bgwInitialize.ReportProgress(1, ex.Message);
                        System.Threading.Thread.Sleep(2500);
                        bgwInitialize.ReportProgress(1, "");
                        System.Threading.Thread.Sleep(750);
                    }
                } while (!configCorrect);
            #endregion

            #region step 2
            currentStep++;
            bgwInitialize.ReportProgress(0, currentStep);
            if (goToStep <= 2)
                do
                {
                    try
                    {
                        bool missing = false;
                        bgwInitialize.ReportProgress(1, "");
                        DatabaseHandler.ConnectionString = DatabaseHandler.GenerateConnectionString(ConfigReader.GetValue("server"));
                        for (int i = 0; i < 3; i++)
                            if (!DatabaseHandler.TestConnection())
                                throw new Exception("Verbindung konnte nicht hergestellt werden");
                        CashpointSettings = DatabaseHandler.GetSettings();

                        // check config settings from database
                        string[] required = new string[] { "DoPrint", "IsEnabled", "IsServiceMode", "OrganizationName", "AutoRefresh", "AutoRefreshInterval" };
                        foreach (string s in required)
                            if (CashpointSettings[s] == null)
                            {
                                missing = true;
                                bgwInitialize.ReportProgress(1, "Benötigte Informationen konnten nicht geladen werden (\"" + s + "\")");
                                System.Threading.Thread.Sleep(250);
                            }

                        databaseCorrect = !missing;
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Write(ex, LOGFILE_NAME);
                        bgwInitialize.ReportProgress(1, ex.Message);
                        System.Threading.Thread.Sleep(2500);
                        bgwInitialize.ReportProgress(1, ex.Message);
                        System.Threading.Thread.Sleep(750);
                    }

                } while (!databaseCorrect);
            #endregion

            #region step 3
            currentStep++;
            bgwInitialize.ReportProgress(0, currentStep);
            if (goToStep <= 3)
                do
                {
                    try
                    {
                        if (printDevice != null)
                        {
                            while (printDevice.PrintStatus == PrintStatus.Printing || _closePrinter.Visible) System.Threading.Thread.Sleep(250);
                            printDevice.Dispose();
                        }

                        bgwInitialize.ReportProgress(1, "");
                        printDevice = new Printer(ConfigReader.GetValue("PrinterName"), !DebugPrinter);
                        printDevice.DeviceStatusChanged += printDevice_DeviceStatusChanged;
                        printDevice.CheckAvailability();
                        printerFound = true;

                        printDevice_DeviceStatusChanged(this, new Microsoft.PointOfService.StatusUpdateEventArgs(printDevice.DeviceStatusCode));
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Write(ex, LOGFILE_NAME);
                        if (!ex.Message.Contains("Fehler beim Setzen des aktuellen Kassenstatus."))
                            bgwInitialize.ReportProgress(1, "Druckerverbindung konnte nicht hergestellt werden.\n" + ex.Message);
                        System.Threading.Thread.Sleep(2000);
                    }
                } while (!printerFound);      
            #endregion

            #region step 4
            currentStep++;
            bgwInitialize.ReportProgress(0, currentStep);

            // check if "ignorelock" is configured
            string result;
            if (ConfigReader.TryGetValue("NOLOCK", out result))
                IgnoreLock = true;
            if (goToStep <= 4 && !IgnoreLock)
            {
                do
                {
                    try
                    {
                        bgwInitialize.ReportProgress(1, "");
                        string errmsg = "";

                        if (addimatLock != null) addimatLock.CloseComPort();
                        addimatLock = new VirtualComPort(!DebugLock);
                        addimatLock.PortReadEvent += new VirtualComPort.ReadEventHandler(addimatLock_PortReadEvent);
                        if (!addimatLock.OpenComPort(ConfigReader.GetValue("Lockport"), ref errmsg))
                            throw new Exception(errmsg);

                        Application.DoEvents();
                        tLock.Start();
                        Application.DoEvents();

                        lockFound = true;
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Write(ex, LOGFILE_NAME);
                        bgwInitialize.ReportProgress(1, "Verbindungsaufbau zum Kellnerschloss fehlgeschlagen\n" + ex.Message);
                        System.Threading.Thread.Sleep(5000);
                    }

                } while (!lockFound);
            }
            #endregion

            #region step 5
            currentStep++;
            bgwInitialize.ReportProgress(0, currentStep);
            if (goToStep <= 5)
                do
                {
                    try
                    {
                        bgwInitialize.ReportProgress(1, "");
                        CashpointSettings = DatabaseHandler.GetSettings();
                        this.users = DatabaseHandler.GetUsers();
                        this.profiles = DatabaseHandler.GetProfiles();
                        dataLoaded = true;
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Write(ex, LOGFILE_NAME);
                        bgwInitialize.ReportProgress(1, ex.Message);
                        System.Threading.Thread.Sleep(2000);
                    }
                } while (!dataLoaded);
            #endregion

            #region step 6
            StatusUpdater updater = new StatusUpdater(LoginForm.CashpointSettings["LiveViewEndpoint"]);
            updater.Start();
            #endregion

            #region step 7
            currentStep++;
            bgwInitialize.ReportProgress(0, currentStep);
            if (goToStep <= 6)
                try
                {
                    regForm = new DepositRegisterForm(profiles, users, printDevice);
                    if (CashpointSettings["IsEnabled"] == "True") // cashpoint unlocked
                    {
                        StatusUpdater.Instance.Update(null, CashpointAction.ACTION_LOGIN);
                        string mode;
                        if (ConfigReader.TryGetValue("Mode", out mode))     // is auto mode ?
                        {
                            if (mode.ToLower() == "auto")   // auto mode
                            {
                                if (CashpointSettings["IsServiceMode"] == "False")
                                    bgwInitialize.ReportProgress(2, "PinLogin");
                                else
                                    bgwInitialize.ReportProgress(2, "KeyLogin");
                            }
                            else    // no auto, config.ini defined
                            {
                                string value = ConfigReader.GetValue("Mode");
                                switch (value.ToLower())
                                {
                                    case "pin":
                                        bgwInitialize.ReportProgress(2, "PinLogin");
                                        break;
                                    case "lock":
                                        bgwInitialize.ReportProgress(2, "KeyLogin");
                                        break;
                                    default:    // invalid value for attribute "mode", so use database setting
                                        if (CashpointSettings["IsServiceMode"] == "False")
                                            bgwInitialize.ReportProgress(2, "PinLogin");
                                        else
                                            bgwInitialize.ReportProgress(2, "KeyLogin");
                                        break;
                                }
                            }
                        }
                        else    // no mode defined, use database setting
                        {
                            if (CashpointSettings["IsServiceMode"] == "False")
                                bgwInitialize.ReportProgress(2, "PinLogin");
                            else
                                bgwInitialize.ReportProgress(2, "KeyLogin");
                        }

                        string doPrintConfigIni;
                        if (ConfigReader.TryGetValue("Printer", out doPrintConfigIni))
                        {
                            try
                            {
                                DepositRegisterForm.DoPrint = Convert.ToBoolean(doPrintConfigIni);
                            }
                            catch (Exception)
                            {
                                DepositRegisterForm.DoPrint = null;
                            }
                        }
                        else
                            DepositRegisterForm.DoPrint = null;
                    }
                    else    // cashpoint locked
                    {
                        StatusUpdater.Instance.Update(null, CashpointAction.ACTION_LOCKED);
                        bgwInitialize.ReportProgress(2, "Disabled");
                    }


                    if (refresher != null) refresher.Stop();
                    refresher = new AutoUpdateChecker(int.Parse(LoginForm.CashpointSettings["AutoRefreshInterval"]));
                    refresher.UpdateRequested += refresher_UpdateRequested;

                    if (CashpointSettings["Autorefresh"].ToLower() == "auto")
                        refresher.Start();
                    else
                        refresher.Stop();

                    DatabaseHandler.TransmitCurrentState(IgnoreLock ? 6 : 1);
                }
                catch (Exception ex)
                {
                    LogWriter.Write(ex, LOGFILE_NAME);
                    bgwInitialize.ReportProgress(1, ex.Message);
                }
            #endregion

            #region step 8
            if (DebugPrinter || DebugLock)
            {
                Invoke(new Action(() =>
                {
                    // create toolbox (recreation needed after cashpoint reloaded)
                    if (debugToolbox != null && debugToolbox.Visible)
                        debugToolbox.Close();

                    if (DebugToolboxVisible)
                        this.Invoke(new Action(() =>
                        {
                            debugToolbox = new DebugForm(printDevice, addimatLock);

                            // form settings to prevent showDialog() to keep toolbox focusable
                            KasseForm.DebugEnabled = true;
                            debugToolbox.Show();
                        }));
                }));   
            }
            #endregion

        }
コード例 #7
0
ファイル: DebugForm.cs プロジェクト: fhoner/Kasse
 public DebugForm(Printer printer)
     : this()
 {
     this.printer = printer;
     this.printer.PrintOccured += printer_PrintOccured;
 }
コード例 #8
0
ファイル: AdministrationForm.cs プロジェクト: fhoner/Kasse
 void printer_PrintStatusChanged(object sender, Printer.PrintStatusChangedEventArgs e)
 {
     if (e.NewStatus == PrintStatus.Stopped)
     {
         if (this.IsHandleCreated) this.Invoke(new Action(() => { btnPrintResult.Enabled = true; }));
     }
 }
コード例 #9
-2
ファイル: Printer.cs プロジェクト: fhoner/Kasse
        public Printer(string logicalName, bool connect)
        {
            instance = this;
            if (connect)
            {
                this.profile = null;
                this.deviceStatus = PrintDeviceStatus.Properly;
                this.PrintStatus = PrintStatus.Stopped;

                try
                {
                    DeviceInfo deviceInfo = null;
                    PosExplorer posExplorer = new PosExplorer();
                    deviceInfo = posExplorer.GetDevice(DeviceType.PosPrinter, logicalName);
                    device = (PosPrinter)posExplorer.CreateInstance(deviceInfo);
                    device.Open();
                    device.Claim(1000);
                    device.AsyncMode = false;
                    device.DeviceEnabled = true;

                    device.StatusUpdateEvent += Device_StatusUpdateEvent;
                    device.ErrorEvent += (a, b) => { WriteLog("ERROR - " + b.ToString()); };
                    WriteLog("");
                    WriteLog("Drucker initialisiert; Status: " + device.State + device);
                    if (device.RecNearEnd) Device_StatusUpdateEvent(this, new StatusUpdateEventArgs(25));
                    this.connected = connect;
                }
                catch (Exception ex)
                {
                    string s = ex.Source;
                    try
                    {
                        if (device != null)
                            device.Release();
                    }
                    catch { }
                    throw new Exception("Verbindung zum Drucker fehlgeschlagen.", ex);
                }
            }
            else
            {
                this.connected = false;
                this.PrintStatus = PrintStatus.Stopped;
                this.deviceStatus = PrintDeviceStatus.Properly;
            }
        }