Example #1
0
        /// <summary>
        ///   Сериализует текущий объект пакета
        /// </summary>
        protected override void SerializePersonCurrent()
        {
            SerializeObject.Vers     = "2.1";
            SerializeObject.Filename = FileName;
            SerializeObject.Smocod   = Batch.Receiver.Code;
            SerializeObject.Nrecords = Count;

            try
            {
                // Сериализуем
                XmlSerializationHelper.SerializeToFile(SerializeObject, GetFileNameFull(), "rec_list");
                base.SerializePersonCurrent();

                // Пишем в базу код успешной выгрзуки
                var batch = ObjectFactory.GetInstance <IBatchManager>().GetById(BatchId);
                if (batch != null)
                {
                    batch.CodeConfirm = ObjectFactory.GetInstance <IConceptCacheManager>().GetById(CodeConfirm.AA);
                    ObjectFactory.GetInstance <IBatchManager>().SaveOrUpdate(batch);
                    ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Flush();
                }
            }
            catch (Exception ex)
            {
                // Ошибка сериализации
                // Логгируем ошибку
                LogManager.GetCurrentClassLogger().Error(ex.Message, ex);
                throw;
            }
        }
Example #2
0
 private void UpdateRenderingInfoFile()
 {
     if (m_keyTermRenderingInfoFile != null)
     {
         XmlSerializationHelper.SerializeToFile(m_keyTermRenderingInfoFile, m_keyTermRenderingInfo);
     }
 }
Example #3
0
        public static void MakeGlyssenScriptFile(Project project, IEnumerable <ProjectExporter.ExportBlock> data,
                                                 string outputPath)
        {
            var glyssenScript = CreateGlyssenScript(project, data);

            XmlSerializationHelper.SerializeToFile(outputPath, glyssenScript);
        }
Example #4
0
        /// <summary>
        ///   Сериализует текущий объект пакета
        /// </summary>
        protected override void SerializePersonCurrent()
        {
            SerializeObject.VERS    = "2.1";
            SerializeObject.FNAME   = FileName;
            SerializeObject.FNAME_I = FileName.Replace("f", "i"); // Меняем префикс в имени файла ответа

            try
            {
                // Сериализуем
                XmlSerializationHelper.SerializeToFile(SerializeObject, GetFileNameFull(), "pflk_list");
                base.SerializePersonCurrent();

                // Пишем в базу код успешной выгрзуки
                var batch = ObjectFactory.GetInstance <IBatchManager>().GetById(BatchId);
                if (batch != null)
                {
                    batch.CodeConfirm = ObjectFactory.GetInstance <IConceptCacheManager>().GetById(CodeConfirm.AA);
                    ObjectFactory.GetInstance <IBatchManager>().SaveOrUpdate(batch);
                    ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Flush();
                }
            }
            catch (Exception ex)
            {
                // Ошибка сериализации
                // Логгируем ошибку
                LogManager.GetCurrentClassLogger().Error(ex.Message, ex);
                throw;
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Combines the specified path with the PapFile path to point to a pap file. That
        /// pap file is deserialized and each data source path in the pap file is modified
        /// to use that combined path. Then the pap file is rewritten and added to the
        /// program's list of recent projects.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void Modify(string path, string dataSourcePath, bool addToRecentlyUsedProjectsList)
        {
            var papFilePath = Path.Combine(path, PapFile);

            if (!File.Exists(papFilePath))
            {
                return;
            }

            var prj = XmlSerializationHelper.DeserializeFromFile <PaProject>(papFilePath);

            if (prj == null)
            {
                return;
            }

            foreach (var dataSource in prj.DataSources.Where(ds => ds.SourceFile != null))
            {
                var newPath  = dataSourcePath ?? Path.GetDirectoryName(papFilePath);
                var filename = Path.GetFileName(dataSource.SourceFile);
                dataSource.SourceFile = Path.Combine(newPath, filename);
            }

            XmlSerializationHelper.SerializeToFile(papFilePath, prj);

            if (addToRecentlyUsedProjectsList)
            {
                App.AddProjectToRecentlyUsedProjectsList(papFilePath, true);
            }
        }
Example #6
0
        /// ------------------------------------------------------------------------------------
        public Exception SaveProjectFieldDisplayProps(PaProject project)
        {
            var       path = PaFieldDisplayProperties.GetFileForProject(project.ProjectPathFilePrefix);
            Exception e    = null;

            XmlSerializationHelper.SerializeToFile(path, this, "FieldDisplayProps", out e);
            return(e);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Saves some of the specified grid's properties.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void Save(DataGridView grid)
        {
            if (grid == null || grid.Columns.Count == 0)
            {
                return;
            }

            GridLines = grid.CellBorderStyle;

            if (SaveAdjustedColHeaderHeight)
            {
                ColHeaderHeight = grid.ColumnHeadersHeight;
            }

            // Save the list of columns sorted by display index.
            var displayIndexes = new SortedList <int, PaField>();

            // Save the specified grid's column properties.
            foreach (var col in grid.Columns.Cast <DataGridViewColumn>())
            {
                var field = _project.GetFieldForName(col.Name);
                if (field != null)
                {
                    if (SaveAdjustedColWidths)
                    {
                        field.WidthInGrid = col.Width;
                    }

                    if (SaveReorderedCols)
                    {
                        displayIndexes[col.DisplayIndex] = field;
                    }
                }
            }

            if (displayIndexes.Count > 0)
            {
                // The display index order saved with the fields should begin with zero, but
                // since the grid may have some SilHerarchicalColumns showing, the first field's
                // display index may be greater than 1. Therefore, we adjust for that by setting
                // the display indexes in sequence beginning from zero.
                int i = 0;
                foreach (var field in displayIndexes.Values)
                {
                    field.DisplayIndexInGrid = i++;
                }
            }

            var filename = _project.ProjectPathFilePrefix + kFiltersFilePrefix;

            XmlSerializationHelper.SerializeToFile(filename, this);
            PaField.SaveProjectFields(_project);
        }
Example #8
0
        /// ------------------------------------------------------------------------------------
        public static Exception SaveProjectFields(PaProject project)
        {
            if (s_displayPropsCache == null)
            {
                s_displayPropsCache = FieldDisplayPropsCache.LoadProjectFieldDisplayProps(project);
            }

            var e    = s_displayPropsCache.SaveProjectFieldDisplayProps(project);
            var path = project.ProjectPathFilePrefix + "Fields.xml";

            XmlSerializationHelper.SerializeToFile(path, project.Fields.ToList(), "Fields", out e);
            return(e);
        }
Example #9
0
        /// <summary>
        /// Выгружает ADT_A01 для выполнения ФЛК с помощью шлюза РС
        /// </summary>
        /// <param name="batch">
        /// The batch.
        /// </param>
        /// <param name="statement">
        /// The statement.
        /// </param>
        public void ExportAdtA01ForFlk(Batch batch, Statement statement)
        {
            var personErp = GetPersonErp(batch, statement);
            var path      = Path.Combine(ConfigManager.ExchangeSettings.WorkingFolderExchange, "Out", "Gateway", "Input");

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

            var file = Path.Combine(path, batch.FileName);

            XmlSerializationHelper.SerializeToFile(personErp, file, "person_list");
        }
Example #10
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Saves this instance of the person info to its file.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void Save()
        {
            FullName = (FullName ?? Project.GetUniquePersonName()).Trim();
            if (FullName == string.Empty)
            {
                FullName = Project.GetUniquePersonName();
            }

            EnsureFolderExists();

            if (CanSave)
            {
                XmlSerializationHelper.SerializeToFile(FullFilePath, this);
            }
        }
Example #11
0
        private static List <Tu> ProcessLanguage(string modifiedLangAbbr, Action <TmxFormat, Tu, string> addTerm)
        {
            string outputFileName = Path.Combine(kLocalizationFolder, "Glyssen." + modifiedLangAbbr + ".tmx");

            TmxFormat newTmx;

            if (File.Exists(outputFileName))
            {
                newTmx = XmlSerializationHelper.DeserializeFromFile <TmxFormat>(outputFileName);

                var tus = newTmx.Body.Tus;

                // If this is not a language that has been worked on by a localizer, we can safely blow
                // away everything and start from scratch. Otherwise, we only want to remove translation units
                // which no longer exist in English.
                if (s_languagesWithCustomizedTranslations.Contains(modifiedLangAbbr))
                {
                    tus.RemoveAll(lt => lt.Tuid.StartsWith("CharacterName.") && !s_englishTranslationUnits.Any(ent => ent.Tuid == lt.Tuid));
                }
                else
                {
                    tus.RemoveAll(t => t.Tuid.StartsWith("CharacterName."));
                }
            }
            else
            {
                newTmx = new TmxFormat();
                newTmx.Header.SrcLang  = modifiedLangAbbr;
                newTmx.Header.Props    = new Prop[2];
                newTmx.Header.Props[0] = new Prop("x-appversion", "0.17.0.0");
                newTmx.Header.Props[1] = new Prop("x-hardlinebreakreplacement", "\\n");
            }

            foreach (string name in s_names)
            {
                Tu tmxTermEntry = new Tu("CharacterName." + name)
                {
                    Prop = new Prop("x-dynamic", "true")
                };
                tmxTermEntry.Tuvs.Add(new Tuv("en", name));

                addTerm(newTmx, tmxTermEntry, name);
            }

            XmlSerializationHelper.SerializeToFile(outputFileName, newTmx);

            return(newTmx.Body.Tus);
        }
Example #12
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Saves this instance of the session to it's file.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public bool Save()
        {
            // REVIEW: Should probably be more intelligent in responding to when saving fails.

            if (string.IsNullOrEmpty(Id))
            {
                return(false);
            }

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

            return(XmlSerializationHelper.SerializeToFile(FullFilePath, this));
        }
        public static void Generate(string sourceQuestionsFilename, string alternativesFilename, string destFilename)
        {
            Dictionary <string, string[]> alternatives = null;

            if (alternativesFilename != null)
            {
                QuestionAlternativeOverrides qAlts = XmlSerializationHelper.DeserializeFromFile <QuestionAlternativeOverrides>(alternativesFilename);
                //alternatives = new Dictionary<string, string[]>();
                //foreach (Alternative a in qAlts.Items)
                //{
                //    Debug.Assert(!alternatives.ContainsKey(a.Text));
                //    alternatives[a.Text] = a.AlternateForms;
                //}
                alternatives = qAlts.Items.ToDictionary(a => a.Text, a => a.AlternateForms);
            }
            XmlSerializationHelper.SerializeToFile(destFilename, Generate(SourceLines(sourceQuestionsFilename), alternatives));
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Saves the list of ambiguous sequences to a project-specific xml file.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void Save(string pathPrefix)
        {
            var tmpList = new AmbiguousSequences(this);

            // Before saving, make sure there are no empty or null units
            // and get rid of those sequences that were added automatically.
            for (int i = tmpList.Count - 1; i >= 0; i--)
            {
                string unit = tmpList[i].Literal;
                if (unit == null || unit.Trim().Length == 0)
                {
                    tmpList.RemoveAt(i);
                }
            }

            XmlSerializationHelper.SerializeToFile(pathPrefix + kFileName, tmpList);
        }
Example #15
0
        private void OnBackgroundProcessorWorkCompleted(object s, RunWorkerCompletedEventArgs args)
        {
            if (m_passes.Count == 0)
            {
                foreach (var newRefTextRow in m_dataGridRefTexts.Rows.OfType <DataGridViewRow>().Where(r => s_createActions.Contains((string)r.Cells[colAction.Index].Value) && !r.Cells[colHeSaidText.Index].ReadOnly && !r.Cells[colIsoCode.Index].ReadOnly))
                {
                    // Generate a new metadata file with the above info
                    var languageName = (string)newRefTextRow.Cells[colName.Index].Value;
                    var folder       = Data.GetLanguageInfo(languageName).OutputFolder;
                    var projectPath  = Path.Combine(folder, languageName + Constants.kProjectFileExtension);
                    if (File.Exists(projectPath))
                    {
                        HandleMessageRaised($"File {projectPath} already exists! Skipping. Please verify contents.", true);
                    }
                    else
                    {
                        var metadata = XmlSerializationHelper.DeserializeFromString <GlyssenDblTextMetadata>(Resources.refTextMetadata);
                        metadata.Language = new GlyssenDblMetadataLanguage
                        {
                            Name       = languageName,
                            HeSaidText = newRefTextRow.Cells[colHeSaidText.Index].Value as string,
                            Iso        = newRefTextRow.Cells[colIsoCode.Index].Value as string
                        };
                        metadata.AvailableBooks = new List <Book>();
                        ProjectUtilities.ForEachBookFileInProject(folder,
                                                                  (bookId, fileName) => metadata.AvailableBooks.Add(new Book {
                            Code = bookId, IncludeInScript = true
                        }));
                        metadata.LastModified = DateTime.Now;

                        Exception error;
                        XmlSerializationHelper.SerializeToFile(projectPath, metadata, out error);
                        if (error != null)
                        {
                            HandleMessageRaised(error.Message, true);
                        }
                    }
                }
                m_btnOk.Enabled = m_btnSkipAll.Enabled = true;
            }
            else
            {
                BackgroundProcessor.RunWorkerAsync();
            }
        }
Example #16
0
        /// ------------------------------------------------------------------------------------
        public static void Save()
        {
            if (s_cache == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(s_tmpFilename))
            {
                s_tmpFilename = Path.GetTempFileName();
            }

            var tmpList = s_cache.Select(e => new TempRecordCacheEntry(e.Key, e.Value)).ToList();

            XmlSerializationHelper.SerializeToFile(s_tmpFilename, tmpList);
            s_cache.Clear();
            tmpList.Clear();
            s_cache = null;
        }
Example #17
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Saves this instance of a SessionFile to it's standoff markup file.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public void Save()
 {
     try
     {
         if (Directory.Exists(Path.GetDirectoryName(FullFilePath)))
         {
             XmlSerializationHelper.SerializeToFile(GetStandoffFile(FullFilePath), this);
         }
         else
         {
             //TODO: this happens because of renaming of the project, whic at the moment
             //can't happen while we have data which hasn't been saved already.  Anyhow,
             //this all needs redesign, as the addition of renaming has led to many many
             //problems of this sort.
         }
     }
     catch (Exception e)
     {
         Palaso.Reporting.ErrorReport.NotifyUserOfProblem(e, "Could not save {0}", FullFilePath);
     }
 }
Example #18
0
        /// <summary>
        ///   Сериализует текущий объект пакета
        /// </summary>
        protected override void SerializePersonCurrent()
        {
            SerializeObject.VERS     = "2.1";
            SerializeObject.FILENAME = FileName;
            SerializeObject.SMOCOD   = Batch.Receiver.Code;
            SerializeObject.NRECORDS = Count;
            SerializeObject.NERR     = SerializeObject.REP.Count(x => x.CODE_ERP == CodeConfirm.CA);

            // Вычисляем код ПВП
            SerializeObject.PRZCOD = null;
            var splittedFileName = Batch.FileName.Split(new[] { '_' });

            if (splittedFileName.Length == 3)
            {
                SerializeObject.PRZCOD = splittedFileName[1];
            }

            try
            {
                // Сериализуем
                XmlSerializationHelper.SerializeToFile(SerializeObject, GetFileNameFull(), "rep_list");
                base.SerializePersonCurrent();

                // Пишем в базу код успешной выгрзуки
                var batch = ObjectFactory.GetInstance <IBatchManager>().GetById(BatchId);
                if (batch != null)
                {
                    batch.CodeConfirm = ObjectFactory.GetInstance <IConceptCacheManager>().GetById(CodeConfirm.AA);
                    ObjectFactory.GetInstance <IBatchManager>().SaveOrUpdate(batch);
                    ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Flush();
                }
            }
            catch (Exception ex)
            {
                // Ошибка сериализации
                // Логгируем ошибку
                LogManager.GetCurrentClassLogger().Error(ex.Message, ex);
                throw;
            }
        }
Example #19
0
        public static void Process()
        {
            foreach (var cv in ControlCharacterVerseData.Singleton.GetAllQuoteInfo())
            {
                var s = cv.LocalizedAlias;
                AddNames(cv.Character);
                if (!string.IsNullOrEmpty(cv.Alias))
                {
                    AddNames(cv.Alias);
                }
                if (!string.IsNullOrEmpty(cv.DefaultCharacter))
                {
                    AddNames(cv.DefaultCharacter);
                }
            }

            s_englishTermsList = DeserializeBiblicalTermsForLanguage("En");

            s_englishTranslationUnits = ProcessLanguage("en", AddEnglishTerm);

            foreach (string langAbbr in s_languagesToProcess)
            {
                BiblicalTermsLocalizations localTermsList = DeserializeBiblicalTermsForLanguage(langAbbr);
                var modifiedLangAbbr = Char.ToLowerInvariant(langAbbr[0]) + langAbbr.Substring(1);
                Action <TmxFormat, Tu, Tuv> processLocalizedGloss = s_languagesWithCustomizedTranslations.Contains(modifiedLangAbbr)
                                        ? (Action <TmxFormat, Tu, Tuv>)UpdateEntryWithLocalizedGloss : AddEntryWithLocalizedGloss;
                ProcessLanguage(modifiedLangAbbr,
                                (tmx, tu, name) => { AddLocalizedTerm(tmx, modifiedLangAbbr, localTermsList, tu, name, processLocalizedGloss); });
            }

            foreach (var conflictingLocalization in s_conflictingLocalizations)
            {
                var path = Path.Combine(kLocalizationFolder, "LocalizationsFromParatextBiblicalTerms." + conflictingLocalization.Key + ".tmx");
                XmlSerializationHelper.SerializeToFile(path, conflictingLocalization.Value);
            }
        }
Example #20
0
 public void Save()
 {
     XmlSerializationHelper.SerializeToFile(FilePath, this);
 }
Example #21
0
 /// ------------------------------------------------------------------------------------
 public void Save()
 {
     XmlSerializationHelper.SerializeToFile(
         GetFileForProject(m_project.ProjectPathFilePrefix), this);
 }
        /// ------------------------------------------------------------------------------------
        public void Save()
        {
            var filename = GetFileForProject(m_project.ProjectPathFilePrefix);

            XmlSerializationHelper.SerializeToFile(filename, this);
        }
Example #23
0
 public void SaveToFile(string filename)
 {
     XmlSerializationHelper.SerializeToFile(filename, this);
 }
Example #24
0
 /// <summary>
 ///   Сериализует текущий объект пакета
 /// </summary>
 protected override void SerializePersonCurrent()
 {
     BuildZglv();
     XmlSerializationHelper.SerializeToFile(SerializeObject, GetFileNameFull(), "snils_zl_list");
     base.SerializePersonCurrent();
 }
Example #25
0
        static void Main(string[] args)
        {
            //var key = "b698bd6365f99a2d28ff5f2953d9de804742cf47baccb1890719397253564652";
            //var key = "e5457c652514029496f7eda5d48fbad171d94b74747f59bc2f592e1a4adc762a";
            //var key = "07fbb153f650b9a882fd916f59d3b84c694b3f6457174cdab8e3470f380c4e7c";
            var key          = "1c8949783fd75ec3a72bbcc3a668eb378f780292c04fd5803d305076dc080036";
            var destination  = @"..\KeesTalksTech.Assessments.Wehkamp.Store.StoreApi\data\products.xml";
            var imagesBackup = @"..\KeesTalksTech.Assessments.Wehkamp.Store.WebApp\wwwroot\images\backup\";

            var client     = new UnsplasharpClient(key);
            var randomizer = new Random();

            List <PhotoProduct> products = new List <PhotoProduct>();

            Console.WriteLine("This tool will generate a products.xml database based on Unsplash photos.");
            Console.WriteLine("Unsplash has a rate limit of 50 request / hour.");

            string[] keywords =
            {
                "lights",   "cloths", "Berlin",  "Paris", "computer", "phone",
                "building", "food",   "love",    "smile", "music",
                "animal",   "car",    "sports",  "bird",  "Beauty",
                "fashion",  "tools",  "working", "wild",  "water",    "portrait",
                "winter",   "summer"
            };

            foreach (var keyword in keywords)
            {
                Console.WriteLine();
                Console.WriteLine($"Downloading '{keyword}' photos from Unsplash.com...");

                var photosTask = client.SearchPhotos(keyword, 1, 30);
                var photos     = photosTask.Result;

                var photosTask2 = client.SearchPhotos(keyword, 2, 30);
                var photos2     = photosTask.Result;

                photos.AddRange(photos2);

                var processed = photos
                                //skip photos without a description
                                .Where(p => !String.IsNullOrEmpty(p.Description))
                                .Where(p => products.FirstOrDefault(p2 => p2.Id == p.Id) == null)
                                .Select(p => new PhotoProduct
                {
                    Id           = p.Id,
                    Name         = p.Description,
                    Description  = $"Photo was taken by {p.User.Name} on {p.CreatedAt}. The primary color of this photo is {p.Color}. Original is {p.Height}x{p.Width}.",
                    PictureUrl   = p.Urls.Regular,
                    ThumbnailUrl = p.Urls.Small,
                    Price        = new PhotoProductPrice()
                    {
                        Amount = Randomizer.GenerateRandomNumber(1, 25, 2)
                    },
                    Keywords    = GetKeywords(p, keyword),
                    Orientation = GetOrientation(p)
                })
                                .ToList();

                processed.ForEach(p => products.Add(p));

                Console.WriteLine($"{processed.Count} downloaded.");
            }

            Console.WriteLine();
            Console.WriteLine($"{products.Count} photo records downloaded.");
            Console.WriteLine();
            Console.WriteLine($"Writing products to file...");

            var path = Directory.GetCurrentDirectory();

            path = Path.Combine(path, destination);

            XmlSerializationHelper.SerializeToFile(path, products);

            Console.WriteLine();
            Console.WriteLine("Downloading backup images...");

            Directory.CreateDirectory(imagesBackup);
            using (var downloader = new HttpClient())
            {
                products.ForEach(p =>
                {
                    Console.WriteLine("Downloading " + p.Id);
                    var s1 = DownloadFile(downloader, p.ThumbnailUrl, Path.Combine(imagesBackup, p.Id + "_tn.jpg")).Result;
                    var s2 = DownloadFile(downloader, p.PictureUrl, Path.Combine(imagesBackup, p.Id + ".jpg")).Result;
                });
            }


            Console.WriteLine();
            Console.WriteLine("Ready!");
            Console.ReadLine();
        }
        /// ------------------------------------------------------------------------------------
        public void Save()
        {
            var filename = m_project.ProjectPathFilePrefix + kFiltersFilePrefix;

            XmlSerializationHelper.SerializeToFile(filename, Filters, "filters");
        }
 /// ------------------------------------------------------------------------------------
 public void Save(string pathPrefix)
 {
     XmlSerializationHelper.SerializeToFile(pathPrefix + kFileName, this);
 }
Example #28
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Saves the transcription file for the current document.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private bool Save(string audioFile)
        {
            var tmpFile = Path.GetDirectoryName(audioFile);

            tmpFile = Path.Combine(tmpFile, "~#!tstWrite!#~");
            try
            {
                // Check to see if the folder and transcription file are writable
                File.WriteAllText(tmpFile, string.Empty);
                string transFilePath = Path.ChangeExtension(audioFile, ".saxml");
                if (File.Exists(transFilePath) &&
                    ((File.GetAttributes(transFilePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly))
                {
                    throw new Exception();
                }
            }
            catch
            {
                // Warn the user that we don't have write privileges
                var audioFileNameOnly = Path.GetFileName(audioFile);
                var transFileNameOnly = Path.ChangeExtension(audioFileNameOnly, ".saxml");

                var msg = LocalizationManager.GetString("Miscellaneous.Messages.DataSourceReading.ReadOnlyFolderMsg",
                                                        "You are attempting to save the transcriptions for {0} in a location for which you do not have write access. Please specify another location in which to make a copy of {1} along with its transcription file ({2}).");

                msg = string.Format(msg, audioFileNameOnly, audioFileNameOnly, transFileNameOnly);
                Utils.MsgBox(Utils.ConvertLiteralNewLines(msg));

                using (var dlg = new FolderBrowserDialog())
                {
                    // Ask the user for a different folder in which to write the transcription file.
                    dlg.ShowNewFolderButton = true;
                    if (dlg.ShowDialog() == DialogResult.Cancel)
                    {
                        return(false);
                    }

                    // Construct the new path for the audio file based on the path the user chose.
                    audioFile = Path.Combine(dlg.SelectedPath, audioFileNameOnly);
                }

                // Try again.
                Save(audioFile);
            }

            try
            {
                File.Delete(tmpFile);
            }
            catch { }

            // If the specified audio file doesn't exist, it means it's original
            // location is read-only. Therefore, copy it to the newly specified
            // location.
            if (!File.Exists(audioFile))
            {
                // Copy the audio file to the new path and save the new path.
                File.Copy(AudioFile, audioFile);
                AudioFile = audioFile;
            }

            return(XmlSerializationHelper.SerializeToFile(TranscriptionFile, this));
        }
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Serializes to file.
 /// </summary>
 /// <param name="filename">The filename.</param>
 /// <returns><c>true</c> if successfully serialized; <c>false</c> otherwise</returns>
 /// ------------------------------------------------------------------------------------
 public bool SerializeToFile(string filename)
 {
     return(XmlSerializationHelper.SerializeToFile(filename, this));
 }
Example #30
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Saves this instance.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public static void Save()
 {
     XmlSerializationHelper.SerializeToFile(s_settingFileName, AllFDOClasses);
 }