GetFileNameWithoutExtension() private méthode

private GetFileNameWithoutExtension ( string path ) : string
path string
Résultat string
Exemple #1
0
    public override void _Ready()
    {
        var levelDirectory = new Directory();

        levelDirectory.Open(Game.LevelDirectory);
        levelDirectory.ListDirBegin(true, true);

        this.itemList = this.GetNode <ItemList>("ItemList");

        while (true)
        {
            var file = levelDirectory.GetNext();

            if (string.IsNullOrEmpty(file))
            {
                break;
            }

            if (!file.EndsWith(".tscn"))
            {
                continue;
            }

            GD.Print($"Discovered scene: {file}");

            var fileName = SystemPath.GetFileNameWithoutExtension(file);

            this.itemList.AddItem(fileName);
            this.levelList.Add(fileName);
        }

        this.itemList.Select(0);
        this.itemList.GrabFocus();
    }
Exemple #2
0
		public InMemoryFile(string filePath)
		{
			Path = new Path(filePath);
			Name = Path.GetFileName(filePath);
			NameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);

			_LastModifiedTimeUtc = null;
		}
Exemple #3
0
        public void SpectralIndexOsc_Test()
        {
            {
                var sourceRecording = PathHelper.ResolveAsset("Recordings", "BAC2_20071008-085040.wav");

                // 1. Create temp directory to store output
                if (!this.outputDirectory.Exists)
                {
                    this.outputDirectory.Create();
                }

                // 2. Get the spectral index
                var recordingSegment = new AudioRecording(sourceRecording.FullName);
                var frameLength      = Oscillations2014.DefaultFrameLength;
                var sampleLength     = Oscillations2014.DefaultSampleLength;
                var threshold        = Oscillations2014.DefaultSensitivityThreshold;
                var spectralIndex    = Oscillations2014.GetSpectralIndex_Osc(recordingSegment, frameLength, sampleLength, threshold);

                // 3. construct name of spectral index vector
                // SAVE THE OUTPUT if true
                // WARNING: this will overwrite fixtures
                var sourceName        = Path.GetFileNameWithoutExtension(sourceRecording.Name);
                var stem              = sourceName + ".SpectralIndex.OSC";
                var expectedIndexPath = PathHelper.ResolveAsset("Oscillations2014", stem + ".EXPECTED.csv");
                if (false)
                {
                    // 4. Save spectral index vector to file
                    //Csv.WriteToCsv(expectedIndexPath, spectralIndex);
                    //Json.Serialise(expectedIndexPath, spectralIndex);
                    Binary.Serialize(expectedIndexPath, spectralIndex);

                    // 5. Get the vector as image and save as image file
                    // no need to do tests on this image but it is useful to visualise output
                    var expectedVectorImage = ImageTools.DrawVectorInColour(DataTools.reverseArray(spectralIndex), cellWidth: 10);
                    var expectedImagePath   = PathHelper.ResolveAsset("Oscillations2014", stem + ".png");
                    expectedVectorImage.Save(expectedImagePath.FullName);
                }

                // 6. Get the vector as image and save as image file
                // no need to do tests on this image but it is useful to compare with expected visual output
                var currentVectorImage = ImageTools.DrawVectorInColour(DataTools.reverseArray(spectralIndex), cellWidth: 10);
                var currentImagePath   = Path.Combine(this.outputDirectory.FullName, stem + ".png");
                currentVectorImage.Save(currentImagePath);

                // 7. Run test. Compare vectors
                // TODO  this test fails when using CSV reader because the reader cuts out first element/line of the vector
                //var expectedVector = (double[])Csv.ReadFromCsv<double>(expectedIndexPath);
                var expectedVector = Binary.Deserialize <double[]>(expectedIndexPath);
                CollectionAssert.That.AreEqual(expectedVector, spectralIndex, 0.000001);
            }
        }
Exemple #4
0
        private void PreviewFiles_Button_Click(object sender, RoutedEventArgs e)
        {
            //vd thêm số 1 vào tên file
            if (_fileNames != null)
            {
                List <FileName> prefilename = new List <FileName>();
                foreach (var file in _fileNames)
                {
                    string   file_name, file_extension;
                    FileName fileName = new FileName();
                    file_name      = Path.GetFileNameWithoutExtension(file.pathFile + file.nameFile); //lấy tên file không bao gồm phần đuôi kiểu file
                    file_extension = Path.GetExtension(file.pathFile + file.nameFile);                //lấy phần đuôi của file vd: .pdf,.png
                    string newname = "";
                    string error   = "";
                    foreach (var action in _actions)
                    {
                        newname = action.Operate(file_name, file_extension);

                        int  check = 1;
                        bool flag  = false;

                        while (!flag)
                        {
                            for (int i = 0; i < _fileNames.Count; i++)
                            {
                                if (_fileNames.IndexOf(file) != i && newname == _fileNames[i].nameFile)
                                {
                                    newname = Path.GetFileNameWithoutExtension(file.pathFile + newname);

                                    newname += $"({check})" + file_extension;
                                    error    = $"File name is exists. Change file name to {newname}";
                                    check++;
                                    i = 0;
                                }
                            }
                            flag = true;
                        }

                        file_extension = Path.GetExtension(file.pathFile + newname);
                        file_name      = Path.GetFileNameWithoutExtension(file.pathFile + newname);
                    }
                    fileName.nameFile    = file.nameFile;
                    fileName.newFileName = newname;
                    fileName.pathFile    = file.pathFile;
                    fileName.errorFile   = error;
                    prefilename.Add(fileName);
                }

                FileListView.ItemsSource = prefilename;
            }
        }
Exemple #5
0
        // [Ignore("The update from 864f7a491e2ea0e938161bd390c1c931ecbdf63c possibly broke this test and I do not know how to repair it.
        // TODO @towsey")]
        public void TwoOscillationTests()
        {
            {
                var sourceRecording = PathHelper.ResolveAsset("Recordings", "BAC2_20071008-085040.wav");

                // 1. get the config dictionary
                var configDict = Oscillations2014.GetDefaultConfigDictionary(sourceRecording);

                // 2. Create temp directory to store output
                if (!this.outputDirectory.Exists)
                {
                    this.outputDirectory.Create();
                }

                // 3. Generate the FREQUENCY x OSCILLATIONS Graphs and csv data
                var tuple = Oscillations2014.GenerateOscillationDataAndImages(sourceRecording, configDict, true);

                // construct name of expected image file to save
                var sourceName = Path.GetFileNameWithoutExtension(sourceRecording.Name);
                var stem       = sourceName + ".FreqOscilSpectrogram";

                // construct name of expected matrix osc spectrogram to save file
                var expectedMatrixFile = PathHelper.ResolveAsset("Oscillations2014", stem + ".Matrix.EXPECTED.csv");

                // SAVE THE OUTPUT if true
                // WARNING: this will overwrite fixtures
                if (false)
                {
                    // 1: save image of oscillation spectrogram
                    string imageName = stem + ".EXPECTED.png";
                    string imagePath = Path.Combine(PathHelper.ResolveAssetPath("Oscillations2014"), imageName);
                    tuple.Item1.Save(imagePath);

                    // 2: Save matrix of oscillation data stored in freqOscilMatrix1
                    //Csv.WriteMatrixToCsv(expectedMatrixFile, tuple.Item2);
                    Binary.Serialize(expectedMatrixFile, tuple.Item2);
                }

                // Run two tests. Have to deserialise the expected data files
                // 1: Compare image files - check that image dimensions are correct
                Assert.AreEqual(350, tuple.Item1.Width);
                Assert.AreEqual(675, tuple.Item1.Height);

                // 2. Compare matrix data
                var expectedMatrix = Binary.Deserialize <double[, ]>(expectedMatrixFile);

                //TODO  Following test fails when using CSV reader because the reader cuts out first line of the matrix
                //var expectedMatrix = Csv.ReadMatrixFromCsv<double>(expectedMatrixFile);
                CollectionAssert.That.AreEqual(expectedMatrix, tuple.Item2, 0.000001);
            }
        }
Exemple #6
0
        private void _UpdateBuildTabsList()
        {
            buildTabsList.Clear();

            int currentTab = buildTabs.CurrentTab;

            bool noCurrentTab = currentTab < 0 || currentTab >= buildTabs.GetTabCount();

            for (int i = 0; i < buildTabs.GetChildCount(); i++)
            {
                var tab = (BuildTab)buildTabs.GetChild(i);

                if (tab == null)
                {
                    continue;
                }

                string itemName = Path.GetFileNameWithoutExtension(tab.BuildInfo.Solution);
                itemName += " [" + tab.BuildInfo.Configuration + "]";

                buildTabsList.AddItem(itemName, tab.IconTexture);

                string itemTooltip = "Solution: " + tab.BuildInfo.Solution;
                itemTooltip += "\nConfiguration: " + tab.BuildInfo.Configuration;
                itemTooltip += "\nStatus: ";

                if (tab.BuildExited)
                {
                    itemTooltip += tab.BuildResult == BuildTab.BuildResults.Success ? "Succeeded" : "Errored";
                }
                else
                {
                    itemTooltip += "Running";
                }

                if (!tab.BuildExited || tab.BuildResult == BuildTab.BuildResults.Error)
                {
                    itemTooltip += $"\nErrors: {tab.ErrorCount}";
                }

                itemTooltip += $"\nWarnings: {tab.WarningCount}";

                buildTabsList.SetItemTooltip(i, itemTooltip);

                if (noCurrentTab || currentTab == i)
                {
                    buildTabsList.Select(i);
                    _BuildTabsItemSelected(i);
                }
            }
        }
Exemple #7
0
        private void ArchivoGuardar(string NomArchLatis)
        {
            //Crear carpteta temporal
            string lxNomCsl  = Path.GetFileNameWithoutExtension(NomArchLatis);
            string lxBaseDir = (Path.GetDirectoryName(NomArchLatis));

            string lxDir = Path.Combine(lxBaseDir, lxNomCsl + "_Qry");

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

            //Guardar cfg.ini
            string lxArchCfgIni = Path.Combine(lxDir, CFG_INI);

            txtCfg.Save(lxArchCfgIni);

            //Guardar script.sql
            string lxScriptSQL = IniRead.ValorObtener(lxArchCfgIni, "CFG", "Script");

            if (string.IsNullOrEmpty(lxScriptSQL))
            {
                lxScriptSQL = Path.Combine(lxDir, lxNomCsl + ".sql");
            }
            else
            {
                lxScriptSQL = Path.Combine(lxDir, lxScriptSQL);
            }

            txtSQL.Save(lxScriptSQL);

            //Comprimir carpeta temporal en formato .zip con extensión .latis
            using (var zip = File.OpenWrite(NomArchLatis)) {
                using (var zipWriter = WriterFactory.Open(zip, ArchiveType.Zip, CompressionType.Deflate)) {
                    string[] lxFileList = Directory.GetFiles(lxDir);
                    foreach (var filePath in lxFileList)
                    {
                        zipWriter.Write(Path.GetFileName(filePath), filePath);
                    }
                }
            }
            StatusBarSet($"Archivo '{NomArchLatis}' Guardado.");

            try {
                //Eliminar directorio temporal
                Directory.Delete(lxDir, true);
            } catch (Exception ex) {
                _ = MessageBox.Show(ex.Message, "Guardar", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #8
0
        private async Task LoadGraphQLDocumentsAsync(
            string path,
            ClientGenerator generator,
            ICollection <HCError> errors)
        {
            Configuration?configuration = await Configuration.LoadConfig(path);

            if (configuration is null)
            {
                throw new InvalidOperationException(
                          "The configuration does not exist.");
            }

            if (configuration.Schemas is null)
            {
                throw new InvalidOperationException(
                          "The configuration has no schemas defined.");
            }

            Dictionary <string, SchemaFile> schemas =
                configuration.Schemas.Where(t => t.Name != null)
                .ToDictionary(t => t.Name !);

            foreach (DocumentInfo document in await GetGraphQLFiles(path, errors))
            {
                if (document.Kind == DocumentKind.Query)
                {
                    generator.AddQueryDocument(
                        IOPath.GetFileNameWithoutExtension(document.FileName),
                        document.FileName,
                        document.Document);
                }
                else
                {
                    string name = IOPath.GetFileNameWithoutExtension(
                        document.FileName);

                    if (schemas.TryGetValue(
                            IOPath.GetFileName(document.FileName),
                            out SchemaFile? file))
                    {
                        name = file.Name !;
                    }

                    generator.AddSchemaDocument(
                        name,
                        document.Document);
                }
            }
        }
Exemple #9
0
        private static RawFordDocument ReadRawDocument(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new ArgumentException($"Unavailable file {filePath}");
            }

            var fileName = Path.GetFileNameWithoutExtension(filePath);
            var pages    = ReadRawPages(filePath);

            var document = new RawFordDocument(fileName, pages);

            return(document);
        }
Exemple #10
0
        private void NextImage_Click(object sender, RoutedEventArgs e)
        {
            if (LabelsList1 != null)
            {
                if (isPreviousFileSave)
                {
                    IsRectangleSelected = false;
                    if (LabelsList1 != null)
                    {
                        LabelsList1 = null;
                    }

                    LabelListView1.ItemsSource = null;

                    if (RectanglesList != null)
                    {
                        RectanglesList = null;
                        //Canvas1.Children.Clear();
                    }

                    Canvas1.Children.Clear();
                    imageIndex++;

                    //MessageBox.Show("Next image is " + ImageList[imageIndex]);


                    Image1.Source = new BitmapImage(new Uri(ImageList[imageIndex]));
                    Canvas1.Children.Add(Image1);
                    string ImageName = Path.GetFileNameWithoutExtension(ImageList[imageIndex]);
                    imageName1.Text = ImageName;

                    cIndx = imageIndex;
                    pIndx = imageIndex - 1;

                    isPreviousFileSave = false;
                }
                else
                {
                    FileSavePopup.IsOpen = true;
                    //SaveFile.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
                    //SaveFile.Click(SaveFile_Click) ;
                }
            }

            else
            {
                MessageBox.Show("There is No labels regarding to this image to save");
                //FileSavePopup.IsOpen = true;
            }
        }
Exemple #11
0
        /// <summary>
        /// Exports the mipmaps in the image.
        /// </summary>
        public void RunExport()
        {
            string imageFilename = IOPath.GetFileNameWithoutExtension(this.ExportTarget.FilePath.ConvertPathSeparatorsToCurrentNativeSeparator());

            string exportPath;

            if (this.Config.KeepFileDirectoryStructure)
            {
                exportPath = IOPath.Combine
                             (
                    this.ExportDirectoryFileChooserButton.Filename,
                    this.ExportTarget.FilePath.ConvertPathSeparatorsToCurrentNativeSeparator().Replace(".blp", string.Empty)
                             );
            }
            else
            {
                exportPath = IOPath.Combine
                             (
                    this.ExportDirectoryFileChooserButton.Filename,
                    imageFilename
                             );
            }

            int i = 0;

            this.MipLevelListStore.Foreach
            (
                (model, path, iter) =>
            {
                bool shouldExport = (bool)this.MipLevelListStore.GetValue(iter, 0);

                if (shouldExport)
                {
                    string formatExtension = GetFileExtensionFromImageFormat((ImageFormat)this.ExportFormatComboBox.Active);
                    Directory.CreateDirectory(Directory.GetParent(exportPath).FullName);

                    string fullExportPath = $"{exportPath}_{i}.{formatExtension}";

                    this.Image.GetMipMap((uint)i).Save
                    (
                        fullExportPath,
                        GetImageEncoderFromFormat((ImageFormat)this.ExportFormatComboBox.Active)
                    );
                }

                ++i;
                return(false);
            }
            );
        }
        private void ProcessPictureUri(MvxIntentResultEventArgs result, Uri uri)
        {
            if (_currentRequestParameters == null)
            {
                MvxPluginLog.Instance.Error("Internal error - response received but _currentRequestParameters is null");
                return; // we have not handled this - so we return null
            }

            var responseSent = false;

            try
            {
                // Note for furture bug-fixing/maintenance - it might be better to use var outputFileUri = data.GetParcelableArrayExtra("outputFileuri") here?
                if (result.ResultCode != Result.Ok)
                {
                    MvxPluginLog.Instance.Trace("Non-OK result received from MvxIntentResult - {0} - request was {1}",
                                                result.ResultCode, result.RequestCode);
                    return;
                }

                if (string.IsNullOrEmpty(uri?.Path))
                {
                    MvxPluginLog.Instance.Trace("Empty uri or file path received for MvxIntentResult");
                    return;
                }

                MvxPluginLog.Instance.Trace("Loading InMemoryBitmap started...");
                var memoryStream = LoadInMemoryBitmap(uri);
                if (memoryStream == null)
                {
                    MvxPluginLog.Instance.Trace("Loading InMemoryBitmap failed...");
                    return;
                }
                MvxPluginLog.Instance.Trace("Loading InMemoryBitmap complete...");
                responseSent = true;
                MvxPluginLog.Instance.Trace("Sending pictureAvailable...");
                _currentRequestParameters.PictureAvailable(memoryStream, Path.GetFileNameWithoutExtension(uri.Path));
                MvxPluginLog.Instance.Trace("pictureAvailable completed...");
                return;
            }
            finally
            {
                if (!responseSent)
                {
                    _currentRequestParameters.AssumeCancelled();
                }

                _currentRequestParameters = null;
            }
        }
Exemple #13
0
        /// <summary>
        /// Stategy for attachment folder identification
        /// </summary>
        /// <param name="pathToFile">path to html file</param>
        /// <returns>path to html attachments</returns>
        private static string FindAttachmentFolder(string pathToFile)
        {
            var attachmentFolder = Path.Combine(
                Path.GetDirectoryName(pathToFile),
                Path.GetFileNameWithoutExtension(pathToFile) + "_files"
                );

            if (Directory.Exists(attachmentFolder))
            {
                return(attachmentFolder);
            }

            return(null);
        }
        protected OptionsFile(string fileName, bool initDeclaredOptionMembers = true) : base(initDeclaredOptionMembers)
        {
            _name = Path.GetFileNameWithoutExtension(fileName);
            _path = Path.Combine(Utilities.GetConfigsPath(), fileName);
            if (!File.Exists(_path))
            {
                _toml = new DocumentSyntax();
                return;
            }

            var bytes = File.ReadAllBytes(_path);

            _toml = Toml.Parse(bytes, _path);
        }
        public static string GenerateNewFileName(string oldFileName)
        {
            int    num = 0;
            var    fileNameWithoutExtension = Path.GetFileNameWithoutExtension(oldFileName);
            var    fileExtension            = Path.GetExtension(oldFileName);
            string newFileName;

            do
            {
                num++;
                newFileName = $"{fileNameWithoutExtension}-{num}{fileExtension}";
            }while (MediaExists(newFileName));
            return(newFileName);
        }
Exemple #16
0
        /// <summary>
        /// test method for getting a spectral index of oscillation values.
        /// </summary>
        public static void TESTMETHOD_GetSpectralIndex_Osc()
        {
            // 1. set up the resources
            var sourceRecording = @"C:\Work\GitHub\audio-analysis\tests\Fixtures\Recordings\BAC2_20071008-085040.wav".ToFileInfo();

            //var sourceRecording = @"C:\Work\GitHub\audio-analysis\tests\Fixtures\Recordings\BAC2_20071008-085040_seconds30to32.wav".ToFileInfo();
            //var sourceRecording = @"C:\Work\GitHub\audio-analysis\tests\Fixtures\Recordings\BAC2_20071008-085040_seconds45to46.wav".ToFileInfo();
            //var sourceRecording = @"C:\Work\GitHub\audio-analysis\tests\Fixtures\Recordings\BAC2_20071008-085040_seconds49to49.wav".ToFileInfo();
            var output             = @"C:\Ecoacoustics\SoftwareTests\TestOscillationSpectrogram".ToDirectoryInfo();
            var sourceName         = Path.GetFileNameWithoutExtension(sourceRecording.Name);
            var opStem             = sourceName + ".SpectralIndex7.OSC";
            var expectedResultsDir = new DirectoryInfo(Path.Combine(output.FullName, TestTools.ExpectedResultsDir));

            if (!expectedResultsDir.Exists)
            {
                expectedResultsDir.Create();
            }

            var recordingSegment = new AudioRecording(sourceRecording.FullName);

            // 2. Get the spectral index using default values
            var spectralIndexShort = GetSpectralIndex_Osc(recordingSegment, DefaultFrameLength, DefaultSampleLength, DefaultSensitivityThreshold);

            // 3. double length of the vector because want to work with 256 element vector for LDFC purposes
            var spectralIndex = DataTools.VectorDoubleLengthByAverageInterpolation(spectralIndexShort);

            // 4. Write the vector to csv file
            var pathName1 = new FileInfo(Path.Combine(output.FullName, opStem + ".csv"));

            Acoustics.Shared.Csv.Csv.WriteToCsv(pathName1, spectralIndex);

            // 4. draw image of the vector for debug purposes.
            //var vectorImage = ImageTools.DrawVectorInColour(DataTools.reverseArray(spectralIndex), cellWidth: 5);
            spectralIndex = DataTools.NormaliseByScalingMaxValueToOne(spectralIndex);
            int cellWidth   = 30;
            int cellHeight  = 2;
            var vectorImage = ImageTools.DrawVectorInGrayScaleWithoutNormalisation(DataTools.reverseArray(spectralIndex), cellWidth, cellHeight, true);

            // set up a frequency scale for easier interpretation
            int    herzInterval = 1000;
            double freqBinWidth = DefaultResampleRate / (double)DefaultFrameLength / 2; // Divide by 2 bcause have doubled length of the spectral index vector
            double yTicInterval = herzInterval / freqBinWidth * cellHeight;
            int    yOffset      = cellHeight / 2;

            vectorImage = ImageTools.DrawYaxisScale(vectorImage, 10, herzInterval, yTicInterval, yOffset);
            var pathName2 = Path.Combine(output.FullName, opStem + ".png");

            vectorImage.Save(pathName2);
        }
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var dialog = new Ookii.Dialogs.Wpf.VistaOpenFileDialog()
            {
                CheckFileExists = true,
                Filter          = "Mods|*.jar;*.zip|Tous les fichiers|*.*",
                Multiselect     = true,
                Title           = "Importer un mod"
            };

            if (dialog.ShowDialog(MainWindow.App) == true)
            {
                var progress        = new LoadingPage();
                var displayProgress = new BaseModel("Chargement...", false);
                displayProgress.Child = progress;
                displayProgress.Owner = MainWindow.App;
                Task.Factory.StartNew(() =>
                {
                    int max     = dialog.FileNames.Length;
                    int current = 0;
                    var newMods = new List <Mod>();
                    foreach (var file in dialog.FileNames)
                    {
                        Dispatcher.Invoke(() =>
                        {
                            progress.ChangeDisplayer("Chargement de : " + Path.GetFileNameWithoutExtension(file) + "...");
                            progress.ChangeFill((float)current / max);
                        });
                        if (MainWindow.mods.FirstOrDefault((m) => m.Filename == Path.GetFileName(file)) == null)
                        {
                            File.Copy(file, Path.Combine(MainWindow.ModDir, Path.GetFileName(file)), true);
                            var mod     = MainWindow.LoadModFromFile(Path.Combine(MainWindow.ModDir, Path.GetFileName(file)));
                            mod.Enabled = true;
                            Dispatcher.Invoke(() => ListMods.Add(new ListMod(mod)));
                            MainWindow.mods.Add(mod);
                        }
                        current++;
                    }
                    ListMods.Sort((left, right) => left.linkedMod.Infos.name.CompareTo(right.linkedMod.Infos.name));
                    Dispatcher.Invoke(() =>
                    {
                        displayProgress.ForceClosing();
                    });
                });
                displayProgress.ShowDialog();
                MainWindow.mods.Sort((left, right) => left.Infos.name.CompareTo(right.Infos.name));
                updateList();
            }
        }
Exemple #18
0
        private void SaveLocalization()
        {
            string lang = null;

            if (ShowGerman)
            {
                lang = "deu";
            }
            if (ShowRussian)
            {
                lang = "rus";
            }
            if (ShowPolish)
            {
                lang = "pol";
            }
            if (ShowFrench)
            {
                lang = "fra";
            }
            if (ShowSpanish)
            {
                lang = "esn";
            }
            if (ShowPortuguese)
            {
                lang = "bra";
            }

            var sb = CreateXamlDocument();

            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                Title    = "Save localization file",
                Filter   = "Xaml files|*.xaml",
                FileName = $"{lang}.xaml"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                if (Path.GetFileNameWithoutExtension(saveFileDialog.FileName).Length != 3)
                {
                    MessageBox.Show($"Filename must match localization 3 character name ({lang}).");
                    return;
                }
                File.WriteAllText(saveFileDialog.FileName, sb);
                MessageBox.Show($"Saved.");
            }
        }
 public Metadata ExtractMetadata(string inputPath)
 {
     try
     {
         var    reader   = new PdfReader(inputPath);
         var    metadata = new Metadata();
         string author;
         if (reader.Info.TryGetValue("Author", out author))
         {
             if (author.Contains(","))
             {
                 var split   = author.Split(',');
                 var author2 = new Author
                 {
                     FirstName = split[1].Replace(" ", Empty),
                     LastName  = split[0].Replace(" ", Empty)
                 };
                 metadata.Authors.Add(author2);
             }
             else
             {
                 var split   = author.Split(' ');
                 var author2 = new Author();
                 if (split.Length > 1)
                 {
                     author2.FirstName = split[0];
                     author2.LastName  = split[1];
                     metadata.Authors.Add(author2);
                 }
             }
         }
         string title;
         if (reader.Info.TryGetValue("Title", out title))
         {
             metadata.Title = !IsNullOrEmpty(title) ? title : Path.GetFileNameWithoutExtension(inputPath);
         }
         else
         {
             metadata.Title = Path.GetFileNameWithoutExtension(inputPath);
         }
         metadata.PageCount = reader.NumberOfPages;
         metadata.Isbn      = ExtractIsbn(inputPath);
         return(metadata);
     }
     catch (Exception ex)
     {
         throw new BookieException($"Error extracting metadata for {inputPath}", ex);
     }
 }
Exemple #20
0
        private async Task LoadSavePointsAsync()
        {
            lock (savePoints)
            {
                if (ctsLoader != null && !ctsLoader.IsCancellationRequested)
                {
                    ctsLoader.Cancel();
                    ctsLoader.Dispose();
                }
                ctsLoader = new System.Threading.CancellationTokenSource();
            }

            string warnings = string.Empty;

            string build  = VersionInfo.Build.Contains(" ") ? VersionInfo.Build.Substring(VersionInfo.Build.IndexOf(" ") + 1) : null;
            var    prefix = string.Empty;

            if (SelectedAction == MainForm.UserAction.SinglePlayerTimetableGame)
            {
                prefix = Path.GetFileName(route.Path) + " " + Path.GetFileNameWithoutExtension(timeTable.FileName);
            }
            else if (activity.FilePath != null)
            {
                prefix = Path.GetFileNameWithoutExtension(activity.FilePath);
            }
            else if (activity.Name == "- " + catalog.GetString("Explore Route") + " -")
            {
                prefix = Path.GetFileName(route.Path);
            }
            // Explore in activity mode
            else
            {
                prefix = "ea$" + Path.GetFileName(route.Path) + "$";
            }

            savePoints = (await Task.Run(() => SavePoint.GetSavePoints(UserSettings.UserDataFolder,
                                                                       prefix, build, route.Name, settings.YoungestFailedToRestore, warnings, ctsLoader.Token))).OrderBy(s => s.RealTime).Reverse().ToList();

            saveBindingSource.DataSource = savePoints;
            labelInvalidSaves.Text       = catalog.GetString(
                "To prevent crashes and unexpected behaviour, Open Rails invalidates games saved from older versions if they fail to restore.\n") +
                                           catalog.GetStringFmt("{0} of {1} saves for this route are no longer valid.", savePoints.Count(s => (s.Valid == false)), savePoints.Count);
            GridSaves_SelectionChanged(null, null);
            // Show warning after the list has been updated as this is more useful.
            if (!string.IsNullOrEmpty(warnings))
            {
                MessageBox.Show(warnings, Application.ProductName + " " + VersionInfo.VersionOrBuild);
            }
        }
        private static string GetUniquePath(string folder, string name, bool isPhoto)
        {
            var ext = Path.GetExtension(name);
            if (ext == string.Empty)
                ext = ((isPhoto) ? ".jpg" : ".mp4");

            name = Path.GetFileNameWithoutExtension(name);

            var nname = name + ext;
            var i = 1;
            while (File.Exists(Path.Combine(folder, nname)))
                nname = name + "_" + (i++) + ext;

            return Path.Combine(folder, nname);
        }
Exemple #22
0
        public LoginForm()
        {
            InitializeComponent();
            PATH = Environment.ExpandEnvironmentVariables(PATH);
            Directory.CreateDirectory(PATH);
            var files = Directory.GetFiles(PATH);

            foreach (var file in files)
            {
                if (file.EndsWith(".flw"))
                {
                    loginTextbox.AutoCompleteCustomSource.Add(IOPath.GetFileNameWithoutExtension(file));
                }
            }
        }
Exemple #23
0
        private static bool ParseParameters(string[] args)
        {
            // Check the correct number of parameters.
            if (args.Length != 1)
            {
                return(false);
            }

            // Get the file names.
            _fileName    = args[0];
            _fileName200 = Path.Combine(Path.GetDirectoryName(_fileName),
                                        Path.GetFileNameWithoutExtension(_fileName) + "_200" + Path.GetExtension(_fileName));

            return(true);
        }
Exemple #24
0
            public File(string path, FileType[] knownTypes)
            {
                this.Path = path;
                this.Name = Paths.GetFileNameWithoutExtension(path);

                string extension = Paths.GetExtension(path);

                foreach (FileType type in knownTypes)
                {
                    if (type.IsExtension(extension))
                    {
                        this.Type = type;
                    }
                }
            }
Exemple #25
0
        public Import(string path)
        {
            Path      = path;
            ShortPath = SPath.GetFileName(path);
            var file = Directory.GetFiles(path).First(ImportRunner.IsAudioFile);

            Filename = SPath.GetFileNameWithoutExtension(file);
            using (var readStream = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                var tagFile = TagLib.File.Create(new StreamFileAbstraction(file, readStream, null));
                Album  = tagFile.Tag.Album ?? string.Empty;
                Author = tagFile.Tag.FirstAlbumArtist ?? string.Empty;
                Title  = tagFile.Tag.Title ?? string.Empty;
            }
        }
Exemple #26
0
        public static Texture2D FromFile(GraphicsDevice graphicsDevice, string filename)
        {
            Bitmap image = BitmapFactory.DecodeFile(filename);

            if (image == null)
            {
                throw new ContentLoadException("Error loading file: " + filename);
            }

            ESImage   theTexture = new ESImage(image, graphicsDevice.PreferedFilter);
            Texture2D result     = new Texture2D(theTexture);

            result.Name = Path.GetFileNameWithoutExtension(filename);
            return(result);
        }
Exemple #27
0
        public static void RunTestExample <T>(string filePartName, bool evaluateFormulae = false)
            where T : IXLExample, new()
        {
            // Make sure tests run on a deterministic culture
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            var example = new T();

            string[] pathParts = filePartName.Split(new char[] { '\\' });
            string   filePath1 = Path.Combine(new List <string>()
            {
                TestsExampleOutputDirectory
            }.Concat(pathParts).ToArray());

            var extension = Path.GetExtension(filePath1);
            var directory = Path.GetDirectoryName(filePath1);

            var fileName = Path.GetFileNameWithoutExtension(filePath1);

            fileName += ActualTestResultPostFix;
            fileName  = Path.ChangeExtension(fileName, extension);

            filePath1 = Path.Combine(directory, "z" + fileName);
            var filePath2 = Path.Combine(directory, fileName);

            //Run test
            example.Create(filePath1);
            using (var wb = new XLWorkbook(filePath1))
                wb.SaveAs(filePath2, true, evaluateFormulae);

            if (CompareWithResources)

            {
                string resourcePath = filePartName.Replace('\\', '.').TrimStart('.');
                using (var streamExpected = _extractor.ReadFileFromResToStream(resourcePath))
                    using (var streamActual = File.OpenRead(filePath2))
                    {
                        string message;
                        var    success          = ExcelDocsComparer.Compare(streamActual, streamExpected, TestHelper.IsRunningOnUnix, out message);
                        var    formattedMessage =
                            String.Format(
                                "Actual file '{0}' is different than the expected file '{1}'. The difference is: '{2}'",
                                filePath2, resourcePath, message);

                        Assert.IsTrue(success, formattedMessage);
                    }
            }
        }
Exemple #28
0
        /// <summary>
        /// Rename all required elements of project
        /// </summary>
        private void RenameProjectFiles()
        {
            string ProjectPath    = ProjectSelector.Directory;
            string OldProjectName = ProjectSelector.FileName;
            string NewProjectName = NameSelectorRef.InputText;

            GlobalFunction.RemoveDirectoryIfValid(ProjectPath + "/Saved");
            GlobalFunction.RemoveDirectoryIfValid(ProjectPath + "/Intermediate");
            GlobalFunction.RemoveDirectoryIfValid(ProjectPath + "/.vs");
            GlobalFunction.RemoveDirectoryIfValid(ProjectPath + "/Binaries");

            #region Change name internal
            //List of all files which need some form of modification
            var Files = GlobalFunction.GetFilesWithExtension(ProjectPath, new string[] { ".cs", ".h", ".cpp", ".uproject", ".sln", ".ini" }, SearchOption.AllDirectories);

            foreach (string i in Files)
            {
                File.WriteAllText(i, File.ReadAllText(i).Replace(OldProjectName, NewProjectName));

                string OldAPI = OldProjectName.ToUpper() + "_API";
                string NewAPI = NewProjectName.ToUpper() + "_API";
                File.WriteAllText(i, File.ReadAllText(i).Replace(OldAPI, NewAPI));
            }
            #endregion

            #region File Rename
            var FileName = from string i in Files
                           where Path.GetFileNameWithoutExtension(i).IndexOf(OldProjectName) != -1
                           select i;

            foreach (string i in FileName)
            {
                string newS = Path.GetDirectoryName(i) + "/" + Path.GetFileName(i).Replace(OldProjectName, NewProjectName);
                File.Move(i, newS);
            }
            Directory.Move(ProjectPath + "\\Source\\" + OldProjectName, ProjectPath + "\\Source\\" + NewProjectName);
            #endregion

            #region Project Icon
            string ProjectIconPath = ProjectPath + "\\" + OldProjectName + ".png";
            if (File.Exists(ProjectIconPath))
            {
                File.Move(ProjectIconPath, ProjectPath + "\\" + NewProjectName + ".png");
            }
            #endregion

            GlobalFunction.ActiveRedirect(ProjectPath, OldProjectName, NewProjectName, false);
        }
Exemple #29
0
        private async Task LoadSavePointsAsync()
        {
            lock (savePoints)
            {
                if (ctsLoader != null && !ctsLoader.IsCancellationRequested)
                {
                    ctsLoader.Cancel();
                    ctsLoader.Dispose();
                }
                ctsLoader = new CancellationTokenSource();
            }

            StringBuilder warnings = new StringBuilder();
            string        prefix   = string.Empty;

            if (SelectedAction == MainForm.UserAction.SinglePlayerTimetableGame)
            {
                prefix = $"{Path.GetFileName(route.Path)} {Path.GetFileNameWithoutExtension(timeTable.FileName)}";
            }
            else if (activity.FilePath != null)
            {
                prefix = Path.GetFileNameWithoutExtension(activity.FilePath);
            }
            else if (activity.Name == $"- {catalog.GetString("Explore Route")} -")
            {
                prefix = Path.GetFileName(route.Path);
            }
            // Explore in activity mode
            else
            {
                prefix = $"ea${Path.GetFileName(route.Path)}$";
            }

            savePoints = (await SavePoint.GetSavePoints(UserSettings.UserDataFolder,
                                                        prefix, route.Name, warnings, multiplayer, globalRoutes, ctsLoader.Token).ConfigureAwait(true)).
                         OrderByDescending(s => s.Valid).ThenByDescending(s => s.RealTime).ToList();

            saveBindingSource.DataSource = savePoints;
            labelInvalidSaves.Text       = catalog.GetString(
                "To prevent crashes and unexpected behaviour, Open Rails invalidates games saved from older versions if they fail to restore.\n") +
                                           catalog.GetString("{0} of {1} saves for this route are no longer valid.", savePoints.Count(s => (s.Valid == false)), savePoints.Count);
            GridSaves_SelectionChanged(null, null);
            // Show warning after the list has been updated as this is more useful.
            if (warnings.Length > 0)
            {
                MessageBox.Show(warnings.ToString(), $"{RuntimeInfo.ProductName} {VersionInfo.Version}");
            }
        }
        /// <summary>
        /// Gets the map from the path
        /// </summary>
        /// <param name="modPath">The mod path</param>
        /// <returns>The map</returns>
        private string GetMap(string modPath)
        {
            var xivTexType = XivTexType.Other;

            if (modPath.Contains(".mdl"))
            {
                return("3D");
            }

            if (modPath.Contains(".mtrl"))
            {
                return("ColorSet");
            }

            if (modPath.Contains("ui/"))
            {
                var subString = modPath.Substring(modPath.IndexOf("/") + 1);
                return(subString.Substring(0, subString.IndexOf("/")));
            }

            if (modPath.Contains("_s.tex") || modPath.Contains("skin_m"))
            {
                xivTexType = XivTexType.Specular;
            }
            else if (modPath.Contains("_d.tex"))
            {
                xivTexType = XivTexType.Diffuse;
            }
            else if (modPath.Contains("_n.tex"))
            {
                xivTexType = XivTexType.Normal;
            }
            else if (modPath.Contains("_m.tex"))
            {
                xivTexType = XivTexType.Multi;
            }
            else if (modPath.Contains(".atex"))
            {
                var atex = Path.GetFileNameWithoutExtension(modPath);
                return(atex.Substring(0, 4));
            }
            else if (modPath.Contains("decal"))
            {
                xivTexType = XivTexType.Mask;
            }

            return(xivTexType.ToString());
        }
Exemple #31
0
        /// <summary>
        /// Renders an XPS document page to the specified PDF page.
        /// </summary>
        /// <param name="page">The target PDF page. The page must belong to the PDF document of this converter.</param>
        /// <param name="xpsPageIndex">The zero-based XPS page number.</param>
        public void RenderPage(PdfPage page, int xpsPageIndex)
        {
            if (page == null)
            {
                throw new ArgumentNullException("page");
            }
            if (!ReferenceEquals(page.Owner, pdfDocument))
            {
                throw new InvalidOperationException(PSXSR.PageMustBelongToPdfDocument);
            }
            // Debug.Assert(xpsPageIndex==0, "xpsPageIndex must be 0 at this stage of implementation.");
            try
            {
                FixedPage fpage = xpsDocument.GetDocument().GetFixedPage(xpsPageIndex);

                // ZipPackage pack = ZipPackage.Open(xpsFilename) as ZipPackage;
                Uri            uri  = new Uri("/Documents/1/Pages/1.fpage", UriKind.Relative);
                ZipPackagePart part = xpsDocument.Package.GetPart(uri) as ZipPackagePart;
                if (part != null)
                {
                    using (Stream stream = part.GetStream())
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            string xml = sr.ReadToEnd();
#if true && DEBUG
                            if (!String.IsNullOrEmpty(xpsDocument.Path))
                            {
                                string xmlPath =
                                    IOPath.Combine(IOPath.GetDirectoryName(xpsDocument.Path),
                                                   IOPath.GetFileNameWithoutExtension(xpsDocument.Path)) + ".xml";
                                using (StreamWriter sw = new StreamWriter(xmlPath))
                                {
                                    sw.Write(xml);
                                }
                            }
#endif
                            //XpsElement el = PdfSharp.Xps.Parsing.XpsParser.Parse(xml);
                            PdfRenderer renderer = new PdfRenderer();
                            renderer.RenderPage(page, fpage);
                        }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                throw;
            }
        }