示例#1
0
        public void TestFormatWithNull()
        {
            const string formatString = "While this is always {AlwaysNullObject}, this should be {CircularValue.Number}";
            // Everything will be null
            var result = StringObjectFormatter.Format(formatString, new TestData());

            Assert.AreEqual("While this is always null, this should be null", result);
        }
示例#2
0
        public void TestUnknownFormatStringToken()
        {
            const string formatString = "Nobody except {Name} knows what {Unknown} is...";
            var          testObj      = new TestData {
                Name = "Alexis"
            };
            var result = StringObjectFormatter.Format(formatString, testObj);

            Assert.AreEqual("Nobody except Alexis knows what {Unknown} is...", result);
        }
示例#3
0
        public void TestBraceEscaping()
        {
            const string formatString = "While {Name} is comfortable, {{John}} is even more comfortable";
            var          testObj      = new TestData {
                Name = "James"
            };
            var result = StringObjectFormatter.Format(formatString, testObj);

            Assert.AreEqual("While James is comfortable, {John} is even more comfortable", result);
        }
示例#4
0
        public void TestBrokenFormat()
        {
            const string formatString = "{Name} has everything, but {Name}} may be missing something, and {{Name} is a bit forgetful";
            var          testObj      = new TestData {
                Name = "James"
            };
            var result = StringObjectFormatter.Format(formatString, testObj);

            Assert.AreEqual("James has everything, but {Name}} may be missing something, and {{Name} is a bit forgetful", result);
        }
示例#5
0
        public void TestFormatTokenSurrounding()
        {
            const string formatString = "It's {Name}'s birthday today, and he will be ✨{Number}🎉🎂!";
            var          testObj      = new TestData
            {
                Name   = "Colin",
                Number = 21
            };
            var result = StringObjectFormatter.Format(formatString, testObj);

            Assert.AreEqual("It's Colin's birthday today, and he will be ✨21🎉🎂!", result);
        }
示例#6
0
        public void Write(Level level, string moduleTag, string message)
        {
            EnsureLog();
            var vars = new
            {
                Date    = DateTime.Now.ToString("O"),
                Level   = level,
                Tag     = moduleTag ?? "Global",
                Message = message
            };
            var formattedMessage = StringObjectFormatter.Format(LineFormat, vars);

            writer.WriteLine(formattedMessage);
        }
示例#7
0
        public void TestValidFormat()
        {
            const string validFormatString = "{Name} is the new {CircularValue.Name} times {Number}";
            var          testObj           = new TestData
            {
                Name          = "Orange",
                CircularValue = new TestData
                {
                    Name = "Black"
                },
                Number = 15
            };
            var result = StringObjectFormatter.Format(validFormatString, testObj);

            Assert.AreEqual("Orange is the new Black times 15", result);
        }
示例#8
0
        public void TestFormattingLambda()
        {
            const string formatString = "Sssss! I am a {Number} year old, {Name} {CircularValue.Name}";
            var          testObj      = new TestData
            {
                Name          = "very slippery and slithery",
                Number        = 6,
                CircularValue = new TestData
                {
                    Name = "snake"
                }
            };
            var result = StringObjectFormatter.Format(formatString, testObj, o => o.ToString().Replace(' ', '_'));

            Assert.AreEqual("Sssss! I am a 6 year old, very_slippery_and_slithery snake", result);
        }
示例#9
0
        private void EnsureLog()
        {
            var temp          = new { FileDate = DateTime.Now.ToString("yyyyMMdd") };
            var formattedName = StringObjectFormatter.Format(FilenameFormat, temp);

            if (logFileName != formattedName)
            {
                logFile?.Dispose();
                writer?.Dispose();
                logFile     = File.Open(Path.Combine(logDirectory, formattedName), FileMode.Append, FileAccess.Write, FileShare.Read);
                logFileName = formattedName;
                writer      = new StreamWriter(logFile)
                {
                    AutoFlush = true
                };
            }
        }
示例#10
0
        public void TestGlobals()
        {
            var formatter = new StringObjectFormatter();

            formatter.Globals["Foo"] = "Hello";
            formatter.Globals["Bar"] = "World";
            var testObj = new TestData
            {
                Name          = "Orange",
                CircularValue = new TestData
                {
                    Name = "Black"
                },
                Number = 15
            };

            Assert.AreEqual("Hello, World! Orange is the new Black", formatter.FormatInstance("{Foo}, {Bar}! {Name} is the new {CircularValue.Name}", testObj));
        }
示例#11
0
        private async Task <bool> DownloadCollectionAsync(EnqueuedCollection collection)
        {
            var tracksCollectionLength = collection.MediaCollection.Tracks.Count;
            var tracksQueue            = new Queue <Track>(collection.MediaCollection.Tracks);

            while (tracksQueue.Count > 0)
            {
                var currentItem = tracksQueue.Dequeue();
                var eventArgs   = new TrackDownloadEventArgs
                {
                    CurrentItemIndex = (tracksCollectionLength - tracksQueue.Count) - 1,
                    PercentCompleted = 0M,
                    State            = DownloadState.PreProcess,
                    TotalItems       = tracksCollectionLength,
                    TrackFile        = null
                };
                OnTrackDequeued(eventArgs);

                try
                {
                    if (!currentItem.IsDownloadable)
                    {
                        continue;
                    }
                    OnTrackDownloadProgress(eventArgs);
                    if (currentItem.Album?.CoverPicture != null)
                    {
                        // Download album artwork if it's not cached
                        var albumSmid = currentItem.Album.GetSmid(collection.Service.Info.Name).ToString();
                        if (!ImageCache.Instance.HasItem(albumSmid))
                        {
                            eventArgs.State = DownloadState.DownloadingAlbumArtwork;
                            OnTrackDownloadProgress(eventArgs);
                            try
                            {
                                await ImageCache.Instance.AddByDownload(albumSmid, currentItem.Album.CoverPicture);
                            }
                            catch (Exception ex)
                            {
                                ImageCache.Instance.AddNull(albumSmid);
                                Log.WriteException(Level.Warning, Tag, ex, "Exception occurred when download album artwork:");
                            }
                        }
                    }
                    eventArgs.TrackFile = await collection.Service.GetDownloadableTrackAsync(currentItem);

                    var downloader = collection.Service.GetDownloader(eventArgs.TrackFile);
                    downloader.Progress += (sender, args) =>
                    {
                        eventArgs.Update(args);
                        OnTrackDownloadProgress(eventArgs);
                    };
                    downloader.Done += (sender, args) =>
                    {
                        eventArgs.State = DownloadState.PostProcess;
                        OnTrackDownloadProgress(eventArgs);
                    };
                    var formatter = new StringObjectFormatter
                    {
                        Globals = { { "ServiceName", collection.Service.Info.Name } }
                    };
                    var playlistCollection = collection.MediaCollection as Playlist;
                    if (playlistCollection != null)
                    {
                        formatter.Globals.Add("PlaylistName", playlistCollection.Title);
                    }
                    var path     = eventArgs.TrackFile.GetPath(collection.PathFormat, formatter);
                    var tempPath = path;
                    if (useTempFile)
                    {
                        tempPath += "-temp";
                    }
                    EnsureParentDirectories(tempPath);
                    eventArgs.State = DownloadState.Downloading;
                    await downloader.DownloadAsyncTask(eventArgs.TrackFile, tempPath);

                    // Attempt to dispose the downloader, since the most probable case will be that it will
                    // implement IDisposable if it uses sockets
                    var disposableDownloader = downloader as IDisposable;
                    disposableDownloader?.Dispose();

                    // Write the tag
                    eventArgs.State = DownloadState.WritingTags;
                    OnTrackDownloadProgress(eventArgs);
                    TrackTagger.Write(collection.Service.Info.Name, currentItem, eventArgs.TrackFile,
                                      Program.DefaultSettings.Settings.AlbumArtworkSaveFormat, tempPath);

                    // Rename to proper path
                    if (useTempFile)
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        File.Move(tempPath, path);
                    }
                }
                catch (Exception ex)
                {
                    var exEventArgs = new ExceptionEventArgs {
                        CurrentState = eventArgs, Exception = ex
                    };
                    OnException(exEventArgs);
                    switch (exEventArgs.SkipTo)
                    {
                    case ExceptionSkip.Item:
                        continue;

                    case ExceptionSkip.Collection:
                    case ExceptionSkip.Fail:
                        skip = exEventArgs.SkipTo;
                        return(false);

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                // Raise the completed event even if an error occurred
                OnTrackDownloadCompleted(eventArgs);
            }
            return(true);
        }