Пример #1
0
        /// <summary>
        /// Save a custom .ckan file that contains all the currently
        /// installed mods as dependencies.
        /// </summary>
        /// <param name="path">Desired location of file</param>
        /// <param name="recommends">True to save the mods as recommended, false for depends</param>
        /// <param name="with_versions">True to include the mod versions in the file, false to omit them</param>
        public void ExportInstalled(string path, bool recommends, bool with_versions)
        {
            TxFileManager file_transaction = new TxFileManager();

            string serialized = SerializeCurrentInstall(recommends, with_versions);
            file_transaction.WriteAllText(path, serialized);
        }
Пример #2
0
        public void Save(bool enforce_consistency = true)
        {
            log.InfoFormat("Saving CKAN registry at {0}", path);

            if (enforce_consistency)
            {
                // No saving the registry unless it's in a sane state.
                registry.CheckSanity();
            }

            string directoryPath = Path.GetDirectoryName(path);

            if (directoryPath == null)
            {
                log.ErrorFormat("Failed to save registry, invalid path: {0}", path);
                throw new DirectoryNotFoundKraken(path, "Can't find a directory in " + path);
            }

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            file_transaction.WriteAllText(path, Serialize());

            ExportInstalled(
                Path.Combine(directoryPath, $"installed-{ksp.Name}.ckan"),
                false, true
                );
            if (!Directory.Exists(ksp.InstallHistoryDir()))
            {
                Directory.CreateDirectory(ksp.InstallHistoryDir());
            }
            ExportInstalled(
                Path.Combine(
                    ksp.InstallHistoryDir(),
                    $"installed-{ksp.Name}-{DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")}.ckan"
                    ),
                false, true
                );
        }
        public virtual int SaveChanges()
        {
            //Assembly asm= Assembly.GetExecutingAssembly();
            var props = this.GetType().GetProperties();//.All(p => p.MemberType.GetType() == typeof(FileSet<Object>));

            foreach (var prop in props)
            {
                var propType = prop.PropertyType;
                if (propType.GenericTypeArguments.Length == 0)
                {
                    continue;
                }
                var attribute = prop.GetCustomAttribute <FileSetUsePrefixPathAttribute>();
                var gen_type  = propType.GenericTypeArguments[0];
                var ret_type  = gen_type.GetType();
                if (ret_type.IsInstanceOfType(typeof(IFileSet)))
                {
                    var    prefix   = attribute == null ? null : this.PrefixPath;
                    string filename = store.GetFileName(gen_type, prefix);
                    if (!string.IsNullOrEmpty(filename))
                    {
                        object o = prop.GetValue(this);
                        //string contents = XmlHelper.SerializeObject(o, prop.PropertyType);
                        string        contents = store.Save(o, prop.PropertyType);
                        TxFileManager fileMgr  = new TxFileManager();
                        using (TransactionScope scope1 = new TransactionScope())
                        {
                            fileMgr.WriteAllText(filename, contents);
                            scope1.Complete();
                        }
                    }
                    else if (string.IsNullOrEmpty(filename))
                    {
                        object o = prop.GetValue(this);
                        store.Save(o, prop.PropertyType);

                        var deletedList = o.GetType().GetProperty("LocalDeleted").GetValue(o);
                        store.ToDelete(deletedList, prop.PropertyType);

                        var updatedList = o.GetType().GetProperty("LocalUpdated").GetValue(o);
                        store.ToUpdate(updatedList, prop.PropertyType);
                    }
                }
            }

            return(0);
        }
Пример #4
0
        public void Save(bool enforce_consistency = true)
        {
            TxFileManager file_transaction = new TxFileManager();

            log.InfoFormat("Saving CKAN registry at {0}", path);

            if (enforce_consistency)
            {
                // No saving the registry unless it's in a sane state.
                registry.CheckSanity();
            }

            string directoryPath = Path.GetDirectoryName(path);

            if (directoryPath == null)
            {
                log.ErrorFormat("Failed to save registry, invalid path: {0}", path);
                throw new DirectoryNotFoundKraken(path, "Can't find a directory in " + path);
            }

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            file_transaction.WriteAllText(path, Serialize());

            ExportInstalled(
                Path.Combine(directoryPath, LatestInstalledExportFilename()),
                false, true
                );
            if (!Directory.Exists(ksp.InstallHistoryDir()))
            {
                Directory.CreateDirectory(ksp.InstallHistoryDir());
            }
            ExportInstalled(
                Path.Combine(ksp.InstallHistoryDir(), HistoricInstalledExportFilename()),
                false, true
                );
        }
Пример #5
0
        public void Save()
        {
            log.DebugFormat("Saving CKAN registry at {0}", path);

            // No saving the registry unless it's in a sane state.
            registry.CheckSanity();

            string directoryPath = Path.GetDirectoryName(path);

            if (directoryPath == null)
            {
                log.ErrorFormat("Failed to save registry, invalid path: {0}", path);
                throw new DirectoryNotFoundKraken(path, "Can't find a directory in " + path);
            }

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            file_transaction.WriteAllText(path, Serialize());
        }
Пример #6
0
        /// <summary>
        /// Create a new fake KSP instance
        /// </summary>
        /// <param name="game">The game of the new instance.</param>
        /// <param name="newName">The name for the new instance.</param>
        /// <param name="newPath">The location of the new instance.</param>
        /// <param name="version">The version of the new instance. Should have a build number.</param>
        /// <param name="dlcs">The IDlcDetector implementations for the DLCs that should be faked and the requested dlc version as a dictionary.</param>
        /// <exception cref="InstanceNameTakenKraken">Thrown if the instance name is already in use.</exception>
        /// <exception cref="NotKSPDirKraken">Thrown by AddInstance() if created instance is not valid, e.g. if a write operation didn't complete for whatever reason.</exception>
        public void FakeInstance(IGame game, string newName, string newPath, GameVersion version, Dictionary <DLC.IDlcDetector, GameVersion> dlcs = null)
        {
            TxFileManager fileMgr = new TxFileManager();

            using (TransactionScope transaction = CkanTransaction.CreateTransactionScope())
            {
                if (HasInstance(newName))
                {
                    throw new InstanceNameTakenKraken(newName);
                }


                if (!version.InBuildMap(game))
                {
                    throw new BadGameVersionKraken(String.Format("The specified KSP version is not a known version: {0}", version.ToString()));
                }
                if (Directory.Exists(newPath) && (Directory.GetFiles(newPath).Length != 0 || Directory.GetDirectories(newPath).Length != 0))
                {
                    throw new BadInstallLocationKraken("The specified folder already exists and is not empty.");
                }

                log.DebugFormat("Creating folder structure and text files at {0} for KSP version {1}", Path.GetFullPath(newPath), version.ToString());

                // Create a KSP root directory, containing a GameData folder, a buildID.txt/buildID64.txt and a readme.txt
                fileMgr.CreateDirectory(newPath);
                fileMgr.CreateDirectory(Path.Combine(newPath, "GameData"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "Ships"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "VAB"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "SPH"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "@thumbs"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "@thumbs", "VAB"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "@thumbs", "SPH"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "saves"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "saves", "scenarios"));
                fileMgr.CreateDirectory(Path.Combine(newPath, "saves", "training"));

                // Don't write the buildID.txts if we have no build, otherwise it would be -1.
                if (version.IsBuildDefined)
                {
                    fileMgr.WriteAllText(Path.Combine(newPath, "buildID.txt"), String.Format("build id = {0}", version.Build));
                    fileMgr.WriteAllText(Path.Combine(newPath, "buildID64.txt"), String.Format("build id = {0}", version.Build));
                }

                // Create the readme.txt WITHOUT build number.
                fileMgr.WriteAllText(Path.Combine(newPath, "readme.txt"), String.Format("Version {0}", new GameVersion(version.Major, version.Minor, version.Patch).ToString()));

                // Create the needed folder structure and the readme.txt for DLCs that should be simulated.
                if (dlcs != null)
                {
                    foreach (KeyValuePair <DLC.IDlcDetector, GameVersion> dlc in dlcs)
                    {
                        DLC.IDlcDetector dlcDetector = dlc.Key;
                        GameVersion      dlcVersion  = dlc.Value;

                        if (!dlcDetector.AllowedOnBaseVersion(version))
                        {
                            throw new WrongGameVersionKraken(
                                      version,
                                      String.Format("KSP version {0} or above is needed for {1} DLC.",
                                                    dlcDetector.ReleaseGameVersion,
                                                    dlcDetector.IdentifierBaseName
                                                    ));
                        }

                        string dlcDir = Path.Combine(newPath, dlcDetector.InstallPath());
                        fileMgr.CreateDirectory(dlcDir);
                        fileMgr.WriteAllText(
                            Path.Combine(dlcDir, "readme.txt"),
                            String.Format("Version {0}", dlcVersion));
                    }
                }

                // Add the new instance to the config
                GameInstance new_instance = new GameInstance(game, newPath, newName, User, false);
                AddInstance(new_instance);
                transaction.Complete();
            }
        }
Пример #7
0
        static void RunStressTest()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            {
                // Pre-test checks
                string       tempDir;
                IFileManager fm = new TxFileManager();
                using (TransactionScope s1 = new TransactionScope())
                {
                    tempDir = (new DirectoryInfo(fm.CreateTempDirectory())).Parent.FullName;
                    Console.WriteLine("Temp path: " + tempDir);
                }

                string[] directories = Directory.GetDirectories(tempDir);
                string[] files       = Directory.GetFiles(tempDir);
                if (directories.Length > 0 || files.Length > 0)
                {
                    Console.WriteLine(string.Format("ERROR  Please ensure temp path {0} has no children before running this test.", tempDir));
                    return;
                }
            }

            // Start each test in its own thread and repeat for a few interations
            const int    numThreads = 10;
            const int    iterations = 250;
            const string text       = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

            long count = 0;

            IList <Thread> threads = new List <Thread>();

            for (int i = 0; i < numThreads; i++)
            {
                Thread t = new Thread(() =>
                {
                    IFileManager fm = new TxFileManager();
                    for (int j = 0; j < iterations; j++)
                    {
                        using (TransactionScope s1 = new TransactionScope())
                        {
                            TransactionOptions to = new TransactionOptions();
                            to.Timeout            = TimeSpan.FromMinutes(30);

                            long myCount = Interlocked.Increment(ref count);
                            if (myCount % 250 == 0)
                            {
                                Console.WriteLine(myCount + " (" + myCount * 100 / (numThreads * iterations) + " %)");
                            }

                            string f1 = fm.CreateTempFileName();
                            string f2 = fm.CreateTempFileName();
                            string d1 = fm.CreateTempDirectory();

                            if (i % 100 == 0)
                            {
                                Console.WriteLine(i);
                            }

                            fm.AppendAllText(f1, text);
                            fm.Copy(f1, f2, false);

                            fm.CreateDirectory(d1);
                            fm.Delete(f2);
                            fm.DeleteDirectory(d1);
                            bool b1   = fm.DirectoryExists(d1);
                            bool b2   = fm.FileExists(f1);
                            string f3 = fm.CreateTempFileName();
                            fm.Move(f1, f3);
                            string f4 = fm.CreateTempFileName();
                            fm.Snapshot(f4);
                            fm.WriteAllBytes(f4, new byte[] { 64, 65 });
                            string f5 = fm.CreateTempFileName();
                            fm.WriteAllText(f5, text);

                            fm.Delete(f1);
                            fm.Delete(f2);
                            fm.Delete(f3);
                            fm.Delete(f4);
                            fm.Delete(f5);
                            fm.DeleteDirectory(d1);
                            s1.Complete();
                        }
                    }
                });

                threads.Add(t);
            }

            foreach (Thread t in threads)
            {
                t.Start();
            }

            Console.WriteLine("All threads started.");

            foreach (Thread t in threads)
            {
                t.Join();
            }

            sw.Stop();

            Console.WriteLine("All threads joined. Elapsed: {0}.", sw.ElapsedMilliseconds);
        }