Ejemplo n.º 1
0
 public void AddMode(UserMode mode)
 {
     if (!Modes.Contains(mode))
     {
         Modes.Add(mode);
     }
 }
Ejemplo n.º 2
0
 public void RemoveMode(UserMode mode)
 {
     if (Modes.Contains(mode))
     {
         Modes.Remove(mode);
     }
 }
Ejemplo n.º 3
0
 public void RemoveMode(ChannelMode mode)
 {
     if (Modes.Contains(mode))
     {
         Modes.Remove(mode);
     }
 }
Ejemplo n.º 4
0
        public void Play()
        {
            var songs = from i in Instruments
                        from s in i.Songs
                        where Notes.Any() ? Notes.Contains(s.Note) : true &&
                        Octaves.Any() ? Octaves.Contains(s.Octave) : true &&
                        Tempos.Any() ? Tempos.Contains(s.Tempo) : true &&
                        Intensities.Any() ? Intensities.Contains(s.Intensity) : true &&
                        Modes.Any() ? Modes.Contains(s.Mode) : true
                        group s by s.Instrument into grouping
                        select grouping;

            var songsDict = new Dictionary <string, List <Song> >();

            foreach (IGrouping <string, Song> grouping in songs)
            {
                var lstSongs = new List <Song>();
                foreach (var s in grouping.Take(MaxSongs))
                {
                    lstSongs.Add(s);
                }
                songsDict.Add(grouping.Key, lstSongs);
            }

            foreach (var instrument in songsDict.Keys)
            {
                var song = songsDict[instrument].ElementAt(0);
                song.Play();
                songsDict[instrument].RemoveAt(0);
            }
        }
Ejemplo n.º 5
0
        private bool CanHandle(ItemEvent arg)
        {
            if (BeforeAction != arg.BeforeAction)
            {
                return(false);
            }

            if (EventType != arg.EventType)
            {
                return(false);
            }

            if (!ItemId.Equals(arg.ItemUID))
            {
                return(false);
            }

            if (Modes.Count > 0 && !Modes.Contains((BoFormMode)arg.FormMode))
            {
                return(false);
            }

            if (ColumnIds.Count > 0 && !ColumnIds.Contains(arg.ColUID))
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 6
0
        public static KeySignature Parse(string input)
        {
            var inputArr = input.Split(' ');
            var tonicAndAccidentalArr = inputArr[0].ToCharArray();

            if (inputArr.Length == 2 &&
                (tonicAndAccidentalArr.Length == 2 ||
                 tonicAndAccidentalArr.Length == 1))
            {
                var tonic      = char.ToUpper(tonicAndAccidentalArr[0]);
                var accidental = tonicAndAccidentalArr.Length == 2 ? tonicAndAccidentalArr[1].ToString() : "";
                var mode       = inputArr[1].ToLower().FirstCharToUpper();

                if (Scale.Contains(tonic) && Accidentals.Contains(accidental) &&
                    Modes.Contains(mode))
                {
                    return(new KeySignature(tonic, accidental, mode));
                }
                else
                {
                    Console.WriteLine($"One or more parts of '{input}' are not valid. Ensure your key signature has no double sharps or double flats.");
                }
            }
            else
            {
                Console.WriteLine($"'{input}' is not a valid key signature. Must contain a tonic and mode separated by a space. (e.g., Bb Major)");
            }
            return(null);
        }
Ejemplo n.º 7
0
 public void AddMode(ChannelMode mode)
 {
     if (!Modes.Contains(mode))
     {
         Modes.Add(mode);
     }
 }
Ejemplo n.º 8
0
        public void RemoveMode(Client client, char mode)
        {
            if (Modes.Contains(mode))
            {
                Modes.Remove(mode);
            }

            // Invoke events
            if (mode.Equals('a'))
            {
                client.OnAwayChange(this, false);
            }
        }
Ejemplo n.º 9
0
        public void AddMode(Client client, char mode)
        {
            if (!Modes.Contains(mode))
            {
                Modes.Add(mode);
            }

            // Invoke events
            if (mode.Equals('a'))
            {
                client.OnAwayChange(this, true);
            }
        }
Ejemplo n.º 10
0
        async Task startMeasureAsync(CommandParameter <TMode> mode)
        {
            using (IsBusy.BusyMode)
            {
                // In command-parameter driven mode select mode
                if (mode.IsSet)
                {
                    if (Modes?.Contains(mode.Value) ?? true)
                    {
                        SelectedMode = mode.Value;
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
                }

                beforeMeasureStart();

                Logger.LogInfoEverywhere($"Запуск замера {SelectedMode}");

                CancelMeasure.CanBeExecuted = true;
                StartMeasure.CanBeExecuted  = false;
                MeasureProgress.Report(0);

                _measureCTS = new CancellationTokenSource();
                try
                {
                    _measureProcess = _calibrator.MeasureAsync(getModelsTestMode(SelectedMode), MeasureProgress, _measureCTS.Token);
                    await _measureProcess;
                }
                catch (OperationCanceledException)
                {
                    Logger.LogInfoEverywhere($"Замер прерван");
                }
                catch (Exception ex)
                {
                    Logger.LogError($"Ошибка при замере", "Ошибка при замере во время калибровки", ex);
                }

                onMeasureFinished();

                await cancelMeasureAnywayAsync();
            }
        }
Ejemplo n.º 11
0
        public override string GetMode()
        {
            if (Modes.Contains(Beatmap.Mode.Standard) &&
                Modes.Contains(Beatmap.Mode.Taiko) &&
                Modes.Contains(Beatmap.Mode.Catch) &&
                Modes.Contains(Beatmap.Mode.Mania))
            {
                return("All Modes");
            }

            if (Modes.Length == 0)
            {
                return("No Modes");
            }

            List <string> modes = new List <string>();

            foreach (Beatmap.Mode mode in Modes)
            {
                modes.Add(Enum.GetName(typeof(Beatmap.Mode), mode));
            }

            return(String.Join(" ", modes));
        }
Ejemplo n.º 12
0
        public static void Log(LogLevel level, string message, int additionalEntrySeparators = 0, bool additionalEntrySeparatorsLogFileOnlyMode = true, [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
        {
            try
            {
                if (Modes.Count == 0 || !IsOn())
                {
                    return;
                }

                if (level < MinimumLevel)
                {
                    return;
                }

                message = Guard.Correct(message);
                var category = string.IsNullOrWhiteSpace(callerFilePath) ? "" : $"{EnvironmentHelpers.ExtractFileName(callerFilePath)} ({callerLineNumber})";

                var messageBuilder = new StringBuilder();
                messageBuilder.Append($"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()}\t");

                if (message.Length == 0)
                {
                    if (category.Length == 0)                     // If both empty. It probably never happens though.
                    {
                        messageBuilder.Append($"{EntrySeparator}");
                    }
                    else                     // If only the message is empty.
                    {
                        messageBuilder.Append($"{category}{EntrySeparator}");
                    }
                }
                else
                {
                    if (category.Length == 0)                     // If only the category is empty.
                    {
                        messageBuilder.Append($"{message}{EntrySeparator}");
                    }
                    else                     // If none of them empty.
                    {
                        messageBuilder.Append($"{category}\t{message}{EntrySeparator}");
                    }
                }

                var finalMessage = messageBuilder.ToString();

                for (int i = 0; i < additionalEntrySeparators; i++)
                {
                    messageBuilder.Insert(0, EntrySeparator);
                }

                var finalFileMessage = messageBuilder.ToString();
                if (!additionalEntrySeparatorsLogFileOnlyMode)
                {
                    finalMessage = finalFileMessage;
                }

                lock (Lock)
                {
                    if (Modes.Contains(LogMode.Console))
                    {
                        lock (Console.Out)
                        {
                            var color = Console.ForegroundColor;
                            switch (level)
                            {
                            case LogLevel.Warning:
                                color = ConsoleColor.Yellow;
                                break;

                            case LogLevel.Error:
                            case LogLevel.Critical:
                                color = ConsoleColor.Red;
                                break;

                            default:
                                break;                                         // Keep original color.
                            }

                            Console.ForegroundColor = color;
                            Console.Write(finalMessage);
                            Console.ResetColor();
                        }
                    }

                    if (Modes.Contains(LogMode.Console))
                    {
                        Debug.Write(finalMessage);
                    }

                    if (!Modes.Contains(LogMode.File))
                    {
                        return;
                    }

                    IoHelpers.EnsureContainingDirectoryExists(FilePath);

                    if (File.Exists(FilePath))
                    {
                        var sizeInBytes = new FileInfo(FilePath).Length;
                        if (sizeInBytes > 1000 * MaximumLogFileSize)
                        {
                            File.Delete(FilePath);
                        }
                    }

                    File.AppendAllText(FilePath, finalFileMessage);
                }
            }
            catch (Exception ex)
            {
                if (Interlocked.Increment(ref LoggingFailedCount) == 1)                 // If it only failed the first time, try log the failure.
                {
                    LogDebug($"Logging failed: {ex}");
                }
                // If logging the failure is successful then clear the failure counter.
                // If it's not the first time the logging failed, then we do not try to log logging failure, so clear the failure counter.
                Interlocked.Exchange(ref LoggingFailedCount, 0);
            }
        }
Ejemplo n.º 13
0
        private static void Log(LogLevel level, string message, string category, int additionalEntrySeparators = 0, bool additionalEntrySeparatorsLogFileOnlyMode = true)
        {
            try
            {
                if (Modes.Count == 0 || !IsOn())
                {
                    return;
                }

                if (level < MinimumLevel)
                {
                    return;
                }

                message  = string.IsNullOrWhiteSpace(message) ? "" : message;
                category = string.IsNullOrWhiteSpace(category) ? "" : category;

                var messageBuilder = new StringBuilder();
                messageBuilder.Append($"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()}");

                if (message != "" && category != "")                 // If none of them empty.
                {
                    messageBuilder.Append($" {category}: {message}{EntrySeparator}");
                }
                else if (message == "" && category != "")                  // If only the message is empty.
                {
                    messageBuilder.Append($" {category}{EntrySeparator}");
                }
                else if (message != "" && category == "")                 // If only the category is empty.
                {
                    messageBuilder.Append($": {message}{EntrySeparator}");
                }
                else                 // if (message == "" && category == "") // If both empty. It probably never happens though.
                {
                    messageBuilder.Append($"{EntrySeparator}");
                }

                var finalMessage = messageBuilder.ToString();

                for (int i = 0; i < additionalEntrySeparators; i++)
                {
                    messageBuilder.Insert(0, EntrySeparator);
                }

                var finalFileMessage = messageBuilder.ToString();
                if (!additionalEntrySeparatorsLogFileOnlyMode)
                {
                    finalMessage = finalFileMessage;
                }

                lock (Lock)
                {
                    if (Modes.Contains(LogMode.Console))
                    {
                        lock (Console.Out)
                        {
                            var color = Console.ForegroundColor;
                            switch (level)
                            {
                            case LogLevel.Warning:
                                color = ConsoleColor.Yellow;
                                break;

                            case LogLevel.Error:
                            case LogLevel.Critical:
                                color = ConsoleColor.Red;
                                break;

                            default: break;                                     // Keep original color.
                            }

                            Console.ForegroundColor = color;
                            Console.Write(finalMessage);
                            Console.ResetColor();
                        }
                    }

                    if (Modes.Contains(LogMode.Console))
                    {
                        Debug.Write(finalMessage);
                    }

                    if (!Modes.Contains(LogMode.File))
                    {
                        return;
                    }

                    IoHelpers.EnsureContainingDirectoryExists(FilePath);

                    if (File.Exists(FilePath))
                    {
                        var sizeInBytes = new FileInfo(FilePath).Length;
                        if (sizeInBytes > 1000 * MaximumLogFileSize)
                        {
                            File.Delete(FilePath);
                        }
                    }

                    if (FileEntryEncryptionPassword != null)
                    {
                        // take the separator down and add a comma (not base64)
                        var replacedSeparatorWithCommaMessage = finalFileMessage.Substring(0, finalFileMessage.Length - EntrySeparator.Length);
                        var encryptedLogMessage = StringCipher.Encrypt(replacedSeparatorWithCommaMessage, FileEntryEncryptionPassword) + ',';

                        File.AppendAllText(FilePath, encryptedLogMessage);
                    }
                    else
                    {
                        File.AppendAllText(FilePath, finalFileMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                if (Interlocked.Increment(ref _loggingFailedCount) == 1)                 // If it only failed the first time, try log the failure.
                {
                    LogDebug($"Logging failed: {ex}", $"{nameof(Logger)}.{nameof(Logging)}.{nameof(Logger)}");
                }
                // If logging the failure is successful then clear the failure counter.
                // If it's not the first time the logging failed, then we don't try to log logging failure, so clear the failure counter.
                Interlocked.Exchange(ref _loggingFailedCount, 0);
            }
        }
Ejemplo n.º 14
0
        public static void TranslatePageParametersToEntities(Process process, IDictionary <string, string> parameters, string defaultOutput)
        {
            var output = parameters.ContainsKey("output") ? parameters["output"] : defaultOutput;

            var isOutput = Outputs.Contains(output);
            var isMode   = Modes.Contains(output);

            foreach (var entity in process.Entities)
            {
                if (isMode)
                {
                    if (output == "map")
                    {
                        entity.Page     = 1;
                        entity.PageSize = 0;
                    }
                    else
                    {
                        if (entity.Page > 0)
                        {
                            int page;
                            if (parameters.ContainsKey("page"))
                            {
                                if (!int.TryParse(parameters["page"], out page))
                                {
                                    page = 1;
                                }
                            }
                            else
                            {
                                page = 1;
                            }

                            entity.Page = page;

                            var size = 0;
                            if (parameters.ContainsKey("size"))
                            {
                                int.TryParse(parameters["size"], out size);
                            }

                            if (size > 0 || output == "page")
                            {
                                entity.PageSize = size > 0 && entity.PageSizes.Any(s => s.Size == size) ? size : entity.PageSizes.First().Size;
                            }
                            else
                            {
                                entity.PageSize = size;
                            }
                        }
                    }
                }
                else
                {
                    if (isOutput)
                    {
                        entity.Page     = 0;
                        entity.PageSize = 0;
                    }
                    else      // unknown output request
                    {
                        entity.Page     = 1;
                        entity.PageSize = 0;
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public async Task <IHttpActionResult> GetLeaderboards(
            Products products,
            Modes modes,
            Runs runs,
            Characters characters,
            bool?production  = null,
            bool?coOp        = null,
            bool?customMusic = null,
            CancellationToken cancellationToken = default)
        {
            var query = from l in db.Leaderboards.AsNoTracking()
                        where products.Contains(l.Product.Name)
                        where modes.Contains(l.Mode.Name)
                        where runs.Contains(l.Run.Name)
                        where characters.Contains(l.Character.Name)
                        select l;

            if (production != null)
            {
                query = query.Where(l => l.IsProduction == production);
            }
            if (coOp != null)
            {
                query = query.Where(l => l.IsCoOp == coOp);
            }
            if (customMusic != null)
            {
                query = query.Where(l => l.IsCustomMusic == customMusic);
            }
            query = from l in query
                    orderby l.Product.ProductId descending, l.Character.Name, l.RunId
            select l;

            var total = await query.CountAsync(cancellationToken);

            var leaderboards = await(from l in query
                                     select new LeaderboardDTO
            {
                Id           = l.LeaderboardId,
                UpdatedAt    = l.LastUpdate,
                Name         = l.Name,
                DisplayName  = l.DisplayName,
                IsProduction = l.IsProduction,
                ProductName  = l.Product.Name,
                Product      = new ProductDTO
                {
                    Id          = l.Product.ProductId,
                    Name        = l.Product.Name,
                    DisplayName = l.Product.DisplayName,
                },
                ModeName = l.Mode.Name,
                Mode     = new ModeDTO
                {
                    Id          = l.Mode.ModeId,
                    Name        = l.Mode.Name,
                    DisplayName = l.Mode.DisplayName,
                },
                RunName = l.Run.Name,
                Run     = new RunDTO
                {
                    Id          = l.Run.RunId,
                    Name        = l.Run.Name,
                    DisplayName = l.Run.DisplayName,
                },
                CharacterName = l.Character.Name,
                Character     = new CharacterDTO
                {
                    Id          = l.Character.CharacterId,
                    Name        = l.Character.Name,
                    DisplayName = l.Character.DisplayName,
                },
                IsCoOp        = l.IsCoOp,
                IsCustomMusic = l.IsCustomMusic,
                Total         = l.Entries.Count,
            })
                               .ToListAsync(cancellationToken);

            var content = new LeaderboardsEnvelope
            {
                Total        = total,
                Leaderboards = leaderboards,
            };

            return(Ok(content));
        }
Ejemplo n.º 16
0
        private static void Log(LogLevel level, string message, string category)
        {
            try
            {
                if (Modes.Count == 0 || !IsOn())
                {
                    return;
                }

                if (level < MinimumLevel)
                {
                    return;
                }

                message  = string.IsNullOrWhiteSpace(message) ? "" : message;
                category = string.IsNullOrWhiteSpace(category) ? "" : category;

                var finalLogMessage = "";
                if (message != "" && category != "")                 // If none of them empty.
                {
                    finalLogMessage = $"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()} {category}: {message}{EntrySeparator}";
                }
                else if (message == "" && category != "")                  // If only the message is empty.
                {
                    finalLogMessage = $"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()} {category}{EntrySeparator}";
                }
                else if (message != "" && category == "")                 // If only the category is empty.
                {
                    finalLogMessage = $"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()}: {message}{EntrySeparator}";
                }
                else                 // if (message == "" && category == "") // If both empty. It probably never happens though.
                {
                    finalLogMessage = $"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()}{EntrySeparator}";
                }

                lock (Lock)
                {
                    if (Modes.Contains(LogMode.Console))
                    {
                        lock (Console.Out)
                        {
                            var color = Console.ForegroundColor;
                            switch (level)
                            {
                            case LogLevel.Warning:
                                color = ConsoleColor.Yellow;
                                break;

                            case LogLevel.Error:
                            case LogLevel.Critical:
                                color = ConsoleColor.Red;
                                break;
                            }

                            Console.ForegroundColor = color;
                            Console.Write(finalLogMessage);
                            Console.ResetColor();
                        }
                    }

                    if (Modes.Contains(LogMode.Console))
                    {
                        Debug.Write(finalLogMessage);
                    }

                    if (!Modes.Contains(LogMode.File))
                    {
                        return;
                    }

                    IoHelpers.EnsureContainingDirectoryExists(FilePath);

                    if (File.Exists(FilePath))
                    {
                        var sizeInBytes = new FileInfo(FilePath).Length;
                        if (sizeInBytes > 1000 * MaximumLogFileSize)
                        {
                            File.Delete(FilePath);
                        }
                    }

                    if (!(FileEntryEncryptionPassword is null))
                    {
                        // take the separator down and add a comma (not base64)
                        var replacedSeparatorWithCommaMessage = finalLogMessage.Substring(0, finalLogMessage.Length - EntrySeparator.Length);
                        var encryptedLogMessage = StringCipher.Encrypt(replacedSeparatorWithCommaMessage, FileEntryEncryptionPassword) + ',';

                        File.AppendAllText(FilePath, encryptedLogMessage);
                    }
                    else
                    {
                        File.AppendAllText(FilePath, finalLogMessage);
                    }
                }
Ejemplo n.º 17
0
        public int RemoveMode(Client client, string channel, char mode, string parameter = "")
        {
            switch (mode)
            {
            case 'v':
            {
                var user = client.UserFromNick(parameter);
                user.RemoveRank(client, channel, UserRank.Voice);
                return(1);
            }

            case 'h':
            {
                var user = client.UserFromNick(parameter);
                user.RemoveRank(client, channel, UserRank.HalfOp);
                return(1);
            }

            case 'o':
            {
                var user = client.UserFromNick(parameter);
                user.RemoveRank(client, channel, UserRank.Op);
                return(1);
            }

            case 'a':
            {
                var user = client.UserFromNick(parameter);
                user.RemoveRank(client, channel, UserRank.Admin);
                return(1);
            }

            case 'q':
            {
                var user = client.UserFromNick(parameter);
                user.RemoveRank(client, channel, UserRank.Owner);
                return(1);
            }

            case 'b':
            {
                RemoveBan(parameter);
                OnModeRemove(mode);
                return(1);
            }

            case 'e':
            {
                RemoveException(parameter);
                OnModeRemove(mode);
                return(1);
            }

            case 'I':
            {
                RemoveInvite(parameter);
                OnModeRemove(mode);
                return(1);
            }

            case 'k':
            {
                if (Key.Equals(parameter))
                {
                    Key = null;
                    if (Modes.Contains(mode))
                    {
                        Modes.Remove(mode);
                    }
                }
                OnModeRemove(mode);
                return(1);
            }

            case 'l':
            {
                Userlimit = -1;
                if (Modes.Contains(mode))
                {
                    Modes.Remove(mode);
                }
                break;
            }

            default:
            {
                if (Modes.Contains(mode))
                {
                    Modes.Remove(mode);
                }
                break;
            }
            }
            OnModeRemove(mode);
            return(0);
        }
Ejemplo n.º 18
0
        public int AddMode(Client client, string channel, char mode, string parameter = "")
        {
            switch (mode)
            {
            case 'v':
            {
                var user = client.UserFromNick(parameter);
                user.AddRank(client, channel, UserRank.Voice);
                return(1);
            }

            case 'h':
            {
                var user = client.UserFromNick(parameter);
                user.AddRank(client, channel, UserRank.HalfOp);
                return(1);
            }

            case 'o':
            {
                var user = client.UserFromNick(parameter);
                user.AddRank(client, channel, UserRank.Op);
                return(1);
            }

            case 'a':
            {
                var user = client.UserFromNick(parameter);
                user.AddRank(client, channel, UserRank.Admin);
                return(1);
            }

            case 'q':
            {
                var user = client.UserFromNick(parameter);
                user.AddRank(client, channel, UserRank.Owner);
                return(1);
            }

            case 'b':
            {
                AddBan(parameter);
                OnModeAdd(mode);
                return(1);
            }

            case 'e':
            {
                AddException(parameter);
                OnModeAdd(mode);
                return(1);
            }

            case 'I':
            {
                AddInvite(parameter);
                OnModeAdd(mode);
                return(1);
            }

            case 'k':
            {
                Key = parameter;
                Modes.Add(mode);
                return(1);
            }

            case 'l':
            {
                int limit;
                if (int.TryParse(parameter, out limit))
                {
                    Userlimit = limit;
                    Modes.Add(mode);
                    OnModeAdd(mode);
                    return(1);
                }
                break;
            }

            default:
            {
                if (!Modes.Contains(mode))
                {
                    Modes.Add(mode);
                }
                break;
            }
            }
            OnModeAdd(mode);
            return(0);
        }
Ejemplo n.º 19
0
        private static void Log(LogLevel level, string message, string category)
        {
            try
            {
                if (Modes.Count == 0 || !IsOn())
                {
                    return;
                }

                if (level < MinimumLevel)
                {
                    return;
                }

                message  = string.IsNullOrWhiteSpace(message) ? "" : message;
                category = string.IsNullOrWhiteSpace(category) ? "" : category;

                var finalLogMessage = $"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()} {category}: {message}{EntrySeparator}";

                lock (Lock)
                {
                    if (Modes.Contains(LogMode.Console))
                    {
                        lock (Console.Out)
                        {
                            var color = Console.ForegroundColor;
                            switch (level)
                            {
                            case LogLevel.Warning:
                                color = ConsoleColor.Yellow;
                                break;

                            case LogLevel.Error:
                            case LogLevel.Critical:
                                color = ConsoleColor.Red;
                                break;
                            }

                            Console.ForegroundColor = color;
                            Console.Write(finalLogMessage);
                            Console.ResetColor();
                        }
                    }

                    if (Modes.Contains(LogMode.Console))
                    {
                        Debug.Write(finalLogMessage);
                    }

                    if (!Modes.Contains(LogMode.File))
                    {
                        return;
                    }

                    var dir = Path.GetDirectoryName(FilePath);
                    if (dir != "")
                    {
                        Directory.CreateDirectory(dir);
                    }

                    if (File.Exists(FilePath))
                    {
                        var sizeInBytes = new FileInfo(FilePath).Length;
                        if (sizeInBytes > 1000 * MaximumLogFileSize)
                        {
                            File.Delete(FilePath);
                        }
                    }

                    if (FileEntryEncryptionPassword != null)
                    {
                        // take the separator down and add a comma (not base64)
                        var replacedSeparatorWithCommaMessage = finalLogMessage.Substring(0, finalLogMessage.Length - EntrySeparator.Length);
                        var encryptedLogMessage = StringCipher.Encrypt(replacedSeparatorWithCommaMessage, FileEntryEncryptionPassword) + ',';

                        File.AppendAllText(FilePath, encryptedLogMessage);
                    }
                    else
                    {
                        File.AppendAllText(FilePath, finalLogMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref _logerFailed);
                if (Interlocked.Read(ref _logerFailed) > 1)
                {
                    Interlocked.Exchange(ref _logerFailed, 0);
                    return;
                }
                LogDebug($"Logging failed: {ex}", $"{nameof(Logger)}.{nameof(Logging)}.{nameof(Logger)}");
            }
        }
Ejemplo n.º 20
0
        private static void Log(LogLevel level, string message, string category)
        {
            try
            {
                if (Modes.Count == 0)
                {
                    return;
                }

                if (level < MinimumLevel)
                {
                    return;
                }

                message  = string.IsNullOrWhiteSpace(message) ? "" : message;
                category = string.IsNullOrWhiteSpace(category) ? "" : category;

                var finalLogMessage = $"{level.ToString().ToUpperInvariant()} {category} {DateTimeOffset.UtcNow}\n{message}{EntrySeparator}";

                lock (Lock)
                {
                    if (Modes.Contains(LogMode.Console))
                    {
                        Console.Write(finalLogMessage);
                    }

                    if (Modes.Contains(LogMode.Console))
                    {
                        Debug.Write(finalLogMessage);
                    }

                    if (Modes.Contains(LogMode.File))
                    {
                        var dir = Path.GetDirectoryName(FilePath);
                        if (dir != "")
                        {
                            Directory.CreateDirectory(dir);
                        }

                        if (File.Exists(FilePath))
                        {
                            var sizeInBytes = new FileInfo(FilePath).Length;
                            if (sizeInBytes > 1000 * MaximumLogFileSize)
                            {
                                File.Delete(FilePath);
                            }
                        }

                        if (FileEntryEncryptionPassword != null)
                        {
                            // take the separator down and add a comma (not base64)
                            var replacedSeparatorWithCommaMessage = finalLogMessage.Substring(0, finalLogMessage.Length - EntrySeparator.Length);
                            var encryptedLogMessage = StringCipher.Encrypt(replacedSeparatorWithCommaMessage, FileEntryEncryptionPassword) + ',';

                            File.AppendAllText(FilePath, encryptedLogMessage);
                        }
                        else
                        {
                            File.AppendAllText(FilePath, finalLogMessage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref _logerFailed);
                if (Interlocked.Read(ref _logerFailed) > 1)
                {
                    Interlocked.Exchange(ref _logerFailed, 0);
                    return;
                }
                LogDebug($"Logging failed: {ex}", $"{nameof(DotNetEssentials)}.{nameof(Logging)}.{nameof(Logger)}");
            }
        }