Exemplo n.º 1
0
        /// <summary>
        /// Deletes the item with name <paramref name="name"/>. Throws <see cref="ArgumentException"/> if name does not exist.
        /// If default is deleted, default is set to null.
        /// </summary>
        /// <param name="name"></param>
        public void DeleteExecutable(string name)
        {
            LeagueExecutable target = GetExecutable(name);

            if (target == null)
            {
                _log.Warning($"Executable with name {name} does not exist");
                throw new ArgumentException($"Executable with name {name} does not exist");
            }

            // Delete the executable
            _log.Information($"Deleting executable {target.Name}");
            Settings.Executables.Remove(target);
        }
Exemplo n.º 2
0
        public ExecutableManager(RiZhi log)
        {
            _log = log ?? throw new ArgumentNullException(nameof(log));

            // Get the exeInfoFile or create new one
            _exeInfoFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "executablesettings.json");
            if (!File.Exists(_exeInfoFilePath))
            {
                // Exe file is missing, set up defaults
                _log.Information($"Executable file does not exist, creating");
                Settings = new ExecutableSettings();
            }
            else
            {
                // Exe file found, load it
                try
                {
                    Settings = JsonConvert.DeserializeObject <ExecutableSettings>(File.ReadAllText(_exeInfoFilePath));
                }
                catch (Exception parseEx)
                {
                    // Failed loading, create new one instead
                    _log.Error($"Error reading executable info file, creating new one. {parseEx}");

                    Settings = new ExecutableSettings();
                }
            }

            // Refresh all known executables versions
            foreach (var executable in Settings.Executables)
            {
                UpdateExecutableVersion(executable);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// This function is responsible for finding and loading in new replays
        /// </summary>
        public async Task InitialLoadAsync()
        {
            _log.Information("Starting initial load of replays");

            List <ReplayFileInfo> newFiles = new List <ReplayFileInfo>();

            // Get all files from all defined replay folders
            IReadOnlyCollection <ReplayFileInfo> allFiles = _fileSystem.GetAllReplayFileInfo();

            // Check if file exists in the database
            foreach (var file in allFiles)
            {
                if (_db.GetFileResult(file.Path) == null)
                {
                    newFiles.Add(file);
                }
            }

            _log.Information($"Discovered {newFiles.Count} new files");

            // Files not in the database are parsed and added
            foreach (var file in newFiles)
            {
                var parseResult = await _reader.ReadFile(file.Path).ConfigureAwait(false);

                FileResult newResult = new FileResult(file, parseResult)
                {
                    IsNewFile = false
                };

                _db.AddFileResult(newResult);
            }

            _log.Information("Initial load of replays complete");
        }
Exemplo n.º 4
0
        // Window has been rendered to the screen
        private async void Window_ContentRendered(object sender, EventArgs e)
        {
            if (!_settingsManager.Settings.AutoUpdateCheck)
            {
                return;
            }

            string latestVersion;

            try
            {
                _log.Information("Checking for updates...");
                latestVersion = await GithubConnection.GetLatestVersion().ConfigureAwait(true);
            }
            catch (HttpRequestException ex)
            {
                _log.Warning("Failed to check for updates - " + ex.ToString());
                return; // keep in mind when adding anything to this function!
            }

            if (String.IsNullOrEmpty(latestVersion))
            {
                _log.Warning("Failed to check for updates - github returned nothing or error code");
                return; // keep in mind when adding anything to this function!
            }

            var assemblyName    = Assembly.GetEntryAssembly()?.GetName();
            var assemblyVersion = assemblyName.Version.ToString(3);

            if (latestVersion.Equals(assemblyVersion, StringComparison.OrdinalIgnoreCase))
            {
                _settingsManager.TemporaryValues["UpdateAvailable"] = false;
            }
            else
            {
                _settingsManager.TemporaryValues["UpdateAvailable"] = true;

                var updateNotif = FlyoutHelper.CreateFlyout(true, true);
                updateNotif.SetFlyoutLabelText(TryFindResource("UpdateAvailableNotifText") as String);
                updateNotif.SetFlyoutButtonText(TryFindResource("UpdateAvailableNotifButton") as String);

                updateNotif.GetFlyoutButton().Click += (object e1, RoutedEventArgs a) =>
                {
                    Process.Start((TryFindResource("GitHubReleasesLink") as Uri).ToString());
                };

                updateNotif.Placement = ModernWpf.Controls.Primitives.FlyoutPlacementMode.Bottom;
                updateNotif.ShowAt(SettingsButton);
            }

            return;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Get an array of all appropriate DataDragon versions
        /// </summary>
        /// <returns></returns>
        public async Task <string[]> GetDataDragonVersionStringsAsync()
        {
            const string url = @"https://ddragon.leagueoflegends.com/api/versions.json";

            HttpResponseMessage response;

            using (var request = new HttpRequestMessage(HttpMethod.Get, url))
            {
                request.Headers.UserAgent.ParseAdd(UserAgent);
                request.Headers.Accept.ParseAdd("text/json");

                try
                {
                    response = await _httpClient.SendAsync(request).ConfigureAwait(true);
                }
                catch (HttpRequestException)
                {
                    _log.Error($"Unable to send HTTP request to {url}");
                    return(null);
                }
            }

            if (response.IsSuccessStatusCode)
            {
                _log.Information($"Made successful HTTP request {url}");

                var json = await response.Content.ReadAsStringAsync().ConfigureAwait(true);

                return(JArray.Parse(json).ToObject <string[]>());
            }
            else
            {
                _log.Error($"HTTP request failed {(int)response.StatusCode} {url}");
                return(null);
            }
        }
Exemplo n.º 6
0
        public SettingsManager(RiZhi log)
        {
            Executables = new ExecutableManager(log);
            _log        = log;
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");

            if (File.Exists(configPath))
            {
                LoadConfigFile(configPath);
            }
            else
            {
                _log.Information("No config file found, creating new defaults");
                Settings = new ObservableSettings();
            }
        }
Exemplo n.º 7
0
        public SettingsManager(RiZhi log)
        {
            _log        = log ?? throw new ArgumentNullException(nameof(log));
            Executables = new ExecutableManager(log);

            if (File.Exists(_configPath))
            {
                LoadConfigFile();
            }
            else
            {
                _log.Information("No config file found, creating new defaults");
                Settings = new ObservableSettings();
            }

            LoadTemporaryValues();
        }
Exemplo n.º 8
0
        public static void Main(string[] args)
        {
            var log = new RiZhi
            {
                FilePrefix      = "ExampleApp",
                AssemblyVersion = "1.0.0",
                AssemblyName    = "Example Program"
            };

            log.Debug("Debug message, appears first");
            log.Information("Information message, appears second");
            log.Warning($"Warning message, appears third. Error Flag = {log.ErrorFlag}");
            log.Error("Error message, appears fourth");

            if (log.ErrorFlag)
            {
                log.Debug($"Error was logged");
            }

            log.WriteLog();
        }
Exemplo n.º 9
0
        public void UpdateAlternativeName(string id, string newName)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(id);
            }

            using (var db = new LiteDatabase(_filePath))
            {
                var fileResults = db.GetCollection <FileResult>("fileResults");

                var result = fileResults
                             .IncludeAll()
                             .FindById(id);

                if (result == null)
                {
                    throw new KeyNotFoundException($"Could not find FileResult by id {id}");
                }
                else
                {
                    _log.Information($"Db updating {result.AlternativeName} to {newName}");

                    // Update the file results (for indexing/search)
                    result.AlternativeName = newName;
                    fileResults.Update(result);

                    // Update the replay entry
                    var replays     = db.GetCollection <ReplayFile>("replayFiles");
                    var replayEntry = replays
                                      .IncludeAll()
                                      .FindById(id);
                    replayEntry.AlternativeName = newName;
                    replays.Update(replayEntry);
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Get replays from database and load to display
        /// </summary>
        public int LoadReplaysFromDatabase()
        {
            _log.Information("Loading replays from database...");
            var databaseResults = _fileManager.GetReplays(SortParameters, SettingsManager.Settings.ItemsPerPage, PreviewReplays.Count);

            _log.Information($"Retrieved {databaseResults.Count} replays");

            foreach (var file in databaseResults)
            {
                AddReplay(file);
            }

            return(databaseResults.Count);
        }
Exemplo n.º 11
0
        public async Task <Process> PlayReplay(string path)
        {
            var replay = await _files.GetSingleFile(path).ConfigureAwait(true);

            var executables = _settingsManager.Executables.GetExecutablesByPatch(replay.ReplayFile.GameVersion);

            if (!executables.Any())
            {
                _log.Information($"No executables found to play replay");

                // No executable found that can be used to play
                await ShowUnsupportedDialog(replay.ReplayFile.GameVersion).ConfigureAwait(true);

                return(null);
            }

            LeagueExecutable target;

            if (executables.Count > 1)
            {
                _log.Information($"More than one possible executable, asking user...");
                // More than one?????
                target = await ShowChooseReplayDialog(executables).ConfigureAwait(true);

                if (target == null)
                {
                    return(null);
                }
            }
            else
            {
                target = executables.First();
            }

            if (_settingsManager.Settings.PlayConfirmation)
            {
                _log.Information($"Asking user for confirmation");

                // Only continue if the user pressed the yes button
                var dialogResult = await ShowConfirmationDialog().ConfigureAwait(true);

                if (dialogResult != ContentDialogResult.Primary)
                {
                    return(null);
                }
            }

            _log.Information($"Using {target.Name} to play replay {replay.FileInfo.Path}");

            Process gameHandle = null;

            try
            {
                gameHandle = target.PlayReplay(replay.FileInfo.Path);
            }
            catch (Exception ex)
            {
                await ShowExceptionDialog(ex).ConfigureAwait(true);

                _log.Error(ex.ToString());
            }

            return(gameHandle);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Get replays from database and load to display
        /// </summary>
        public void LoadReplays()
        {
            _log.Information("Loading replays from database...");
            var databaseResults = _fileManager.GetReplays(SortParameters, SettingsManager.Settings.ItemsPerPage, PreviewReplays.Count);

            _log.Information($"Retrieved {databaseResults.Count} replays");
            foreach (var file in databaseResults)
            {
                var previewModel = CreateReplayPreview(file);

                App.Current.Dispatcher.Invoke((Action) delegate
                {
                    PreviewReplays.Add(previewModel);
                });

                FileResults.Add(file.FileInfo.Path, file);
            }
        }
Exemplo n.º 13
0
        public ResponseBase CheckImageCache(RequestBase request)
        {
            string downloadLocation = String.Empty;

            // what kind of request is it?
            switch (request)
            {
            case ChampionRequest c:     // check if each unique string isnt null
                if (String.IsNullOrEmpty(c.ChampionName))
                {
                    throw new ArgumentNullException();
                }

                downloadLocation = Path.Combine(CachePath, "champs", $"{c.ChampionName}.png");
                break;

            case ItemRequest i:
                if (String.IsNullOrEmpty(i.ItemID))
                {
                    throw new ArgumentNullException();
                }

                downloadLocation = Path.Combine(CachePath, "items", $"{i.ItemID}.png");
                break;

            case MapRequest m:
                if (String.IsNullOrEmpty(m.MapID))
                {
                    throw new ArgumentNullException();
                }

                downloadLocation = Path.Combine(CachePath, "maps", $"{m.MapID}.png");
                break;

            default:
                break;
            }

            // Create the response item
            ResponseBase response = new ResponseBase
            {
                Request = request
            };

            // Does the file already exist in that location?
            if (!File.Exists(downloadLocation))
            {
                _log.Information($"Cache miss on {downloadLocation}");
                response.IsFaulted = true;
                response.Exception = new FileNotFoundException("Cache miss", downloadLocation);
                return(response);
            }

            //// Get the image
            //try
            //{
            //    response.ResponseImage = GetImageFromFile(downloadLocation);
            //}
            //catch (OutOfMemoryException ex)
            //{
            //    // If the file is not formatted as an image, return an exception
            //    _log.Warning($"Image is not a valid format {downloadLocation}");
            //    response.IsFaulted = true;
            //    response.Exception = new Exception("Image is not a valid format", ex);
            //    return response;
            //}

            response.ResponsePath = downloadLocation;
            response.IsFaulted    = false;
            return(response);
        }