Exemplo n.º 1
0
        public static void FinishInstall()
        {
            //MessageBox.Show(Strings.AboutToInstallDatabase);

            ExecuteEmbeddedSqlScript("TemPOS.Resources.EnableClrScript.sql", false);
            if (!DataModelBase.DatabaseExists("TemPOS"))
            {
                //System.Windows.Forms.Form window = CreateNotificationWindow();
                //window.Show();
                try
                {
                    //ExecuteEmbeddedSqlScript("TemPOS.Resources.EnableClrScript.sql");
                    ExecuteEmbeddedSqlScript("TemPOS.Resources.InstallDatabaseScript.sql", false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Types.Strings.DatabaseInstallationException);
                    return;
                }
                //window.Hide();
            }

            // Warning: Do not apply database patches at install time,
            //          instead apply patches the first time the app starts.
        }
Exemplo n.º 2
0
    private void LoadDataModelsFromDisk()
    {
        var enumerator = this._dataModels.GetEnumerator();

        while (enumerator.MoveNext())
        {
            DataModelBase dataModel = enumerator.Current.Value;
            dataModel.LoadDataModelFromDisk();
        }
    }
Exemplo n.º 3
0
    private void RegisterDataModel(DataModelBase dataModel)
    {
        string dataModelTypeName = dataModel.GetType().Name;

        if (this._dataModels.ContainsKey(dataModelTypeName))
        {
            DebugLog.LogErrorColor("Already registered datamodel for type " + dataModelTypeName, LogColor.orange);
            return;
        }
        this._dataModels.Add(dataModel.GetType().Name, dataModel);
    }
Exemplo n.º 4
0
 private void Window_Closing(object sender, CancelEventArgs e)
 {
     if (!AllowClose)
     {
         e.Cancel = true;
     }
     else
     {
         DeviceManager.ClosePosDevices();
         DataModelBase.CloseAll();
     }
 }
Exemplo n.º 5
0
        private static void ExecuteEmbeddedSqlScript(string path, bool useDatabase = true)
        {
            // Get the PosControls assembly
            var assemblyName = path.Substring(0, path.IndexOf('.'));
            var assembly     = GetAssemblyByName(assemblyName);

            using (var stream = assembly.GetManifestResourceStream(path))
            {
                if (stream != null)
                {
                    DataModelBase.ExecuteSqlScript(new StreamReader(stream), useDatabase);
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Fetch recent error details from ErrorLog table.
        /// </summary>
        private void RefreshErrorsList()
        {
            bool createdConnection        = false;
            AdoDataConnection database    = null;
            List <ErrorLog>   newTempList = null;

            try
            {
                createdConnection = DataModelBase.CreateConnection(ref database);

                DataTable ErrorLogTable = database.Connection.RetrieveData(database.AdapterType,
                                                                           "SELECT ID, Source, Type, Message, Detail, CreatedOn FROM ErrorLog ORDER BY ID DESC");

                // Load only first 2000 Error information to list.
                newTempList = ErrorLogTable.Rows.Cast <DataRow>()
                              .Select(row => new ErrorLog()
                {
                    ID        = row.ConvertField <int>("ID"),
                    Source    = row.Field <String>("Source"),
                    Type      = row.Field <String>("Type"),
                    Message   = row.Field <String>("Message"),
                    Detail    = row.Field <String>("Detail"),
                    CreatedOn = row.Field <DateTime>("CreatedOn")
                })
                              .Distinct()
                              .Take(DefaultErrorLogSize)
                              .ToList();

                // Update the error list
                lock (m_errLock)
                {
                    m_ErrorList = newTempList;
                }

                // Notify that the ErrorList have been updated
                OnUpdatedErrors();
            }
            catch (Exception)
            {
                // Do nothing, if exception raised while logging Errors
            }
            finally
            {
                if (createdConnection && database != null)
                {
                    database.Dispose();
                }
            }
        }
Exemplo n.º 7
0
        private void DoListTables(string[] tokens)
        {
            // use DatabaseName (not needed)
            // select distinct name from sysobjects where xtype='U'
            SqlConnection cn  = DataModelBase.GetConnection();
            SqlCommand    cmd = new SqlCommand("select distinct name from sysobjects where xtype='U'", cn);
            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                PrintLine(rdr[0].ToString());
            }
            rdr.Close();
            DataModelBase.FinishedWithConnection(cn);
        }
Exemplo n.º 8
0
        private void DoSqlNonQueryCommand(string sqlCommand)
        {
            if (sqlCommand == null)
            {
                return;
            }
            Int32         rowsAffected;
            SqlConnection cn = DataModelBase.GetConnection();

            using (SqlCommand sqlCmd = cn.CreateCommand())
            {
                sqlCmd.CommandText = sqlCommand;
                rowsAffected       = sqlCmd.ExecuteNonQuery();
            }
            DataModelBase.FinishedWithConnection(cn);
            OutputSqlNonQuery(rowsAffected != 0);
        }
Exemplo n.º 9
0
        public async Task Post(string url, DataModelBase body = null, AuthenticationHeaderValue authentication = null)
        {
            using (HttpClient client = clientFactory.CreateClient(Options.HttpClienteName))
            {
                var jsonBody = body?.Serialize();

                client.DefaultRequestHeaders.Authorization = authentication;

                logger.LogInformation("POST: {baseAddress}{url}", client.BaseAddress, url);
                logger.LogDebug("Body: {body}", body?.ToJson());

                using (HttpResponseMessage responseMessage = await client.PostAsync(url, jsonBody))
                {
                    await responseMessage.GetContentWithStatusCodeValidated();

                    logger.LogInformation("POST {statusCode}: {baseAddress}{url}", responseMessage.StatusCode, client.BaseAddress, url);
                }
            }
        }
Exemplo n.º 10
0
        private static bool EnsureDatabaseConnection()
        {
            int count = 0;

            if (LocalSetting.FileExists)
            {
                while (count < 2)
                {
                    string statusMessage;
                    if (DataModelBase.TestConnection(out statusMessage))
                    {
                        return(true);
                    }
                    _ensureDatabaseConnectionStatus = statusMessage;
                    count++;
                }
            }
            _ensureDatabaseConnectionStatus = "Local settings does not exist yet.";
            return(false);
        }
Exemplo n.º 11
0
        private void DoSqlReaderCommand(string sqlCommand)
        {
            if (string.IsNullOrEmpty(sqlCommand))
            {
                return;
            }

            var list = new List <SqlModel>();

            SqlConnection cn  = DataModelBase.GetConnection();
            SqlCommand    cmd = new SqlCommand(sqlCommand, cn);
            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                list.Add(new SqlModel(rdr));
            }
            rdr.Close();
            DataModelBase.FinishedWithConnection(cn);
            OutputSqlQuery(list.ToArray());
        }
Exemplo n.º 12
0
        public static bool InstallSQLAssembly()
        {
            string databaseName = LocalSetting.DatabaseServerDatabaseName;
            string assemblyPath =
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
                + @"\TemposProcs.dll";

            if (!ServiceHelper.IsSqlServiceRunningLocally || !File.Exists(assemblyPath))
            {
                return(false);
            }

            try
            {
                return(DataModelBase.InstallAssembly(assemblyPath, databaseName, "PointOfSale", true));
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex.Message + Environment.NewLine + ex.StackTrace);
                Logger.CloseLog();
                return(false);
            }
        }
Exemplo n.º 13
0
        private void DoFinishInstall()
        {
            bool exists = false;

            try
            {
                exists = DataModelBase.DatabaseExists("TemPOS");
            }
            catch {  }

            if (!exists)
            {
                _notification = ActionNotificationControl.Create(null,
                                                                 Types.Strings.InstallingSQLDatabase, Types.Strings.Notification);
                _notification.Show();

                new Thread(DoFinishInstallThreadStart).Start();
            }
            else
            {
                _notification = null;
                FinalStartUp();
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Called when all startup conditions have been meet. The database is now
        /// accessible as well.
        /// </summary>
        private void FinalStartUp()
        {
            if ((_notification != null) && _notification.IsLoaded && _notification.IsVisible)
            {
                _notification.Close();
            }

            // Disable AlwaysUseDefaults which was being used prior to this...
            ConfigurationManager.AlwaysUseDefaults = false;

            // Task Manager Protection
            // SettingManager.SetStoreSetting("DontDisableTaskManager", 0);
            int?isDisabled = SettingManager.GetInt32("DontDisableTaskManager");

            if (isDisabled.HasValue && (isDisabled.Value == 1))
            {
                BeginStartup();
                return;
            }
            if (!TaskManagerServiceHelper.IsInstalled)
            {
                if (PosDialogWindow.ShowDialog(Types.Strings.DoYouWantToInstallTheTaskManagerAccessService,
                                               Types.Strings.InstallService, DialogButtons.YesNo, false) == DialogButton.Yes)
                {
                    new Thread(TaskManagerServiceHelper.InstallThread).Start();
                }
            }
            else if (!TaskManagerServiceHelper.IsStarted)
            {
                if (PosDialogWindow.ShowDialog(Types.Strings.DoYouWantToStartTheTaskManagerAccessService,
                                               Types.Strings.StartService, DialogButtons.YesNo, false) == DialogButton.Yes)
                {
                    new Thread(TaskManagerServiceHelper.StartThread).Start();
                }
            }
            else
            {
                TaskManagerServiceHelper.IsTaskManagerDisabled = true;
            }


            // Install the SQL Assembly (if one is pending installation)
            if (Updater.InstallSQLAssembly())
            {
#if DEBUG
                PosDialogWindow.ShowDialog("New SQL Assembly Installed", Types.Strings.Information);
#endif
            }

            // Apply any required database patches at runtime
            SqlServerSetup.ApplyDatabasePatches();

            // Check to make sure the model classes and the tables match
            if (!DataModelBase.ValidateDatabase())
            {
#if DEBUG
                string results = DataModelBase.InvalidDatabaseReport();
                PosDialogWindow.ShowDialog(
                    results,
                    "Invalid Database Report");
#else
                PosDialogWindow.ShowDialog(
                    Strings.TheDatabaseDesignCurrentlyBeingUsedIsIncorrectForThisVersionOfTempos,
                    Strings.StartupError);
#endif
                UserControlManager.ShowTaskbar(true);
                Application.Current.Shutdown();
                return;
            }

            // Enable user control
            UserControlManager.Enable(ConfigurationManager.UseKeyboardHook);
            UserControlManager.ShowTaskbar(false);

            // Start-up MainWindow
            Show();
            _mainWindow = new MainWindow();
            _mainWindow.Show();
        }
Exemplo n.º 15
0
        void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;

            // Stop the auto-logoof timer
            LoginControl.StopAutoLogoutTimer();

            // Close all database connections
            DataModelBase.CloseAll();

#if !DEMO
            // Send the exception to the upgrade server
            Updater.StartCrashReport(e.Exception);
#endif
            // Save the exception, serialized to the AppData folder
            try
            {
                DateTime now           = DateTime.Now;
                string   rootDirectory =
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
                    Path.DirectorySeparatorChar + "TemPOS";
                if (!Directory.Exists(rootDirectory))
                {
                    Directory.CreateDirectory(rootDirectory);
                }
                string path = rootDirectory + Path.DirectorySeparatorChar + "crashdata-" +
                              now.Year + now.Month.ToString("D2") + now.Day.ToString("D2") + "-" +
                              now.Hour.ToString("D2") + now.Minute.ToString("D2") + now.Second.ToString("D2") +
                              ".bin";
                using (FileStream fileStream = new FileStream(path, FileMode.CreateNew))
                {
                    byte[] serialData = e.Exception.SerializeObject();
                    using (BinaryWriter writer = new BinaryWriter(fileStream))
                    {
                        writer.Write(serialData);
                    }
                }
            }
            catch { }

            // Display the exception message
            DisplayExceptionDialog(e.Exception);

            // Remove employee table lock (that prevents simultaneous login)
            if (SessionManager.ActiveEmployee != null)
            {
                PosHelper.Unlock(TableName.Employee, SessionManager.ActiveEmployee.Id);
            }

            // Close this app
            if (_mainWindow != null)
            {
                _mainWindow.AllowClose = true;
                _mainWindow.Close();
            }

            // Disable user control crap
            if (ConfigurationManager.UseKeyboardHook)
            {
                UserControlManager.Disable();
            }

            UserControlManager.ShowTaskbar(true);
#if !DEBUG
            if (PastRestartPoint)
            {
                // Restart application
                Process.Start(Application.ResourceAssembly.Location, "/RESTART");
                App.SwitchToDefaultDesktopOnClose = false;
            }
            else
            {
                App.SwitchToDefaultDesktopOnClose = true;
            }
#else
            App.SwitchToDefaultDesktopOnClose = true;
#endif
            // Shutdown current application
            Application.Current.Shutdown();
            Process.GetCurrentProcess().Kill();
        }
Exemplo n.º 16
0
        public static void ApplyDatabasePatches()
        {
            string       patchName           = Strings.None;
            StoreSetting storeSetting        = SettingManager.GetStoreSetting("DatabasePatchVersion");
            int          currentPatchVersion = 0;

            if ((storeSetting != null) && storeSetting.IntValue.HasValue)
            {
                currentPatchVersion = storeSetting.IntValue.Value;
            }
            try
            {
                if (currentPatchVersion < 1)
                {
                    // Adds IngredientParQuantity to Ingredient table
                    patchName = "Patch #1";
                    ExecuteEmbeddedSqlScript("TemPOS.Resources.AddIngredientParQuantity.sql", true);
                    currentPatchVersion = 1;
                }

                if (currentPatchVersion < 2)
                {
                    // Flags database as trustworthy
                    patchName = "Patch #2";
                    DataModelBase.ExecuteNonQuery("ALTER DATABASE " +
                                                  LocalSetting.DatabaseServerDatabaseName + " SET TRUSTWORTHY ON" +
                                                  Environment.NewLine + "GO");
                    currentPatchVersion = 2;
                }

                if (currentPatchVersion < 3)
                {
                    // Adds TicketCouponPseudoEmployeeId, and TicketDiscountPseudoEmployeeId
                    // Removes TicketDiscountEmployeeId
                    patchName = "Patch #3";
                    ExecuteEmbeddedSqlScript("TemPOS.Resources.AddPseudoEmployeeId.sql");
                    currentPatchVersion = 3;
                }

                if (currentPatchVersion < 4)
                {
                    // Adds the ItemGroup table, and ItemIsGrouping and TicketItemParentTicketItemId fields
                    patchName = "Patch #4";
                    ExecuteEmbeddedSqlScript("TemPOS.Resources.AddItemGrouping-Part1.sql");
                    try
                    {
                        ExecuteEmbeddedSqlScript("TemPOS.Resources.AddItemGrouping-Part2.sql");
                    }
                    catch (SqlException ex)
                    {
                        if (ex.Message.Contains("identical to an assembly that is already registered"))
                        {
                            SqlConnection.ClearAllPools();
                        }
                    }
                    ExecuteEmbeddedSqlScript("TemPOS.Resources.AddItemGrouping-Part3.sql");
                    currentPatchVersion = 4;
                }

                if (currentPatchVersion < 5)
                {
                    // Adds TicketItemFireTime
                    patchName = "Patch #5";
                    ExecuteEmbeddedSqlScript("TemPOS.Resources.AddTicketItemFireTime.sql");
                    currentPatchVersion = 5;
                }

                if (currentPatchVersion < 6)
                {
                    // Adds TicketItemFireTime
                    patchName = "Patch #6";
                    ExecuteEmbeddedSqlScript("TemPOS.Resources.AddItemButtonImage.sql");
                    currentPatchVersion = 6;
                }
            }
            catch (Exception ex)
            {
                try
                {
                    SettingManager.SetStoreSetting("DatabasePatchVersion", currentPatchVersion);
                }
                catch (Exception)
                {
                }
                PosDialogWindow.ShowDialog(ex.Message, Types.Strings.DatabasePatchException + patchName);
                return;
            }
            SettingManager.SetStoreSetting("DatabasePatchVersion", currentPatchVersion);
        }