Exemplo n.º 1
0
        private static ILocalisation LocalisationRequested(ServiceScope scope)
        {
            ILocalisation loc = new NoLocalisation();

            scope.ReplaceService(loc);
            return(loc);
        }
Exemplo n.º 2
0
 public static void SaveAllSettings()
 {
     ServiceScope.Get <ISettingsManager>().Save(_MPTagThatSettings);
     ServiceScope.Get <ISettingsManager>().Save(_fileNameToTagSettings);
     ServiceScope.Get <ISettingsManager>().Save(_tagToFileNameSettings);
     ServiceScope.Get <ISettingsManager>().Save(_caseConversionSettings);
     ServiceScope.Get <ISettingsManager>().Save(_organiseSettings);
     ServiceScope.Get <ISettingsManager>().Save(_treeViewFilterSettings);
 }
Exemplo n.º 3
0
        public void NotifyThemeChange()
        {
            QueueMessage msg = new QueueMessage();

            msg.MessageData["action"] = "themechanged";
            IMessageQueue queue = ServiceScope.Get <IMessageBroker>().GetOrCreate("message");

            queue.Send(msg);
        }
Exemplo n.º 4
0
        /// <summary>
        ///   Changes the language.
        /// </summary>
        /// <param name = "cultureName">Name of the culture.</param>
        public void ChangeLanguage(string cultureName)
        {
            _stringProvider.ChangeLanguage(cultureName);
            RegionSettings settings = new RegionSettings();

            ServiceScope.Get <ISettingsManager>().Load(settings);
            settings.Culture = cultureName;
            ServiceScope.Get <ISettingsManager>().Save(settings);
        }
        public void Save()
        {
            NLog.Logger log = ServiceScope.Get <ILogger>().GetLogger;
            log.Trace("Saving({0},{1})", filename, modified.ToString());
            if (!modified)
            {
                return;
            }
            if (!Directory.Exists(Options.ConfigDir))
            {
                Directory.CreateDirectory(Options.ConfigDir);
            }

            string fullFilename = String.Format(@"{0}\{1}", Options.ConfigDir, filename);

            log.Trace("Saving {0}", fullFilename);
            if (document == null)
            {
                return;
            }
            if (document.DocumentElement == null)
            {
                return;
            }
            if (document.ChildNodes.Count == 0)
            {
                return;
            }
            if (document.DocumentElement.ChildNodes == null)
            {
                return;
            }
            try
            {
                if (File.Exists(fullFilename + ".bak"))
                {
                    File.Delete(fullFilename + ".bak");
                }
                if (File.Exists(fullFilename))
                {
                    File.Move(fullFilename, fullFilename + ".bak");
                }
            }

            catch (Exception) {}

            using (StreamWriter stream = new StreamWriter(fullFilename, false))
            {
                document.Save(stream);
                stream.Flush();
                stream.Close();
            }
            modified = false;
        }
Exemplo n.º 6
0
        public ReadOnlyDialog(string fileName)
        {
            InitializeComponent();

            BackColor = ServiceScope.Get <IThemeManager>().CurrentTheme.BackColor;

            labelHeader.Text = ServiceScope.Get <ILocalisation>().ToString("readonly", "Header");
            lbFile.Text      = fileName;

            ServiceScope.Get <IThemeManager>().NotifyThemeChange();
        }
Exemplo n.º 7
0
        public StringManager()
        {
            RegionSettings settings = new RegionSettings();

            ServiceScope.Get <ISettingsManager>().Load(settings);

            if (settings.Culture == string.Empty)
            {
                _stringProvider  = new LocalisationProvider("Language", null);
                settings.Culture = _stringProvider.CurrentCulture.Name;
                ServiceScope.Get <ISettingsManager>().Save(settings);
            }
            else
            {
                _stringProvider = new LocalisationProvider("Language", settings.Culture);
            }
        }
Exemplo n.º 8
0
 private void Dispose(bool alsoManaged)
 {
     if (isDisposed) //already disposed?
     {
         return;
     }
     if (alsoManaged)
     {
         bool updateGlobal = current == global;
         current = oldInstance; //set current scope to previous one
         if (updateGlobal)
         {
             global = current;
         }
     }
     isDisposed = true;
 }
Exemplo n.º 9
0
        public Assembly Load(string script)
        {
            string scriptFile = String.Format(@"scripts\{0}", script);

            try
            {
                string configDir          = Options.ConfigDir.Substring(0, Options.ConfigDir.LastIndexOf("\\"));
                string compiledScriptsDir = Path.Combine(configDir, @"scripts\compiled");
                if (!Directory.Exists(compiledScriptsDir))
                {
                    Directory.CreateDirectory(compiledScriptsDir);
                }

                string finalName = String.Format(@"{0}.dll", Path.GetFileNameWithoutExtension(scriptFile));
                finalName = Path.Combine(compiledScriptsDir, finalName);
                string name = String.Format(@"{0}.dll", Path.GetFileNameWithoutExtension(scriptFile));

                // The script file could have been deleted while already executing the progrsm
                if (!File.Exists(scriptFile) && !File.Exists(finalName))
                {
                    return(null);
                }

                DateTime lastwriteSourceFile = File.GetLastWriteTime(scriptFile);

                // Load the compiled Assembly only, if it is newer than the source file, to get changes done on the file
                if (File.Exists(finalName) && File.GetLastWriteTime(finalName) > lastwriteSourceFile)
                {
                    _assembly = Assembly.LoadFile(finalName);
                }
                else
                {
                    _assembly = CSScript.Load(scriptFile, finalName, true);

                    // And reload the assembly from the compiled dir, so that we may execute it
                    Assembly.LoadFile(finalName);
                }
                return(_assembly);
            }
            catch (Exception ex)
            {
                ServiceScope.Get <ILogger>().GetLogger.Error("Error loading script: {0} {1}", scriptFile, ex.Message);
                return(null);
            }
        }
Exemplo n.º 10
0
        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
                                      DataGridViewElementStates elementState, object value, object formattedValue,
                                      string errorText, DataGridViewCellStyle cellStyle,
                                      DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            Image cellImage = (Image)formattedValue;

            int starNumber = (int)value;

            if (starNumber > -1 && starNumber < 6)
            {
                cellImage = starHotImages[starNumber];
            }

            if (DataGridView.Rows[rowIndex].Selected)
            {
                cellStyle.BackColor =
                    ServiceScope.Get <IThemeManager>().CurrentTheme.SelectionBackColor;
            }
            else
            {
                if ((string)this.DataGridView.Rows[rowIndex].Tag == "Changed")
                {
                    cellStyle.BackColor =
                        ServiceScope.Get <IThemeManager>().CurrentTheme.ChangedBackColor;
                }
                else
                {
                    if (rowIndex % 2 == 0)
                    {
                        cellStyle.BackColor =
                            ServiceScope.Get <IThemeManager>().CurrentTheme.DefaultBackColor;
                    }
                    else
                    {
                        cellStyle.BackColor =
                            ServiceScope.Get <IThemeManager>().CurrentTheme.AlternatingRowBackColor;
                    }
                }
            }

            // surpress painting of selection
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, cellImage, errorText, cellStyle,
                       advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.SelectionBackground));
        }
Exemplo n.º 11
0
        public void ChangeLanguage(string cultureName)
        {
            if (!_availableLanguages.ContainsKey(cultureName))
            {
                throw new ArgumentException("Language not available");
            }

            _currentLanguage = _availableLanguages[cultureName];

            ReloadAll();

            QueueMessage msg = new QueueMessage();

            msg.MessageData["action"] = "languagechanged";
            IMessageQueue queue = ServiceScope.Get <IMessageBroker>().GetOrCreate("message");

            queue.Send(msg);
        }
Exemplo n.º 12
0
 public ServiceScope(bool isFirst)
 {
     lock (syncObject)
     {
         bool updateGlobal = global == current;
         oldInstance = current;
         services    = new Dictionary <Type, object>();
         current     = this;
         if (updateGlobal)
         {
             global = this;
         }
         if (isFirst)
         {
             isRunning = true;
         }
     }
 }
Exemplo n.º 13
0
        public StringId(string skinLabel)
        {
            // Parse string example @mytv#10
            Regex label = new Regex("@(?<section>[a-z]+):(?<id>[a-z][0-9]+)");

            Match combineString = label.Match(skinLabel);

            if (combineString.Success)
            {
                _section = combineString.Groups["section"].Value;
                _id      = combineString.Groups["id"].Value;
            }
            else
            {
                ServiceScope.Get <ILogger>().GetLogger.Error("String Manager - Invalid string Id: {0}", skinLabel);
                _section = "system";
                _id      = "NotFound";
            }
        }
Exemplo n.º 14
0
        private void LoadStrings(string directory, string language, bool log)
        {
            string filename = "strings_" + language + ".xml";

            ServiceScope.Get <ILogger>().GetLogger.Info("Loading strings file: {0}", filename);

            string path = Path.Combine(directory, filename);

            if (File.Exists(path))
            {
                StringFile strings;
                try
                {
                    XmlSerializer s = new XmlSerializer(typeof(StringFile));
                    TextReader    r = new StreamReader(path);
                    strings = (StringFile)s.Deserialize(r);
                }
                catch (Exception ex)
                {
                    ServiceScope.Get <ILogger>().GetLogger.Error("Error loading strings file: {0}", ex.Message);
                    return;
                }

                foreach (StringLocalised languageString in strings.localisedStrings)
                {
                    // No case matching.
                    languageString.id = languageString.id.ToLower();
                    if (_languageStrings.ContainsKey(languageString.id))
                    {
                        continue;
                    }

                    languageString.language = language;
                    _languageStrings.Add(languageString.id, languageString);
                    if (log)
                    {
                        ServiceScope.Get <ILogger>()
                        .GetLogger.Info("    String not found, using English: {0}", languageString.ToString());
                    }
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// The number of allowed objects in the BindingList has been exceeded
        /// Copy all the data to the database
        /// </summary>
        private void CopyLIstToDatabase()
        {
            ServiceScope.Get <ILogger>().GetLogger.Debug("Number of Songs in list exceeded the limit. Database mode enabled");

            if (!CreateDbConnection())
            {
                return;
            }

            _dbIdList.Clear();

            foreach (TrackData track in _bindingList)
            {
                _db.Store(track);
                _dbIdList.Add(_dbIdList.Count, track.Id);
            }

            _bindingList.Clear();
            _databaseModeEnabled = true;
            ServiceScope.Get <ILogger>().GetLogger.Debug("Finished enabling database mode.");
        }
Exemplo n.º 16
0
        private void ReadArtistDatabase()
        {
            if (!File.Exists(_MPTagThatSettings.MediaPortalDatabase))
            {
                return;
            }

            string connection = string.Format(@"Data Source={0}", _MPTagThatSettings.MediaPortalDatabase);

            try
            {
                SQLiteConnection conn = new SQLiteConnection(connection);
                conn.Open();
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText =
                        "select distinct strartist from artist union select stralbumartist from albumartist order by 1";
                    using (SQLiteDataReader reader = cmd.ExecuteReader())
                    {
                        List <string> rows = new List <string>();
                        while (reader.Read())
                        {
                            rows.Add(reader.GetString(0));
                        }

                        // Now copy the list to the string array
                        string[] tmpArray = rows.ToArray();
                        _mediaPortalArtists = (string[])tmpArray.Clone();
                    }
                }
                conn.Close();
            }
            catch (Exception ex)
            {
                ServiceScope.Get <ILogger>().GetLogger.Error("Error reading Music Database: {0}", ex.Message);
            }
        }
Exemplo n.º 17
0
        public static TrackData.MP3Error ValidateMp3File(string fileName, out string strError)
        {
            ValidateOrFixFile(fileName, false);

            strError = "";
            // we might have an error in mp3val. the Log should contain the error
            if (StdOutList.Count == 0)
            {
                return(TrackData.MP3Error.NoError);
            }

            TrackData.MP3Error error = TrackData.MP3Error.NoError;

            // No errors found
            if (StdOutList[0].Contains("Done!"))
            {
                return(TrackData.MP3Error.NoError);
            }
            else if (StdOutList[0].Contains(@"No supported tags in the file"))
            {
                return(TrackData.MP3Error.NoError); // Fixed by MPTagThat :-)
            }
            else if (StdOutList[0].Contains(@"Garbage at the beginning of the file"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "01");
            }
            else if (StdOutList[0].Contains(@"Garbage at the end of the file"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "02");
            }
            else if (StdOutList[0].Contains(@"MPEG stream error, resynchronized successfully"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "03");
            }
            else if (StdOutList[0].Contains(@"This is a RIFF file, not MPEG stream"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "04");
            }
            else if (StdOutList[0].Contains(@"It seems that file is truncated or there is garbage at the end of the file"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "05");
            }
            else if (StdOutList[0].Contains(@"Wrong number of MPEG frames specified in Xing header"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "06");
            }
            else if (StdOutList[0].Contains(@"Wrong number of MPEG data bytes specified in Xing header"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "07");
            }
            else if (StdOutList[0].Contains(@"Wrong number of MPEG frames specified in VBRI header"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "08");
            }
            else if (StdOutList[0].Contains(@"Wrong number of MPEG data bytes specified in VBRI header"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "09");
            }
            else if (StdOutList[0].Contains(@"Wrong CRC in"))
            {
                error    = TrackData.MP3Error.Fixable; // Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "10");
            }
            else if (StdOutList[0].Contains(@"Several APEv2 tags in one file"))
            {
                return(TrackData.MP3Error.NoError); // Handled by MPTagThat
            }
            else if (StdOutList[0].Contains(@"Too few MPEG frames"))
            {
                error    = TrackData.MP3Error.NonFixable; // Non Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "11");
            }
            else if (StdOutList[0].Contains(@"VBR detected, but no VBR header is present. Seeking may not work properly"))
            {
                error    = TrackData.MP3Error.NonFixable; // Non Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "12");
            }
            else if (StdOutList[0].Contains(@"Different MPEG versions or layers in one file"))
            {
                error    = TrackData.MP3Error.NonFixable; // Non Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "13");
            }
            else if (StdOutList[0].Contains(@"Non-layer-III frame encountered"))
            {
                error    = TrackData.MP3Error.NonFixable; // Non Fixable error
                strError = ServiceScope.Get <ILocalisation>().ToString("mp3val", "14");
            }

            if (error == TrackData.MP3Error.Fixable)
            {
                log.Warn("MP3 Validate Fixable error: {0}", StdOutList[0]);
            }
            else if (error == TrackData.MP3Error.NonFixable)
            {
                log.Warn("MP3 Validate Non-Fixable error: {0}", StdOutList[0]);
            }

            // This happens, if we fixed an error
            if (StdOutList.Count > 2)
            {
                if (StdOutList[StdOutList.Count - 2].Contains(@"FIXED:"))
                {
                    error = TrackData.MP3Error.Fixed;
                }
            }

            return(error);
        }
Exemplo n.º 18
0
 internal static void Reset()
 {
     current   = null;
     global    = null;
     isRunning = false;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Save the Modified file
        /// </summary>
        /// <param name="track"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public static bool SaveFile(TrackData track, ref string errorMessage)
        {
            errorMessage = "";
            if (!track.Changed)
            {
                return(true);
            }

            if (track.Readonly && !Options.MainSettings.ChangeReadOnlyAttributte &&
                (Options.ReadOnlyFileHandling == 0 || Options.ReadOnlyFileHandling == 2))
            {
                Form         dlg       = new ReadOnlyDialog(track.FullFileName);
                DialogResult dlgResult = dlg.ShowDialog();

                switch (dlgResult)
                {
                case DialogResult.Yes:
                    Options.ReadOnlyFileHandling = 0; // Yes
                    break;

                case DialogResult.OK:
                    Options.ReadOnlyFileHandling = 1; // Yes to All
                    break;

                case DialogResult.No:
                    Options.ReadOnlyFileHandling = 2; // No
                    break;

                case DialogResult.Cancel:
                    Options.ReadOnlyFileHandling = 3; // No to All
                    break;
                }
            }

            if (track.Readonly)
            {
                if (!Options.MainSettings.ChangeReadOnlyAttributte && Options.ReadOnlyFileHandling > 1)
                {
                    errorMessage = "File is readonly";
                    return(false);
                }

                try
                {
                    System.IO.File.SetAttributes(track.FullFileName,
                                                 System.IO.File.GetAttributes(track.FullFileName) & ~FileAttributes.ReadOnly);

                    track.Readonly = false;
                }
                catch (Exception ex)
                {
                    log.Error("File Save: Can't reset Readonly attribute: {0} {1}", track.FullFileName, ex.Message);
                    errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "ErrorResetAttr");
                    return(false);
                }
            }

            TagLib.File file  = null;
            bool        error = false;

            try
            {
                TagLib.ByteVector.UseBrokenLatin1Behavior = true;
                file = TagLib.File.Create(track.FullFileName);
            }
            catch (CorruptFileException)
            {
                log.Warn("File Read: Ignoring track {0} - Corrupt File!", track.FullFileName);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "CorruptFile");
                error        = true;
            }
            catch (UnsupportedFormatException)
            {
                log.Warn("File Read: Ignoring track {0} - Unsupported format!", track.FullFileName);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "UnsupportedFormat");
                error        = true;
            }
            catch (FileNotFoundException)
            {
                log.Warn("File Read: Ignoring track {0} - Physical file no longer existing!", track.FullFileName);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "NonExistingFile");
                error        = true;
            }
            catch (Exception ex)
            {
                log.Error("File Read: Error processing file: {0} {1}", track.FullFileName, ex.Message);
                errorMessage = string.Format(ServiceScope.Get <ILocalisation>().ToString("message", "ErrorReadingFile"), ex.Message);
                error        = true;
            }

            if (file == null || error)
            {
                log.Error("File Read: Error processing file.: {0}", track.FullFileName);
                return(false);
            }

            try
            {
                // Get the ID3 Frame for ID3 specifc frame handling
                TagLib.Id3v1.Tag id3v1tag = null;
                TagLib.Id3v2.Tag id3v2tag = null;
                if (track.IsMp3)
                {
                    id3v1tag = file.GetTag(TagTypes.Id3v1, true) as TagLib.Id3v1.Tag;
                    id3v2tag = file.GetTag(TagTypes.Id3v2, true) as TagLib.Id3v2.Tag;
                }

                // Remove Tags, if they have been removed in TagEdit Panel
                foreach (TagLib.TagTypes tagType in track.TagsRemoved)
                {
                    file.RemoveTags(tagType);
                }

                #region Main Tags
                string[] splitValues = track.Artist.Split(new[] { ';', '|' });
                file.Tag.Performers = splitValues;

                splitValues           = track.AlbumArtist.Split(new[] { ';', '|' });
                file.Tag.AlbumArtists = splitValues;

                file.Tag.Album          = track.Album.Trim();
                file.Tag.BeatsPerMinute = (uint)track.BPM;


                if (track.Comment != "")
                {
                    file.Tag.Comment = "";
                    if (track.IsMp3)
                    {
                        id3v1tag.Comment = track.Comment;
                        foreach (Comment comment in track.ID3Comments)
                        {
                            CommentsFrame commentsframe = CommentsFrame.Get(id3v2tag, comment.Description, comment.Language, true);
                            commentsframe.Text        = comment.Text;
                            commentsframe.Description = comment.Description;
                            commentsframe.Language    = comment.Language;
                        }
                    }
                    else
                    {
                        file.Tag.Comment = track.Comment;
                    }
                }
                else
                {
                    file.Tag.Comment = "";
                }

                if (track.IsMp3)
                {
                    id3v2tag.IsCompilation = track.Compilation;
                }

                file.Tag.Disc      = track.DiscNumber;
                file.Tag.DiscCount = track.DiscCount;

                splitValues     = track.Genre.Split(new[] { ';', '|' });
                file.Tag.Genres = splitValues;

                file.Tag.Title = track.Title;

                file.Tag.Track      = track.TrackNumber;
                file.Tag.TrackCount = track.TrackCount;

                file.Tag.Year = (uint)track.Year;

                file.Tag.ReplayGainTrack     = track.ReplayGainTrack;
                file.Tag.ReplayGainTrackPeak = track.ReplayGainTrackPeak;
                file.Tag.ReplayGainAlbum     = track.ReplayGainAlbum;
                file.Tag.ReplayGainAlbumPeak = track.ReplayGainAlbumPeak;

                #endregion

                #region Detailed Information

                splitValues        = track.Composer.Split(new[] { ';', '|' });
                file.Tag.Composers = splitValues;
                file.Tag.Conductor = track.Conductor;
                file.Tag.Copyright = track.Copyright;
                file.Tag.Grouping  = track.Grouping;

                splitValues               = track.ArtistSortName.Split(new[] { ';', '|' });
                file.Tag.PerformersSort   = splitValues;
                splitValues               = track.AlbumArtistSortName.Split(new[] { ';', '|' });
                file.Tag.AlbumArtistsSort = splitValues;
                file.Tag.AlbumSort        = track.AlbumSortName;
                file.Tag.TitleSort        = track.TitleSortName;

                #endregion

                #region Picture

                List <TagLib.Picture> pics = new List <TagLib.Picture>();
                foreach (Picture pic in track.Pictures)
                {
                    TagLib.Picture tagPic = new TagLib.Picture();

                    try
                    {
                        byte[]     byteArray = pic.Data;
                        ByteVector data      = new ByteVector(byteArray);
                        tagPic.Data        = data;
                        tagPic.Description = pic.Description;
                        tagPic.MimeType    = "image/jpg";
                        tagPic.Type        = pic.Type;
                        pics.Add(tagPic);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error saving Picture: {0}", ex.Message);
                    }

                    file.Tag.Pictures = pics.ToArray();
                }

                // Clear the picture
                if (track.Pictures.Count == 0)
                {
                    file.Tag.Pictures = pics.ToArray();
                }

                #endregion

                #region Lyrics

                if (track.Lyrics != null && track.Lyrics != "")
                {
                    file.Tag.Lyrics = track.Lyrics;
                    if (track.IsMp3)
                    {
                        foreach (Lyric lyric in track.LyricsFrames)
                        {
                            UnsynchronisedLyricsFrame lyricframe = UnsynchronisedLyricsFrame.Get(id3v2tag, lyric.Description, lyric.Language, true);
                            lyricframe.Text        = lyric.Text;
                            lyricframe.Description = lyric.Description;
                            lyricframe.Language    = lyric.Language;
                        }
                    }
                    else
                    {
                        file.Tag.Lyrics = track.Lyrics;
                    }
                }
                else
                {
                    file.Tag.Lyrics = "";
                }
                #endregion

                #region Ratings

                if (track.IsMp3)
                {
                    if (track.Ratings.Count > 0)
                    {
                        foreach (PopmFrame rating in track.Ratings)
                        {
                            PopularimeterFrame popmFrame = PopularimeterFrame.Get(id3v2tag, rating.User, true);
                            popmFrame.Rating    = Convert.ToByte(rating.Rating);
                            popmFrame.PlayCount = Convert.ToUInt32(rating.PlayCount);
                        }
                    }
                    else
                    {
                        id3v2tag.RemoveFrames("POPM");
                    }
                }
                else if (track.TagType == "ogg" || track.TagType == "flac")
                {
                    if (track.Ratings.Count > 0)
                    {
                        XiphComment xiph = file.GetTag(TagLib.TagTypes.Xiph, true) as XiphComment;
                        xiph.SetField("RATING", track.Rating.ToString());
                    }
                }

                #endregion

                #region Non- Standard Taglib and User Defined Frames

                if (Options.MainSettings.ClearUserFrames)
                {
                    foreach (Frame frame in track.UserFrames)
                    {
                        ByteVector frameId = new ByteVector(frame.Id);

                        if (frame.Id == "TXXX")
                        {
                            id3v2tag.SetUserTextAsString(frame.Description, "");
                        }
                        else
                        {
                            id3v2tag.SetTextFrame(frameId, "");
                        }
                    }
                }

                List <Frame> allFrames = new List <Frame>();
                allFrames.AddRange(track.Frames);

                // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them
                if (track.SavedUserFrames != null && !Options.MainSettings.ClearUserFrames)
                {
                    // Clean the previously saved Userframes, to avoid duplicates
                    foreach (Frame frame in track.SavedUserFrames)
                    {
                        ByteVector frameId = new ByteVector(frame.Id);

                        if (frame.Id == "TXXX")
                        {
                            id3v2tag.SetUserTextAsString(frame.Description, "");
                        }
                        else
                        {
                            id3v2tag.SetTextFrame(frameId, "");
                        }
                    }

                    allFrames.AddRange(track.UserFrames);
                }

                foreach (Frame frame in allFrames)
                {
                    ByteVector frameId = new ByteVector(frame.Id);

                    // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them
                    if (frame.Id == "TXXX")
                    {
                        if (frame.Description != "")
                        {
                            id3v2tag.SetUserTextAsString(frame.Description, "");
                            id3v2tag.SetUserTextAsString(frame.Description, frame.Value);
                        }
                    }
                    else
                    {
                        id3v2tag.SetTextFrame(frameId, "");
                        id3v2tag.SetTextFrame(frameId, frame.Value);
                    }
                }

                #endregion


                // Now, depending on which frames the user wants to save, we will remove the other Frames
                file = Util.FormatID3Tag(file);

                // Set the encoding for ID3 Tags
                if (track.IsMp3)
                {
                    TagLib.Id3v2.Tag.ForceDefaultEncoding = true;
                    switch (Options.MainSettings.CharacterEncoding)
                    {
                    case 0:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.Latin1;
                        break;

                    case 1:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16;
                        break;

                    case 2:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16BE;
                        break;

                    case 3:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF8;
                        break;

                    case 4:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16LE;
                        break;
                    }
                }

                // Save the file
                file.Save();
            }
            catch (Exception ex)
            {
                log.Error("File Save: Error processing file: {0} {1}", track.FullFileName, ex.Message);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "ErrorSave");
                error        = true;
            }

            if (error)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 20
0
        /// <summary>
        ///   Serialize public properties of a Settings object to a given xml file
        /// </summary>
        /// <param name = "obj">Setting Object to serialize</param>
        /// <param name = "fileName">Xml file name</param>
        public static void Serialize(object obj)
        {
            string         fileName      = "";
            INamedSettings namedSettings = obj as INamedSettings;

            if (namedSettings != null)
            {
                fileName = obj + "." + namedSettings.Name + ".xml";
            }
            else
            {
                fileName = obj + ".xml";
            }
            NLog.Logger log = ServiceScope.Get <ILogger>().GetLogger;
            log.Trace("Serialize({0},{1})", obj.ToString(), fileName);
            Dictionary <string, string> globalSettingsList = new Dictionary <string, string>();
            Dictionary <string, string> userSettingsList   = new Dictionary <string, string>();
            XmlSettingsProvider         xmlWriter          = new XmlSettingsProvider(fileName);
            string fullFileName = String.Format(@"{0}\{1}", Options.ConfigDir, fileName);

            ;

            bool isFirstSave = (!File.Exists(fullFileName));

            foreach (PropertyInfo property in obj.GetType().GetProperties())
            {
                Type   thisType   = property.PropertyType;
                string defaultval = "";

                #region CLR Typed property

                if (isCLRType(thisType))
                {
                    object[]     attributes = property.GetCustomAttributes(typeof(SettingAttribute), false);
                    SettingScope scope      = SettingScope.Global;
                    if (attributes.Length != 0)
                    {
                        SettingAttribute attribute = (SettingAttribute)attributes[0];
                        scope      = attribute.SettingScope;
                        defaultval = attribute.DefaultValue;
                    }
                    else
                    {
                        scope      = SettingScope.Global;
                        defaultval = "";
                    }
                    string value = defaultval;

                    if (!isFirstSave) //else default value will be used if it exists
                    {
                        if (obj.GetType().GetProperty(property.Name).GetValue(obj, null) != null)
                        {
                            value = obj.GetType().GetProperty(property.Name).GetValue(obj, null).ToString();
                        }
                        if (scope == SettingScope.User)
                        {
                            userSettingsList.Add(property.Name, value);
                        }
                        else
                        {
                            globalSettingsList.Add(property.Name, value);
                        }
                    }
                    else
                    {
                        if (scope == SettingScope.Global)
                        {
                            globalSettingsList.Add(property.Name, value);
                        }
                        if (scope == SettingScope.User)
                        {
                            userSettingsList.Add(property.Name, value);
                        }
                    }
                }
                #endregion

                #region not CLR Typed property

                else
                {
                    XmlSerializer xmlSerial = new XmlSerializer(thisType);
                    StringBuilder sb        = new StringBuilder();
                    StringWriter  strWriter = new StringWriter(sb);
                    XmlTextWriter writer    = new XmlNoNamespaceWriter(strWriter);
                    writer.Formatting = Formatting.Indented;
                    object propertyValue = obj.GetType().GetProperty(property.Name).GetValue(obj, null);
                    xmlSerial.Serialize(writer, propertyValue);
                    strWriter.Close();
                    strWriter.Dispose();
                    // remove unneeded encoding tag
                    sb.Remove(0, 41);
                    object[]     attributes = property.GetCustomAttributes(typeof(SettingAttribute), false);
                    SettingScope scope      = SettingScope.Global;
                    if (attributes.Length != 0)
                    {
                        SettingAttribute attribute = (SettingAttribute)attributes[0];
                        scope      = attribute.SettingScope;
                        defaultval = attribute.DefaultValue;
                    }
                    else
                    {
                        scope      = SettingScope.Global;
                        defaultval = "";
                    }
                    string value = defaultval;
                    /// a changer
                    if (!isFirstSave || defaultval == "")
                    {
                        value = sb.ToString();
                    }
                    if (scope == SettingScope.User)
                    {
                        userSettingsList.Add(property.Name, value);
                    }
                    else
                    {
                        globalSettingsList.Add(property.Name, value);
                    }
                }

                #endregion
            }

            #region write Settings

            // write settings to xml
            foreach (KeyValuePair <string, string> pair in globalSettingsList)
            {
                xmlWriter.SetValue(obj.ToString(), pair.Key, pair.Value, SettingScope.Global);
            }
            foreach (KeyValuePair <string, string> pair in userSettingsList)
            {
                xmlWriter.SetValue(obj.ToString(), pair.Key, pair.Value, SettingScope.User);
            }
            xmlWriter.Save();

            #endregion
        }
Exemplo n.º 21
0
        /// <summary>
        ///   De-serialize public properties of a Settings object from a given xml file
        /// </summary>
        /// <param name = "obj">Setting Object to retrieve</param>
        /// <param name = "fileName">Xml file name</param>
        public static void Deserialize(object obj)
        {
            string         fileName      = "";
            INamedSettings namedSettings = obj as INamedSettings;

            if (namedSettings != null)
            {
                fileName = obj + "." + namedSettings.Name + ".xml";
            }
            else
            {
                fileName = obj + ".xml";
            }
            XmlSettingsProvider xmlreader = new XmlSettingsProvider(fileName);

            NLog.Logger log = ServiceScope.Get <ILogger>().GetLogger;
            log.Trace("Deserialize({0},{1})", obj.ToString(), fileName);
            // if xml file doesn't exist yet then create it
            string fullFileName = String.Format(@"{0}\{1}", Options.ConfigDir, fileName);

            ;
            if (!File.Exists(fullFileName))
            {
                Serialize(obj);
            }

            foreach (PropertyInfo property in obj.GetType().GetProperties())
            {
                Type thisType = property.PropertyType;

                #region get scope

                SettingScope scope      = SettingScope.Global;
                object[]     attributes = property.GetCustomAttributes(typeof(SettingAttribute), false);
                string       defaultval = "";
                if (attributes.Length != 0)
                {
                    SettingAttribute attribute = (SettingAttribute)attributes[0];
                    scope      = attribute.SettingScope;
                    defaultval = attribute.DefaultValue;
                }
                else
                {
                    scope      = SettingScope.Global;
                    defaultval = "";
                }

                #endregion

                if (isCLRType(thisType))

                #region CLR Typed property

                {
                    try
                    {
                        string value = xmlreader.GetValue(obj.ToString(), property.Name, scope);
                        if (value == null || value == string.Empty)
                        {
                            value = defaultval;
                        }
                        if (thisType == typeof(string))
                        {
                            property.SetValue(obj, value, null);
                        }
                        if (thisType == typeof(bool))
                        {
                            property.SetValue(obj, bool.Parse(value), null);
                        }
                        if (thisType == typeof(Int16))
                        {
                            property.SetValue(obj, Int16.Parse(value), null);
                        }
                        if (thisType == typeof(Int32))
                        {
                            property.SetValue(obj, Int32.Parse(value), null);
                        }
                        if (thisType == typeof(Int64))
                        {
                            property.SetValue(obj, Int64.Parse(value), null);
                        }
                        if (thisType == typeof(UInt16))
                        {
                            property.SetValue(obj, UInt16.Parse(value), null);
                        }
                        if (thisType == typeof(UInt32))
                        {
                            property.SetValue(obj, UInt32.Parse(value), null);
                        }
                        if (thisType == typeof(UInt64))
                        {
                            property.SetValue(obj, UInt64.Parse(value), null);
                        }
                        if (thisType == typeof(float))
                        {
                            property.SetValue(obj, float.Parse(value), null);
                        }
                        if (thisType == typeof(double))
                        {
                            property.SetValue(obj, double.Parse(value), null);
                        }
                        if (thisType == typeof(Int16))
                        {
                            property.SetValue(obj, Int16.Parse(value), null);
                        }
                        if (thisType == typeof(Int32))
                        {
                            property.SetValue(obj, Int32.Parse(value), null);
                        }
                        if (thisType == typeof(DateTime))
                        {
                            property.SetValue(obj, DateTime.Parse(value), null);
                        }
                        if (thisType == typeof(bool?))
                        {
                            property.SetValue(obj, bool.Parse(value), null);
                        }
                        if (thisType == typeof(Int16?))
                        {
                            property.SetValue(obj, Int16.Parse(value), null);
                        }
                        if (thisType == typeof(Int32?))
                        {
                            property.SetValue(obj, Int32.Parse(value), null);
                        }
                        if (thisType == typeof(Int64?))
                        {
                            property.SetValue(obj, Int64.Parse(value), null);
                        }
                        if (thisType == typeof(UInt16?))
                        {
                            property.SetValue(obj, UInt16.Parse(value), null);
                        }
                        if (thisType == typeof(UInt32?))
                        {
                            property.SetValue(obj, UInt32.Parse(value), null);
                        }
                        if (thisType == typeof(UInt64?))
                        {
                            property.SetValue(obj, UInt64.Parse(value), null);
                        }
                        if (thisType == typeof(float?))
                        {
                            property.SetValue(obj, float.Parse(value), null);
                        }
                        if (thisType == typeof(double?))
                        {
                            property.SetValue(obj, double.Parse(value), null);
                        }
                        if (thisType == typeof(Int16?))
                        {
                            property.SetValue(obj, Int16.Parse(value), null);
                        }
                        if (thisType == typeof(Int32?))
                        {
                            property.SetValue(obj, Int32.Parse(value), null);
                        }
                    }
                    catch (Exception) {}
                }
                #endregion

                else
                #region not CLR Typed property

                {
                    XmlSerializer xmlSerial = new XmlSerializer(thisType);

                    string value = xmlreader.GetValue(obj.ToString(), property.Name, scope);
                    if (value != null)
                    {
                        TextReader reader = new StringReader(value);
                        try
                        {
                            property.SetValue(obj, xmlSerial.Deserialize(reader), null);
                        }
                        catch (Exception) {}
                    }
                }

                #endregion
            }
        }
Exemplo n.º 22
0
 public ThemeManager()
 {
     Logger        = ServiceScope.Get <ILogger>();
     _currentTheme = new Theme();
 }
 public void Save()
 {
     ServiceScope.Get <ISettingsManager>().Save(this);
 }
Exemplo n.º 24
0
        private void LoadStrings(string directory, string language, bool log)
        {
            string filename = "strings_" + language + ".xml";

            ServiceScope.Get <ILogger>().GetLogger.Info("Loading strings file: {0}", filename);

            string path = Path.Combine(directory, filename);

            if (File.Exists(path))
            {
                StringFile strings;
                try
                {
                    XmlSerializer s = new XmlSerializer(typeof(StringFile));
                    TextReader    r = new StreamReader(path);
                    strings = (StringFile)s.Deserialize(r);
                }
                catch (Exception ex)
                {
                    ServiceScope.Get <ILogger>().GetLogger.Error("Error loading strings file: {0}", ex.Message);
                    return;
                }

                if (_characters < strings.characters)
                {
                    _characters = strings.characters;
                }

                foreach (StringSection section in strings.sections)
                {
                    // convert section name tolower -> no case matching.
                    section.name = section.name.ToLower();

                    Dictionary <string, StringLocalised> newSection;
                    if (_languageStrings.ContainsKey(section.name))
                    {
                        newSection = _languageStrings[section.name];
                        _languageStrings.Remove(section.name);
                    }
                    else
                    {
                        newSection = new Dictionary <string, StringLocalised>();
                    }

                    foreach (StringLocalised languageString in section.localisedStrings)
                    {
                        languageString.id = languageString.id.ToLower();

                        if (!newSection.ContainsKey(languageString.id))
                        {
                            languageString.language = language;
                            newSection.Add(languageString.id, languageString);
                            if (log)
                            {
                                ServiceScope.Get <ILogger>().GetLogger.Info("    String not found, using English: {0}", languageString.ToString());
                            }
                        }
                    }

                    if (newSection.Count > 0)
                    {
                        _languageStrings.Add(section.name, newSection);
                    }
                }
            }
        }
Exemplo n.º 25
0
        public Options()
        {
            int portable = ServiceScope.Get <ISettingsManager>().GetPortable();

            if (portable == 0)
            {
                _configDir = String.Format(@"{0}\MPTagThat\Config",
                                           Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
            }
            else
            {
                _configDir = String.Format(@"{0}\Config", Application.StartupPath);
            }

            MaximumNumberOfSongsInList = ServiceScope.Get <ISettingsManager>().GetMaxSongs();

            _MPTagThatSettings = new MPTagThatSettings();
            ServiceScope.Get <ISettingsManager>().Load(_MPTagThatSettings);

            _caseConversionSettings = new CaseConversionSettings();
            ServiceScope.Get <ISettingsManager>().Load(_caseConversionSettings);
            // Set Default Values, when starting the first Time
            if (_caseConversionSettings.CaseConvExceptions.Count == 0)
            {
                _caseConversionSettings.CaseConvExceptions.Add("I");
                _caseConversionSettings.CaseConvExceptions.Add("II");
                _caseConversionSettings.CaseConvExceptions.Add("III");
                _caseConversionSettings.CaseConvExceptions.Add("IV");
                _caseConversionSettings.CaseConvExceptions.Add("V");
                _caseConversionSettings.CaseConvExceptions.Add("VI");
                _caseConversionSettings.CaseConvExceptions.Add("VII");
                _caseConversionSettings.CaseConvExceptions.Add("VIII");
                _caseConversionSettings.CaseConvExceptions.Add("IX");
                _caseConversionSettings.CaseConvExceptions.Add("X");
                _caseConversionSettings.CaseConvExceptions.Add("XI");
                _caseConversionSettings.CaseConvExceptions.Add("XII");
                _caseConversionSettings.CaseConvExceptions.Add("feat.");
                _caseConversionSettings.CaseConvExceptions.Add("vs.");
                _caseConversionSettings.CaseConvExceptions.Add("DJ");
                _caseConversionSettings.CaseConvExceptions.Add("I'm");
                _caseConversionSettings.CaseConvExceptions.Add("I'll");
                _caseConversionSettings.CaseConvExceptions.Add("I'd");
                _caseConversionSettings.CaseConvExceptions.Add("UB40");
                _caseConversionSettings.CaseConvExceptions.Add("U2");
                _caseConversionSettings.CaseConvExceptions.Add("NRG");
                _caseConversionSettings.CaseConvExceptions.Add("ZZ");
                _caseConversionSettings.CaseConvExceptions.Add("OMD");
                _caseConversionSettings.CaseConvExceptions.Add("A1");
                _caseConversionSettings.CaseConvExceptions.Add("U96");
                _caseConversionSettings.CaseConvExceptions.Add("2XLC");
                _caseConversionSettings.CaseConvExceptions.Add("ATB");
                _caseConversionSettings.CaseConvExceptions.Add("EMF");
                _caseConversionSettings.CaseConvExceptions.Add("CD");
                _caseConversionSettings.CaseConvExceptions.Add("CD1");
                _caseConversionSettings.CaseConvExceptions.Add("CD2");
                _caseConversionSettings.CaseConvExceptions.Add("MC");
                _caseConversionSettings.CaseConvExceptions.Add("USA");
                _caseConversionSettings.CaseConvExceptions.Add("UK");
                _caseConversionSettings.CaseConvExceptions.Add("TLC");
                _caseConversionSettings.CaseConvExceptions.Add("UFO");
                _caseConversionSettings.CaseConvExceptions.Add("AC");
                _caseConversionSettings.CaseConvExceptions.Add("DC");
                _caseConversionSettings.CaseConvExceptions.Add("DMX");
                _caseConversionSettings.CaseConvExceptions.Add("ABBA");
            }


            _fileNameToTagSettings = new FileNameToTagFormatSettings();
            ServiceScope.Get <ISettingsManager>().Load(_fileNameToTagSettings);

            // Set Default Values, when starting the first Time
            if (_fileNameToTagSettings.FormatValues.Count == 0)
            {
                // Add Default Values
                _fileNameToTagSettings.FormatValues.Add(@"<K> - <T>");
                _fileNameToTagSettings.FormatValues.Add(@"<A> - <T>");
                _fileNameToTagSettings.FormatValues.Add(@"<K> - <A> - <T>");
                _fileNameToTagSettings.FormatValues.Add(@"<A> - <K> - <T>");
                _fileNameToTagSettings.FormatValues.Add(@"<A>\<B>\<K> - <T>");
                _fileNameToTagSettings.FormatValues.Add(@"<A>\<B>\<A> - <K> - <T>");
                _fileNameToTagSettings.FormatValues.Add(@"<A>\<B>\<K> - <A> - <T>");
            }

            _fileNameToTagSettingsTemp = new List <string>(_fileNameToTagSettings.FormatValues);

            _tagToFileNameSettings = new TagToFileNameFormatSettings();
            ServiceScope.Get <ISettingsManager>().Load(_tagToFileNameSettings);

            // Set Default Values, when starting the first Time
            if (_tagToFileNameSettings.FormatValues.Count == 0)
            {
                // Add Default Values
                _tagToFileNameSettings.FormatValues.Add(@"<K> - <T>");
                _tagToFileNameSettings.FormatValues.Add(@"<A> - <T>");
                _tagToFileNameSettings.FormatValues.Add(@"<K> - <A> - <T>");
                _tagToFileNameSettings.FormatValues.Add(@"<A> - <K> - <T>");
            }

            _tagToFileNameSettingsTemp = new List <string>(_tagToFileNameSettings.FormatValues);

            _organiseSettings = new OrganiseFormatSettings();
            ServiceScope.Get <ISettingsManager>().Load(_organiseSettings);

            // Set Default Values, when starting the first Time
            if (_organiseSettings.FormatValues.Count == 0)
            {
                // Add Default values
                _organiseSettings.FormatValues.Add(@"<A>\<B>\<K> - <T>");
                _organiseSettings.FormatValues.Add(@"<A:1>\<A>\<B>\<K> - <T>");
                _organiseSettings.FormatValues.Add(@"<O>\<B>\<K> - <A> - <T>");
                _organiseSettings.FormatValues.Add(@"<O:1>\<A>\<B>\<K> - <T>");
            }

            _organiseSettingsTemp = new List <string>(_organiseSettings.FormatValues);

            _treeViewFilterSettings = new TreeViewFilterSettings();
            ServiceScope.Get <ISettingsManager>().Load(_treeViewFilterSettings);

            // Set default values
            if (_treeViewFilterSettings.Filter.Count == 0)
            {
                TreeViewFilter filter = new TreeViewFilter();
                filter.Name       = "";
                filter.FileMask   = "";
                filter.FileFilter = "*.*";
                _treeViewFilterSettings.Filter.Add(filter);
            }

            // Load Artists / AlbumArtists for Auto Completion
            if (_MPTagThatSettings.UseMediaPortalDatabase)
            {
                ReadArtistDatabase();
            }

            _copyPasteBuffer = new List <TrackData>();

            ReadOnlyFileHandling = 2; // Don't change attribute as a default.

            Songlist = new SongList();
        }