예제 #1
0
        public void TestExcelExportFile()
        {
            string filename = PathToTestData + "test.xlsx";

            // display error messages in english
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            using (ExcelPackage pck = new ExcelPackage())
            {
                ExcelWorksheet worksheet = pck.Workbook.Worksheets.Add("test");

                worksheet.Cells["A1"].Value = "test1";
                worksheet.Cells["B3"].Value = "test2";
                worksheet.Cells["B7"].Value = "test2";

                TLogging.Log("writing to " + filename);

                pck.SaveAs(new FileInfo(filename));
            }

            new ExcelPackage(new FileInfo(filename));
            PackTools.Unzip(PathToTestData + "testUnzip", filename);

            FileInfo f = new FileInfo(PathToTestData + "testUnzip/xl/sharedStrings.xml");

            Assert.AreNotEqual(0, f.Length, "file sharedStrings.xml should not be empty");

            Assert.IsInstanceOf(typeof(ExcelPackage), new ExcelPackage(new FileInfo(filename)), "cannot open excel file");
        }
예제 #2
0
        public void TestCompressingString()
        {
            string testText = "<test>blablablablabla</test>";

            string compressed = PackTools.ZipString(testText);

            Assert.AreEqual(testText, PackTools.UnzipString(compressed)[0], "compressing a string");
        }
예제 #3
0
        public void TestExcelExportFile()
        {
            string filename = PathToTestData + "test.xlsx";

            // display error messages in english
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            using (ExcelPackage pck = new ExcelPackage())
            {
                ExcelWorksheet worksheet = pck.Workbook.Worksheets.Add("test");

                worksheet.Cells["A1"].Value = "test1";
                worksheet.Cells["B3"].Value = "test2";
                worksheet.Cells["B7"].Value = "test2";

                TLogging.Log("writing to " + filename);

                pck.SaveAs(new FileInfo(filename));
            }

            // Set up an empty folder to unzip to
            string unzipRoot = PathToTestData + "testUnzip";

            if (Directory.Exists(unzipRoot))
            {
                // Something left over from last time??
                Directory.Delete(unzipRoot, true);
                Thread.Sleep(1000);
            }

            Directory.CreateDirectory(unzipRoot);

            // Unzip the Excel file
            new ExcelPackage(new FileInfo(filename));
            PackTools.Unzip(unzipRoot, filename);

            FileInfo f = new FileInfo(unzipRoot + "/xl/sharedStrings.xml");

            Assert.AreNotEqual(0, f.Length, "file sharedStrings.xml should not be empty");

            Assert.IsInstanceOf(typeof(ExcelPackage), new ExcelPackage(new FileInfo(filename)), "cannot open excel file");

            // Try to remove the folder that we unzipped to as part of clean-up
            Thread.Sleep(1000);
            try
            {
                Directory.Delete(unzipRoot, true);
            }
            catch (Exception)
            {
            }
            Thread.Sleep(500);
        }
예제 #4
0
    void start_recv_data()
    {
        if (this.is_Connect == false)
        {
            return;
        }

        while (true)
        {
            if (!this.client.Connected)
            {
                break;
            }

            try
            {
                Debug.Log("读取数据中...");
                int recv_len = 0;
                // small
                if (this.receved < RECV_LEN)
                {
                    recv_len = this.client.Receive(this.recv_buffer, this.receved, RECV_LEN - this.receved,
                                                   SocketFlags.None);
                }
                else
                {
                    if (this.long_pkg == null)
                    {
                        var out_header = new byte[PackTools.PACK_LENGTH];
                        Array.Copy(this.recv_buffer, out_header, out_header.Length);
                        ClientHeader header = PackTools.UnPackObject(out_header);
                        this.long_pkg_size = Convert.ToInt32(header.Length);
                        this.long_pkg      = new byte[header.Length];
                        //将上次的数据拷贝到这次的大包数组里
                        Array.Copy(this.recv_buffer, 0, this.long_pkg, 0, this.receved);
                    }

                    recv_len = this.client.Receive(this.recv_buffer, this.receved, RECV_LEN - this.receved,
                                                   SocketFlags.None);
                }

                if (recv_len > 0)
                {
                    this.receved += recv_len;
                    tcp_Func();
                }
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
                EventManager.Instance.Call("EVENT.NET.CLOSE", null);
                break;
            }
        }
    }
예제 #5
0
        /// <summary>
        /// create a patch file containing all differences between two versions of the software
        /// </summary>
        public static void CreateDiff(String ATmpDirectory, String ADeliveryDirectory,
                                      String AAppName,
                                      String AZipName,
                                      String oldPatch, String newPatch)
        {
            if (Directory.Exists(ATmpDirectory + Path.DirectorySeparatorChar + oldPatch))
            {
                // never reuse an unzipped tar file, because it might be from a different language
                Directory.Delete(ATmpDirectory + Path.DirectorySeparatorChar + oldPatch, true);
            }

            string OldTarFile = ADeliveryDirectory + Path.DirectorySeparatorChar +
                                AZipName + "-" + oldPatch + ".tar.gz";

            if (File.Exists(OldTarFile))
            {
                UnzipTarFile(ATmpDirectory + Path.DirectorySeparatorChar + oldPatch,
                             OldTarFile,
                             AAppName);
            }

            if (Directory.Exists(ATmpDirectory + Path.DirectorySeparatorChar + newPatch))
            {
                // never reuse an unzipped tar file, because we might have done two builds with the same build number.
                // then the patch file would be old
                Directory.Delete(ATmpDirectory + Path.DirectorySeparatorChar + newPatch, true);
            }

            UnzipTarFile(ATmpDirectory + Path.DirectorySeparatorChar + newPatch,
                         ADeliveryDirectory + Path.DirectorySeparatorChar + AZipName + "-" + newPatch + ".tar.gz",
                         AAppName);

            string DiffDirectory = ATmpDirectory + '/' + "Patch-win" + "_" + oldPatch + '_' + newPatch;

            // clear the diff directory
            PreparePatchTmpDirectory(DiffDirectory);
            Directory.CreateDirectory(DiffDirectory + Path.DirectorySeparatorChar + "openpetraorg-" + newPatch);

            CreateDiffFiles(ATmpDirectory,
                            DiffDirectory + Path.DirectorySeparatorChar + "openpetraorg-" + newPatch,
                            ATmpDirectory + Path.DirectorySeparatorChar + oldPatch + Path.DirectorySeparatorChar + "openpetraorg-" + oldPatch,
                            ATmpDirectory + Path.DirectorySeparatorChar + newPatch + Path.DirectorySeparatorChar + "openpetraorg-" + newPatch,
                            string.Empty);

            // put it all into a zip file
            string ZipFileName = TAppSettingsManager.GetValue("OutputZipFilename");

            PackTools.ZipDirectory(DiffDirectory, DiffDirectory + "/../" + ZipFileName);

            // copy that file to the delivery directory
            System.IO.File.Copy(DiffDirectory + "/../" + ZipFileName,
                                ADeliveryDirectory + Path.DirectorySeparatorChar + ZipFileName, true);
            TLogging.Log("Successfully created file " + ADeliveryDirectory + Path.DirectorySeparatorChar + ZipFileName);
        }
예제 #6
0
    void on_recv_tcp_cmd(byte[] tcp_data, int start, int data_len)
    {
        var out_header = new byte[PackTools.PACK_LENGTH];

        Array.Copy(tcp_data, out_header, out_header.Length);
        var header = PackTools.UnPackObject(out_header);

        var out_msg = new byte[data_len];

        Array.Copy(tcp_data, start, out_msg, 0, data_len);

        SMessage message = new SMessage(header, out_msg);

        this.readQueue.Enqueue(message);
    }
예제 #7
0
        public void TestExcelExportStream()
        {
            string filename = PathToTestData + "test.xlsx";

            // display error messages in english
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            // could also use: FileStream fs = new FileStream(filename, FileMode.Create)
            // but we want to prove here that it works with a MemoryStream, for delivering the files over the web
            using (StreamWriter sw = new StreamWriter(filename))
            {
                using (MemoryStream m = new MemoryStream())
                {
                    using (ExcelPackage pck = new ExcelPackage(m))
                    {
                        ExcelWorksheet worksheet = pck.Workbook.Worksheets.Add("test");

                        worksheet.Cells[1, 1].Value = "test1";
                        worksheet.Cells["B3"].Value = "test2";
                        worksheet.Cells["B7"].Value = "test2";

                        pck.SaveAs(m);
                    }

                    TLogging.Log("writing to " + filename);

                    m.WriteTo(sw.BaseStream);
                    m.Close();
                    sw.Close();
                }
            }

            PackTools.Unzip(PathToTestData + "testUnzip", filename);

            FileInfo f = new FileInfo(PathToTestData + "testUnzip/xl/sharedStrings.xml");

            Assert.AreNotEqual(0, f.Length, "file sharedStrings.xml should not be empty");

            // System.MethodAccessException : Attempt by security transparent method 'OfficeOpenXml.Utils.EncryptedPackageHandler.IsStorageFile(System.String)' to call native code
            // through method 'OfficeOpenXml.Utils.EncryptedPackageHandler.StgIsStorageFile(System.String)' failed.
            // Methods must be security critical or security safe-critical to call native code.
            //Assert.IsInstanceOf(typeof(ExcelPackage), new ExcelPackage(new FileInfo(filename)), "cannot open excel file");
        }
예제 #8
0
    public void start_send_data(ClientHeader header, byte[] body)
    {
        if (this.is_Connect == false)
        {
            return;
        }

        if (!this.client.Connected)
        {
            return;
        }

        var         data   = PackTools.PackObject(header);
        List <byte> buffer = new List <byte>(data);

        buffer.AddRange(body);
        this.sendQueue.Enqueue(buffer.ToArray());
    }
예제 #9
0
    void tcp_Func()
    {
        var tcp_data = this.long_pkg != null ? this.long_pkg : this.recv_buffer;


        while (this.receved > 0)
        {
            ClientHeader header;
            try
            {
                var out_header = new byte[PackTools.PACK_LENGTH];
                Array.Copy(tcp_data, out_header, out_header.Length);
                header = PackTools.UnPackObject(out_header);
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
                break;
            }

            if (this.receved < header.Length)
            {
                break;
            }

            int pkgSize        = Convert.ToInt32(header.Length);
            int raw_data_start = PackTools.PACK_LENGTH;
            int raw_data_len   = pkgSize - PackTools.PACK_LENGTH;
            this.on_recv_tcp_cmd(tcp_data, raw_data_start, raw_data_len);

            if (this.receved > pkgSize)
            {
                this.recv_buffer = new byte[RECV_LEN];
                Array.Copy(tcp_data, pkgSize, this.recv_buffer, 0, this.receved - pkgSize);
            }

            this.receved -= pkgSize;
            if (this.receved == 0 && this.long_pkg != null)
            {
                this.long_pkg      = null;
                this.long_pkg_size = 0;
            }
        }
    }
예제 #10
0
        private void _DrawBuild(IPhoneConfig config, BuildOptions options)
        {
            if (GUILayout.Button("Build iPhone", _buttonWidth))
            {
                if (string.IsNullOrEmpty(config.projectPath))
                {
                    EditorUtility.DisplayDialog("Warning", "Please choose a Project Location", "Ok");
                    return;
                }

                var projectPath = os.path.join(config.projectPath, "Unity-iPhone.xcodeproj");
                if (Directory.Exists(projectPath))
                {
                    var title   = "Warning";
                    var message = "Build folder already exists. Would you like to append or replace it?";
                    var option  = EditorUtility.DisplayDialogComplex(title, message, "Cancel", "Append", "Replace");

                    if (option == 0)
                    {
                        return;
                    }
                    else if (option == 1)
                    {
                        options |= BuildOptions.AcceptExternalModificationsToPlayer;
                    }
                }

                var error = BuildPipeline.BuildPlayer(_GetLevels(), config.projectPath, BuildTarget.iOS, options);
                if (!string.IsNullOrEmpty(error))
                {
                    Console.Error.WriteLine("BuildPipeline.BuildPlayer() error={0}", error);
                    return;
                }

                if (config.builtinResources)
                {
                    var rawFolder = os.path.join(config.projectPath, "Data/Raw");
                    var flags     = PackFlags.SearchAllDirectories;
                    PackTools.PackResourcesTo(rawFolder, flags);
                }

                os.startfile(projectPath, null, true);
            }
        }
예제 #11
0
        private static void UnzipTarFile(String ATmpDirectory, String AFileName, String AAppName)
        {
            string[] directories;
            PreparePatchTmpDirectory(ATmpDirectory);

            // openpetraorg-0.0.10-0.tar.gz -> openpetraorg-0.0.10-0\bin30 etc
            PackTools.ExtractTarGz(ATmpDirectory, AFileName);

            // remove version number from directory name...
            directories = System.IO.Directory.GetDirectories(ATmpDirectory);

            foreach (string dir in directories)
            {
                if (Path.GetFileName(dir).IndexOf(AAppName + "-") == 0)
                {
                    System.IO.Directory.Move(dir, dir.Substring(0, dir.Length - Path.GetFileName(dir).Length) + AAppName);
                }
            }
        }
예제 #12
0
        private Process _PackApkResoucesAndRepackApk()
        {
            var config         = _config.android;
            var apkPath        = config.apkPath;
            var apktoolPath    = config.apktoolPath;
            var unpackedFolder = apkPath.Substring(0, apkPath.Length - 4);

            var rawFolder = os.path.join(unpackedFolder, Constants.LocalApkDirectory);
            var flags     = PackFlags.SearchAllDirectories;

            PackTools.PackResourcesTo(rawFolder, flags, srcPath => srcPath.EndWithAnyEx(Constants.BuiltinFileExtensions));

            var process = new Process();
            var psi     = process.StartInfo;

            psi.FileName        = apktoolPath;
            psi.Arguments       = string.Format("b {0}", unpackedFolder);
            psi.UseShellExecute = true;

            process.Start();
            return(process);
        }
예제 #13
0
        public static bool ResetDatabase(string AZippedNewDatabaseData)
        {
            TDataBase DBConnectionObj = null;

            List <string>            tables               = TTableList.GetDBNames();
            bool                     SubmissionResult     = false;
            TDBTransaction           ReadWriteTransaction = new TDBTransaction();
            SortedList <int, string> CurrencyPerLedger    = new SortedList <int, string>();

            string ClientID = "ClientID";

            try
            {
                ClientID = DomainManager.GClientID.ToString();
            }
            catch (Exception)
            {
            }

            try
            {
                // Open a separate DB Connection for the importing of the data...
                DBConnectionObj = DBAccess.Connect("ExportAllTables");

                // ...and start a DB Transaction on that separate DB Connection
                DBConnectionObj.WriteTransaction(ref ReadWriteTransaction, ref SubmissionResult, delegate
                {
                    try
                    {
                        TProgressTracker.InitProgressTracker(ClientID,
                                                             Catalog.GetString("Restoring Database..."),
                                                             tables.Count + 3);

                        tables.Reverse();

                        // ignore s_session table, to avoid locking during the restore
                        tables.Remove("s_session");

                        TProgressTracker.SetCurrentState(ClientID,
                                                         Catalog.GetString("Deleting current data..."),
                                                         0);

                        // need to reset connection between s_user and p_partner to avoid broken foreign key
                        ReadWriteTransaction.DataBaseObj.ExecuteNonQuery("UPDATE pub_s_user SET p_partner_key_n = NULL", ReadWriteTransaction);

                        foreach (string table in tables)
                        {
                            ReadWriteTransaction.DataBaseObj.ExecuteNonQuery("DELETE FROM pub_" + table, ReadWriteTransaction);
                        }

                        if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(ClientID);

                            // As SubmissionResult is still false, a DB Transaction Rollback will get
                            // executed automatically and the Method will be exited with return value 'false'!
                            return;
                        }

                        TSimpleYmlParser ymlParser = new TSimpleYmlParser(PackTools.UnzipString(AZippedNewDatabaseData));

                        ymlParser.ParseCaptions();

                        tables.Reverse();

                        TProgressTracker.SetCurrentState(ClientID,
                                                         Catalog.GetString("Loading initial tables..."),
                                                         1);

                        // one transaction to import the user table and user permissions. otherwise logging in will not be possible if other import fails?
                        bool success = true;
                        success      = success && LoadTable("s_user", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger);
                        success      = success && LoadTable("s_module", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger);
                        success      = success && LoadTable("s_user_module_access_permission", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger);
                        success      = success && LoadTable("s_system_defaults", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger);
                        success      = success && LoadTable("s_system_status", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger);

                        if (!success)
                        {
                            // As SubmissionResult is still TSubmitChangesResult.scrError, a DB Transaction Rollback will get
                            // executed automatically and the Method will be exited with return value 'false'!
                            return;
                        }

                        if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(ClientID);

                            // As SubmissionResult is still false, a DB Transaction Rollback will get
                            // executed automatically and the Method will be exited with return value 'false'!
                            return;
                        }

                        tables.Remove("s_user");
                        tables.Remove("s_module");
                        tables.Remove("s_user_module_access_permission");
                        tables.Remove("s_system_defaults");
                        tables.Remove("s_system_status");

                        int tableCounter = 2;

                        foreach (string table in tables)
                        {
                            TProgressTracker.SetCurrentState(ClientID,
                                                             String.Format(Catalog.GetString("Loading Table {0}..."), table),
                                                             tableCounter);

                            tableCounter++;

                            if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                            {
                                TProgressTracker.FinishJob(ClientID);

                                // As SubmissionResult is still false, a DB Transaction Rollback will get
                                // executed automatically and the Method will be exited with return value 'false'!
                                return;
                            }

                            LoadTable(table, ymlParser, ReadWriteTransaction, ref CurrencyPerLedger);
                        }

                        TProgressTracker.SetCurrentState(ClientID,
                                                         Catalog.GetString("Loading Sequences..."),
                                                         tables.Count + 5 + 3);

                        // set sequences appropriately, not lagging behind the imported data
                        foreach (string seq in TTableList.GetDBSequenceNames())
                        {
                            LoadSequence(seq, ymlParser, ReadWriteTransaction);
                        }

                        TProgressTracker.SetCurrentState(ClientID,
                                                         Catalog.GetString("Finishing Restore..."),
                                                         tables.Count + 5 + 4);

                        SubmissionResult = true;

                        // reset all cached tables
                        TCacheableTablesManager.GCacheableTablesManager.MarkAllCachedTableNeedsRefreshing();
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("Problem in ResetDatabase: " + e.ToString());
                        TLogging.LogStackTrace(TLoggingType.ToLogfile);

                        throw;
                    }
                });
            }
            finally
            {
                if (DBConnectionObj != null)
                {
                    DBConnectionObj.CloseDBConnection();
                }
            }

            // if we import an older database, we need to upgrade it.
            // this happens in a separate database connection and database transactions.
            TProgressTracker.SetCurrentState(ClientID,
                                             Catalog.GetString("Updating the database..."),
                                             tables.Count + 5 + 5);

            TDBUpgrades upgrades = new TDBUpgrades();

            upgrades.UpgradeDatabase();

            TProgressTracker.FinishJob(ClientID);

            return(SubmissionResult);
        }
예제 #14
0
        private Boolean ApplyPetraPatch(String APatchFile)
        {
            Boolean ReturnValue;
            String  TempPath;

            string[] directories;
            String[] files;
            ReturnValue = false;
            TLogging.Log("installing patch " + APatchFile);

            // create temp directory
            TempPath = Path.GetFullPath(Path.GetTempPath() + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(APatchFile));

            if (Directory.Exists(TempPath))
            {
                //  remove old temp directory: for testing patches, otherwise we are using the old version
                Directory.Delete(TempPath, true);
            }

            Directory.CreateDirectory(TempPath);

            // extract the tar patch file into the temp directory
            PackTools.Unzip(TempPath, APatchFile);

            // make sure that PetraClient has been stopped
            if (PatchApplication.ProcessStillRunning(FBinPath + Path.DirectorySeparatorChar + "PetraClient.exe"))
            {
                TLogging.Log("Wait for PetraClient to stop...");

                while (PatchApplication.ProcessStillRunning(FBinPath + Path.DirectorySeparatorChar + "PetraClient.exe"))
                {
                    TLogging.Log("Wait for PetraClient to stop...");
                }
            }

            try
            {
                // apply the patch
                TLogging.Log("applying patch, please wait");

                // go through all directories in patch, all files
                directories = System.IO.Directory.GetDirectories(TempPath);

                foreach (string dir in directories)
                {
                    ApplyPatchRecursively(TempPath, dir);
                }

                // rename the manually patched .dll and .exe files in net-patches directory,
                // since they should be part of the official patch in bin directory

                // go through bin/netpatches (or sapatches or remotepatches)
                directories = System.IO.Directory.GetDirectories(FBinPath, "*patches");

                foreach (string dir in directories)
                {
                    // delete the file.old if it already exists, if there is a file without .old
                    // that way we prevent the deletion of nrr (non routine request) files that have gone to the wrong directory
                    files = System.IO.Directory.GetFiles(dir, "*.old");

                    foreach (string filename in files)
                    {
                        if (System.IO.File.Exists(filename.Substring(0, filename.Length - 4)))
                        {
                            System.IO.File.Delete(filename);
                        }
                        else
                        {
                            // restore the .dll file (nrr)
                            System.IO.File.Move(filename, filename.Substring(0, filename.Length - 4));
                        }
                    }

                    // rename .dll file to file.dll.old
                    files = System.IO.Directory.GetFiles(directories[0], "*.dll");

                    foreach (string filename in files)
                    {
                        System.IO.File.Move(filename, filename + ".old");
                    }

                    // rename .exe file to file.exe.old
                    files = System.IO.Directory.GetFiles(directories[0], "*.exe");

                    foreach (string filename in files)
                    {
                        System.IO.File.Move(filename, filename + ".old");
                    }
                }

                // delete the .dll.orig files, because we have applied the new version for all files
                // those files have been created manually when we give out special dll files (not recommended)
                files = System.IO.Directory.GetFiles(FBinPath, "*.orig");

                foreach (string filename in files)
                {
                    if (System.IO.File.Exists(filename.Substring(0, filename.Length - 5)))
                    {
                        System.IO.File.Delete(filename);
                    }
                }

                TLogging.Log("Patch " + APatchFile + " has been applied successfully!");
                ReturnValue = true;
            }
            catch (Exception e)
            {
                TLogging.Log("Patch could not be installed: " + e.Message);
                TLogging.Log(e.ToString());
                TLogging.Log(e.StackTrace);
                TLogging.Log("Restoring the situation before the patch...");

                // if unsuccessful, restore the previous situation;
                // go through all directories in patch, all files
                directories = System.IO.Directory.GetDirectories(TempPath);

                foreach (string dir in directories)
                {
                    UndoPatchRecursively(TempPath, dir);
                }

                TLogging.Log("Please contact your IT support and send the file " + TLogWriter.GetLogFileName());
            }

            // clean up the safety backup files of the patch
            directories = System.IO.Directory.GetDirectories(TempPath);

            foreach (string dir in directories)
            {
                CleanupPatchRecursively(TempPath, dir);
            }

            // delete temp directory recursively (and the backup zip files)
            Directory.Delete(TempPath, true);
            return(ReturnValue);
        }
예제 #15
0
        public static bool ResetDatabase(string AZippedNewDatabaseData)
        {
            List <string> tables = TTableList.GetDBNames();

            TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Importing database"),
                                                 tables.Count + 3);

            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                tables.Reverse();

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("deleting current data"),
                                                 0);

                foreach (string table in tables)
                {
                    DBAccess.GDBAccessObj.ExecuteNonQuery("DELETE FROM pub_" + table, Transaction);
                }

                if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                {
                    TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    return(false);
                }

                TSimpleYmlParser ymlParser = new TSimpleYmlParser(PackTools.UnzipString(AZippedNewDatabaseData));

                ymlParser.ParseCaptions();

                tables.Reverse();

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("loading initial tables"),
                                                 1);

                // one transaction to import the user table and user permissions. otherwise logging in will not be possible if other import fails?
                bool success = true;
                success = success && LoadTable("s_user", ymlParser, Transaction);
                success = success && LoadTable("s_module", ymlParser, Transaction);
                success = success && LoadTable("s_user_module_access_permission", ymlParser, Transaction);
                success = success && LoadTable("s_system_defaults", ymlParser, Transaction);
                success = success && LoadTable("s_system_status", ymlParser, Transaction);

                // make sure we have the correct database version
                TFileVersionInfo serverExeInfo = new TFileVersionInfo(TSrvSetting.ApplicationVersion);
                DBAccess.GDBAccessObj.ExecuteNonQuery(String.Format(
                                                          "UPDATE PUB_s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion'",
                                                          serverExeInfo.ToString()), Transaction);

                if (!success)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    return(false);
                }

                if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                {
                    TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    return(false);
                }

                DBAccess.GDBAccessObj.CommitTransaction();

                tables.Remove("s_user");
                tables.Remove("s_module");
                tables.Remove("s_user_module_access_permission");
                tables.Remove("s_system_defaults");
                tables.Remove("s_system_status");

                FCurrencyPerLedger = new SortedList <int, string>();

                Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

                int tableCounter = 2;

                foreach (string table in tables)
                {
                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     String.Format(Catalog.GetString("loading table {0}"), table),
                                                     tableCounter);

                    tableCounter++;

                    if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                        DBAccess.GDBAccessObj.RollbackTransaction();
                        return(false);
                    }

                    LoadTable(table, ymlParser, Transaction);
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("loading sequences"),
                                                 tables.Count + 5 + 3);

                // set sequences appropriately, not lagging behind the imported data
                foreach (string seq in TTableList.GetDBSequenceNames())
                {
                    LoadSequence(seq, ymlParser, Transaction);
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("finish import"),
                                                 tables.Count + 5 + 4);

                DBAccess.GDBAccessObj.CommitTransaction();

                // reset all cached tables
                TCacheableTablesManager.GCacheableTablesManager.MarkAllCachedTableNeedsRefreshing();

                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
            }
            catch (Exception e)
            {
                TLogging.Log("Problem in ResetDatabase: " + e.Message);
                TLogging.Log(e.StackTrace);
                DBAccess.GDBAccessObj.RollbackTransaction();
                return(false);
            }

            return(true);
        }
예제 #16
0
        public static bool ResetDatabase(string AZippedNewDatabaseData)
        {
            List <string>  tables           = TTableList.GetDBNames();
            bool           SubmissionResult = false;
            TDBTransaction Transaction      = null;

            string ClientID = "ClientID";

            try
            {
                ClientID = DomainManager.GClientID.ToString();
            }
            catch (Exception)
            {
            }

            TProgressTracker.InitProgressTracker(ClientID,
                                                 Catalog.GetString("Restoring Database..."),
                                                 tables.Count + 3);

            DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref Transaction,
                                                       ref SubmissionResult,
                                                       delegate
            {
                try
                {
                    tables.Reverse();

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Deleting current data..."),
                                                     0);

                    foreach (string table in tables)
                    {
                        DBAccess.GDBAccessObj.ExecuteNonQuery("DELETE FROM pub_" + table, Transaction);
                    }

                    if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(ClientID);

                        // As SubmissionResult is still false, a DB Transaction Rollback will get
                        // executed automatically and the Method will be exited with return value 'false'!
                        return;
                    }

                    TSimpleYmlParser ymlParser = new TSimpleYmlParser(PackTools.UnzipString(AZippedNewDatabaseData));

                    ymlParser.ParseCaptions();

                    tables.Reverse();

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Loading initial tables..."),
                                                     1);

                    // one transaction to import the user table and user permissions. otherwise logging in will not be possible if other import fails?
                    bool success = true;
                    success      = success && LoadTable("s_user", ymlParser, Transaction);
                    success      = success && LoadTable("s_module", ymlParser, Transaction);
                    success      = success && LoadTable("s_user_module_access_permission", ymlParser, Transaction);
                    success      = success && LoadTable("s_system_defaults", ymlParser, Transaction);
                    success      = success && LoadTable("s_system_status", ymlParser, Transaction);

                    // make sure we have the correct database version
                    TFileVersionInfo serverExeInfo = new TFileVersionInfo(TSrvSetting.ApplicationVersion);
                    DBAccess.GDBAccessObj.ExecuteNonQuery(String.Format(
                                                              "UPDATE PUB_s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion'",
                                                              serverExeInfo.ToString()), Transaction);

                    if (!success)
                    {
                        // As SubmissionResult is still TSubmitChangesResult.scrError, a DB Transaction Rollback will get
                        // executed automatically and the Method will be exited with return value 'false'!
                        return;
                    }

                    if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(ClientID);

                        // As SubmissionResult is still false, a DB Transaction Rollback will get
                        // executed automatically and the Method will be exited with return value 'false'!
                        return;
                    }

                    tables.Remove("s_user");
                    tables.Remove("s_module");
                    tables.Remove("s_user_module_access_permission");
                    tables.Remove("s_system_defaults");
                    tables.Remove("s_system_status");

                    FCurrencyPerLedger = new SortedList <int, string>();

                    int tableCounter = 2;

                    foreach (string table in tables)
                    {
                        TProgressTracker.SetCurrentState(ClientID,
                                                         String.Format(Catalog.GetString("Loading Table {0}..."), table),
                                                         tableCounter);

                        tableCounter++;

                        if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(ClientID);

                            // As SubmissionResult is still false, a DB Transaction Rollback will get
                            // executed automatically and the Method will be exited with return value 'false'!
                            return;
                        }

                        LoadTable(table, ymlParser, Transaction);
                    }

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Loading Sequences..."),
                                                     tables.Count + 5 + 3);

                    // set sequences appropriately, not lagging behind the imported data
                    foreach (string seq in TTableList.GetDBSequenceNames())
                    {
                        LoadSequence(seq, ymlParser, Transaction);
                    }

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Finishing Restore..."),
                                                     tables.Count + 5 + 4);

                    SubmissionResult = true;

                    // reset all cached tables
                    TCacheableTablesManager.GCacheableTablesManager.MarkAllCachedTableNeedsRefreshing();

                    TProgressTracker.FinishJob(ClientID);
                }
                catch (Exception e)
                {
                    TLogging.Log("Problem in ResetDatabase: " + e.ToString());
                    TLogging.LogStackTrace(TLoggingType.ToLogfile);

                    throw;
                }
            });

            return(SubmissionResult);
        }
예제 #17
0
파일: test.cs 프로젝트: weiplanet/openpetra
        public void TestExcelExportFile()
        {
            string filename = PathToTestData + "test.xlsx";

            // display error messages in english
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            using (FileStream sw = File.Create(filename))
            {
                XSSFWorkbook workbook  = new XSSFWorkbook();
                ISheet       worksheet = workbook.CreateSheet("test");

                IRow  wsrow  = null;
                ICell wscell = null;

                wsrow  = worksheet.CreateRow(1);
                wscell = wsrow.CreateCell(1);
                wscell.SetCellValue("test1");
                wsrow  = worksheet.CreateRow(3);
                wscell = wsrow.CreateCell(2);
                wscell.SetCellValue("test2");
                wsrow  = worksheet.CreateRow(7);
                wscell = wsrow.CreateCell(2);
                wscell.SetCellValue("test2");

                TLogging.Log("writing to " + filename);
                workbook.Write(sw);
                sw.Close();
            }

            // can we read the file?
            using (var stream = new FileStream(filename, FileMode.Open))
            {
                stream.Position = 0;
                Assert.IsInstanceOf(typeof(XSSFWorkbook), new XSSFWorkbook(stream), "cannot open excel file");
            }

            // can we read the file?
            using (var stream = new FileStream(filename, FileMode.Open))
            {
                stream.Position = 0;
                XSSFWorkbook workbook  = new XSSFWorkbook(stream);
                ISheet       worksheet = workbook[0];
                Assert.AreEqual("test", worksheet.SheetName, "get the first worksheet");
                IRow  row  = worksheet.GetRow(1);
                ICell cell = row.GetCell(1);
                Assert.AreEqual("test1", cell.ToString(), "get the cell value");
                //Assert.IsInstanceOf(typeof(XSSFWorkbook), new XSSFWorkbook(stream), "cannot open excel file");
            }

            // Set up an empty folder to unzip to
            string unzipRoot = PathToTestData + "testUnzip";

            if (Directory.Exists(unzipRoot))
            {
                // Something left over from last time??
                Directory.Delete(unzipRoot, true);
                Thread.Sleep(1000);
            }

            Directory.CreateDirectory(unzipRoot);

            // Unzip the Excel file
            PackTools.Unzip(unzipRoot, filename);

            FileInfo f = new FileInfo(unzipRoot + "/xl/sharedStrings.xml");

            Assert.AreNotEqual(0, f.Length, "file sharedStrings.xml should not be empty");

            // Try to remove the folder that we unzipped to as part of clean-up
            Thread.Sleep(1000);
            try
            {
                Directory.Delete(unzipRoot, true);
            }
            catch (Exception)
            {
            }
            Thread.Sleep(500);
        }