Esempio n. 1
0
 public void IntroScreensCreator_Dispose(object sender, EventArgs e)
 {
     if (Directory.Exists(tmpWorkDir))
     {
         DirectoryExtension.SafeDelete(tmpWorkDir);
     }
 }
        private static List <Tone2014> ReadFromPackage(string packagePath, Platform platform)
        {
            if (packagePath.ToLowerInvariant().EndsWith("_prfldb") || packagePath.ToLowerInvariant().EndsWith("_profile"))
            {
                return(ReadFromProfile(packagePath));
            }
            else
            {
                var    tones  = new List <Tone2014>();
                string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string tmpDir = Path.Combine(appDir, String.Format("{0}_{1}", Path.GetFileNameWithoutExtension(packagePath), platform.platform));

                Packer.Unpack(packagePath, appDir);

                var toneManifestFiles = Directory.EnumerateFiles(tmpDir, "*.json", SearchOption.AllDirectories);
                foreach (var file in toneManifestFiles)
                {
                    foreach (Tone2014 tone in ReadFromManifest(file))
                    {
                        if (tones.All(a => a.Name != tone.Name))
                        {
                            tones.Add(tone);
                        }
                    }
                }

                DirectoryExtension.SafeDelete(tmpDir);

                return(tones);
            }
        }
        /// <summary>
        /// Converts CDLC packages between platforms
        /// </summary>
        /// <param name="sourcePackage"></param>
        /// <param name="sourcePlatform"></param>
        /// <param name="targetPlatform"></param>
        /// <param name="appId"></param>
        /// <returns>Errors if any</returns>
        public static string Convert(string sourcePackage, Platform sourcePlatform, Platform targetPlatform, string appId)
        {
            var needRebuildPackage = sourcePlatform.IsConsole != targetPlatform.IsConsole;
            var tmpDir             = Path.GetTempPath();

            var unpackedDir = Packer.Unpack(sourcePackage, tmpDir, false, true, false, sourcePlatform);

            // DESTINATION
            var nameTemplate = (!targetPlatform.IsConsole) ? "{0}{1}.psarc" : "{0}{1}";
            var packageName  = Path.GetFileNameWithoutExtension(sourcePackage).StripPlatformEndName();

            packageName = packageName.Replace(".", "_");
            var targetFileName = String.Format(nameTemplate, Path.Combine(Path.GetDirectoryName(sourcePackage), packageName), targetPlatform.GetPathName()[2]);

            // CONVERSION
            if (needRebuildPackage)
            {
                ConvertPackageRebuilding(unpackedDir, targetFileName, sourcePlatform, targetPlatform, appId);
            }
            else
            {
                ConvertPackageForSimilarPlatform(unpackedDir, targetFileName, sourcePlatform, targetPlatform, appId);
            }

            DirectoryExtension.SafeDelete(unpackedDir);

            return(String.Empty);
        }
        public static string GetFileNameFromProcess(Process process)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }
            if (process.HasExited)
            {
                throw new InvalidOperationException(nameof(process));
            }

            var fileName = DirectoryExtension.GetMainModuleFileName(process);

            var sb = Pool.Get <StringBuilder>();

            try
            {
                var logTxt = sb.Clear().Append(nameof(GetFileNameFromProcess)).Append(" returned: ").Append(fileName).ToString();
                Console.WriteLine(logTxt);
                Log.WriteLine(logTxt);
            }
            finally { Pool.Free(ref sb); }

            return(fileName);
        }
Esempio n. 5
0
        private void Window_Activated(object sender, EventArgs e)
        {
            FileWatcher_ToUpdate = Enumerable.ToList(Enumerable.Distinct(FileWatcher_ToUpdate));
            if (FileWatcher_ToUpdate.Count == 0 || FileWatcher_Updating)
            {
                return;
            }
            string str1 = "Following files has changed:\n";

            foreach (RDAFile rdaFile in FileWatcher_ToUpdate)
            {
                str1 = str1 + rdaFile.FileName + "\n";
            }
            string Message = str1 + "\nDo you want to update the RDA File Items?";

            FileWatcher_Updating = true;
            if (MessageWindow.Show(Message, MessageWindow.MessageWindowType.YesNo) == MessageBoxResult.Yes)
            {
                foreach (RDAFile rdaFile in FileWatcher_ToUpdate)
                {
                    string str2 = DirectoryExtension.GetTempWorkingDirectory() + "\\" + rdaFile.FileName;
                    string str3 = StringExtension.MakeUnique(Path.ChangeExtension(str2, null) + "$", Path.GetExtension(str2), (d => File.Exists(d)));
                    File.Copy(str2, str3);
                    rdaFile.SetFile(str3);
                }
            }
            FileWatcher_Updating = false;
            FileWatcher_ToUpdate.Clear();
        }
        public async Task ReceiveMessageShouldGetContactFromDirectoryWhenNotInContacts()
        {
            // Arrange
            var message  = Dummy.CreateMessage();
            var identity = message.From.ToIdentity();
            var account  = Dummy.CreateAccount();

            account.Identity = identity;
            DirectoryExtension
            .GetDirectoryAccountAsync(identity, Arg.Any <CancellationToken>())
            .Returns(account);

            var target = GetTarget();

            // Act
            await target.ReceiveAsync(message, CancellationToken);

            // Assert
            target.ReceivedItems.Count.ShouldBe(1);
            target.ReceivedItems[0].message.ShouldBe(message);
            var actualContact = target.ReceivedItems[0].contact;

            actualContact.ShouldNotBeNull();
            actualContact.Name.ShouldBe(account.FullName);

            foreach (var property in typeof(ContactDocument).GetProperties())
            {
                property
                .GetValue(actualContact)
                .ShouldBe(
                    property.GetValue(account));
            }
        }
Esempio n. 7
0
        private static List <Tone2014> ReadFromPackage(string packagePath, Platform platform)
        {
            if (packagePath.EndsWith("_prfldb") || packagePath.EndsWith("_profile"))
            {
                return(ReadFromProfile(packagePath));
            }
            else
            {
                List <Tone2014> tones  = new List <Tone2014>();
                string          appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string          tmpDir = Path.Combine(appDir, Path.GetFileNameWithoutExtension(packagePath)
                                                      + String.Format("_{0}", platform.platform.ToString()));

                Packer.Unpack(packagePath, appDir);
                string[] toneManifestFiles = Directory.GetFiles(tmpDir, "*.json", SearchOption.AllDirectories);

                foreach (var file in toneManifestFiles)
                {
                    tones.AddRange(ReadFromManifest(file));
                }

                DirectoryExtension.SafeDelete(tmpDir);

                return(tones);
            }
        }
Esempio n. 8
0
 public void DLCInlayCreator_Dispose(object sender, EventArgs e)
 {
     if (Directory.Exists(defaultDir))
     {
         DirectoryExtension.SafeDelete(defaultDir);
     }
 }
Esempio n. 9
0
        public static ResultInfo MappingMode(string option, string link, string target)
        {
            ResultInfo result = DataDeal(ref option, ref link, ref target);

            if (!result.IsSuccess)
            {
                return(result);
            }

            try
            {
                if (File.Exists(target))
                {
                    File.Move(target, link);
                }
                else if (Directory.Exists(target))
                {
                    DirectoryExtension.Move(target, link);
                }
                else
                {
                    return(new ResultInfo(false, "请确保文件或目录存在"));
                }

                Cmd cmd = new Cmd();
                result = cmd.Start(MkLinkCommand, option, target, link);
                cmd.Close();
                return(result);
            }
            catch (Exception e)
            {
                return(new ResultInfo(false, e.Message));
            }
        }
Esempio n. 10
0
        private static void UnpackPS3Package(string sourceFileName, string savePath, Platform platform)
        {
            var rootDir        = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "edat");
            var outputFilename = Path.Combine(rootDir, Path.GetFileName(sourceFileName));

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

            if (File.Exists(sourceFileName))
            {
                File.Copy(sourceFileName, outputFilename, true);
            }
            else
            {
                throw new FileNotFoundException(String.Format("File '{0}' not found.", sourceFileName));
            }

            var outputMessage = RijndaelEncryptor.DecryptPS3Edat();

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

            foreach (var fileName in Directory.EnumerateFiles(rootDir, "*.psarc.dat"))
            {
                using (var outputFileStream = File.OpenRead(fileName))
                {
                    ExtractPSARC(fileName, Path.GetDirectoryName(fileName), outputFileStream, new Platform(GamePlatform.PS3, GameVersion.None));
                }

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

            var outName   = Path.GetFileNameWithoutExtension(sourceFileName);
            var outputDir = Path.Combine(savePath, outName.Substring(0, outName.LastIndexOf(".")) + String.Format("_{0}", platform.platform.ToString()));

            foreach (var unpackedDir in Directory.EnumerateDirectories(rootDir))
            {
                if (Directory.Exists(unpackedDir))
                {
                    if (Directory.Exists(outputDir))
                    {
                        DirectoryExtension.SafeDelete(outputDir);
                    }

                    DirectoryExtension.Move(unpackedDir, outputDir);
                }
            }

            if (outputMessage.IndexOf("Decrypt all EDAT files successfully") < 0)
            {
                throw new InvalidOperationException("Rebuilder error, please check if .edat files are created correctly and see output below:" + Environment.NewLine + Environment.NewLine + outputMessage);
            }
        }
        public MainForm()
        {
            try
            {
                string keyName   = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
                string valueName = Path.GetFileName(Application.ExecutablePath);
                if (Registry.GetValue(keyName, valueName, null) == null)
                {
                    Registry.SetValue(keyName, valueName, 32768, RegistryValueKind.DWord);
                }
            }
            catch
            {
                ErrorBox.Show(Lng.Elem("Registry write error"), Lng.Elem(@"You need to start the application with administrator right for the first time if you want to use the map functionality or create HKEY_LOCAL_MACHINE\SOFTWARE\[WOW6432Node\]Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\Storyteller.exe REG_DWORD 0x8000 registry entries."));
            }

            InitializeComponent();

            LoadIcons();

            imageList.Images.Add("0", IconChar.Folder.ToBitmap(16, Color.DarkGoldenrod));
            imageList.Images.Add("1", IconChar.Image.ToBitmap(16, Color.ForestGreen));
            imageList.Images.Add("2", IconChar.FileAudio.ToBitmap(16, Color.LightSeaGreen));
            imageList.Images.Add("3", IconChar.User.ToBitmap(16, Color.BlanchedAlmond));

            DirectoryExtension.CreateApplicationDirectories();

            tvImages.Nodes.GetFilesAndFolders(PathProvider.Maps, 1, ExtensionProvider.ImagesFilter);
            tvMusic.Nodes.GetFilesAndFolders(PathProvider.Music, 2, ExtensionProvider.AudioFilter);
            tvSoundEffects.Nodes.GetFilesAndFolders(PathProvider.SoundEffects, 2, ExtensionProvider.AudioFilter);
            tvCharacters.Nodes.GetFilesAndFolders(PathProvider.Characters, 1, ExtensionProvider.ImagesFilter);
            tvVideoClips.Nodes.GetFilesAndFolders(PathProvider.VideoClips, 1, ExtensionProvider.VideoFilter);

            tvImages.ExpandAll();

            FillListViewGroup(lvMarket, "Accomodation");
            FillListViewGroup(lvMarket, "Animals");
            FillListViewGroup(lvMarket, "Clothes");
            FillListViewGroup(lvMarket, "Debauchery");
            FillListViewGroup(lvMarket, "Food");
            FillListViewGroup(lvMarket, "Other");
            FillListViewGroup(lvMarket, "Trappings");
            FillListViewGroup(lvMarket, "Travelling");

            GetLanguages();

            Lng.Translate(this);

            LoadStory(rtbStory);

            charcterGenerator = new CharcterGenerator
            {
                TopLevel        = false,
                FormBorderStyle = FormBorderStyle.None,
                Dock            = DockStyle.Fill
            };
            pCharacterContent.Controls.Add(charcterGenerator);
            charcterGenerator.Show();
        }
Esempio n. 12
0
 private void FileWatcher_Changed(object sender, FileSystemEventArgs e)
 {
     if (!(e.FullPath.Replace(DirectoryExtension.GetTempWorkingDirectory(), "").Trim('\\') == File.FileName.Replace("/", "\\")) || MainWindow.CurrentMainWindow.FileWatcher_ToUpdate.Contains(File))
     {
         return;
     }
     MainWindow.CurrentMainWindow.FileWatcher_ToUpdate.Add(File);
 }
Esempio n. 13
0
        private List <string> EnumerateMatchingFiles(DataDirSpec dds)
        {
            var mask = new Regex("^" + Regex.Escape(dds.FilenameFilter).Replace("\\*", ".*").Replace("\\?", ".") + "$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            return(DirectoryExtension
                   .EnumerateDirectoryRecursive(dds.Path, dds.RecursionDepth)
                   .Where(p => mask.IsMatch(Path.GetFileName(p)))
                   .ToList());
        }
        private static void ConvertPackageForSimilarPlatform(string unpackedDir, string targetFileName, Platform sourcePlatform, Platform targetPlatform, string appId)
        {
            // Old and new paths
            var sourceDir0 = sourcePlatform.GetPathName()[0].ToLower();
            var sourceDir1 = sourcePlatform.GetPathName()[1].ToLower();
            var targetDir0 = targetPlatform.GetPathName()[0].ToLower();
            var targetDir1 = targetPlatform.GetPathName()[1].ToLower();

            if (!targetPlatform.IsConsole)
            {
                // Replace AppId
                var appIdFile = Path.Combine(unpackedDir, "appid.appid");
                File.WriteAllText(appIdFile, appId);
            }

            // Replace aggregate graph values
            var aggregateFile      = Directory.EnumerateFiles(unpackedDir, "*.nt", SearchOption.AllDirectories).FirstOrDefault();
            var aggregateGraphText = File.ReadAllText(aggregateFile);

            // Tags
            aggregateGraphText = Regex.Replace(aggregateGraphText, GraphItem.GetPlatformTagDescription(sourcePlatform.platform), GraphItem.GetPlatformTagDescription(targetPlatform.platform), RegexOptions.Multiline);
            // Paths
            aggregateGraphText = Regex.Replace(aggregateGraphText, sourceDir0, targetDir0, RegexOptions.Multiline);
            aggregateGraphText = Regex.Replace(aggregateGraphText, sourceDir1, targetDir1, RegexOptions.Multiline);
            File.WriteAllText(aggregateFile, aggregateGraphText);

            // Rename directories
            foreach (var dir in Directory.GetDirectories(unpackedDir, "*.*", SearchOption.AllDirectories))
            {
                if (dir.EndsWith(sourceDir0))
                {
                    var newDir = dir.Substring(0, dir.LastIndexOf(sourceDir0)) + targetDir0;
                    DirectoryExtension.SafeDelete(newDir);
                    DirectoryExtension.Move(dir, newDir);
                }
                else if (dir.EndsWith(sourceDir1))
                {
                    var newDir = dir.Substring(0, dir.LastIndexOf(sourceDir1)) + targetDir1;
                    DirectoryExtension.SafeDelete(newDir);
                    DirectoryExtension.Move(dir, newDir);
                }
            }

            // Recreates SNG because SNG have different keys in PC and Mac
            bool updateSNG = ((sourcePlatform.platform == GamePlatform.Pc && targetPlatform.platform == GamePlatform.Mac) || (sourcePlatform.platform == GamePlatform.Mac && targetPlatform.platform == GamePlatform.Pc));

            // Packing
            var dirToPack = unpackedDir;

            if (sourcePlatform.platform == GamePlatform.XBox360)
            {
                dirToPack = Directory.GetDirectories(Path.Combine(unpackedDir, Packer.ROOT_XBox360))[0];
            }

            Packer.Pack(dirToPack, targetFileName, updateSNG, targetPlatform);
            DirectoryExtension.SafeDelete(unpackedDir);
        }
Esempio n. 15
0
        private static void ExtractPSARC(string filename, string savePath, Stream inputStream, Platform platform, bool isExternalFile = true)
        {
            string psarcFilename = Path.GetFileNameWithoutExtension(filename);

            if (isExternalFile)
            {
                psarcFilename += String.Format("_{0}", platform.platform);
            }

            var destpath = Path.Combine(savePath, psarcFilename);

            if (Directory.Exists(destpath) && isExternalFile)
            {
                DirectoryExtension.SafeDelete(destpath);
            }

            var psarc = new PSARC.PSARC();

            psarc.Read(inputStream, true);

            var    step     = Math.Round(1.0 / (psarc.TOC.Count + 2) * 100, 3);
            double progress = 0;

            GlobalExtension.ShowProgress("Inflating Entries ...");

            foreach (var entry in psarc.TOC)
            {
                // custom InflateEntries
                // var debugMe = "Check the TOC";
                var fullfilename = Path.Combine(destpath, entry.Name);

                if (Path.GetExtension(entry.Name).ToLower() == ".psarc")
                {
                    psarc.InflateEntry(entry);
                    ExtractPSARC(fullfilename, destpath, entry.Data, platform, false);
                }
                else
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(fullfilename));
                    psarc.InflateEntry(entry, fullfilename);
                    if (entry.Data != null)
                    {
                        entry.Data.Dispose(); //Close();
                    }
                }

                if (!String.IsNullOrEmpty(psarc.ErrMSG))
                {
                    throw new InvalidDataException(psarc.ErrMSG);
                }

                progress += step;
                GlobalExtension.UpdateProgress.Value = (int)progress;
            }
            // GlobalExtension.HideProgress();
        }
 protected virtual void Dispose(Boolean disposing)
 {
     if (disposing)
     {
         if (_deleteOnClose)
         {
             DirectoryExtension.SafeDelete(packageDir);
         }
     }
 }
Esempio n. 17
0
        private void btnPackSongPack_Click(object sender, EventArgs e)
        {
            var srcPath = String.Empty;
            var errMsg  = String.Empty;

            using (var fbd = new VistaFolderBrowserDialog())
            {
                fbd.Description  = "Select the Song Pack folder created in Step #1.";
                fbd.SelectedPath = destPath;

                if (fbd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                srcPath = fbd.SelectedPath;
            }

            ToggleUIControls(false);
            GlobalExtension.UpdateProgress        = this.pbUpdateProgress;
            GlobalExtension.CurrentOperationLabel = this.lblCurrentOperation;
            Thread.Sleep(100); // give Globals a chance to initialize
            GlobalExtension.ShowProgress("Packing archive ...", 30);
            Application.DoEvents();

            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Restart();

                var songPackDir = AggregateGraph2014.DoLikeSongPack(srcPath, txtAppId.Text);
                destPath = Path.Combine(Path.GetDirectoryName(srcPath), String.Format("{0}_songpack_p.psarc", Path.GetFileName(srcPath)));
                // PC Only for now can't mix platform packages
                Packer.Pack(songPackDir, destPath, predefinedPlatform: new Platform(GamePlatform.Pc, GameVersion.RS2014));

                // clean up now (song pack folder)
                if (Directory.Exists(songPackDir))
                {
                    DirectoryExtension.SafeDelete(songPackDir);
                }

                sw.Stop();
                GlobalExtension.ShowProgress("Finished packing archive (elapsed time): " + sw.Elapsed, 100);
            }
            catch (Exception ex)
            {
                errMsg  = String.Format("{0}\n{1}", ex.Message, ex.InnerException);
                errMsg += Environment.NewLine + "Make sure there aren't any non-PC CDLC in the SongPacks folder.";
            }

            PromptComplete(destPath, true, errMsg);
            GlobalExtension.Dispose();
            ToggleUIControls(true);
        }
        private void BtnDone_Click(object sender, EventArgs e)
        {
            var  charactersDirectory = Path.Combine(PathProvider.Characters, tbName.Text);
            bool createCharacter     = !Directory.Exists(charactersDirectory) || ConfirmBox.Show(Lng.Elem("Character already exists, do you want to owerwrite it?"));

            if (createCharacter)
            {
                DirectoryExtension.CreateIfNotExists(charactersDirectory);
                character.Save(Path.Combine(charactersDirectory, String.Concat("character", ExtensionProvider.CharacterSheetExtension)), images);
            }
        }
Esempio n. 19
0
        private void UpdateStatic()
        {
            // unpack static.psarc
            const int numSteps = 5; // max number of times ReportProgress will be called
            var       step     = (int)Math.Round(1.0 / (numSteps + 2) * 100, 0);
            var       progress = 0;

            progress += step;
            ProcessStarted(progress, "Unpacking static file ... ");

            var srcPath  = Path.Combine(rsDir, "static.psarc");
            var destPath = Path.Combine(rsDir, "static.psarc.org");

            // backup the original static.psarc and never overwrite it
            if (!File.Exists(destPath))
            {
                File.Copy(srcPath, destPath, false);
            }

            var tmpModDir = Path.Combine(tmpWorkDir, "cis_static");

            if (Directory.Exists(tmpModDir))
            {
                DirectoryExtension.SafeDelete(tmpModDir, true);
            }
            Directory.CreateDirectory(tmpModDir);

            destPath = tmpModDir;
            // Packer.Unpack(srcPath, destPath); // not working here
            ExternalApps.UnpackPsarc(srcPath, destPath, DLCInlayCreator.GlobalTitlePlatform);

            // convert user png images to dds images
            progress += step * 3;
            ProcessStarted(progress, "Convertng user PNG images ...");

            // CRITICAL PATH AND ARGS
            var rootDir = string.Format("static_{0}", DLCInlayCreator.GlobalTitlePlatform);

            srcPath  = imageArray[6, 3];
            destPath = Path.Combine(tmpModDir, rootDir, "gfxassets\\views", Path.GetFileName(imageArray[6, 2]));
            ExternalApps.Png2Dds(srcPath, destPath, ImageHandler.Size2IntX(imageArray[6, 1]), ImageHandler.Size2IntY(imageArray[6, 1]));

            // repack static.psarc
            progress += step;
            ProcessStarted(progress, "Repacking static file ...");
            srcPath  = Path.Combine(tmpModDir, rootDir);
            destPath = Path.Combine(rsDir, "static.psarc");
            // Packer.Pack(srcPath, destPath);  // not working
            ExternalApps.RepackPsarc(srcPath, destPath, DLCInlayCreator.GlobalTitlePlatform);

            ProcessCompleted(null, null);
        }
        public static void CreateSourceFile(string sourceTemplateFile, string entityListFile, string basePath)
        {
            var sourceTemplateContent = EmbeddedResourceReader.GetContent(sourceTemplateFile);
            var entityListContent     = EmbeddedResourceReader.GetContent(entityListFile);
            var entities      = entityListContent.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var namespacePart = Path.GetFileNameWithoutExtension(entityListFile);

            namespacePart = namespacePart.Substring(namespacePart.LastIndexOf('.') + 1);

#if USE_TRANSLATION_CSV
            var  languageFileContent = CsvFile.GetContent();
            var  rows = CsvFile.SplitContent(languageFileContent).ToList();
            var  potentialTranslations = entities.Skip(1).Select(entity => entity.Substring(0, entity.GetSecondIndexOf(';')));
            bool written = false;
            foreach (var potentialTranslation in potentialTranslations)
            {
                if (!rows.Any(row => row.Equals(potentialTranslation, StringComparison.Ordinal)))
                {
                    rows.Add(potentialTranslation);
                    languageFileContent += $"{Environment.NewLine}{potentialTranslation}";
                    written              = true;
                }
            }
            if (written)
            {
                var path = Path.Combine(Application.StartupPath, @"..\..\..\Mtf.Languages\Languages\Csv\AllLanguages.csv");
                File.WriteAllText(path, languageFileContent);
                Environment.Exit(-1);
            }
#endif
            var propertyNames = entities[0].Split(';');
            for (int i = 1; i < entities.Length; i++)
            {
                var entity             = entities[i];
                var propertyValues     = entity.Split(';');
                var currentFileContent = sourceTemplateContent;
                currentFileContent = currentFileContent.Replace("{Namespace}", namespacePart);
                var className = GetClassName(propertyValues[0]);
                currentFileContent = currentFileContent.Replace("{ClassName}", className);

                for (int j = 0; j < propertyNames.Length; j++)
                {
                    var propertyName = propertyNames[j];
                    var value        = propertyName == "Price" ? PriceConverter.Get(propertyValues[j]) : propertyValues[j];
                    currentFileContent = currentFileContent.Replace($"{{{propertyName}}}", value);
                }

                var directory = Path.Combine(basePath, namespacePart);
                DirectoryExtension.CreateIfNotExists(directory);
                File.WriteAllText(Path.Combine(directory, String.Concat(className, ".cs")), currentFileContent);
            }
        }
Esempio n. 21
0
        private void OpenFile(string fileName, bool isreadonly)
        {
            RDAReader reader = new RDAReader();

            ResetDocument();
            CurrentFileName = fileName;
            if (!isreadonly)
            {
                fileName = DirectoryExtension.GetTempWorkingDirectory() + "\\" + Path.GetFileName(fileName);
            }
            else
            {
                file_Save.IsEnabled = false;
            }
            CurrentReader   = reader;
            reader.FileName = fileName;
            progressBar_Status.Visibility = Visibility.Visible;
            Title = GetTitle() + " - " + Path.GetFileName(reader.FileName);
            reader.backgroundWorker = new BackgroundWorker();
            reader.backgroundWorker.WorkerReportsProgress = true;
            reader.backgroundWorker.ProgressChanged      += (sender2, e2) => DispatcherExtension.Dispatch(System.Windows.Application.Current, () =>
            {
                progressBar_Status.Value = e2.ProgressPercentage;
                label_Status.Text        = reader.backgroundWorkerLastMessage;
            });
            reader.backgroundWorker.DoWork += (sender2, e2) =>
            {
                try
                {
                    if (!isreadonly)
                    {
                        DispatcherExtension.Dispatch(System.Windows.Application.Current, () => label_Status.Text = "Copying *.rda file to a temparary directory ...");
                        FileSystem.CopyFile(CurrentFileName, fileName, UIOption.AllDialogs, UICancelOption.ThrowException);
                    }
                    reader.ReadRDAFile();
                }
                catch (Exception ex)
                {
                    DispatcherExtension.Dispatch(System.Windows.Application.Current, () =>
                    {
                        int num = (int)MessageWindow.Show(ex.Message);
                        NewFile();
                    });
                }
            };
            reader.backgroundWorker.RunWorkerCompleted += (sender2, e2) =>
            {
                progressBar_Status.Visibility = Visibility.Collapsed;
                RebuildTreeView();
            };
            reader.backgroundWorker.RunWorkerAsync();
        }
Esempio n. 22
0
        /// <summary>
        /// read a list of path + files in source ini path
        /// </summary>
        private Dictionary <DirectoryInfo, List <FileInfo> > GetLocalFiles()
        {
            _logger.Write(string.Format("Scanning {0}...", _ini.SourcePath));

            var filesInPath = DirectoryExtension.GetFilesByExt(_ini.SourcePath, _ini.SearchPattern, ',');
            var sourceFiles = filesInPath.OrderBy(p => p)
                              .GroupBy(p => Path.GetDirectoryName(p))
                              .ToDictionary(p => new DirectoryInfo(p.Key), p => p.Select(f => new FileInfo(f)).ToList());

            var lengthSum = filesInPath.Sum(p => new FileInfo(p).Length);

            _logger.Write(string.Format("{0} folders, {1} files, {2}", sourceFiles.Count, filesInPath.Count, lengthSum.ToFileSize()));

            return(sourceFiles);
        }
        public void ExtractBeforeConvert(string inputPath, string outputDir, bool allDif)
        {
            // unpacker creates the sng2tabDir directory if it doesn't exist
            string sng2tabDir  = Path.Combine(tmpWorkDir, "sng2tab");
            string unpackedDir = Packer.Unpack(inputPath, sng2tabDir);

            var sngFiles = Directory.EnumerateFiles(unpackedDir, "*.sng", SearchOption.AllDirectories);

            foreach (var sngFilePath in sngFiles)
            {
                Convert(sngFilePath, outputDir, allDif);
            }

            DirectoryExtension.SafeDelete(sng2tabDir);
        }
Esempio n. 24
0
        private static List <Tone> ReadFromPackage(string packagePath, Platform platform)
        {
            var    tones       = new List <Tone>();
            string appDir      = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string unpackedDir = Packer.Unpack(packagePath, appDir, predefinedPlatform: platform);

            foreach (var file in Directory.EnumerateFiles(unpackedDir, "tone*.manifest.json", SearchOption.AllDirectories))
            {
                tones.Add(ReadFromManifest(file));
            }

            DirectoryExtension.SafeDelete(unpackedDir);

            return(tones);
        }
        private void SetDefaults()
        {
            var rootFolder = DirectoryExtension.GetBaseOrAppDirectory();
            var dataFolder = rootFolder + "\\DataCache\\";

            if (!Directory.Exists(dataFolder))
            {
                try {
                    Directory.CreateDirectory(dataFolder);
                    _defaultDependencyFileLocation = dataFolder;
                } catch (Exception) {
                    _defaultDependencyFileLocation = rootFolder;
                }
            }
        }
Esempio n. 26
0
        private void ExtractBeforeConvert(string inputFile, string savePath, bool all)
        {
            string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Packer.Unpack(inputFile, appDir);
            string unpackedDir = Path.Combine(appDir, Path.GetFileNameWithoutExtension(inputFile) + String.Format("_{0}", Packer.GetPlatform(inputFile).platform.ToString()));

            string[] sngFiles = Directory.GetFiles(unpackedDir, "*.sng", SearchOption.AllDirectories);

            foreach (var sng in sngFiles)
            {
                Convert(sng, savePath, all);
            }

            DirectoryExtension.SafeDelete(unpackedDir);
        }
Esempio n. 27
0
 private void ResetDocument()
 {
     CurrentFileName     = "";
     file_Save.IsEnabled = true;
     if (FileWatcher != null)
     {
         FileWatcher.Dispose();
     }
     FileWatcher = new FileSystemWatcher();
     FileWatcher.IncludeSubdirectories = true;
     FileWatcher.NotifyFilter          = NotifyFilters.LastWrite;
     CurrentReader.Dispose();
     DirectoryExtension.CleanDirectory(DirectoryExtension.GetTempWorkingDirectory());
     FileWatcher.Path = DirectoryExtension.GetTempWorkingDirectory();
     FileWatcher.EnableRaisingEvents = true;
 }
Esempio n. 28
0
        private void SaveImages(object sender, DoWorkEventArgs e)
        {
            // method using Background Worker to report progress
            var       savePath = e.Argument as string;
            const int numSteps = 7; // max number of times progress change is reported
            var       step     = (int)Math.Round(1.0 / (numSteps + 2) * 100, 0);
            var       progress = 0;

            // Create temp folder for zipping files
            var tmpZipDir = Path.Combine(tmpWorkDir, "cis_zip");

            if (Directory.Exists(tmpZipDir))
            {
                DirectoryExtension.SafeDelete(tmpZipDir, true);
            }
            Directory.CreateDirectory(tmpZipDir);

            // convert user png images to dds images
            for (int i = 0; i < imageArray.GetUpperBound(0); i++)
            {
                progress += step;
                bwSaveImages.ReportProgress(progress, "Converting user PNG images ... " + i.ToString());

                if (imageArray[i, 3] != null) // user has specified a replacement image
                {
                    // CRITICAL PATH AND ARGS
                    var srcPath  = imageArray[i, 3];
                    var destPath = Path.Combine(tmpZipDir, Path.GetFileName(imageArray[i, 2]));
                    ExternalApps.Png2Dds(srcPath, destPath, ImageHandler.Size2IntX(imageArray[i, 1]), ImageHandler.Size2IntY(imageArray[i, 1]));
                }
            }
            progress += step;
            bwSaveImages.ReportProgress(progress, "Saving Intro Screens Template file ... ");

            // Write ini file setup.smb
            var           iniFile = Path.Combine(tmpZipDir, "setup.smb");
            Configuration iniCFG  = new Configuration();

            iniCFG["General"].Add(new Setting("author", String.IsNullOrEmpty(txtAuthor.Text) ? "CSC" : txtAuthor.Text));
            iniCFG["General"].Add(new Setting("seqname", String.IsNullOrEmpty(txtSeqName.Text) ? "SystemSaved" : txtSeqName.Text));
            iniCFG["General"].Add(new Setting("cscvers", ToolkitVersion.version));
            iniCFG["General"].Add(new Setting("modified", DateTime.Now.ToShortDateString()));
            iniCFG.Save(iniFile);

            // Zip intro sequence *.cis file
            ExternalApps.InjectZip(tmpZipDir, savePath, false, true);
        }
Esempio n. 29
0
        private async Task <Contact> GetContact(Message message, CancellationToken cancellationToken)
        {
            Contact contact;

            try
            {
                contact = await _contactService.GetAsync(message.From.ToIdentity(), cancellationToken);
            }
            catch (LimeException lex)
            {
                var directory = new DirectoryExtension(_sender);
                var account   = await directory.GetDirectoryAccountAsync(message.From.ToIdentity(), cancellationToken);

                contact = await _contactService.GetAsync(message.From.ToIdentity(), cancellationToken);
            }
            return(contact);
        }
Esempio n. 30
0
        //private object FindCreateMegaRoot(IEnumerable<INode> nodes, string v)
        //{
        //    GetPathTokens();

        //    return null;
        //}

        //private static IEnumerable<string> SplitSubPaths(string fullPath)
        //{
        //    var paths = (fullPath ?? string.Empty).Split(Path.DirectorySeparatorChar).Where(p => !string.IsNullOrWhiteSpace(p));
        //    return paths;
        //}


        //private void BuildNodeTree(IEnumerable<INode> nodes)
        //{

        //    INode root = nodes.Single(x => x.Type == NodeType.Root);



        //}



        //public void Sync(IEnumerable<INode> nodes, string megaRoot, string localRoot)
        //{
        //    FindMegaFolder(nodes, megaRoot);

        //}

        //private INode FindMegaFolder(IEnumerable<INode> nodes, string folderName)
        //{
        //    string parentId =  nodes.FirstOrDefault(x => x.Type == NodeType.Root)?.Id ;
        //    var tokens = folderName.Split('\\');
        //    for (int i = 0; i < tokens.Length; i++)
        //    {
        //        var folderNode = FindMegaFolder(nodes, tokens[i], parentId);
        //        if (folderNode == null)
        //            return null;
        //        if (i == (tokens.Length - 1))
        //            return folderNode;

        //        parentId = folderNode.Id;

        //    }
        //    return null;
        //}

        //private INode FindMegaFolder(IEnumerable<INode> nodes, string folderName, string parentId)
        //{
        //    return nodes.FirstOrDefault(p => p.Type == NodeType.Directory && p.ParentId == parentId && p.Name == folderName);
        //}



        /// <summary>
        /// read a list of path + files in source ini path
        /// </summary>
        private Dictionary <DirectoryInfo, List <FileInfo> > GetLocalFiles(string root)
        {
            //   _logger.Write(string.Format("Scanning {0}...", _ini.SourcePath));

            //var srcPath = @"D:\tmp\mega-photos-test";

            var filesInPath = DirectoryExtension.GetFilesByExt(root, "jpg", ',');
            var sourceFiles = filesInPath.OrderBy(p => p)
                              .GroupBy(p => Path.GetDirectoryName(p))
                              .ToDictionary(p => new DirectoryInfo(p.Key), p => p.Select(f => new FileInfo(f)).ToList());

            var lengthSum = filesInPath.Sum(p => new FileInfo(p).Length);

            // _logger.Write(string.Format("{0} folders, {1} files, {2}", sourceFiles.Count, filesInPath.Count, lengthSum.ToFileSize()));

            return(sourceFiles);
        }