From fedc158dc0b889f5ab98ab7c2287a8d2ac10e00c Mon Sep 17 00:00:00 2001 From: Aaron Schultz Date: Fri, 26 Mar 2021 11:41:16 +0100 Subject: [PATCH] Cleanup --- .../StatisticsAnalysisTool/App.xaml | 4 +- .../StatisticsAnalysisTool/App.xaml.cs | 4 +- .../StatisticsAnalysisTool/Common/Alert.cs | 69 +- .../Common/AlertController.cs | 83 +- .../Common/ApiController.cs | 68 +- .../Common/CategoryController.cs | 31 +- .../Common/Converter.cs | 15 +- .../Common/ExtensionMethod.cs | 39 +- .../StatisticsAnalysisTool/Common/FixPoint.cs | 13 +- .../Common/Formatting.cs | 29 +- .../Common/FrequentlyValues.cs | 102 +- .../Common/ImageController.cs | 10 +- .../Common/ItemController.cs | 305 +-- .../Common/LanguageController.cs | 95 +- .../Common/Locations.cs | 102 +- .../Common/ProgressBarSmoother.cs | 12 +- .../Common/SoundController.cs | 36 +- .../Common/Utilities.cs | 46 +- .../Common/WebDownload.cs | 14 +- .../Enumerations/ChestStatus.cs | 2 +- .../Enumerations/DungeonStatus.cs | 2 +- .../Enumerations/EventCodes.cs | 2 +- .../Enumerations/OperationCodes.cs | 2 +- .../GameData/LootChestData.cs | 116 +- .../GameData/WorldData.cs | 111 +- .../Languages/en-US.xml | 4 +- .../Models/ClusterInfo.cs | 4 +- .../Models/DungeonStats.cs | 38 +- .../Models/GameInfoPlayers.cs | 8 +- .../Models/GoldModels.cs | 11 +- .../StatisticsAnalysisTool/Models/Guild.cs | 8 +- .../StatisticsAnalysisTool/Models/Item.cs | 31 +- .../Models/ItemCategoryTree.cs | 216 +- .../StatisticsAnalysisTool/Models/ItemData.cs | 10 +- .../Models/ItemInformationModels.cs | 100 +- .../Models/ItemJsonObject.cs | 9 +- .../Models/MarketHistoriesResponse.cs | 10 +- .../Models/MarketHistoryResponse.cs | 8 +- .../Models/MarketOrder.cs | 20 +- .../Models/MarketStats.cs | 4 +- .../Models/NetworkModel/CharacterEquipment.cs | 20 +- .../Models/NetworkModel/CombatTime.cs | 2 +- .../Models/NetworkModel/Container.cs | 1 + .../Models/NetworkModel/LocalUserData.cs | 4 +- .../Models/NetworkModel/Loot.cs | 35 +- .../Models/NetworkModel/PartyMemberCircle.cs | 12 +- .../Models/NetworkModel/PlayerGameObject.cs | 31 +- .../Models/SearchInfos.cs | 20 +- .../Models/WeaponCategories.cs | 6 +- .../Models/WorldJsonObject.cs | 9 +- .../Network/Controller/CombatController.cs | 124 +- .../Network/Controller/DungeonController.cs | 235 +- .../Network/Controller/EntityController.cs | 128 +- .../Network/Controller/TrackingController.cs | 122 +- .../Events/ActiveSpellEffectsUpdateEvent.cs | 13 +- .../Events/CharacterEquipmentChangedEvent.cs | 15 +- .../Network/Events/DiedEvent.cs | 16 +- .../Network/Events/HealthUpdateEvent.cs | 66 +- .../Events/InCombatStateUpdateEvent.cs | 33 +- .../Network/Events/LeaveEvent.cs | 11 +- .../Network/Events/LootChestOpenedEvent.cs | 10 +- .../Network/Events/NewCharacterEvent.cs | 31 +- .../Network/Events/NewEquipmentItemEvent.cs | 35 +- .../Network/Events/NewLootChestEvent.cs | 16 +- .../Network/Events/NewLootEvent.cs | 10 +- .../Network/Events/NewMobEvent.cs | 18 +- .../Network/Events/NewShrineEvent.cs | 31 +- .../Network/Events/PartyChangedOrderEvent.cs | 24 +- .../Network/Events/PartyDisbandedEvent.cs | 22 +- .../Network/Events/PartySilverGainedEvent.cs | 48 +- .../Events/SiegeCampClaimStartEvent.cs | 15 +- .../Network/Events/TakeSilverEvent.cs | 46 +- .../Network/Events/TestEvent.cs | 34 +- .../Network/Events/TestEvent2.cs | 13 +- .../Network/Events/TestEvent3.cs | 13 +- .../Network/Events/UpdateFameEvent.cs | 62 +- .../Network/Events/UpdateMoneyEvent.cs | 14 +- .../Network/Events/UpdateReSpecPointsEvent.cs | 22 +- .../Network/FameCountUpTimer.cs | 45 +- .../ActiveSpellEffectsUpdateEventHandler.cs | 7 +- .../Handler/ChangeClusterResponseHandler.cs | 7 +- .../CharacterEquipmentChangedEventHandler.cs | 10 +- .../Network/Handler/DiedEventHandler.cs | 4 +- .../Handler/HealthUpdateEventHandler.cs | 8 +- .../InCombatStateUpdateEventHandler.cs | 9 +- .../Network/Handler/JoinResponseHandler.cs | 23 +- .../Network/Handler/LeaveEventHandler.cs | 5 +- .../Handler/LootChestOpenedEventHandler.cs | 7 +- .../Handler/NewCharacterEventHandler.cs | 12 +- .../Handler/NewEquipmentItemEventHandler.cs | 7 +- .../Handler/NewLootChestEventHandler.cs | 7 +- .../Network/Handler/NewLootEventHandler.cs | 12 +- .../Network/Handler/NewMobEventHandler.cs | 5 +- .../Network/Handler/NewShrineEventHandler.cs | 5 +- .../Handler/PartyChangedOrderEventHandler.cs | 12 +- .../Handler/PartyDisbandedEventHandler.cs | 5 +- .../Handler/PartyMakeLeaderEventHandler.cs | 5 +- .../Handler/PartySilverGainedEventHandler.cs | 8 +- .../SiegeCampClaimStartEventHandler.cs | 7 +- .../Network/Handler/TakeSilverEventHandler.cs | 8 +- .../Network/Handler/TestHandler.cs | 8 +- .../Network/Handler/TestHandler2.cs | 8 +- .../Network/Handler/TestHandler3.cs | 8 +- .../Network/Handler/UpdateFameEventHandler.cs | 22 +- .../Handler/UpdateMoneyEventHandler.cs | 9 +- .../Handler/UpdateReSpecPointsEventHandler.cs | 9 +- .../Network/NetworkManager.cs | 40 +- .../Notification/DamageMeterFragment.cs | 80 +- .../Notification/DungeonChestFragment.cs | 95 +- .../DungeonNotificationFragment.cs | 313 ++- .../Notification/FameNotificationFragment.cs | 3 +- .../Network/Operations/MoveOperation.cs | 14 +- .../Responses/ChangeClusterResponse.cs | 27 +- .../Operations/Responses/JoinResponse.cs | 70 +- .../Responses/PartyMakeLeaderResponse.cs | 16 +- .../Network/ReSpecPointsCountUpTimer.cs | 56 +- .../Network/SilverCountUpTimer.cs | 56 +- .../Network/Time/GameTimeSpan.cs | 14 +- .../Network/Time/GameTimeStamp.cs | 12 +- .../Network/ValueCountUpTimer.cs | 6 +- .../Properties/Annotations.cs | 2314 +++++++++-------- .../Properties/AssemblyInfo.cs | 17 +- .../ViewModels/InfoWindowViewModel.cs | 18 +- .../ViewModels/ItemAlertWindowViewModel.cs | 30 +- .../ViewModels/ItemWindowViewModel.cs | 378 +-- .../ViewModels/MainWindowViewModel.cs | 1092 ++++---- .../ViewModels/SettingsWindowViewModel.cs | 148 +- .../StatisticsAnalysisTool/packages.config | 1 + 128 files changed, 3944 insertions(+), 4298 deletions(-) diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml b/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml index 0810a29f9..cc6bbe5f4 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml @@ -5,8 +5,8 @@ - - + + diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml.cs index 3f576e8a5..f0dd1df14 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/App.xaml.cs @@ -3,9 +3,9 @@ namespace StatisticsAnalysisTool { /// - /// Interaktionslogik für "App.xaml" + /// Interaktionslogik für "App.xaml" /// public partial class App : Application { } -} +} \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Alert.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Alert.cs index bd07a6724..11e73e23b 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Alert.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Alert.cs @@ -1,25 +1,25 @@ -using log4net; -using StatisticsAnalysisTool.Annotations; -using StatisticsAnalysisTool.Exceptions; -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Views; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; +using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; +using log4net; +using StatisticsAnalysisTool.Annotations; +using StatisticsAnalysisTool.Exceptions; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Views; namespace StatisticsAnalysisTool.Common { public class Alert { + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly MainWindow _mainWindow; - private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private AlertController AlertController { get; } - private Item _item; private int _alertModeMinSellPriceIsUndercutPrice; private bool _isEventActive; + private Item _item; public Alert(MainWindow mainWindow, AlertController alertController, Item item, int alertModeMinSellPriceIsUndercutPrice) { @@ -29,13 +29,32 @@ public Alert(MainWindow mainWindow, AlertController alertController, Item item, AlertModeMinSellPriceIsUndercutPrice = alertModeMinSellPriceIsUndercutPrice; } - public void StartEvent() + private AlertController AlertController { get; } + + public Item Item + { + get => _item; + set + { + _item = value; + OnPropertyChanged(); + } + } + + public int AlertModeMinSellPriceIsUndercutPrice { - if (_isEventActive) + get => _alertModeMinSellPriceIsUndercutPrice; + set { - return; + _alertModeMinSellPriceIsUndercutPrice = value; + OnPropertyChanged(); } - + } + + public void StartEvent() + { + if (_isEventActive) return; + _isEventActive = true; AlertEventAsync(_item.UniqueName); } @@ -49,16 +68,14 @@ public void StopEvent() private async void AlertEventAsync(string uniqueName) { while (_isEventActive) - { try { var cityPrices = await ApiController.GetCityItemPricesFromJsonAsync(uniqueName, null, null).ConfigureAwait(false); foreach (var marketResponse in cityPrices ?? new List()) - { - if (Locations.GetName(marketResponse.City) != Location.BlackMarket - && marketResponse.SellPriceMinDate >= DateTime.UtcNow.AddMinutes(-5) - && marketResponse.SellPriceMin <= (ulong)AlertModeMinSellPriceIsUndercutPrice + if (Locations.GetName(marketResponse.City) != Location.BlackMarket + && marketResponse.SellPriceMinDate >= DateTime.UtcNow.AddMinutes(-5) + && marketResponse.SellPriceMin <= (ulong) AlertModeMinSellPriceIsUndercutPrice && AlertModeMinSellPriceIsUndercutPrice > 0) { SoundController.PlayAlertSound(); @@ -73,7 +90,6 @@ private async void AlertEventAsync(string uniqueName) break; } - } await Task.Delay(25000); } @@ -86,23 +102,6 @@ private async void AlertEventAsync(string uniqueName) Log.Warn(nameof(AlertEventAsync), e); return; } - } - } - - public Item Item { - get => _item; - set { - _item = value; - OnPropertyChanged(); - } - } - - public int AlertModeMinSellPriceIsUndercutPrice { - get => _alertModeMinSellPriceIsUndercutPrice; - set { - _alertModeMinSellPriceIsUndercutPrice = value; - OnPropertyChanged(); - } } public event PropertyChangedEventHandler PropertyChanged; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/AlertController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/AlertController.cs index f9b7f8c93..e896a06e6 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/AlertController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/AlertController.cs @@ -1,9 +1,4 @@ -using log4net; -using Newtonsoft.Json; -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Properties; -using StatisticsAnalysisTool.Views; -using System; +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; @@ -12,15 +7,20 @@ using System.Linq; using System.Reflection; using System.Text; +using log4net; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; +using StatisticsAnalysisTool.Views; namespace StatisticsAnalysisTool.Common { public class AlertController { - private readonly MainWindow _mainWindow; - private readonly ICollectionView _itemsView; - private readonly ObservableCollection _alerts = new ObservableCollection(); private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private readonly ObservableCollection _alerts = new ObservableCollection(); + private readonly ICollectionView _itemsView; + private readonly MainWindow _mainWindow; private readonly int _maxAlertsAtSameTime = 10; @@ -34,17 +34,11 @@ public AlertController(MainWindow mainWindow, ICollectionView itemsView) private void Add(Item item, int alertModeMinSellPriceIsUndercutPrice) { - if (IsAlertInCollection(item.UniqueName) || !IsSpaceInAlertsCollection()) - { - return; - } + if (IsAlertInCollection(item.UniqueName) || !IsSpaceInAlertsCollection()) return; - _alerts.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) + _alerts.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { - if (e.Action == NotifyCollectionChangedAction.Add) - { - SaveActiveAlertsToLocalFile(); - } + if (e.Action == NotifyCollectionChangedAction.Add) SaveActiveAlertsToLocalFile(); }; var alertController = this; @@ -55,12 +49,9 @@ private void Add(Item item, int alertModeMinSellPriceIsUndercutPrice) private void Remove(string uniqueName) { - _alerts.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) + _alerts.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { - if (e.Action == NotifyCollectionChangedAction.Remove) - { - SaveActiveAlertsToLocalFile(); - } + if (e.Action == NotifyCollectionChangedAction.Remove) SaveActiveAlertsToLocalFile(); }; var alert = GetAlertByUniqueName(uniqueName); @@ -75,10 +66,7 @@ public bool ToggleAlert(ref Item item) { try { - if (!IsAlertInCollection(item.UniqueName) && !IsSpaceInAlertsCollection()) - { - return false; - } + if (!IsAlertInCollection(item.UniqueName) && !IsSpaceInAlertsCollection()) return false; if (IsAlertInCollection(item.UniqueName)) { @@ -100,21 +88,15 @@ public void DeactivateAlert(string uniqueName) { try { - var itemCollection = (ObservableCollection)_itemsView.SourceCollection; + var itemCollection = (ObservableCollection) _itemsView.SourceCollection; var item = itemCollection.FirstOrDefault(i => i.UniqueName == uniqueName); - if (item == null) - { - return; - } + if (item == null) return; item.IsAlertActive = false; Remove(item.UniqueName); - _mainWindow.Dispatcher?.Invoke(() => - { - _itemsView.Refresh(); - }); + _mainWindow.Dispatcher?.Invoke(() => { _itemsView.Refresh(); }); } catch (Exception e) { @@ -126,22 +108,16 @@ private void ActivateAlert(string uniqueName, int minSellUndercutPrice) { try { - var itemCollection = (ObservableCollection)_itemsView.SourceCollection; + var itemCollection = (ObservableCollection) _itemsView.SourceCollection; var item = itemCollection.FirstOrDefault(i => i.UniqueName == uniqueName); - if (item == null) - { - return; - } + if (item == null) return; item.IsAlertActive = true; item.AlertModeMinSellPriceIsUndercutPrice = minSellUndercutPrice; Add(item, item.AlertModeMinSellPriceIsUndercutPrice); - _mainWindow.Dispatcher?.Invoke(() => - { - _itemsView.Refresh(); - }); + _mainWindow.Dispatcher?.Invoke(() => { _itemsView.Refresh(); }); } catch (Exception e) { @@ -149,14 +125,20 @@ private void ActivateAlert(string uniqueName, int minSellUndercutPrice) } } - private bool IsAlertInCollection(string uniqueName) => _alerts.Any(alert => alert.Item.UniqueName == uniqueName); + private bool IsAlertInCollection(string uniqueName) + { + return _alerts.Any(alert => alert.Item.UniqueName == uniqueName); + } private Alert GetAlertByUniqueName(string uniqueName) { return _alerts.FirstOrDefault(alert => alert.Item.UniqueName == uniqueName); } - public bool IsSpaceInAlertsCollection() => _alerts.Count < _maxAlertsAtSameTime; + public bool IsSpaceInAlertsCollection() + { + return _alerts.Count < _maxAlertsAtSameTime; + } #region Alert file controls @@ -165,27 +147,24 @@ private void SetActiveAlertsFromLocalFile() var localFilePath = $"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ActiveAlertsFileName}"; if (File.Exists(localFilePath)) - { try { var localItemString = File.ReadAllText(localFilePath, Encoding.UTF8); foreach (var alert in JsonConvert.DeserializeObject>(localItemString)) - { ActivateAlert(alert.UniqueName, alert.MinSellUndercutPrice); - } } catch (Exception e) { Log.Error(nameof(SetActiveAlertsFromLocalFile), e); } - } } private void SaveActiveAlertsToLocalFile() { var localFilePath = $"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ActiveAlertsFileName}"; - var activeItemAlerts = _alerts.Select(alert => new AlertSaveObject() { UniqueName = alert.Item.UniqueName, MinSellUndercutPrice = alert.AlertModeMinSellPriceIsUndercutPrice }).ToList(); + var activeItemAlerts = _alerts.Select(alert => new AlertSaveObject + {UniqueName = alert.Item.UniqueName, MinSellUndercutPrice = alert.AlertModeMinSellPriceIsUndercutPrice}).ToList(); var fileString = JsonConvert.SerializeObject(activeItemAlerts); try diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ApiController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ApiController.cs index 2cc4186bf..56d2a8425 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ApiController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ApiController.cs @@ -1,19 +1,20 @@ -namespace StatisticsAnalysisTool.Common -{ - using Exceptions; - using log4net; - using Models; - using Newtonsoft.Json; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Threading.Tasks; +using log4net; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Exceptions; +using StatisticsAnalysisTool.Models; +namespace StatisticsAnalysisTool.Common +{ public static class ApiController { - private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static async Task GetItemInfoFromJsonAsync(string uniqueName) { @@ -28,7 +29,7 @@ public static async Task GetItemInfoFromJsonAsync(string unique { using (var content = response.Content) { - var emptyItemInfo = new ItemInformation() + var emptyItemInfo = new ItemInformation { UniqueName = uniqueName, LastUpdate = DateTime.Now @@ -65,20 +66,23 @@ public static async Task GetItemInfoFromJsonAsync(string unique } } - public static async Task GetItemInfoFromJsonAsync(Item item) => await GetItemInfoFromJsonAsync(item.UniqueName); + public static async Task GetItemInfoFromJsonAsync(Item item) + { + return await GetItemInfoFromJsonAsync(item.UniqueName); + } /// - /// Returns all city item prices bye uniqueName, locations and qualities. + /// Returns all city item prices bye uniqueName, locations and qualities. /// /// public static async Task> GetCityItemPricesFromJsonAsync(string uniqueName) { var locations = Locations.GetLocationsListByArea(true, true, true, true); - return await GetCityItemPricesFromJsonAsync(uniqueName, locations, new List() { 1,2,3,4,5 } ); + return await GetCityItemPricesFromJsonAsync(uniqueName, locations, new List {1, 2, 3, 4, 5}); } /// - /// Returns city item prices bye uniqueName, locations and qualities. + /// Returns city item prices bye uniqueName, locations and qualities. /// /// public static async Task> GetCityItemPricesFromJsonAsync(string uniqueName, List locations, List qualities) @@ -89,7 +93,7 @@ public static async Task> GetCityItemPricesFromJsonAsync(st if (locations?.Count >= 1) { url += "?locations="; - url = (locations).Aggregate(url, (current, location) => current + $"{location},"); + url = locations.Aggregate(url, (current, location) => current + $"{location},"); } if (qualities?.Count >= 1) @@ -106,10 +110,7 @@ public static async Task> GetCityItemPricesFromJsonAsync(st using (var response = await client.GetAsync(url)) { - if (response.StatusCode == (HttpStatusCode) 429) - { - throw new TooManyRequestsException(); - } + if (response.StatusCode == (HttpStatusCode) 429) throw new TooManyRequestsException(); using (var content = response.Content) { @@ -121,7 +122,7 @@ public static async Task> GetCityItemPricesFromJsonAsync(st { throw new TooManyRequestsException(); } - catch(Exception e) + catch (Exception e) { Log.Error(nameof(GetCityItemPricesFromJsonAsync), e); return null; @@ -129,7 +130,8 @@ public static async Task> GetCityItemPricesFromJsonAsync(st } } - public static async Task> GetHistoryItemPricesFromJsonAsync(string uniqueName, IList locations, DateTime? date, IList qualities, int timeScale = 24) + public static async Task> GetHistoryItemPricesFromJsonAsync(string uniqueName, IList locations, + DateTime? date, IList qualities, int timeScale = 24) { var locationsString = ""; var qualitiesString = ""; @@ -156,10 +158,7 @@ public static async Task> GetHistoryItemPricesFrom { using (var content = response.Content) { - if (response.StatusCode == (HttpStatusCode)429) - { - throw new TooManyRequestsException(); - } + if (response.StatusCode == (HttpStatusCode) 429) throw new TooManyRequestsException(); return JsonConvert.DeserializeObject>(await content.ReadAsStringAsync()); } @@ -169,7 +168,7 @@ public static async Task> GetHistoryItemPricesFrom { throw new TooManyRequestsException(); } - catch(Exception e) + catch (Exception e) { Log.Error(nameof(GetHistoryItemPricesFromJsonAsync), e); return null; @@ -195,7 +194,7 @@ public static async Task GetGameInfoSearchFromJsonAsync( } } } - catch(Exception e) + catch (Exception e) { Log.Error(nameof(GetGameInfoSearchFromJsonAsync), e); return gameInfoSearchResponse; @@ -217,7 +216,8 @@ public static async Task GetGameInfoPlayersFromJsonAsyn { using (var content = response.Content) { - return JsonConvert.DeserializeObject(await content.ReadAsStringAsync()) ?? gameInfoPlayerResponse; + return JsonConvert.DeserializeObject(await content.ReadAsStringAsync()) ?? + gameInfoPlayerResponse; } } } @@ -256,9 +256,9 @@ public static async Task GetGameInfoGuildsFromJsonAsync( public static async Task> GetGoldPricesFromJsonAsync(DateTime? dateTime, int count, int timeout = 30) { - var checkedDateTime = (dateTime != null) ? dateTime.ToString() : string.Empty; + var checkedDateTime = dateTime != null ? dateTime.ToString() : string.Empty; - var url = $"https://www.albion-online-data.com/api/v2/stats/Gold?" + + var url = "https://www.albion-online-data.com/api/v2/stats/Gold?" + $"date={checkedDateTime}" + $"&count={count}"; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/CategoryController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/CategoryController.cs index 977b5cc84..7525a2c4f 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/CategoryController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/CategoryController.cs @@ -1,12 +1,12 @@ -using StatisticsAnalysisTool.Models; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using StatisticsAnalysisTool.Models; namespace StatisticsAnalysisTool.Common { public static class CategoryController { - public static List Categories = new List() + public static List Categories = new List { new CategoryObject("bag", Category.Bag, ParentCategory.Accessories), new CategoryObject("cape", Category.Cape, ParentCategory.Accessories), @@ -167,7 +167,7 @@ public static class CategoryController new CategoryObject("mercenarytrophy", Category.MercenaryTrophy, ParentCategory.Trophies), new CategoryObject("oretrophy", Category.OreTrophy, ParentCategory.Trophies), new CategoryObject("rocktrophy", Category.RockTrophy, ParentCategory.Trophies), - new CategoryObject("woodtrophy", Category.WoodTrophy, ParentCategory.Trophies), + new CategoryObject("woodtrophy", Category.WoodTrophy, ParentCategory.Trophies) }; public static readonly Dictionary CategoryNames = new Dictionary @@ -447,14 +447,25 @@ public static class CategoryController {ParentCategory.Trophies, LanguageController.Translation("TROPHIES")} }; - public static CategoryObject GetCategory(string categoryId) => Categories.SingleOrDefault(x => x.CategoryId == categoryId); + public static CategoryObject GetCategory(string categoryId) + { + return Categories.SingleOrDefault(x => x.CategoryId == categoryId); + } - public static string GetCategoryName(Category category) => CategoryNames.TryGetValue(category, out var name) ? name : null; + public static string GetCategoryName(Category category) + { + return CategoryNames.TryGetValue(category, out var name) ? name : null; + } - public static string GetParentCategoryName(ParentCategory parentCategory) => ParentCategoryNames.TryGetValue(parentCategory, out var name) ? name : null; + public static string GetParentCategoryName(ParentCategory parentCategory) + { + return ParentCategoryNames.TryGetValue(parentCategory, out var name) ? name : null; + } - public static Dictionary GetCategoriesByParentCategory(ParentCategory parentCategory) => - Categories?.Where(x => x.ParentCategory == parentCategory).ToDictionary(x => x.Category, x => x.CategoryName); + public static Dictionary GetCategoriesByParentCategory(ParentCategory parentCategory) + { + return Categories?.Where(x => x.ParentCategory == parentCategory).ToDictionary(x => x.Category, x => x.CategoryName); + } } public enum Category @@ -595,7 +606,7 @@ public enum Category MercenaryTrophy, OreTrophy, RockTrophy, - WoodTrophy, + WoodTrophy } public enum ParentCategory diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Converter.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Converter.cs index eaba1ecb3..07584c7fb 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Converter.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Converter.cs @@ -4,10 +4,7 @@ public static class Converter { public static string GoldToDollar(ulong itemSilverPrice, int currentGoldPrice) { - if (itemSilverPrice == 0 || currentGoldPrice == 0) - { - return 0.ToString(); - } + if (itemSilverPrice == 0 || currentGoldPrice == 0) return 0.ToString(); // 750 Gold - 4,95 USD // 21.000 Gold - 99,95 USD @@ -15,13 +12,13 @@ public static string GoldToDollar(ulong itemSilverPrice, int currentGoldPrice) double minReceivedGold = 750; double maxReceivedGold = 21000; - double minGoldPriceInCent = 4.95; - double maxGoldPriceInCent = 99.95; + var minGoldPriceInCent = 4.95; + var maxGoldPriceInCent = 99.95; - double minOneGoldInCent = minGoldPriceInCent / minReceivedGold; - double maxOneGoldInCent = maxGoldPriceInCent / maxReceivedGold; + var minOneGoldInCent = minGoldPriceInCent / minReceivedGold; + var maxOneGoldInCent = maxGoldPriceInCent / maxReceivedGold; - var itemPriceInGold = itemSilverPrice / (ulong)currentGoldPrice; + var itemPriceInGold = itemSilverPrice / (ulong) currentGoldPrice; var maxPrice = minOneGoldInCent * itemPriceInGold; var minPrice = maxOneGoldInCent * itemPriceInGold; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ExtensionMethod.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ExtensionMethod.cs index e08ef325a..16ae15205 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ExtensionMethod.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ExtensionMethod.cs @@ -11,29 +11,28 @@ public static class ExtensionMethod { public static void OrderByReference(this ObservableCollection collection, List comparison) { - for (int i = 0; i < comparison.Count; i++) - { + for (var i = 0; i < comparison.Count; i++) if (!comparison.ElementAt(i).Equals(collection.ElementAt(i))) - { collection.Move(collection.IndexOf(comparison[i]), i); - } - } } - - public static string ToShortNumberString(this long num) => GetShortNumber(num); - public static string ToShortNumberString(this int num) => GetShortNumber(num); + public static string ToShortNumberString(this long num) + { + return GetShortNumber(num); + } + + public static string ToShortNumberString(this int num) + { + return GetShortNumber(num); + } public static string ToShortNumberString(this double num) { try { - if (double.IsNaN(num)) - { - return "0"; - } + if (double.IsNaN(num)) return "0"; - return double.IsInfinity(num) ? double.MaxValue.ToString(CultureInfo.InvariantCulture) : GetShortNumber((decimal)num); + return double.IsInfinity(num) ? double.MaxValue.ToString(CultureInfo.InvariantCulture) : GetShortNumber((decimal) num); } catch (OverflowException) { @@ -61,10 +60,7 @@ private static string GetShortNumber(this decimal num) return (num / 100m).ToString("#.00'K'", CultureInfo.CurrentCulture); } - if (num < 1000) - { - return num.ToString("N0", CultureInfo.CurrentCulture); - } + if (num < 1000) return num.ToString("N0", CultureInfo.CurrentCulture); if (num < 10000) { @@ -90,10 +86,7 @@ private static string GetShortNumber(this decimal num) public static DateTime? GetHighestDateTime(this ObservableCollection list) { - if (!list.Any()) - { - return null; - } + if (!list.Any()) return null; return list.Max(); } @@ -102,7 +95,7 @@ private static string GetShortNumber(this decimal num) { try { - var valueEnumerable = (IEnumerable)value; + var valueEnumerable = (IEnumerable) value; var myBytes = valueEnumerable.OfType().ToArray(); return new Guid(myBytes); } @@ -145,7 +138,7 @@ public static double ToPositiveFromNegativeOrZero(this double healthChange) public static Dictionary ToDictionary(this IEnumerable array) { return array - .Select((v, i) => new { Key = i, Value = v }) + .Select((v, i) => new {Key = i, Value = v}) .ToDictionary(o => o.Key, o => o.Value); } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FixPoint.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FixPoint.cs index 17d597d50..f8ee102ca 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FixPoint.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FixPoint.cs @@ -1,4 +1,5 @@ -using System.Globalization; +using System; +using System.Globalization; namespace StatisticsAnalysisTool.Common { @@ -6,12 +7,10 @@ public readonly struct FixPoint { public const long InternalFactor = 10000L; public static readonly FixPoint One = new FixPoint(InternalFactor); - public double DoubleValue => (double)InternalValue / InternalFactor; + public double DoubleValue => (double) InternalValue / InternalFactor; public long IntegerValue => InternalValue / InternalFactor; - public long InternalValue { - get; - } + public long InternalValue { get; } private FixPoint(long internalValue) { @@ -25,8 +24,8 @@ public static FixPoint FromInternalValue(long internalValue) public static FixPoint FromFloatingPointValue(double value) { - value = System.Math.Min(System.Math.Max(value, double.MinValue), double.MaxValue); - return new FixPoint((long)System.Math.Round(value * InternalFactor)); + value = Math.Min(Math.Max(value, double.MinValue), double.MaxValue); + return new FixPoint((long) Math.Round(value * InternalFactor)); } public override string ToString() diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Formatting.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Formatting.cs index 162dd88d7..f38d00f32 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Formatting.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Formatting.cs @@ -1,12 +1,15 @@ using System; +using System.Globalization; namespace StatisticsAnalysisTool.Common { - using System.Globalization; - public class Formatting { - public static string CurrentDateTimeFormat(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc).ToLocalTime().ToString("G", new CultureInfo(LanguageController.CurrentCultureInfo.TextInfo.CultureName)); + public static string CurrentDateTimeFormat(DateTime value) + { + return DateTime.SpecifyKind(value, DateTimeKind.Utc).ToLocalTime() + .ToString("G", new CultureInfo(LanguageController.CurrentCultureInfo.TextInfo.CultureName)); + } public static string DateTimeToLastUpdateTime(DateTime dateTime) { @@ -16,20 +19,11 @@ public static string DateTimeToLastUpdateTime(DateTime dateTime) var hours = (endTime - startTime).TotalHours; var days = (endTime - startTime).TotalDays; - if (minutes <= 120) - { - return $"{minutes:N0} {LanguageController.Translation("MINUTES")}"; - } + if (minutes <= 120) return $"{minutes:N0} {LanguageController.Translation("MINUTES")}"; - if (hours <= 48) - { - return $"{hours:N0} {LanguageController.Translation("HOURS")}"; - } + if (hours <= 48) return $"{hours:N0} {LanguageController.Translation("HOURS")}"; - if (days <= 365) - { - return $"{days:N0} {LanguageController.Translation("DAYS")}"; - } + if (days <= 365) return $"{days:N0} {LanguageController.Translation("DAYS")}"; return $"{LanguageController.Translation("OVER_A_YEAR")}"; } @@ -54,10 +48,7 @@ public static string ToStringShort(double num) return (num / 100f).ToString("#.00'K'", CultureInfo.CurrentCulture); } - if (num < 1000) - { - return num.ToString("N0", CultureInfo.CurrentCulture); - } + if (num < 1000) return num.ToString("N0", CultureInfo.CurrentCulture); if (num < 10000) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FrequentlyValues.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FrequentlyValues.cs index 52d193797..10aadfec0 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FrequentlyValues.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/FrequentlyValues.cs @@ -6,54 +6,90 @@ public static class FrequentlyValues { public static readonly Dictionary ItemTiers = new Dictionary { - {ItemTier.Unknown, string.Empty }, - {ItemTier.T1, "Tier 1" }, - {ItemTier.T2, "Tier 2" }, - {ItemTier.T3, "Tier 3" }, - {ItemTier.T4, "Tier 4" }, - {ItemTier.T5, "Tier 5" }, - {ItemTier.T6, "Tier 6" }, - {ItemTier.T7, "Tier 7" }, - {ItemTier.T8, "Tier 8" } + {ItemTier.Unknown, string.Empty}, + {ItemTier.T1, "Tier 1"}, + {ItemTier.T2, "Tier 2"}, + {ItemTier.T3, "Tier 3"}, + {ItemTier.T4, "Tier 4"}, + {ItemTier.T5, "Tier 5"}, + {ItemTier.T6, "Tier 6"}, + {ItemTier.T7, "Tier 7"}, + {ItemTier.T8, "Tier 8"} }; public static readonly Dictionary ItemLevels = new Dictionary { - {ItemLevel.Unknown, string.Empty }, - {ItemLevel.Level0, "0" }, - {ItemLevel.Level1, "1" }, - {ItemLevel.Level2, "2" }, - {ItemLevel.Level3, "3" } + {ItemLevel.Unknown, string.Empty}, + {ItemLevel.Level0, "0"}, + {ItemLevel.Level1, "1"}, + {ItemLevel.Level2, "2"}, + {ItemLevel.Level3, "3"} }; public static readonly Dictionary ItemQualities = new Dictionary { - {ItemQuality.Unknown, -1 }, - {ItemQuality.Normal, 1 }, - {ItemQuality.Good, 2 }, - {ItemQuality.Outstanding, 3 }, - {ItemQuality.Excellent, 4 }, - {ItemQuality.Masterpiece, 5 } + {ItemQuality.Unknown, -1}, + {ItemQuality.Normal, 1}, + {ItemQuality.Good, 2}, + {ItemQuality.Outstanding, 3}, + {ItemQuality.Excellent, 4}, + {ItemQuality.Masterpiece, 5} }; - public static readonly Dictionary GameLanguages = new Dictionary() + public static readonly Dictionary GameLanguages = new Dictionary { - {GameLanguage.UnitedStates, "EN-US" }, - {GameLanguage.Germany, "DE-DE" }, - {GameLanguage.Russia, "RU-RU" }, - {GameLanguage.Poland, "PL-PL" }, - {GameLanguage.Brazil, "PT-BR" }, - {GameLanguage.France, "FR-FR" }, - {GameLanguage.Spain, "ES-ES" }, - {GameLanguage.Chinese, "ZH-CN" } + {GameLanguage.UnitedStates, "EN-US"}, + {GameLanguage.Germany, "DE-DE"}, + {GameLanguage.Russia, "RU-RU"}, + {GameLanguage.Poland, "PL-PL"}, + {GameLanguage.Brazil, "PT-BR"}, + {GameLanguage.France, "FR-FR"}, + {GameLanguage.Spain, "ES-ES"}, + {GameLanguage.Chinese, "ZH-CN"} }; } - public enum GameLanguage { UnitedStates, Germany, Russia, Poland, Brazil, France, Spain, Chinese } + public enum GameLanguage + { + UnitedStates, + Germany, + Russia, + Poland, + Brazil, + France, + Spain, + Chinese + } - public enum ItemTier { Unknown = -1, T1 = 1, T2 = 2, T3 = 3, T4 = 4, T5 = 5, T6 = 6, T7 = 7, T8 = 8 } + public enum ItemTier + { + Unknown = -1, + T1 = 1, + T2 = 2, + T3 = 3, + T4 = 4, + T5 = 5, + T6 = 6, + T7 = 7, + T8 = 8 + } - public enum ItemLevel { Unknown = -1, Level0 = 0, Level1 = 1, Level2 = 2, Level3 = 3 } + public enum ItemLevel + { + Unknown = -1, + Level0 = 0, + Level1 = 1, + Level2 = 2, + Level3 = 3 + } - public enum ItemQuality { Unknown = -1, Normal = 0, Good = 1, Outstanding = 2, Excellent = 3, Masterpiece = 4 } + public enum ItemQuality + { + Unknown = -1, + Normal = 0, + Good = 1, + Outstanding = 2, + Excellent = 3, + Masterpiece = 4 + } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ImageController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ImageController.cs index 1dafeed95..af02c72d3 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ImageController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ImageController.cs @@ -1,11 +1,11 @@ -using StatisticsAnalysisTool.Properties; -using System; +using System; using System.Diagnostics; using System.IO; using System.Net; using System.Reflection; using System.Threading.Tasks; using System.Windows.Media.Imaging; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.Common { @@ -34,7 +34,9 @@ public static BitmapImage GetItemImage(string uniqueName = null, int pixelHeight } catch { - return new BitmapImage(new Uri(@"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Resources/Trash.png", UriKind.Absolute)); + return new BitmapImage(new Uri( + @"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Resources/Trash.png", + UriKind.Absolute)); } } @@ -46,7 +48,7 @@ public static void SaveImageLocal(BitmapImage image, string localFilePath) image.DownloadCompleted += (sender, args) => { var encoder = new PngBitmapEncoder(); - encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender)); + encoder.Frames.Add(BitmapFrame.Create((BitmapImage) sender)); using (var fileStream = new FileStream(localFilePath, FileMode.Create)) { encoder.Save(fileStream); diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ItemController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ItemController.cs index 99def6af1..779938e24 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ItemController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ItemController.cs @@ -1,133 +1,39 @@ -using Newtonsoft.Json; -using StatisticsAnalysisTool.Properties; +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; +using System.Linq; using System.Net; using System.Net.Http; +using System.Text; using System.Threading.Tasks; using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.Common { - using Models; - using System; - using System.Linq; - using System.Text; - using System.Windows.Media; - using System.Windows.Media.Imaging; - public class ItemController { public static ObservableCollection Items; - private static readonly string FullItemInformationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.FullItemInformationFileName); + private static readonly string FullItemInformationFilePath = + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.FullItemInformationFileName); private static ObservableCollection _itemInformationList = new ObservableCollection(); - #region Item list - - public static async Task GetItemListFromJsonAsync() - { - var url = Settings.Default.ItemListSourceUrl; - var localFilePath = $"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}"; - - if (!GetItemListSourceUrlIfExist(ref url)) - return false; - - if (File.Exists(localFilePath)) - { - var fileDateTime = File.GetLastWriteTime(localFilePath); - - if (fileDateTime.AddDays(Settings.Default.UpdateItemListByDays) < DateTime.Now) - { - if (await GetItemListFromWebAsync(url)) - { - Items = GetItemListFromLocal(); - } - return (Items?.Count > 0); - } + public static readonly Brush ToggleOnColor = new SolidColorBrush((Color) Application.Current.Resources["Color.Blue.2"]); - Items = GetItemListFromLocal(); - return (Items?.Count > 0); - } + public static readonly Brush ToggleOffColor = new SolidColorBrush((Color) Application.Current.Resources["Color.Text.Normal"]); - if (await GetItemListFromWebAsync(url)) - { - Items = GetItemListFromLocal(); - } - return (Items?.Count > 0); - } - - private static bool GetItemListSourceUrlIfExist(ref string url) + public static Item GetItemByIndex(int index) { - if (string.IsNullOrEmpty(Settings.Default.ItemListSourceUrl)) - { - url = Settings.Default.DefaultItemListSourceUrl; - if (string.IsNullOrEmpty(url)) - return false; - - Settings.Default.ItemListSourceUrl = Settings.Default.DefaultItemListSourceUrl; - MessageBox.Show(LanguageController.Translation("DEFAULT_ITEMLIST_HAS_BEEN_LOADED"), LanguageController.Translation("NOTE")); - } - return true; - } - - private static ObservableCollection GetItemListFromLocal() - { - try - { - var localItemString = File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}", Encoding.UTF8); - return ConvertItemJsonObjectToItem(JsonConvert.DeserializeObject>(localItemString)); - } - catch - { - return new ObservableCollection(); - } + return Items.FirstOrDefault(i => i.Index == index); } - private static ObservableCollection ConvertItemJsonObjectToItem(ObservableCollection itemJsonObjectList) - { - var result = itemJsonObjectList.Select(item => new Item() - { - LocalizationNameVariable = item.LocalizationNameVariable, - LocalizationDescriptionVariable = item.LocalizationDescriptionVariable, - LocalizedNames = item.LocalizedNames, - Index = item.Index, - UniqueName = item.UniqueName - }).ToList(); - - return new ObservableCollection(result); - } - - private static async Task GetItemListFromWebAsync(string url) - { - using (var client = new HttpClient()) - { - client.Timeout = TimeSpan.FromSeconds(30); - try - { - using (var response = await client.GetAsync(url)) - { - using (var content = response.Content) - { - var fileString = await content.ReadAsStringAsync(); - File.WriteAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}", fileString, Encoding.UTF8); - return true; - } - } - } - catch - { - return false; - } - } - } - - #endregion Item list - - public static Item GetItemByIndex(int index) => Items.FirstOrDefault(i => i.Index == index); - public static string LocalizedName(LocalizedNames localizedNames, string currentLanguage = null, string alternativeName = "NO_ITEM_NAME") { if (localizedNames == null) @@ -136,7 +42,8 @@ public static string LocalizedName(LocalizedNames localizedNames, string current if (string.IsNullOrEmpty(currentLanguage)) currentLanguage = LanguageController.CurrentCultureInfo.TextInfo.CultureName.ToUpper(); - switch (FrequentlyValues.GameLanguages.FirstOrDefault(x => string.Equals(x.Value, currentLanguage, StringComparison.CurrentCultureIgnoreCase)).Key) + switch (FrequentlyValues.GameLanguages + .FirstOrDefault(x => string.Equals(x.Value, currentLanguage, StringComparison.CurrentCultureIgnoreCase)).Key) { case GameLanguage.UnitedStates: return localizedNames.EnUs ?? alternativeName; @@ -169,36 +76,27 @@ public static string LocalizedName(LocalizedNames localizedNames, string current public static int GetItemLevel(string uniqueName) { - if (uniqueName == null || !uniqueName.Contains("@")) - { - return 0; - } + if (uniqueName == null || !uniqueName.Contains("@")) return 0; - return int.TryParse(uniqueName.Split('@')[1], out int number) ? number : 0; + return int.TryParse(uniqueName.Split('@')[1], out var number) ? number : 0; } public static int GetItemTier(Item item) { - if (item?.UniqueName == null) - { - return -1; - } + if (item?.UniqueName == null) return -1; var itemNameTierText = item.UniqueName.Split('_')[0]; - if (itemNameTierText.Substring(0, 1) == "T" && int.TryParse(itemNameTierText.Substring(1, 1), out var result)) - { - return result; - } + if (itemNameTierText.Substring(0, 1) == "T" && int.TryParse(itemNameTierText.Substring(1, 1), out var result)) return result; - if (item.FullItemInformation?.Tier != null) - { - return item.FullItemInformation.Tier; - } + if (item.FullItemInformation?.Tier != null) return item.FullItemInformation.Tier; return -1; } - public static ItemQuality GetQuality(int value) => FrequentlyValues.ItemQualities.FirstOrDefault(x => x.Value == value).Key; + public static ItemQuality GetQuality(int value) + { + return FrequentlyValues.ItemQualities.FirstOrDefault(x => x.Value == value).Key; + } public static Style LocationStyle(Location location) { @@ -255,10 +153,7 @@ public static Style GetStyleByTimestamp(DateTime value) public static Style PriceStyle(bool bestSellMinPrice) { - if (bestSellMinPrice) - { - return Application.Current.FindResource("ListView.Grid.StackPanel.Label.BestPrice") as Style; - } + if (bestSellMinPrice) return Application.Current.FindResource("ListView.Grid.StackPanel.Label.BestPrice") as Style; return Application.Current.FindResource("ListView.Grid.StackPanel.Label.Price") as Style; } @@ -278,22 +173,113 @@ public static ulong GetMinPrice(List list) return min; } - public static readonly Brush ToggleOnColor = new SolidColorBrush((Color)Application.Current.Resources["Color.Blue.2"]); + #region Item list - public static readonly Brush ToggleOffColor = new SolidColorBrush((Color)Application.Current.Resources["Color.Text.Normal"]); + public static async Task GetItemListFromJsonAsync() + { + var url = Settings.Default.ItemListSourceUrl; + var localFilePath = $"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}"; + + if (!GetItemListSourceUrlIfExist(ref url)) + return false; + + if (File.Exists(localFilePath)) + { + var fileDateTime = File.GetLastWriteTime(localFilePath); + + if (fileDateTime.AddDays(Settings.Default.UpdateItemListByDays) < DateTime.Now) + { + if (await GetItemListFromWebAsync(url)) Items = GetItemListFromLocal(); + return Items?.Count > 0; + } + + Items = GetItemListFromLocal(); + return Items?.Count > 0; + } + + if (await GetItemListFromWebAsync(url)) Items = GetItemListFromLocal(); + return Items?.Count > 0; + } + + private static bool GetItemListSourceUrlIfExist(ref string url) + { + if (string.IsNullOrEmpty(Settings.Default.ItemListSourceUrl)) + { + url = Settings.Default.DefaultItemListSourceUrl; + if (string.IsNullOrEmpty(url)) + return false; + + Settings.Default.ItemListSourceUrl = Settings.Default.DefaultItemListSourceUrl; + MessageBox.Show(LanguageController.Translation("DEFAULT_ITEMLIST_HAS_BEEN_LOADED"), LanguageController.Translation("NOTE")); + } + + return true; + } + + private static ObservableCollection GetItemListFromLocal() + { + try + { + var localItemString = File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}", Encoding.UTF8); + return ConvertItemJsonObjectToItem(JsonConvert.DeserializeObject>(localItemString)); + } + catch + { + return new ObservableCollection(); + } + } + + private static ObservableCollection ConvertItemJsonObjectToItem(ObservableCollection itemJsonObjectList) + { + var result = itemJsonObjectList.Select(item => new Item + { + LocalizationNameVariable = item.LocalizationNameVariable, + LocalizationDescriptionVariable = item.LocalizationDescriptionVariable, + LocalizedNames = item.LocalizedNames, + Index = item.Index, + UniqueName = item.UniqueName + }).ToList(); + + return new ObservableCollection(result); + } + + private static async Task GetItemListFromWebAsync(string url) + { + using (var client = new HttpClient()) + { + client.Timeout = TimeSpan.FromSeconds(30); + try + { + using (var response = await client.GetAsync(url)) + { + using (var content = response.Content) + { + var fileString = await content.ReadAsStringAsync(); + File.WriteAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}", fileString, + Encoding.UTF8); + return true; + } + } + } + catch + { + return false; + } + } + } + + #endregion Item list #region ItemInformation - public static bool IsFullItemInformationComplete => Items?.All(item => IsItemInformationUpToDate(item?.FullItemInformation?.LastUpdate)) ?? false; + public static bool IsFullItemInformationComplete => + Items?.All(item => IsItemInformationUpToDate(item?.FullItemInformation?.LastUpdate)) ?? false; public static async Task GetFullItemInformationAsync(Item item) { var itemInformation = _itemInformationList.FirstOrDefault(x => x.UniqueName == item?.UniqueName); - if (itemInformation?.HttpStatus == HttpStatusCode.NotFound) - { - return itemInformation; - } + if (itemInformation?.HttpStatus == HttpStatusCode.NotFound) return itemInformation; if (string.IsNullOrEmpty(itemInformation?.UniqueName) || !IsItemInformationUpToDate(itemInformation.LastUpdate)) { @@ -306,10 +292,7 @@ public static async Task GetFullItemInformationAsync(Item item) private static ItemInformation SetEssentialItemInformation(ItemInformation itemInformation, string uniqueName) { - if (itemInformation == null) - { - return null; - } + if (itemInformation == null) return null; itemInformation.Level = GetItemLevel(uniqueName); itemInformation.UniqueName = uniqueName; @@ -318,10 +301,7 @@ private static ItemInformation SetEssentialItemInformation(ItemInformation itemI private static void AddItemInformationToLocal(ItemInformation currentItemInformation) { - if (currentItemInformation == null) - { - return; - } + if (currentItemInformation == null) return; var localItemInfo = _itemInformationList.FirstOrDefault(x => x.UniqueName == currentItemInformation.UniqueName); _itemInformationList.Remove(localItemInfo); @@ -332,10 +312,7 @@ private static void AddItemInformationToLocal(ItemInformation currentItemInforma private static bool IsItemInformationUpToDate(DateTime? lastUpdate) { - if (lastUpdate == null || lastUpdate.Value.Year == 1) - { - return false; - } + if (lastUpdate == null || lastUpdate.Value.Year == 1) return false; var lastUpdateWithCycleDays = lastUpdate.Value.AddDays(Settings.Default.FullItemInformationUpdateCycleDays); return lastUpdateWithCycleDays >= DateTime.UtcNow; @@ -345,15 +322,11 @@ public static BitmapImage ExistFullItemInformationLocal(string uniqueName) { if (_itemInformationList.Any(x => x.UniqueName == uniqueName) && IsItemInformationUpToDate(_itemInformationList.FirstOrDefault(x => x.UniqueName == uniqueName)?.LastUpdate)) - { return new BitmapImage(new Uri(@"pack://application:,,,/Resources/check.png")); - } if (_itemInformationList.Any(x => x.UniqueName == uniqueName) && !IsItemInformationUpToDate(_itemInformationList.FirstOrDefault(x => x.UniqueName == uniqueName)?.LastUpdate)) - { return new BitmapImage(new Uri(@"pack://application:,,,/Resources/outdated.png")); - } return null; } @@ -361,10 +334,7 @@ public static BitmapImage ExistFullItemInformationLocal(string uniqueName) public static void SaveItemInformationLocal() { var list = _itemInformationList; - if (list == null) - { - return; - } + if (list == null) return; var itemInformationString = JsonConvert.SerializeObject(list); @@ -378,23 +348,16 @@ public static async Task GetItemInformationListFromLocalAsync() { await Task.Run(() => { - if (_itemInformationList != null && _itemInformationList.Count > 0) - { - return; - } + if (_itemInformationList != null && _itemInformationList.Count > 0) return; if (File.Exists(FullItemInformationFilePath)) - { using (var streamReader = new StreamReader(FullItemInformationFilePath, Encoding.UTF8)) { var readContents = streamReader.ReadToEnd(); _itemInformationList = JsonConvert.DeserializeObject>(readContents); } - } else - { _itemInformationList = new ObservableCollection(); - } SetItemInformationToItems(Items); }); @@ -402,10 +365,7 @@ await Task.Run(() => private static void SetItemInformationToItems(ObservableCollection items) { - if (items == null) - { - return; - } + if (items == null) return; foreach (var item in items) { @@ -414,7 +374,10 @@ private static void SetItemInformationToItems(ObservableCollection items) } } - public static bool IsItemSlotType(ItemInformation itemInfo, string slotType) => itemInfo?.SlotType == slotType; + public static bool IsItemSlotType(ItemInformation itemInfo, string slotType) + { + return itemInfo?.SlotType == slotType; + } #endregion ItemInformation } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/LanguageController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/LanguageController.cs index 662f119bd..1f308404e 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/LanguageController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/LanguageController.cs @@ -1,33 +1,35 @@ -using log4net; -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Properties; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; +using System.Threading; using System.Windows; using System.Xml; +using log4net; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.Common { public static class LanguageController { - public static List LanguageFiles { get; set; } - private static readonly Dictionary _translations = new Dictionary(); private static CultureInfo _currentCultureInfo; private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public static List LanguageFiles { get; set; } - public static CultureInfo CurrentCultureInfo { + public static CultureInfo CurrentCultureInfo + { get => _currentCultureInfo; - set { + set + { _currentCultureInfo = value; Settings.Default.CurrentLanguageCultureName = value.TextInfo.CultureName; try { - System.Threading.Thread.CurrentThread.CurrentUICulture = value; + Thread.CurrentThread.CurrentUICulture = value; } catch (Exception e) { @@ -43,29 +45,17 @@ public static bool InitializeLanguage() if (CurrentCultureInfo == null) { if (!string.IsNullOrEmpty(Settings.Default.CurrentLanguageCultureName)) - { CurrentCultureInfo = new CultureInfo(Settings.Default.CurrentLanguageCultureName); - } else if (!string.IsNullOrEmpty(Settings.Default.DefaultLanguageCultureName)) - { CurrentCultureInfo = new CultureInfo(Settings.Default.DefaultLanguageCultureName); - } else - { throw new CultureNotFoundException(); - } } - if (SetLanguage()) - { - return true; - } + if (SetLanguage()) return true; CurrentCultureInfo = new CultureInfo(Settings.Default.DefaultLanguageCultureName); - if (SetLanguage()) - { - return true; - } + if (SetLanguage()) return true; throw new CultureNotFoundException(); } @@ -80,15 +70,13 @@ public static string Translation(string key) { try { - if (_translations.TryGetValue(key, out var value)) - { - return (!string.IsNullOrEmpty(value)) ? value : key; - } + if (_translations.TryGetValue(key, out var value)) return !string.IsNullOrEmpty(value) ? value : key; } catch (ArgumentNullException) { return "TRANSLATION-ERROR"; } + return key; } @@ -98,24 +86,15 @@ public static bool SetLanguage() try { - if (LanguageFiles == null) - { - throw new FileNotFoundException(); - } + if (LanguageFiles == null) throw new FileNotFoundException(); var fileInfos = (from file in LanguageFiles - where file.FileName.ToUpper() == CurrentCultureInfo?.TextInfo.CultureName.ToUpper() - select new FileInformation(file.FileName, file.FilePath)).FirstOrDefault(); + where file.FileName.ToUpper() == CurrentCultureInfo?.TextInfo.CultureName.ToUpper() + select new FileInformation(file.FileName, file.FilePath)).FirstOrDefault(); - if (fileInfos == null) - { - return false; - } + if (fileInfos == null) return false; - if (!ReadAndAddLanguageFile(fileInfos.FilePath)) - { - return false; - } + if (!ReadAndAddLanguageFile(fileInfos.FilePath)) return false; return true; } @@ -140,12 +119,8 @@ private static bool ReadAndAddLanguageFile(string filePath) _translations.Clear(); var xmlReader = XmlReader.Create(filePath); while (xmlReader.Read()) - { if (xmlReader.Name == "translation" && xmlReader.HasAttributes) - { AddTranslationsToDictionary(xmlReader); - } - } } catch (Exception e) { @@ -153,47 +128,29 @@ private static bool ReadAndAddLanguageFile(string filePath) Log.Error(nameof(ReadAndAddLanguageFile), e); return false; } + return true; } private static void AddTranslationsToDictionary(XmlReader xmlReader) { while (xmlReader.MoveToNextAttribute()) - { if (_translations.ContainsKey(xmlReader.Value)) - { Log.Warn($"{nameof(AddTranslationsToDictionary)}: {Translation("DOUBLE_VALUE_EXISTS_IN_THE_LANGUAGE_FILE")}: {xmlReader.Value}"); - } - else if (xmlReader.Name == "name") - { - _translations.Add(xmlReader.Value, xmlReader.ReadString()); - } - } + else if (xmlReader.Name == "name") _translations.Add(xmlReader.Value, xmlReader.ReadString()); } private static void InitializeLanguageFilesFromDirectory() { - if (LanguageFiles != null) - { - return; - } + if (LanguageFiles != null) return; var languageFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.LanguageDirectoryName); - if (!Directory.Exists(languageFilePath)) - { - return; - } + if (!Directory.Exists(languageFilePath)) return; var files = DirectoryController.GetFiles(languageFilePath, "*.xml"); - if (files == null) - { - return; - } + if (files == null) return; - if (LanguageFiles == null) - { - LanguageFiles = new List(); - } + if (LanguageFiles == null) LanguageFiles = new List(); foreach (var file in files) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Locations.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Locations.cs index 854aa6f74..b48c19a10 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Locations.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Locations.cs @@ -1,57 +1,65 @@ using System.Collections.Generic; using System.Linq; +using System.Windows; +using System.Windows.Media; namespace StatisticsAnalysisTool.Common { - using System.Windows; - using System.Windows.Media; - public static class Locations { public static readonly Dictionary Names = new Dictionary { - {Location.Thetford, "Thetford" }, - {Location.SwampCross, "Swamp Cross" }, - {Location.Lymhurst, "Lymhurst" }, - {Location.ForestCross, "Forest Cross" }, - {Location.Bridgewatch, "Bridgewatch" }, - {Location.SteppeCross, "Steppe Cross" }, - {Location.HighlandCross, "Highland Cross" }, - {Location.BlackMarket, "Black Market" }, - {Location.Martlock, "Martlock" }, - {Location.Caerleon, "Caerleon" }, - {Location.FortSterling, "Fort Sterling" }, - {Location.MountainCross, "Mountain Cross" }, - {Location.ArthursRest, "Arthur's Rest" }, - {Location.MerlynsRest, "Merlyn's Rest" }, - {Location.MorganasRest, "Morgana's Rest" } + {Location.Thetford, "Thetford"}, + {Location.SwampCross, "Swamp Cross"}, + {Location.Lymhurst, "Lymhurst"}, + {Location.ForestCross, "Forest Cross"}, + {Location.Bridgewatch, "Bridgewatch"}, + {Location.SteppeCross, "Steppe Cross"}, + {Location.HighlandCross, "Highland Cross"}, + {Location.BlackMarket, "Black Market"}, + {Location.Martlock, "Martlock"}, + {Location.Caerleon, "Caerleon"}, + {Location.FortSterling, "Fort Sterling"}, + {Location.MountainCross, "Mountain Cross"}, + {Location.ArthursRest, "Arthur's Rest"}, + {Location.MerlynsRest, "Merlyn's Rest"}, + {Location.MorganasRest, "Morgana's Rest"} }; public static readonly Dictionary ParameterNames = new Dictionary { - {Location.Thetford, "Thetford" }, - {Location.SwampCross, "Swamp Cross" }, - {Location.Lymhurst, "Lymhurst" }, - {Location.ForestCross, "Forest Cross" }, - {Location.Bridgewatch, "Bridgewatch" }, - {Location.SteppeCross, "Steppe Cross" }, - {Location.HighlandCross, "Highland Cross" }, - {Location.BlackMarket, "Black Market" }, - {Location.Martlock, "Martlock" }, - {Location.Caerleon, "Caerleon" }, - {Location.FortSterling, "Fort Sterling" }, - {Location.MountainCross, "Mountain Cross" }, - {Location.ArthursRest, "Arthurs Rest" }, - {Location.MerlynsRest, "Merlyns Rest" }, - {Location.MorganasRest, "Morganas Rest" } + {Location.Thetford, "Thetford"}, + {Location.SwampCross, "Swamp Cross"}, + {Location.Lymhurst, "Lymhurst"}, + {Location.ForestCross, "Forest Cross"}, + {Location.Bridgewatch, "Bridgewatch"}, + {Location.SteppeCross, "Steppe Cross"}, + {Location.HighlandCross, "Highland Cross"}, + {Location.BlackMarket, "Black Market"}, + {Location.Martlock, "Martlock"}, + {Location.Caerleon, "Caerleon"}, + {Location.FortSterling, "Fort Sterling"}, + {Location.MountainCross, "Mountain Cross"}, + {Location.ArthursRest, "Arthurs Rest"}, + {Location.MerlynsRest, "Merlyns Rest"}, + {Location.MorganasRest, "Morganas Rest"} }; - public static string GetName(Location location) => Names.TryGetValue(location, out var name) ? name : null; + public static string GetName(Location location) + { + return Names.TryGetValue(location, out var name) ? name : null; + } + + public static string GetParameterName(Location location) + { + return ParameterNames.TryGetValue(location, out var name) ? name : null; + } - public static string GetParameterName(Location location) => ParameterNames.TryGetValue(location, out var name) ? name : null; + public static Location GetName(string location) + { + return ParameterNames.FirstOrDefault(x => x.Value == location).Key; + } - public static Location GetName(string location) => ParameterNames.FirstOrDefault(x => x.Value == location).Key; - public static List GetLocationsListByArea(bool blackZoneOutposts, bool villages, bool cities, bool blackMarket) { var locationAreas = new List(); @@ -71,7 +79,6 @@ public static List GetLocationsListByArea(bool blackZoneOutposts, bool v var locations = new List(); foreach (var area in locationAreas) - { switch (area) { case LocationArea.BlackMarket: @@ -101,7 +108,7 @@ public static List GetLocationsListByArea(bool blackZoneOutposts, bool v locations.Add(GetParameterName(Location.Caerleon)); break; } - } + return locations; } @@ -110,17 +117,12 @@ public static Brush GetLocationBrush(Location location, bool transparent) try { if (transparent) - { - return (Brush)Application.Current.Resources[$"SolidColorBrush.City.{GetParameterName(location)}.Transparent"]; - } - else - { - return (Brush)Application.Current.Resources[$"SolidColorBrush.City.{GetParameterName(location)}"]; - } + return (Brush) Application.Current.Resources[$"SolidColorBrush.City.{GetParameterName(location)}.Transparent"]; + return (Brush) Application.Current.Resources[$"SolidColorBrush.City.{GetParameterName(location)}"]; } catch { - return (Brush)Application.Current.Resources["SolidColorBrush.City.Default.Transparent"]; + return (Brush) Application.Current.Resources["SolidColorBrush.City.Default.Transparent"]; } } @@ -128,11 +130,11 @@ public static Color GetLocationColor(Location location) { try { - return (Color)Application.Current.Resources[$"Color.City.{location}"]; + return (Color) Application.Current.Resources[$"Color.City.{location}"]; } catch { - return (Color)Application.Current.Resources["Color.City.Default"]; + return (Color) Application.Current.Resources["Color.City.Default"]; } } } @@ -153,7 +155,7 @@ public enum Location MountainCross = 4006, ArthursRest = 4300, MerlynsRest = -2, - MorganasRest = -3, + MorganasRest = -3 } public enum LocationArea diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ProgressBarSmoother.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ProgressBarSmoother.cs index e71c8855e..71df1bbe9 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ProgressBarSmoother.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/ProgressBarSmoother.cs @@ -9,9 +9,12 @@ namespace StatisticsAnalysisTool.Common // https://stackoverflow.com/questions/14485818/how-to-update-a-progress-bar-so-it-increases-smoothly public class ProgressBarSmoother { + public static readonly DependencyProperty SmoothValueProperty = + DependencyProperty.RegisterAttached("SmoothValue", typeof(double), typeof(ProgressBarSmoother), new PropertyMetadata(0.0, changing)); + public static double GetSmoothValue(DependencyObject obj) { - return (double)obj.GetValue(SmoothValueProperty); + return (double) obj.GetValue(SmoothValueProperty); } public static void SetSmoothValue(DependencyObject obj, double value) @@ -19,13 +22,10 @@ public static void SetSmoothValue(DependencyObject obj, double value) obj.SetValue(SmoothValueProperty, value); } - public static readonly DependencyProperty SmoothValueProperty = - DependencyProperty.RegisterAttached("SmoothValue", typeof(double), typeof(ProgressBarSmoother), new PropertyMetadata(0.0, changing)); - private static void changing(DependencyObject d, DependencyPropertyChangedEventArgs e) { - var anim = new DoubleAnimation((double)e.OldValue, (double)e.NewValue, new TimeSpan(0, 0, 0, 0, 250)); + var anim = new DoubleAnimation((double) e.OldValue, (double) e.NewValue, new TimeSpan(0, 0, 0, 0, 250)); (d as ProgressBar)?.BeginAnimation(RangeBase.ValueProperty, anim, HandoffBehavior.Compose); } } -} +} \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/SoundController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/SoundController.cs index d679e34a5..a38166d27 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/SoundController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/SoundController.cs @@ -1,44 +1,33 @@ -using log4net; -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Properties; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Media; +using System.Reflection; +using log4net; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.Common { public class SoundController { - private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static List AlertSounds { get; set; } public static void InitializeSoundFilesFromDirectory() { - if (AlertSounds != null) - { - return; - } - + if (AlertSounds != null) return; + var soundFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.SoundDirectoryName); - if (!Directory.Exists(soundFilePath)) - { - return; - } + if (!Directory.Exists(soundFilePath)) return; var files = DirectoryController.GetFiles(soundFilePath, "*.wav"); - if (files == null) - { - return; - } + if (files == null) return; - if (AlertSounds == null) - { - AlertSounds = new List(); - } + if (AlertSounds == null) AlertSounds = new List(); foreach (var file in files) { @@ -56,7 +45,8 @@ public static void PlayAlertSound() player.Play(); player.Dispose(); } - catch (Exception e) when (e is InvalidOperationException || e is UriFormatException || e is FileNotFoundException || e is ArgumentException) + catch (Exception e) when (e is InvalidOperationException || e is UriFormatException || e is FileNotFoundException || + e is ArgumentException) { Log.Error(nameof(PlayAlertSound), e); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Utilities.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Utilities.cs index 0475675bb..6f2a66b07 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Utilities.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Utilities.cs @@ -1,12 +1,12 @@ -using AutoUpdaterDotNET; -using StatisticsAnalysisTool.Properties; -using System; +using System; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Windows; using System.Windows.Interop; +using AutoUpdaterDotNET; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.Common { @@ -33,11 +33,20 @@ public static bool IsWindowOpen(string name = "") where T : Window : Application.Current.Windows.OfType().Any(w => w.Name.Equals(name)); } - public static string UlongMarketPriceToString(ulong value) => value.ToString("N0", new CultureInfo(LanguageController.CurrentCultureInfo.TextInfo.CultureName)); + public static string UlongMarketPriceToString(ulong value) + { + return value.ToString("N0", new CultureInfo(LanguageController.CurrentCultureInfo.TextInfo.CultureName)); + } - public static string MarketPriceDateToString(DateTime value) => Formatting.CurrentDateTimeFormat(value); + public static string MarketPriceDateToString(DateTime value) + { + return Formatting.CurrentDateTimeFormat(value); + } - public static string GetValuePerHour(double value, TimeSpan time) => Formatting.ToStringShort(value / (time.TotalSeconds / 60 / 60)); + public static string GetValuePerHour(double value, TimeSpan time) + { + return Formatting.ToStringShort(value / (time.TotalSeconds / 60 / 60)); + } public static double GetValuePerHourToDouble(double value, TimeSpan time) { @@ -53,23 +62,17 @@ public static double GetValuePerHourToDouble(double value, TimeSpan time) public static double GetValuePerSecondToDouble(double value, DateTime? combatStart, TimeSpan time, double maxValue = -1) { - if (double.IsInfinity(value)) - { - return (maxValue > 0) ? maxValue : double.MaxValue; - } + if (double.IsInfinity(value)) return maxValue > 0 ? maxValue : double.MaxValue; if (time.Ticks <= 1 && combatStart != null) { - var startTimeSpan = DateTime.UtcNow - (DateTime)combatStart; + var startTimeSpan = DateTime.UtcNow - (DateTime) combatStart; var calculation = value / startTimeSpan.TotalSeconds; - return (calculation > maxValue) ? maxValue : calculation; + return calculation > maxValue ? maxValue : calculation; } var valuePerSeconds = value / time.TotalSeconds; - if (maxValue > 0 && valuePerSeconds > maxValue) - { - return maxValue; - } + if (maxValue > 0 && valuePerSeconds > maxValue) return maxValue; return valuePerSeconds; } @@ -99,7 +102,9 @@ private struct FlashInfo public uint dwFlags; //The Flash Status. public uint uCount; // number of times to flash the window - public uint dwTimeout; //The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate. + + public uint + dwTimeout; //The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate. } [DllImport("user32.dll")] @@ -110,10 +115,7 @@ public static void FlashWindow(this Window win, uint count = uint.MaxValue) { win.Dispatcher.Invoke(() => { - if (win.IsActive) - { - return; - } + if (win.IsActive) return; var h = new WindowInteropHelper(win); @@ -135,7 +137,7 @@ public static void StopFlashingWindow(this Window win) win.Dispatcher.Invoke(() => { var h = new WindowInteropHelper(win); - var info = new FlashInfo { hwnd = h.Handle }; + var info = new FlashInfo {hwnd = h.Handle}; info.cbSize = Convert.ToUInt32(Marshal.SizeOf(info)); info.dwFlags = FlashwStop; info.uCount = uint.MaxValue; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/WebDownload.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/WebDownload.cs index 711c9bf81..cbe0a9e3d 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/WebDownload.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Common/WebDownload.cs @@ -5,18 +5,20 @@ namespace StatisticsAnalysisTool.Common { public class WebDownload : WebClient { - /// - /// Time in milliseconds - /// - public int Timeout { get; set; } - - public WebDownload() : this(30000) { } + public WebDownload() : this(30000) + { + } public WebDownload(int timeout) { Timeout = timeout; } + /// + /// Time in milliseconds + /// + public int Timeout { get; set; } + protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address); diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/ChestStatus.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/ChestStatus.cs index a522cb279..b0f6808d9 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/ChestStatus.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/ChestStatus.cs @@ -10,6 +10,6 @@ public enum ChestStatus RareChestOpen, LegendaryChestClose, LegendaryChestOpen, - Unknown, + Unknown } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/DungeonStatus.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/DungeonStatus.cs index b9bc6a097..702244aa0 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/DungeonStatus.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/DungeonStatus.cs @@ -3,6 +3,6 @@ public enum DungeonStatus { Active, - Done, + Done } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/EventCodes.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/EventCodes.cs index ed899c796..0e586530a 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/EventCodes.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/EventCodes.cs @@ -424,6 +424,6 @@ public enum EventCodes Unknown419, Unknown420, Unknown421, - Unknown422, + Unknown422 } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/OperationCodes.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/OperationCodes.cs index 4c1fa5e96..7a1922fea 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/OperationCodes.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Enumerations/OperationCodes.cs @@ -393,6 +393,6 @@ public enum OperationCodes GetNextOpenWorldAttackScheduleTime, RecoverVaultFromHideout, GetGuildEnergyDrainInfo, - ChannelingUpdate, + ChannelingUpdate } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/LootChestData.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/LootChestData.cs index 6b80a2643..43b062504 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/LootChestData.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/LootChestData.cs @@ -1,16 +1,16 @@ -using log4net; -using Newtonsoft.Json; -using PcapDotNet.Base; -using StatisticsAnalysisTool.Enumerations; -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Properties; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; +using log4net; +using Newtonsoft.Json; +using PcapDotNet.Base; +using StatisticsAnalysisTool.Enumerations; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.GameData { @@ -21,94 +21,64 @@ public static class LootChestData public static ChestType GetChestType(string value) { - if (value.Contains("BOOKCHEST")) - { - return ChestType.BookChest; - } + if (value.Contains("BOOKCHEST")) return ChestType.BookChest; - if (value.Contains("CHEST") || value.Contains("AVALON")) - { - return ChestType.Chest; - } + if (value.Contains("CHEST") || value.Contains("AVALON")) return ChestType.Chest; return ChestType.Unknown; } public static DungeonMode GetDungeonMode(string value) { - if (value.Contains("MORGANA_SOLO_CHEST") || value.Contains("KEEPER_SOLO_CHEST") || value.Contains("HERETIC_SOLO_CHEST") || value.Contains("UNDEAD_SOLO_CHEST") - || value.Contains("MORGANA_SOLO_BOOKCHEST") || value.Contains("KEEPER_SOLO_BOOKCHEST") || value.Contains("HERETIC_SOLO_BOOKCHEST") || value.Contains("UNDEAD_SOLO_BOOKCHEST")) - { + if (value.Contains("MORGANA_SOLO_CHEST") || value.Contains("KEEPER_SOLO_CHEST") || value.Contains("HERETIC_SOLO_CHEST") || + value.Contains("UNDEAD_SOLO_CHEST") + || value.Contains("MORGANA_SOLO_BOOKCHEST") || value.Contains("KEEPER_SOLO_BOOKCHEST") || value.Contains("HERETIC_SOLO_BOOKCHEST") || + value.Contains("UNDEAD_SOLO_BOOKCHEST")) return DungeonMode.Solo; - } - if (value.Contains("MORGANA_CHEST") || value.Contains("KEEPER_CHEST") || value.Contains("HERETIC_CHEST") || value.Contains("UNDEAD_CHEST") - || value.Contains("MORGANA_BOOKCHEST") || value.Contains("KEEPER_BOOKCHEST") || value.Contains("HERETIC_BOOKCHEST") || value.Contains("UNDEAD_BOOKCHEST")) - { + if (value.Contains("MORGANA_CHEST") || value.Contains("KEEPER_CHEST") || value.Contains("HERETIC_CHEST") || value.Contains("UNDEAD_CHEST") + || value.Contains("MORGANA_BOOKCHEST") || value.Contains("KEEPER_BOOKCHEST") || value.Contains("HERETIC_BOOKCHEST") || + value.Contains("UNDEAD_BOOKCHEST")) return DungeonMode.Standard; - } - if (value.Contains("AVALON")) - { - return DungeonMode.Avalon; - } + if (value.Contains("AVALON")) return DungeonMode.Avalon; return DungeonMode.Unknown; } public static ChestRarity GetChestRarity(string value) { - if (value.Contains("BOOKCHEST_STANDARD") || value.Contains("CHEST_STANDARD") || (value.Contains("AVALON") && value.Contains("STANDARD"))) - { + if (value.Contains("BOOKCHEST_STANDARD") || value.Contains("CHEST_STANDARD") || value.Contains("AVALON") && value.Contains("STANDARD")) return ChestRarity.Standard; - } - - if (value.Contains("BOOKCHEST_UNCOMMON") || value.Contains("CHEST_UNCOMMON") || value.Contains("CHEST_BOSS_UNCOMMON") || (value.Contains("AVALON") && value.Contains("UNCOMMON"))) - { - return ChestRarity.Uncommon; - } - if (value.Contains("BOOKCHEST_RARE") || value.Contains("CHEST_RARE") || value.Contains("CHEST_BOSS_RARE") || (value.Contains("AVALON") && value.Contains("RARE"))) - { - return ChestRarity.Rare; - } + if (value.Contains("BOOKCHEST_UNCOMMON") || value.Contains("CHEST_UNCOMMON") || value.Contains("CHEST_BOSS_UNCOMMON") || + value.Contains("AVALON") && value.Contains("UNCOMMON")) return ChestRarity.Uncommon; - if (value.Contains("BOOKCHEST_LEGENDARY") || value.Contains("CHEST_LEGENDARY") || value.Contains("CHEST_BOSS_LEGENDARY") || (value.Contains("AVALON") && value.Contains("LEGENDARY"))) - { - return ChestRarity.Legendary; - } + if (value.Contains("BOOKCHEST_RARE") || value.Contains("CHEST_RARE") || value.Contains("CHEST_BOSS_RARE") || + value.Contains("AVALON") && value.Contains("RARE")) return ChestRarity.Rare; + + if (value.Contains("BOOKCHEST_LEGENDARY") || value.Contains("CHEST_LEGENDARY") || value.Contains("CHEST_BOSS_LEGENDARY") || + value.Contains("AVALON") && value.Contains("LEGENDARY")) return ChestRarity.Legendary; return ChestRarity.Unknown; } - public static bool IsBossChest(string value) => value.Contains("BOSS"); + public static bool IsBossChest(string value) + { + return value.Contains("BOSS"); + } public static Faction GetFaction(string value) { - if (value.Contains("KEEPER")) - { - return Faction.Keeper; - } + if (value.Contains("KEEPER")) return Faction.Keeper; - if (value.Contains("HERETIC")) - { - return Faction.Heretic; - } + if (value.Contains("HERETIC")) return Faction.Heretic; - if (value.Contains("MORGANA")) - { - return Faction.Morgana; - } + if (value.Contains("MORGANA")) return Faction.Morgana; - if (value.Contains("UNDEAD")) - { - return Faction.Undead; - } + if (value.Contains("UNDEAD")) return Faction.Undead; - if (value.Contains("AVALON")) - { - return Faction.Avalon; - } + if (value.Contains("AVALON")) return Faction.Avalon; return Faction.Unknown; } @@ -130,10 +100,7 @@ public static async Task GetDataListFromJsonAsync() if (fileDateTime.AddDays(Settings.Default.UpdateWorldDataByDays) < DateTime.Now) { - if (await GetLootChestListFromWebAsync(url)) - { - LootChests = GetLootChestDataFromLocal(); - } + if (await GetLootChestListFromWebAsync(url)) LootChests = GetLootChestDataFromLocal(); return LootChests != null && !LootChests.IsNullOrEmpty(); } @@ -141,10 +108,7 @@ public static async Task GetDataListFromJsonAsync() return LootChests != null && !LootChests.IsNullOrEmpty(); } - if (await GetLootChestListFromWebAsync(url)) - { - LootChests = GetLootChestDataFromLocal(); - } + if (await GetLootChestListFromWebAsync(url)) LootChests = GetLootChestDataFromLocal(); return LootChests != null && !LootChests.IsNullOrEmpty(); } @@ -154,7 +118,9 @@ private static IEnumerable GetLootChestDataFromLocal() { try { - var localItemString = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameFiles", Settings.Default.LootChestDataFileName), Encoding.UTF8); + var localItemString = + File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameFiles", Settings.Default.LootChestDataFileName), + Encoding.UTF8); return JsonConvert.DeserializeObject(localItemString).LootChests.LootChest; } catch @@ -175,7 +141,9 @@ private static async Task GetLootChestListFromWebAsync(string url) using (var content = response.Content) { var fileString = await content.ReadAsStringAsync(); - File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameFiles", Settings.Default.LootChestDataFileName), fileString, Encoding.UTF8); + File.WriteAllText( + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameFiles", Settings.Default.LootChestDataFileName), fileString, + Encoding.UTF8); return true; } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/WorldData.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/WorldData.cs index b8819a0bc..fd7e5aec6 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/WorldData.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/GameData/WorldData.cs @@ -1,9 +1,3 @@ -using log4net; -using Newtonsoft.Json; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Enumerations; -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Properties; using System; using System.Collections.ObjectModel; using System.IO; @@ -12,10 +6,15 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; +using log4net; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Enumerations; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.GameData { - public static class WorldData { public static ObservableCollection MapData; @@ -24,12 +23,9 @@ public static class WorldData public static string GetUniqueNameOrDefault(string index) { var name = MapData?.FirstOrDefault(x => x.Index == index)?.UniqueName ?? index; - var splitName = name?.Split(new[] { "@" }, StringSplitOptions.None); + var splitName = name?.Split(new[] {"@"}, StringSplitOptions.None); - if (splitName != null && splitName.Length > 0 && name.ToLower().Contains('@')) - { - return GetMapNameByMapType(GetMapType(splitName[1])); - } + if (splitName != null && splitName.Length > 0 && name.ToLower().Contains('@')) return GetMapNameByMapType(GetMapType(splitName[1])); return name; } @@ -38,7 +34,7 @@ public static string GetUniqueNameOrDefault(string index) { try { - var splitName = index.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries); + var splitName = index.Split(new[] {"@"}, StringSplitOptions.RemoveEmptyEntries); if (splitName.Length > 1 && index.ToLower().Contains('@')) { @@ -79,30 +75,15 @@ private static string GetMapNameByMapType(MapType mapType) public static MapType GetMapType(string index) { - if (index.ToUpper().Contains("HELLCLUSTER")) - { - return MapType.HellGate; - } + if (index.ToUpper().Contains("HELLCLUSTER")) return MapType.HellGate; - if (index.ToUpper().Contains("RANDOMDUNGEON")) - { - return MapType.RandomDungeon; - } + if (index.ToUpper().Contains("RANDOMDUNGEON")) return MapType.RandomDungeon; - if (index.ToUpper().Contains("CORRUPTEDDUNGEON")) - { - return MapType.CorruptedDungeon; - } + if (index.ToUpper().Contains("CORRUPTEDDUNGEON")) return MapType.CorruptedDungeon; - if (index.ToUpper().Contains("ISLAND")) - { - return MapType.Island; - } + if (index.ToUpper().Contains("ISLAND")) return MapType.Island; - if (index.ToUpper().Contains("HIDEOUT")) - { - return MapType.Hideout; - } + if (index.ToUpper().Contains("HIDEOUT")) return MapType.Hideout; return MapType.Unknown; } @@ -124,34 +105,29 @@ public static async Task GetDataListFromJsonAsync() if (fileDateTime.AddDays(Settings.Default.UpdateWorldDataByDays) < DateTime.Now) { - if (await GetWorldListFromWebAsync(url)) - { - MapData = GetWorldDataFromLocal(); - } - return (MapData?.Count > 0); + if (await GetWorldListFromWebAsync(url)) MapData = GetWorldDataFromLocal(); + return MapData?.Count > 0; } MapData = GetWorldDataFromLocal(); - return (MapData?.Count > 0); + return MapData?.Count > 0; } - if (await GetWorldListFromWebAsync(url)) - { - MapData = GetWorldDataFromLocal(); - } - return (MapData?.Count > 0); + if (await GetWorldListFromWebAsync(url)) MapData = GetWorldDataFromLocal(); + return MapData?.Count > 0; } - public static ClusterInfo GetClusterInfoByIndex(string clusterIndex, string mainClusterIndex, MapType mapType = MapType.Unknown, Guid? guid = null) + public static ClusterInfo GetClusterInfoByIndex(string clusterIndex, string mainClusterIndex, MapType mapType = MapType.Unknown, + Guid? guid = null) { - return MapData.FirstOrDefault(x => x.Index == clusterIndex) ?? new ClusterInfo() + return MapData.FirstOrDefault(x => x.Index == clusterIndex) ?? new ClusterInfo { - Index = clusterIndex, - MainClusterIndex = mainClusterIndex, - UniqueName = GetUniqueNameOrDefault(clusterIndex), + Index = clusterIndex, + MainClusterIndex = mainClusterIndex, + UniqueName = GetUniqueNameOrDefault(clusterIndex), MapType = mapType, Type = GetTypeByIndex(clusterIndex) ?? GetTypeByIndex(mainClusterIndex) ?? string.Empty, - Guid = guid, + Guid = guid }; } @@ -162,26 +138,13 @@ public static string GetTypeByIndex(string index) public static ClusterType GetClusterType(string type) { + if (type.ToUpper().Contains("SAFEAREA")) return ClusterType.SafeArea; - if (type.ToUpper().Contains("SAFEAREA")) - { - return ClusterType.SafeArea; - } - - if (type.ToUpper().Contains("YELLOW")) - { - return ClusterType.Yellow; - } + if (type.ToUpper().Contains("YELLOW")) return ClusterType.Yellow; - if (type.ToUpper().Contains("RED")) - { - return ClusterType.Red; - } + if (type.ToUpper().Contains("RED")) return ClusterType.Red; - if (type.ToUpper().Contains("BLACK")) - { - return ClusterType.Black; - } + if (type.ToUpper().Contains("BLACK")) return ClusterType.Black; return ClusterType.Unknown; } @@ -192,10 +155,12 @@ private static ObservableCollection GetWorldDataFromLocal() { try { - var localItemString = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"GameFiles",Settings.Default.WorldDataFileName), Encoding.UTF8); + var localItemString = + File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameFiles", Settings.Default.WorldDataFileName), + Encoding.UTF8); return ConvertItemJsonObjectToMapData(JsonConvert.DeserializeObject>(localItemString)); } - catch(Exception e) + catch (Exception e) { Log.Error(nameof(GetWorldDataFromLocal), e); return new ObservableCollection(); @@ -204,7 +169,7 @@ private static ObservableCollection GetWorldDataFromLocal() private static ObservableCollection ConvertItemJsonObjectToMapData(ObservableCollection worldJsonObject) { - var result = worldJsonObject.Select(item => new ClusterInfo() + var result = worldJsonObject.Select(item => new ClusterInfo { Index = item.Index, UniqueName = item.UniqueName, @@ -226,7 +191,8 @@ private static async Task GetWorldListFromWebAsync(string url) using (var content = response.Content) { var fileString = await content.ReadAsStringAsync(); - File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameFiles", Settings.Default.WorldDataFileName), fileString, Encoding.UTF8); + File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameFiles", Settings.Default.WorldDataFileName), + fileString, Encoding.UTF8); return true; } } @@ -242,7 +208,8 @@ private static async Task GetWorldListFromWebAsync(string url) #endregion } - public enum MapType { + public enum MapType + { RandomDungeon, HellGate, CorruptedDungeon, diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Languages/en-US.xml b/StatisticsAnalysisTool/StatisticsAnalysisTool/Languages/en-US.xml index c2c374a9e..af8a593f3 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Languages/en-US.xml +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Languages/en-US.xml @@ -197,7 +197,7 @@ Woodgatherer Helmet Woodgatherer Shoes Woodgatherer Backpack - + Bridgewatch Caerleon Fort Sterling @@ -350,7 +350,7 @@ Dungeon run Time Damage Meter Reset Damage Meter - + Standard Uncommon Rare diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ClusterInfo.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ClusterInfo.cs index 646c5a76b..2927b4e23 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ClusterInfo.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ClusterInfo.cs @@ -1,6 +1,6 @@ -using StatisticsAnalysisTool.Enumerations; +using System; +using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.GameData; -using System; namespace StatisticsAnalysisTool.Models { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/DungeonStats.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/DungeonStats.cs index 4752dd478..727edb5db 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/DungeonStats.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/DungeonStats.cs @@ -1,52 +1,62 @@ -using StatisticsAnalysisTool.Annotations; -using System.ComponentModel; +using System.ComponentModel; using System.Runtime.CompilerServices; +using StatisticsAnalysisTool.Annotations; namespace StatisticsAnalysisTool.Models { public class DungeonStats : INotifyPropertyChanged { private int _enteredDungeon; + private int _openedLegendaryChests; + private int _openedRareChests; private int _openedStandardChests; private int _openedUncommonChests; - private int _openedRareChests; - private int _openedLegendaryChests; - public int EnteredDungeon { + public int EnteredDungeon + { get => _enteredDungeon; - set { + set + { _enteredDungeon = value; OnPropertyChanged(); } } - public int OpenedStandardChests { + public int OpenedStandardChests + { get => _openedStandardChests; - set { + set + { _openedStandardChests = value; OnPropertyChanged(); } } - public int OpenedUncommonChests { + public int OpenedUncommonChests + { get => _openedUncommonChests; - set { + set + { _openedUncommonChests = value; OnPropertyChanged(); } } - public int OpenedRareChests { + public int OpenedRareChests + { get => _openedRareChests; - set { + set + { _openedRareChests = value; OnPropertyChanged(); } } - public int OpenedLegendaryChests { + public int OpenedLegendaryChests + { get => _openedLegendaryChests; - set { + set + { _openedLegendaryChests = value; OnPropertyChanged(); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GameInfoPlayers.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GameInfoPlayers.cs index b9f953054..8aaa18306 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GameInfoPlayers.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GameInfoPlayers.cs @@ -1,8 +1,8 @@ -namespace StatisticsAnalysisTool.Models -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; +namespace StatisticsAnalysisTool.Models +{ public class GameInfoPlayersResponse { public double AverageItemPower { get; set; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GoldModels.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GoldModels.cs index 4a47f9f02..22f366e55 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GoldModels.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/GoldModels.cs @@ -1,12 +1,11 @@ -namespace StatisticsAnalysisTool.Models -{ - using Newtonsoft.Json; - using System; +using System; +using Newtonsoft.Json; +namespace StatisticsAnalysisTool.Models +{ public class GoldResponseModel { - [JsonProperty(PropertyName = "price")] - public int Price { get; set; } + [JsonProperty(PropertyName = "price")] public int Price { get; set; } [JsonProperty(PropertyName = "timestamp")] public DateTime Timestamp { get; set; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Guild.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Guild.cs index 21e18e9f8..b0ec6ff14 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Guild.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Guild.cs @@ -1,8 +1,8 @@ -namespace StatisticsAnalysisTool.Models -{ - using Newtonsoft.Json; - using System; +using System; +using Newtonsoft.Json; +namespace StatisticsAnalysisTool.Models +{ public class GameInfoGuildsResponse { public string Id { get; set; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Item.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Item.cs index 28817d921..05d28f275 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Item.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/Item.cs @@ -1,12 +1,13 @@ -using FontAwesome5; -using StatisticsAnalysisTool.Common; -using System.Windows.Media; +using System.Windows.Media; using System.Windows.Media.Imaging; +using FontAwesome5; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Models { public class Item { + private BitmapImage _icon; public string LocalizationNameVariable { get; set; } public string LocalizationDescriptionVariable { get; set; } public LocalizedNames LocalizedNames { get; set; } @@ -17,21 +18,10 @@ public class Item ? $"{ItemController.LocalizedName(LocalizedNames, null, UniqueName)}{GetUniqueNameIfDebug()}" : $"{ItemController.LocalizedName(LocalizedNames, null, UniqueName)}\n{ItemController.LocalizedName(LocalizedNames, "EN-US", string.Empty)}{GetUniqueNameIfDebug()}"; - private string GetUniqueNameIfDebug() - { -#if DEBUG - return $"\n{UniqueName}"; -#else - return string.Empty; -#endif - } - public string LocalizedName => ItemController.LocalizedName(LocalizedNames, null, UniqueName); public int Level => ItemController.GetItemLevel(UniqueName); public int Tier => ItemController.GetItemTier(this); - - private BitmapImage _icon; public BitmapImage Icon => _icon ?? (_icon = ImageController.GetItemImage(UniqueName)); public BitmapImage ExistFullItemInformationLocal => ItemController.ExistFullItemInformationLocal(UniqueName); @@ -39,7 +29,16 @@ private string GetUniqueNameIfDebug() public int AlertModeMinSellPriceIsUndercutPrice { get; set; } public bool IsAlertActive { get; set; } - public EFontAwesomeIcon AlertToggle => (IsAlertActive) ? EFontAwesomeIcon.Solid_ToggleOn : EFontAwesomeIcon.Solid_ToggleOff; - public Brush AlertToggleColor => (IsAlertActive) ? ItemController.ToggleOnColor : ItemController.ToggleOffColor; + public EFontAwesomeIcon AlertToggle => IsAlertActive ? EFontAwesomeIcon.Solid_ToggleOn : EFontAwesomeIcon.Solid_ToggleOff; + public Brush AlertToggleColor => IsAlertActive ? ItemController.ToggleOnColor : ItemController.ToggleOffColor; + + private string GetUniqueNameIfDebug() + { +#if DEBUG + return $"\n{UniqueName}"; +#else + return string.Empty; +#endif + } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemCategoryTree.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemCategoryTree.cs index 5be0980e8..b957ac943 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemCategoryTree.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemCategoryTree.cs @@ -4,209 +4,148 @@ namespace StatisticsAnalysisTool.Models { public class ItemCategoryTree { - [JsonProperty("head")] - public Head Head { get; set; } + [JsonProperty("head")] public Head Head { get; set; } - [JsonProperty("mainhand")] - public Mainhand Mainhand { get; set; } + [JsonProperty("mainhand")] public Mainhand Mainhand { get; set; } - [JsonProperty("potion")] - public Potion Potion { get; set; } + [JsonProperty("potion")] public Potion Potion { get; set; } - [JsonProperty("armor")] - public Armor Armor { get; set; } + [JsonProperty("armor")] public Armor Armor { get; set; } - [JsonProperty("bag")] - public Bag Bag { get; set; } + [JsonProperty("bag")] public Bag Bag { get; set; } - [JsonProperty("mount")] - public Mount Mount { get; set; } + [JsonProperty("mount")] public Mount Mount { get; set; } - [JsonProperty("shoes")] - public Shoes Shoes { get; set; } + [JsonProperty("shoes")] public Shoes Shoes { get; set; } - [JsonProperty("cape")] - public Cape Cape { get; set; } + [JsonProperty("cape")] public Cape Cape { get; set; } - [JsonProperty("food")] - public Food Food { get; set; } + [JsonProperty("food")] public Food Food { get; set; } - [JsonProperty("offhand")] - public Offhand Offhand { get; set; } + [JsonProperty("offhand")] public Offhand Offhand { get; set; } } public class Head { - [JsonProperty("fibergatherer_helmet")] - public string FibergathererHelmet { get; set; } + [JsonProperty("fibergatherer_helmet")] public string FibergathererHelmet { get; set; } - [JsonProperty("woodgatherer_helmet")] - public string WoodgathererHelmet { get; set; } + [JsonProperty("woodgatherer_helmet")] public string WoodgathererHelmet { get; set; } - [JsonProperty("leather_helmet")] - public string LeatherHelmet { get; set; } + [JsonProperty("leather_helmet")] public string LeatherHelmet { get; set; } - [JsonProperty("plate_helmet")] - public string PlateHelmet { get; set; } + [JsonProperty("plate_helmet")] public string PlateHelmet { get; set; } - [JsonProperty("hidegatherer_helmet")] - public string HidegathererHelmet { get; set; } + [JsonProperty("hidegatherer_helmet")] public string HidegathererHelmet { get; set; } - [JsonProperty("rockgatherer_helmet")] - public string RockgathererHelmet { get; set; } + [JsonProperty("rockgatherer_helmet")] public string RockgathererHelmet { get; set; } - [JsonProperty("cloth_helmet")] - public string ClothHelmet { get; set; } + [JsonProperty("cloth_helmet")] public string ClothHelmet { get; set; } - [JsonProperty("oregatherer_helmet")] - public string OregathererHelmet { get; set; } + [JsonProperty("oregatherer_helmet")] public string OregathererHelmet { get; set; } - [JsonProperty("fishgatherer_helmet")] - public string FishgathererHelmet { get; set; } + [JsonProperty("fishgatherer_helmet")] public string FishgathererHelmet { get; set; } } public class Mainhand { - [JsonProperty("firestaff")] - public string Firestaff { get; set; } + [JsonProperty("firestaff")] public string Firestaff { get; set; } - [JsonProperty("dagger")] - public string Dagger { get; set; } + [JsonProperty("dagger")] public string Dagger { get; set; } - [JsonProperty("hammer")] - public string Hammer { get; set; } + [JsonProperty("hammer")] public string Hammer { get; set; } - [JsonProperty("crossbow")] - public string Crossbow { get; set; } + [JsonProperty("crossbow")] public string Crossbow { get; set; } - [JsonProperty("mace")] - public string Mace { get; set; } + [JsonProperty("mace")] public string Mace { get; set; } - [JsonProperty("cursestaff")] - public string Cursestaff { get; set; } + [JsonProperty("cursestaff")] public string Cursestaff { get; set; } - [JsonProperty("bow")] - public string Bow { get; set; } + [JsonProperty("bow")] public string Bow { get; set; } - [JsonProperty("arcanestaff")] - public string Arcanestaff { get; set; } + [JsonProperty("arcanestaff")] public string Arcanestaff { get; set; } - [JsonProperty("axe")] - public string Axe { get; set; } + [JsonProperty("axe")] public string Axe { get; set; } - [JsonProperty("sword")] - public string Sword { get; set; } + [JsonProperty("sword")] public string Sword { get; set; } - [JsonProperty("spear")] - public string Spear { get; set; } + [JsonProperty("spear")] public string Spear { get; set; } - [JsonProperty("froststaff")] - public string Froststaff { get; set; } + [JsonProperty("froststaff")] public string Froststaff { get; set; } - [JsonProperty("naturestaff")] - public string Naturestaff { get; set; } + [JsonProperty("naturestaff")] public string Naturestaff { get; set; } - [JsonProperty("quarterstaff")] - public string Quarterstaff { get; set; } + [JsonProperty("quarterstaff")] public string Quarterstaff { get; set; } - [JsonProperty("holystaff")] - public string Holystaff { get; set; } + [JsonProperty("holystaff")] public string Holystaff { get; set; } } public class Potion { - [JsonProperty("potion")] - public string PotionValue { get; set; } + [JsonProperty("potion")] public string PotionValue { get; set; } - [JsonProperty("fishingbait")] - public string Fishingbait { get; set; } + [JsonProperty("fishingbait")] public string Fishingbait { get; set; } - [JsonProperty("vanity")] - public string Vanity { get; set; } + [JsonProperty("vanity")] public string Vanity { get; set; } } public class Armor { - [JsonProperty("rockgatherer_armor")] - public string RockgathererArmor { get; set; } + [JsonProperty("rockgatherer_armor")] public string RockgathererArmor { get; set; } - [JsonProperty("oregatherer_armor")] - public string OregathererArmor { get; set; } + [JsonProperty("oregatherer_armor")] public string OregathererArmor { get; set; } - [JsonProperty("leather_armor")] - public string LeatherArmor { get; set; } + [JsonProperty("leather_armor")] public string LeatherArmor { get; set; } - [JsonProperty("fibergatherer_armor")] - public string FibergathererArmor { get; set; } + [JsonProperty("fibergatherer_armor")] public string FibergathererArmor { get; set; } - [JsonProperty("hidegatherer_armor")] - public string HidegathererArmor { get; set; } + [JsonProperty("hidegatherer_armor")] public string HidegathererArmor { get; set; } - [JsonProperty("plate_armor")] - public string PlateArmor { get; set; } + [JsonProperty("plate_armor")] public string PlateArmor { get; set; } - [JsonProperty("cloth_armor")] - public string ClothArmor { get; set; } + [JsonProperty("cloth_armor")] public string ClothArmor { get; set; } - [JsonProperty("fishgatherer_armor")] - public string FishgathererArmor { get; set; } + [JsonProperty("fishgatherer_armor")] public string FishgathererArmor { get; set; } - [JsonProperty("woodgatherer_armor")] - public string WoodgathererArmor { get; set; } + [JsonProperty("woodgatherer_armor")] public string WoodgathererArmor { get; set; } } public class Bag { - [JsonProperty("bag")] - public string BagValue { get; set; } + [JsonProperty("bag")] public string BagValue { get; set; } } public class Mount { - [JsonProperty("rare_mount")] - public string RareMount { get; set; } + [JsonProperty("rare_mount")] public string RareMount { get; set; } - [JsonProperty("ridinghorse")] - public string Ridinghorse { get; set; } + [JsonProperty("ridinghorse")] public string Ridinghorse { get; set; } - [JsonProperty("armoredhorse")] - public string Armoredhorse { get; set; } + [JsonProperty("armoredhorse")] public string Armoredhorse { get; set; } - [JsonProperty("ox")] - public string Ox { get; set; } + [JsonProperty("ox")] public string Ox { get; set; } } public class Shoes { - [JsonProperty("unique_shoes")] - public string UniqueShoes { get; set; } + [JsonProperty("unique_shoes")] public string UniqueShoes { get; set; } - [JsonProperty("fibergatherer_shoes")] - public string FibergathererShoes { get; set; } + [JsonProperty("fibergatherer_shoes")] public string FibergathererShoes { get; set; } - [JsonProperty("rockgatherer_shoes")] - public string RockgathererShoes { get; set; } + [JsonProperty("rockgatherer_shoes")] public string RockgathererShoes { get; set; } - [JsonProperty("hidegatherer_shoes")] - public string HidegathererShoes { get; set; } + [JsonProperty("hidegatherer_shoes")] public string HidegathererShoes { get; set; } - [JsonProperty("plate_shoes")] - public string PlateShoes { get; set; } + [JsonProperty("plate_shoes")] public string PlateShoes { get; set; } - [JsonProperty("cloth_shoes")] - public string ClothShoes { get; set; } + [JsonProperty("cloth_shoes")] public string ClothShoes { get; set; } - [JsonProperty("fishgatherer_shoes")] - public string FishgathererShoes { get; set; } + [JsonProperty("fishgatherer_shoes")] public string FishgathererShoes { get; set; } - [JsonProperty("woodgatherer_shoes")] - public string WoodgathererShoes { get; set; } + [JsonProperty("woodgatherer_shoes")] public string WoodgathererShoes { get; set; } - [JsonProperty("leather_shoes")] - public string LeatherShoes { get; set; } + [JsonProperty("leather_shoes")] public string LeatherShoes { get; set; } - [JsonProperty("oregatherer_shoes")] - public string OregathererShoes { get; set; } + [JsonProperty("oregatherer_shoes")] public string OregathererShoes { get; set; } } public class Cape @@ -214,8 +153,7 @@ public class Cape [JsonProperty("rockgatherer_backpack")] public string RockgathererBackpack { get; set; } - [JsonProperty("oregatherer_backpack")] - public string OregathererBackpack { get; set; } + [JsonProperty("oregatherer_backpack")] public string OregathererBackpack { get; set; } [JsonProperty("fishgatherer_backpack")] public string FishgathererBackpack { get; set; } @@ -226,8 +164,7 @@ public class Cape [JsonProperty("hidegatherer_backpack")] public string HidegathererBackpack { get; set; } - [JsonProperty("cape")] - public string CapeValue { get; set; } + [JsonProperty("cape")] public string CapeValue { get; set; } [JsonProperty("fibergatherer_backpack")] public string FibergathererBackpack { get; set; } @@ -235,34 +172,25 @@ public class Cape public class Food { - [JsonProperty("fish")] - public string Fish { get; set; } + [JsonProperty("fish")] public string Fish { get; set; } - [JsonProperty("cooked")] - public string Cooked { get; set; } + [JsonProperty("cooked")] public string Cooked { get; set; } - [JsonProperty("vanity")] - public string Vanity { get; set; } + [JsonProperty("vanity")] public string Vanity { get; set; } } public class Offhand { - [JsonProperty("shield")] - public string Shield { get; set; } + [JsonProperty("shield")] public string Shield { get; set; } - [JsonProperty("horn")] - public string Horn { get; set; } + [JsonProperty("horn")] public string Horn { get; set; } - [JsonProperty("book")] - public string Book { get; set; } + [JsonProperty("book")] public string Book { get; set; } - [JsonProperty("totem")] - public string Totem { get; set; } + [JsonProperty("totem")] public string Totem { get; set; } - [JsonProperty("torch")] - public string Torch { get; set; } + [JsonProperty("torch")] public string Torch { get; set; } - [JsonProperty("orb")] - public string Orb { get; set; } + [JsonProperty("orb")] public string Orb { get; set; } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemData.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemData.cs index 53a0316b6..ec4e7af27 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemData.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemData.cs @@ -1,6 +1,6 @@ -using StatisticsAnalysisTool.Common; -using System.Collections.Generic; +using System.Collections.Generic; using System.Text; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Models { @@ -23,8 +23,10 @@ public class ItemData //public List LocalizedNames { get; set; } public List LocalizedNames { get; set; } - public string LocalizedName { - get { + public string LocalizedName + { + get + { var name = UniqueName; if (LocalizedNames.Exists(a => a.Key == LanguageController.CurrentCultureInfo.TextInfo.CultureName.ToUpper())) diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemInformationModels.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemInformationModels.cs index b3ddf3b55..7a6bb71b5 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemInformationModels.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemInformationModels.cs @@ -1,8 +1,9 @@ -using Newtonsoft.Json; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Net; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Common; +using Formatting = StatisticsAnalysisTool.Common.Formatting; namespace StatisticsAnalysisTool.Models { @@ -32,11 +33,9 @@ public class ItemInformation [JsonProperty(PropertyName = "showinmarketplace")] public bool ShowInMarketplace { get; set; } - [JsonProperty(PropertyName = "level")] - public int Level { get; set; } + [JsonProperty(PropertyName = "level")] public int Level { get; set; } - [JsonProperty(PropertyName = "tier")] - public int Tier { get; set; } + [JsonProperty(PropertyName = "tier")] public int Tier { get; set; } [JsonProperty(PropertyName = "enchantmentLevel")] public int EnchantmentLevel { get; set; } @@ -69,14 +68,11 @@ public class ItemInformation [JsonProperty("physicalAttackDamageBonus")] public double PhysicalAttackDamageBonus { get; set; } - [JsonProperty("skinCount")] - public object SkinCount { get; set; } + [JsonProperty("skinCount")] public object SkinCount { get; set; } - [JsonProperty("physicalArmor")] - public int PhysicalArmor { get; set; } + [JsonProperty("physicalArmor")] public int PhysicalArmor { get; set; } - [JsonProperty("magicResistance")] - public int MagicResistance { get; set; } + [JsonProperty("magicResistance")] public int MagicResistance { get; set; } [JsonProperty("magicAttackDamageBonus")] public object MagicAttackDamageBonus { get; set; } @@ -84,8 +80,7 @@ public class ItemInformation [JsonProperty("itemPowerProgressionType")] public string ItemPowerProgressionType { get; set; } - [JsonProperty("craftingRequirements")] - public CraftingRequirements CraftingRequirements { get; set; } + [JsonProperty("craftingRequirements")] public CraftingRequirements CraftingRequirements { get; set; } [JsonProperty(PropertyName = "unlockedToEquip")] public bool? UnlockedToEquip { get; set; } @@ -162,8 +157,7 @@ public class ItemInformation [JsonProperty(PropertyName = "lastUpdate")] public DateTime LastUpdate { get; set; } - [JsonIgnore] - public string LastFullItemInformationUpdate => Common.Formatting.CurrentDateTimeFormat(LastUpdate) ?? string.Empty; + [JsonIgnore] public string LastFullItemInformationUpdate => Formatting.CurrentDateTimeFormat(LastUpdate) ?? string.Empty; public CategoryObject CategoryObject => CategoryController.GetCategory(CategoryId); public HttpStatusCode HttpStatus { get; set; } @@ -174,14 +168,12 @@ public class CraftResourceList [JsonProperty(PropertyName = "uniqueName")] public string UniqueName { get; set; } - [JsonProperty(PropertyName = "count")] - public int Count { get; set; } + [JsonProperty(PropertyName = "count")] public int Count { get; set; } } public class CraftingRequirements { - [JsonProperty(PropertyName = "time")] - public double Time { get; set; } + [JsonProperty(PropertyName = "time")] public double Time { get; set; } [JsonProperty(PropertyName = "silver")] public int Silver { get; set; } @@ -216,62 +208,45 @@ public class Enchantments public class LocalizedNames { - [JsonProperty(PropertyName = "EN-US")] - public string EnUs { get; set; } + [JsonProperty(PropertyName = "EN-US")] public string EnUs { get; set; } - [JsonProperty(PropertyName = "DE-DE")] - public string DeDe { get; set; } + [JsonProperty(PropertyName = "DE-DE")] public string DeDe { get; set; } - [JsonProperty(PropertyName = "KO-KR")] - public string KoKr { get; set; } + [JsonProperty(PropertyName = "KO-KR")] public string KoKr { get; set; } - [JsonProperty(PropertyName = "RU-RU")] - public string RuRu { get; set; } + [JsonProperty(PropertyName = "RU-RU")] public string RuRu { get; set; } - [JsonProperty(PropertyName = "PL-PL")] - public string PlPl { get; set; } + [JsonProperty(PropertyName = "PL-PL")] public string PlPl { get; set; } - [JsonProperty(PropertyName = "PT-BR")] - public string PtBr { get; set; } + [JsonProperty(PropertyName = "PT-BR")] public string PtBr { get; set; } - [JsonProperty(PropertyName = "FR-FR")] - public string FrFr { get; set; } + [JsonProperty(PropertyName = "FR-FR")] public string FrFr { get; set; } - [JsonProperty(PropertyName = "ES-ES")] - public string EsEs { get; set; } + [JsonProperty(PropertyName = "ES-ES")] public string EsEs { get; set; } - [JsonProperty(PropertyName = "ZH-CN")] - public string ZhCn { get; set; } + [JsonProperty(PropertyName = "ZH-CN")] public string ZhCn { get; set; } } public class LocalizedDescriptions { - [JsonProperty(PropertyName = "EN-US")] - public string EnUs { get; set; } + [JsonProperty(PropertyName = "EN-US")] public string EnUs { get; set; } - [JsonProperty(PropertyName = "DE-DE")] - public string DeDe { get; set; } + [JsonProperty(PropertyName = "DE-DE")] public string DeDe { get; set; } - [JsonProperty(PropertyName = "KO-KR")] - public string KoKr { get; set; } + [JsonProperty(PropertyName = "KO-KR")] public string KoKr { get; set; } [JsonProperty(PropertyName = "RU-RUS")] public string RuRu { get; set; } - [JsonProperty(PropertyName = "PL-PL")] - public string PlPl { get; set; } + [JsonProperty(PropertyName = "PL-PL")] public string PlPl { get; set; } - [JsonProperty(PropertyName = "PT-BR")] - public string PtBr { get; set; } + [JsonProperty(PropertyName = "PT-BR")] public string PtBr { get; set; } - [JsonProperty(PropertyName = "FR-FR")] - public string FrFr { get; set; } + [JsonProperty(PropertyName = "FR-FR")] public string FrFr { get; set; } - [JsonProperty(PropertyName = "ES-ES")] - public string EsEs { get; set; } + [JsonProperty(PropertyName = "ES-ES")] public string EsEs { get; set; } - [JsonProperty(PropertyName = "ZH-CN")] - public string ZhCn { get; set; } + [JsonProperty(PropertyName = "ZH-CN")] public string ZhCn { get; set; } } public class BuffOverTime @@ -279,14 +254,11 @@ public class BuffOverTime [JsonProperty(PropertyName = "target")] public string Target { get; set; } - [JsonProperty(PropertyName = "type")] - public string Type { get; set; } + [JsonProperty(PropertyName = "type")] public string Type { get; set; } - [JsonProperty(PropertyName = "time")] - public double Time { get; set; } + [JsonProperty(PropertyName = "time")] public double Time { get; set; } - [JsonProperty(PropertyName = "value")] - public double Value { get; set; } + [JsonProperty(PropertyName = "value")] public double Value { get; set; } [JsonProperty(PropertyName = "effectAreaRadius")] public object EffectAreaRadius { get; set; } @@ -381,11 +353,9 @@ public class Channeling public class Buff { - [JsonProperty(PropertyName = "type")] - public string Type { get; set; } + [JsonProperty(PropertyName = "type")] public string Type { get; set; } - [JsonProperty(PropertyName = "value")] - public double Value { get; set; } + [JsonProperty(PropertyName = "value")] public double Value { get; set; } } //public class PassiveSlots diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemJsonObject.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemJsonObject.cs index 5877b571f..7b9d3146c 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemJsonObject.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/ItemJsonObject.cs @@ -10,13 +10,10 @@ public class ItemJsonObject [JsonProperty("LocalizationDescriptionVariable")] public string LocalizationDescriptionVariable { get; set; } - [JsonProperty("LocalizedNames")] - public LocalizedNames LocalizedNames { get; set; } + [JsonProperty("LocalizedNames")] public LocalizedNames LocalizedNames { get; set; } - [JsonProperty("Index")] - public int Index { get; set; } + [JsonProperty("Index")] public int Index { get; set; } - [JsonProperty("UniqueName")] - public string UniqueName { get; set; } + [JsonProperty("UniqueName")] public string UniqueName { get; set; } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoriesResponse.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoriesResponse.cs index 517d1cdbd..7c14daff6 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoriesResponse.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoriesResponse.cs @@ -1,9 +1,9 @@ -namespace StatisticsAnalysisTool.Models -{ - using Annotations; - using Newtonsoft.Json; - using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Annotations; +namespace StatisticsAnalysisTool.Models +{ public class MarketHistoriesResponse { [JsonProperty(PropertyName = "location")] diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoryResponse.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoryResponse.cs index a3b2bf0d2..eb1b16559 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoryResponse.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketHistoryResponse.cs @@ -1,8 +1,8 @@ -namespace StatisticsAnalysisTool.Models -{ - using Newtonsoft.Json; - using System; +using System; +using Newtonsoft.Json; +namespace StatisticsAnalysisTool.Models +{ public class MarketHistoryResponse { [JsonProperty(PropertyName = "item_count")] diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketOrder.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketOrder.cs index 26c8c3baf..cddcdba14 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketOrder.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketOrder.cs @@ -1,8 +1,9 @@ -using Newtonsoft.Json; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Windows; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Common; +using Formatting = StatisticsAnalysisTool.Common.Formatting; namespace StatisticsAnalysisTool.Models { @@ -11,8 +12,7 @@ public class MarketResponse [JsonProperty(PropertyName = "item_id")] public string ItemTypeId { get; set; } - [JsonProperty(PropertyName = "city")] - public string City { get; set; } + [JsonProperty(PropertyName = "city")] public string City { get; set; } [JsonProperty(PropertyName = "quality")] public int QualityLevel { get; set; } @@ -48,7 +48,7 @@ public MarketResponseTotal(MarketResponse item) { ItemTypeId = item.ItemTypeId; City = Locations.GetName(item.City); - QualityLevel = (byte)item.QualityLevel; + QualityLevel = (byte) item.QualityLevel; SellPriceMin = item.SellPriceMin; SellPriceMax = item.SellPriceMax; BuyPriceMin = item.BuyPriceMin; @@ -105,22 +105,22 @@ public MarketCurrentPricesItem(MarketResponseTotal marketResponseTotal) public string SellPriceMinString => Utilities.UlongMarketPriceToString(SellPriceMin); public DateTime SellPriceMinDate { get; set; } public string SellPriceMinDateString => Utilities.MarketPriceDateToString(SellPriceMinDate); - public string SellPriceMinDateLastUpdateTime => Common.Formatting.DateTimeToLastUpdateTime(SellPriceMinDate); + public string SellPriceMinDateLastUpdateTime => Formatting.DateTimeToLastUpdateTime(SellPriceMinDate); public ulong SellPriceMax { get; set; } public string SellPriceMaxString => Utilities.UlongMarketPriceToString(SellPriceMax); public DateTime SellPriceMaxDate { get; set; } public string SellPriceMaxDateString => Utilities.MarketPriceDateToString(SellPriceMaxDate); - public string SellPriceMaxDateLastUpdateTime => Common.Formatting.DateTimeToLastUpdateTime(SellPriceMaxDate); + public string SellPriceMaxDateLastUpdateTime => Formatting.DateTimeToLastUpdateTime(SellPriceMaxDate); public ulong BuyPriceMin { get; set; } public string BuyPriceMinString => Utilities.UlongMarketPriceToString(BuyPriceMin); public DateTime BuyPriceMinDate { get; set; } public string BuyPriceMinDateString => Utilities.MarketPriceDateToString(BuyPriceMinDate); - public string BuyPriceMinDateLastUpdateTime => Common.Formatting.DateTimeToLastUpdateTime(BuyPriceMinDate); + public string BuyPriceMinDateLastUpdateTime => Formatting.DateTimeToLastUpdateTime(BuyPriceMinDate); public ulong BuyPriceMax { get; set; } public string BuyPriceMaxString => Utilities.UlongMarketPriceToString(BuyPriceMax); public DateTime BuyPriceMaxDate { get; set; } public string BuyPriceMaxDateString => Utilities.MarketPriceDateToString(BuyPriceMaxDate); - public string BuyPriceMaxDateLastUpdateTime => Common.Formatting.DateTimeToLastUpdateTime(BuyPriceMaxDate); + public string BuyPriceMaxDateLastUpdateTime => Formatting.DateTimeToLastUpdateTime(BuyPriceMaxDate); public bool BestSellMinPrice { get; set; } public bool BestSellMaxPrice { get; set; } public bool BestBuyMinPrice { get; set; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketStats.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketStats.cs index a240f7242..cb244ec42 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketStats.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/MarketStats.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; namespace StatisticsAnalysisTool.Models { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CharacterEquipment.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CharacterEquipment.cs index cb1563a7b..40f24fec9 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CharacterEquipment.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CharacterEquipment.cs @@ -3,15 +3,15 @@ public class CharacterEquipment { public long? ObjectId { get; set; } - public int MainHand { get; set;} - public int OffHand { get; set;} - public int Head { get; set;} - public int Chest { get; set;} - public int Shoes { get; set;} - public int Bag { get; set;} - public int Cape { get; set;} - public int Mount { get; set;} - public int Potion { get; set;} - public int BuffFood { get; set;} + public int MainHand { get; set; } + public int OffHand { get; set; } + public int Head { get; set; } + public int Chest { get; set; } + public int Shoes { get; set; } + public int Bag { get; set; } + public int Cape { get; set; } + public int Mount { get; set; } + public int Potion { get; set; } + public int BuffFood { get; set; } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CombatTime.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CombatTime.cs index 632344f60..e16e21ba5 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CombatTime.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/CombatTime.cs @@ -11,6 +11,6 @@ public CombatTime(DateTime startTime) public DateTime StartTime { get; } public DateTime? EndTime { get; set; } - public TimeSpan CombatTimeSpan => (EndTime != null) ? (DateTime)EndTime - (DateTime)StartTime : new TimeSpan(0); + public TimeSpan CombatTimeSpan => EndTime != null ? (DateTime) EndTime - StartTime : new TimeSpan(0); } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Container.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Container.cs index d3b790ebc..4a333cac4 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Container.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Container.cs @@ -10,6 +10,7 @@ public enum ContainerType Chest, Player } + public class Container { public string Id { get; set; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/LocalUserData.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/LocalUserData.cs index 8a918cba8..fd2b90a7a 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/LocalUserData.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/LocalUserData.cs @@ -1,5 +1,5 @@ -using StatisticsAnalysisTool.Common; -using System; +using System; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Models.NetworkModel { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Loot.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Loot.cs index 6ca64eaed..05ed75c14 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Loot.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/Loot.cs @@ -1,34 +1,27 @@ -using Newtonsoft.Json; -using System; +using System; +using Newtonsoft.Json; namespace StatisticsAnalysisTool.Models.NetworkModel { public class Loot { - [JsonIgnore] - public int ObjectId { get; set; } + [JsonIgnore] public int ObjectId { get; set; } - [JsonIgnore] - public int ItemRefId { get; set; } + [JsonIgnore] public int ItemRefId { get; set; } - [JsonProperty] - public DateTime LocalPickupTime { get; set; } + [JsonProperty] public DateTime LocalPickupTime { get; set; } - [JsonProperty] - public DateTime UtcPickupTime { get; set; } + [JsonProperty] public DateTime UtcPickupTime { get; set; } - [JsonProperty] - public string BodyName { get; set; } + [JsonProperty] public string BodyName { get; set; } - [JsonProperty] - public string ItemName { get; set; } - [JsonProperty] - public string LongName { get; set; } - [JsonProperty] - public int Quantity { get; set; } + [JsonProperty] public string ItemName { get; set; } - [JsonIgnore] - public string LooterName { get; set; } + [JsonProperty] public string LongName { get; set; } + + [JsonProperty] public int Quantity { get; set; } + + [JsonIgnore] public string LooterName { get; set; } public string GetLine() { @@ -40,4 +33,4 @@ public override string ToString() return string.Join(", ", LocalPickupTime.ToString("HH:mm:ss"), LooterName, Quantity, LongName, BodyName); } } -} +} \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PartyMemberCircle.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PartyMemberCircle.cs index 830a55d9d..ae2aaf687 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PartyMemberCircle.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PartyMemberCircle.cs @@ -1,6 +1,6 @@ -using StatisticsAnalysisTool.Annotations; -using System.ComponentModel; +using System.ComponentModel; using System.Runtime.CompilerServices; +using StatisticsAnalysisTool.Annotations; namespace StatisticsAnalysisTool.Models.NetworkModel { @@ -8,14 +8,16 @@ public class PartyMemberCircle : INotifyPropertyChanged { private string _name; - public string Name { + public string Name + { get => _name; - set { + set + { _name = value; OnPropertyChanged(); } } - + public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PlayerGameObject.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PlayerGameObject.cs index 61f3a4de7..fb94f0d5f 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PlayerGameObject.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/NetworkModel/PlayerGameObject.cs @@ -1,12 +1,17 @@ -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Linq; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Models.NetworkModel { public class PlayerGameObject : GameObject { + public PlayerGameObject(long objectId) + { + ObjectId = objectId; + } + public Guid UserGuid { get; set; } public string Name { get; set; } = "Unknown"; public CharacterEquipment CharacterEquipment { get; set; } = null; @@ -16,11 +21,6 @@ public class PlayerGameObject : GameObject public long Damage { get; set; } public double Dps => Utilities.GetValuePerSecondToDouble(Damage, CombatStart, CombatTime, 9999); - public PlayerGameObject(long objectId) - { - ObjectId = objectId; - } - public override string ToString() { return $"{ObjectType}[ObjectId: {ObjectId}, Name: '{Name}']"; @@ -34,21 +34,12 @@ public void AddCombatTime(CombatTime combatTime) public int CompareTo(object obj) { - if (!(obj is long)) - { - return -1; - } + if (!(obj is long)) return -1; - var dmg = (long)obj; - if (Damage > dmg) - { - return 1; - } + var dmg = (long) obj; + if (Damage > dmg) return 1; - if (Damage == dmg) - { - return 0; - } + if (Damage == dmg) return 0; return -1; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/SearchInfos.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/SearchInfos.cs index 7ffd7de5c..e3ddd865b 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/SearchInfos.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/SearchInfos.cs @@ -1,8 +1,8 @@ -namespace StatisticsAnalysisTool.Models -{ - using Newtonsoft.Json; - using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; +namespace StatisticsAnalysisTool.Models +{ public class GameInfoSearchResponse { [JsonProperty(PropertyName = "guilds")] @@ -14,11 +14,9 @@ public class GameInfoSearchResponse public class SearchGuildResponse { - [JsonProperty(PropertyName = "Id")] - public string Id { get; set; } + [JsonProperty(PropertyName = "Id")] public string Id { get; set; } - [JsonProperty(PropertyName = "Name")] - public string Name { get; set; } + [JsonProperty(PropertyName = "Name")] public string Name { get; set; } [JsonProperty(PropertyName = "AllianceId")] public string AllianceId { get; set; } @@ -35,11 +33,9 @@ public class SearchGuildResponse public class SearchPlayerResponse { - [JsonProperty(PropertyName = "Id")] - public string Id { get; set; } + [JsonProperty(PropertyName = "Id")] public string Id { get; set; } - [JsonProperty(PropertyName = "Name")] - public string Name { get; set; } + [JsonProperty(PropertyName = "Name")] public string Name { get; set; } [JsonProperty(PropertyName = "GuildId")] public string GuildId { get; set; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WeaponCategories.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WeaponCategories.cs index b4596d749..c796fcb92 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WeaponCategories.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WeaponCategories.cs @@ -4,10 +4,8 @@ namespace StatisticsAnalysisTool.Models { public class WeaponCategories { - [JsonProperty("id")] - public string Id { get; set; } + [JsonProperty("id")] public string Id { get; set; } - [JsonProperty("name")] - public string Name { get; set; } + [JsonProperty("name")] public string Name { get; set; } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WorldJsonObject.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WorldJsonObject.cs index a6c69f0fd..4be6ad18b 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WorldJsonObject.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Models/WorldJsonObject.cs @@ -4,13 +4,10 @@ namespace StatisticsAnalysisTool.Models { public class WorldJsonObject { - [JsonProperty("Index")] - public string Index { get; set; } + [JsonProperty("Index")] public string Index { get; set; } - [JsonProperty("UniqueName")] - public string UniqueName { get; set; } + [JsonProperty("UniqueName")] public string UniqueName { get; set; } - [JsonProperty("Type")] - public string Type { get; set; } + [JsonProperty("Type")] public string Type { get; set; } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/CombatController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/CombatController.cs index 19bdbe8f8..1cbb9fe25 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/CombatController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/CombatController.cs @@ -14,10 +14,10 @@ namespace StatisticsAnalysisTool.Network.Controller { public class CombatController { - private readonly TrackingController _trackingController; private readonly MainWindow _mainWindow; private readonly MainWindowViewModel _mainWindowViewModel; - + private readonly TrackingController _trackingController; + public CombatController(TrackingController trackingController, MainWindow mainWindow, MainWindowViewModel mainWindowViewModel) { _trackingController = trackingController; @@ -36,21 +36,13 @@ public CombatController(TrackingController trackingController, MainWindow mainWi public void AddDamage(long causerId, double healthChange) { var gameObject = _trackingController?.EntityController?.GetEntity(causerId); - if (gameObject == null || healthChange >= 0 || gameObject.Value.Value?.ObjectType != GameObjectType.Player || !_trackingController.EntityController.IsUserInParty(gameObject.Value.Value.Name)) - { - return; - } + if (gameObject == null || healthChange >= 0 || gameObject.Value.Value?.ObjectType != GameObjectType.Player || + !_trackingController.EntityController.IsUserInParty(gameObject.Value.Value.Name)) return; - var damageValue = (int)Math.Round(healthChange.ToPositiveFromNegativeOrZero(), MidpointRounding.AwayFromZero); - if (damageValue <= 0) - { - return; - } + var damageValue = (int) Math.Round(healthChange.ToPositiveFromNegativeOrZero(), MidpointRounding.AwayFromZero); + if (damageValue <= 0) return; - if (gameObject.Value.Value?.CombatStart == null) - { - gameObject.Value.Value.CombatStart = DateTime.UtcNow; - } + if (gameObject.Value.Value?.CombatStart == null) gameObject.Value.Value.CombatStart = DateTime.UtcNow; gameObject.Value.Value.Damage += damageValue; @@ -59,62 +51,48 @@ public void AddDamage(long causerId, double healthChange) public void UpdateDamageMeterUi(List> entities) { - if (!IsUiUpdateAllowed()) - { - return; - } + if (!IsUiUpdateAllowed()) return; var highestDamage = GetHighestDamage(entities); _trackingController.EntityController.DetectUsedWeapon(); foreach (var damageObject in entities) - { if (_mainWindowViewModel.DamageMeter.Any(x => x.CauserGuid == damageObject.Value.UserGuid)) - { _mainWindow.Dispatcher?.Invoke(async () => { var fragment = _mainWindowViewModel.DamageMeter.FirstOrDefault(x => x.CauserGuid == damageObject.Value.UserGuid); if (fragment != null) { - fragment.CauserMainHand = await SetItemInfoIfSlotTypeMainHandAsync(fragment.CauserMainHand, damageObject.Value?.CharacterEquipment?.MainHand); + fragment.CauserMainHand = await SetItemInfoIfSlotTypeMainHandAsync(fragment.CauserMainHand, + damageObject.Value?.CharacterEquipment?.MainHand); - if (damageObject.Value?.Damage > 0) - { - fragment.DamageInPercent = ((double)damageObject.Value.Damage / highestDamage) * 100; - } + if (damageObject.Value?.Damage > 0) fragment.DamageInPercent = (double) damageObject.Value.Damage / highestDamage * 100; fragment.Damage = damageObject.Value?.Damage.ToShortNumberString(); - if (damageObject.Value?.Dps != null) - { - fragment.Dps = damageObject.Value.Dps; - } + if (damageObject.Value?.Dps != null) fragment.Dps = damageObject.Value.Dps; - if (damageObject.Value != null) - { - fragment.DamagePercentage = GetDamagePercentage(entities, damageObject.Value.Damage); - } + if (damageObject.Value != null) fragment.DamagePercentage = GetDamagePercentage(entities, damageObject.Value.Damage); } _mainWindowViewModel.SetDamageMeterSort(); }); - } else - { _mainWindow.Dispatcher?.InvokeAsync(async () => { var mainHandItem = ItemController.GetItemByIndex(damageObject.Value?.CharacterEquipment?.MainHand ?? 0); if (damageObject.Value != null) { - var damageMeterFragment = new DamageMeterFragment() + var damageMeterFragment = new DamageMeterFragment { CauserGuid = damageObject.Value.UserGuid, Damage = damageObject.Value.Damage.ToShortNumberString(), Dps = damageObject.Value.Dps, - DamageInPercent = ((double)damageObject.Value.Damage / highestDamage) * 100, + DamageInPercent = (double) damageObject.Value.Damage / highestDamage * 100, DamagePercentage = GetDamagePercentage(entities, damageObject.Value.Damage), Name = damageObject.Value.Name, - CauserMainHand = await SetItemInfoIfSlotTypeMainHandAsync(mainHandItem, damageObject.Value?.CharacterEquipment?.MainHand) + CauserMainHand = + await SetItemInfoIfSlotTypeMainHandAsync(mainHandItem, damageObject.Value?.CharacterEquipment?.MainHand) }; _mainWindowViewModel.DamageMeter.Add(damageMeterFragment); @@ -122,8 +100,6 @@ public void UpdateDamageMeterUi(List> entit _mainWindowViewModel.SetDamageMeterSort(); }); - } - } } public void ResetDamageMeter() @@ -132,24 +108,15 @@ public void ResetDamageMeter() _trackingController.EntityController.ResetEntitiesDamage(); _trackingController.EntityController.ResetEntitiesDamageStartTime(); - _mainWindow?.Dispatcher?.InvokeAsync(() => - { - _mainWindowViewModel?.DamageMeter?.Clear(); - }); + _mainWindow?.Dispatcher?.InvokeAsync(() => { _mainWindowViewModel?.DamageMeter?.Clear(); }); } private async Task SetItemInfoIfSlotTypeMainHandAsync(Item currentItem, int? newIndex) { - if (newIndex == null || newIndex <= 0) - { - return currentItem; - } + if (newIndex == null || newIndex <= 0) return currentItem; - var item = ItemController.GetItemByIndex((int)newIndex); - if (item == null) - { - return currentItem; - } + var item = ItemController.GetItemByIndex((int) newIndex); + if (item == null) return currentItem; var fullItemInfo = await ItemController.GetFullItemInformationAsync(item); if (ItemController.IsItemSlotType(fullItemInfo, "mainhand")) @@ -162,7 +129,7 @@ private async Task SetItemInfoIfSlotTypeMainHandAsync(Item currentItem, in } private DateTime _lastDamageUiUpdate; - + private bool IsUiUpdateAllowed() { var currentDateTime = DateTime.UtcNow; @@ -178,7 +145,7 @@ private bool IsUiUpdateAllowed() private long GetHighestDamage(List> playerObjects) { - return (playerObjects.Count <= 0) ? 0 : playerObjects.Max(x => x.Value.Damage); + return playerObjects.Count <= 0 ? 0 : playerObjects.Max(x => x.Value.Damage); } private double GetDamagePercentage(List> playerObjects, double playerDamage) @@ -200,35 +167,20 @@ public void UpdateCombatMode(long objectId, bool inActiveCombat, bool inPassiveC private void AddCombatTime(long objectId, bool inActiveCombat, bool inPassiveCombat) { - if (!_trackingController.EntityController.IsUserInParty(objectId)) - { - return; - } + if (!_trackingController.EntityController.IsUserInParty(objectId)) return; var playerObject = _trackingController.EntityController.GetEntity(objectId); - - if (playerObject?.Value == null) - { - return; - } - if ((inActiveCombat || inPassiveCombat) && playerObject.Value.Value.CombatTimes.Any(x => x?.EndTime == null)) - { - return; - } + if (playerObject?.Value == null) return; - if (inActiveCombat || inPassiveCombat) - { - playerObject.Value.Value.AddCombatTime(new CombatTime(DateTime.UtcNow)); - } + if ((inActiveCombat || inPassiveCombat) && playerObject.Value.Value.CombatTimes.Any(x => x?.EndTime == null)) return; + + if (inActiveCombat || inPassiveCombat) playerObject.Value.Value.AddCombatTime(new CombatTime(DateTime.UtcNow)); if (!inActiveCombat && !inPassiveCombat) { var combatTime = playerObject.Value.Value.CombatTimes.FirstOrDefault(x => x.EndTime == null); - if (combatTime != null) - { - combatTime.EndTime = DateTime.UtcNow; - } + if (combatTime != null) combatTime.EndTime = DateTime.UtcNow; } } @@ -241,7 +193,7 @@ private void AddCombatTime(long objectId, bool inActiveCombat, bool inPassiveCom private List> SetRandomDamageValues(int playerAmount = 5) { var randomPlayerList = new List>(); - + for (var i = 0; i < playerAmount; i++) { var causerGuid = new Guid($"{_random.Next(1000, 9999)}0000-0000-0000-0000-000000000000"); @@ -249,14 +201,14 @@ private List> SetRandomDamageValues(int pla var objectId = _random.Next(20, 9999); var len = _random.Next(3, 10); var randomTime = _random.Next(1, 1000); - + randomPlayerList.Add(new KeyValuePair(causerGuid, new PlayerGameObject(objectId) { - CharacterEquipment = new CharacterEquipment() + CharacterEquipment = new CharacterEquipment { MainHand = GetRandomWeaponIndex() }, - CombatTime = new TimeSpan(0,0,0, randomTime), + CombatTime = new TimeSpan(0, 0, 0, randomTime), Damage = damage, Name = GenerateName(len), ObjectSubType = GameObjectSubType.Player, @@ -270,12 +222,12 @@ private List> SetRandomDamageValues(int pla private static string GenerateName(int len) { - string[] consonants = { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "l", "n", "p", "q", "r", "s", "sh", "zh", "t", "v", "w", "x" }; - string[] vowels = { "a", "e", "i", "o", "u", "ae", "y" }; - string Name = ""; + string[] consonants = {"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "l", "n", "p", "q", "r", "s", "sh", "zh", "t", "v", "w", "x"}; + string[] vowels = {"a", "e", "i", "o", "u", "ae", "y"}; + var Name = ""; Name += consonants[_random.Next(consonants.Length)].ToUpper(); Name += vowels[_random.Next(vowels.Length)]; - int b = 2; //b tells how many times a new letter has been added. It's 2 right now because the first two letters are already in the name. + var b = 2; //b tells how many times a new letter has been added. It's 2 right now because the first two letters are already in the name. while (b < len) { Name += consonants[_random.Next(consonants.Length)]; @@ -289,7 +241,7 @@ private static string GenerateName(int len) private static int GetRandomWeaponIndex() { - var indexArray = new List { 6211, 5926, 1176, 1171, 6553, 1087, 6413, 5181, 5080, 5705, 4998, 4777, 4696, 2075, 5472, 0 }; + var indexArray = new List {6211, 5926, 1176, 1171, 6553, 1087, 6413, 5181, 5080, 5705, 4998, 4777, 4696, 2075, 5472, 0}; var index = _random.Next(indexArray.Count); var itemIndex = indexArray[index]; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/DungeonController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/DungeonController.cs index df6d05ceb..0fb32a501 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/DungeonController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/DungeonController.cs @@ -20,17 +20,15 @@ namespace StatisticsAnalysisTool.Network.Controller { public class DungeonController { - private readonly TrackingController _trackingController; + private const int _maxDungeons = 9999; + + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly MainWindow _mainWindow; private readonly MainWindowViewModel _mainWindowViewModel; - - private Guid? _lastGuid; + private readonly TrackingController _trackingController; private Guid? _currentGuid; - public LocalUserData LocalUserData { get; set; } - private const int _maxDungeons = 9999; - - private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private Guid? _lastGuid; public DungeonController(TrackingController trackingController, MainWindow mainWindow, MainWindowViewModel mainWindowViewModel) { @@ -39,6 +37,8 @@ public DungeonController(TrackingController trackingController, MainWindow mainW _mainWindowViewModel = mainWindowViewModel; } + public LocalUserData LocalUserData { get; set; } + public void AddDungeon(MapType mapType, Guid? mapGuid, string mainMapIndex) { LeaveDungeonCheck(mapType); @@ -48,10 +48,7 @@ public void AddDungeon(MapType mapType, Guid? mapGuid, string mainMapIndex) if (mapType != MapType.RandomDungeon || mapGuid == null) { - if (_lastGuid != null) - { - SetCurrentDungeonActive((Guid)_lastGuid, true); - } + if (_lastGuid != null) SetCurrentDungeonActive((Guid) _lastGuid, true); _currentGuid = null; _lastGuid = null; @@ -60,15 +57,15 @@ public void AddDungeon(MapType mapType, Guid? mapGuid, string mainMapIndex) try { - _currentGuid = (Guid)mapGuid; - var currentGuid = (Guid)_currentGuid; + _currentGuid = (Guid) mapGuid; + var currentGuid = (Guid) _currentGuid; AddDungeonRunIfNextMap(currentGuid); SetNewStartTimeWhenOneMoreTimeEnter(currentGuid); if (_lastGuid != null && !_mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains(currentGuid))) { - AddMapToExistDungeon(currentGuid, (Guid)_lastGuid); + AddMapToExistDungeon(currentGuid, (Guid) _lastGuid); _lastGuid = currentGuid; _mainWindowViewModel.DungeonStatsDay.EnteredDungeon = GetDungeonsCount(DateTime.UtcNow.AddDays(-1)); @@ -79,23 +76,21 @@ public void AddDungeon(MapType mapType, Guid? mapGuid, string mainMapIndex) return; } - if (_lastGuid == null && !_mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains((Guid)mapGuid))) + if (_lastGuid == null && !_mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains((Guid) mapGuid))) { if (_mainWindow.Dispatcher.CheckAccess()) - { _mainWindowViewModel.TrackingDungeons.Insert( 0, - new DungeonNotificationFragment(currentGuid, _mainWindowViewModel.TrackingDungeons.Count + 1, mainMapIndex, DateTime.UtcNow)); - } + new DungeonNotificationFragment(currentGuid, _mainWindowViewModel.TrackingDungeons.Count + 1, mainMapIndex, + DateTime.UtcNow)); else - { _mainWindow.Dispatcher.Invoke(delegate { _mainWindowViewModel.TrackingDungeons.Insert( 0, - new DungeonNotificationFragment(currentGuid, _mainWindowViewModel.TrackingDungeons.Count + 1, mainMapIndex, DateTime.UtcNow)); + new DungeonNotificationFragment(currentGuid, _mainWindowViewModel.TrackingDungeons.Count + 1, mainMapIndex, + DateTime.UtcNow)); }); - } _lastGuid = mapGuid; _mainWindowViewModel.DungeonStatsDay.EnteredDungeon = GetDungeonsCount(DateTime.UtcNow.AddDays(-1)); @@ -118,26 +113,20 @@ public void AddDungeon(MapType mapType, Guid? mapGuid, string mainMapIndex) public void SetDungeonChestOpen(int id) { if (_currentGuid != null) - { try { - var dun = GetCurrentDungeon((Guid)_currentGuid); + var dun = GetCurrentDungeon((Guid) _currentGuid); var chest = dun?.DungeonChests?.FirstOrDefault(x => x.Id == id); - if (chest == null) - { - return; - } + if (chest == null) return; chest.IsChestOpen = true; chest.Opened = DateTime.UtcNow; - } catch (Exception e) { Log.Error(nameof(SetDungeonChestOpen), e); } - } SetDungeonStatsDay(); SetDungeonStatsTotal(); @@ -146,15 +135,11 @@ public void SetDungeonChestOpen(int id) public void SetDungeonChestInformation(int id, string uniqueName) { if (_currentGuid != null && uniqueName != null) - { try { - var dun = GetCurrentDungeon((Guid)_currentGuid); + var dun = GetCurrentDungeon((Guid) _currentGuid); - if (dun == null || _currentGuid == null || dun.DungeonChests?.Any(x => x.Id == id) == true) - { - return; - } + if (dun == null || _currentGuid == null || dun.DungeonChests?.Any(x => x.Id == id) == true) return; var dunChest = new DungeonChestFragment { @@ -165,16 +150,9 @@ public void SetDungeonChestInformation(int id, string uniqueName) }; if (_mainWindow.Dispatcher.CheckAccess()) - { dun.DungeonChests?.Add(dunChest); - } else - { - _mainWindow.Dispatcher.Invoke(delegate - { - dun.DungeonChests?.Add(dunChest); - }); - } + _mainWindow.Dispatcher.Invoke(delegate { dun.DungeonChests?.Add(dunChest); }); dun.Faction = LootChestData.GetFaction(uniqueName); dun.Mode = LootChestData.GetDungeonMode(uniqueName); @@ -183,7 +161,6 @@ public void SetDungeonChestInformation(int id, string uniqueName) { Log.Error(nameof(SetDungeonChestInformation), e); } - } } private DungeonNotificationFragment GetCurrentDungeon(Guid guid) @@ -193,11 +170,15 @@ private DungeonNotificationFragment GetCurrentDungeon(Guid guid) private int GetChests(DateTime? chestIsNewerAsDateTime, ChestRarity rarity) { - var dungeons = _mainWindowViewModel.TrackingDungeons.Where(x => x.StartDungeon > chestIsNewerAsDateTime || chestIsNewerAsDateTime == null); + var dungeons = _mainWindowViewModel.TrackingDungeons.Where(x => + x.StartDungeon > chestIsNewerAsDateTime || chestIsNewerAsDateTime == null); return dungeons.Select(dun => dun.DungeonChests.Where(x => x.Rarity == rarity)).Select(filteredChests => filteredChests.Count()).Sum(); } - public int GetDungeonsCount(DateTime dungeonIsNewerAsDateTime) => _mainWindowViewModel.TrackingDungeons.Count(x => x.StartDungeon > dungeonIsNewerAsDateTime); + public int GetDungeonsCount(DateTime dungeonIsNewerAsDateTime) + { + return _mainWindowViewModel.TrackingDungeons.Count(x => x.StartDungeon > dungeonIsNewerAsDateTime); + } public void SetDungeonStatsDay() { @@ -218,10 +199,10 @@ public void SetDungeonStatsTotal() public void SetDiedIfInDungeon(DiedObject dieObject) { if (_currentGuid != null && LocalUserData.Username != null && dieObject.DiedName == LocalUserData.Username) - { try { - var item = _mainWindowViewModel.TrackingDungeons.First(x => x.MapsGuid.Contains((Guid)_currentGuid) && x.StartDungeon > DateTime.UtcNow.AddDays(-1)); + var item = _mainWindowViewModel.TrackingDungeons.First(x => + x.MapsGuid.Contains((Guid) _currentGuid) && x.StartDungeon > DateTime.UtcNow.AddDays(-1)); item.DiedName = dieObject.DiedName; item.KilledBy = dieObject.KilledBy; item.DiedInDungeon = true; @@ -230,24 +211,17 @@ public void SetDiedIfInDungeon(DiedObject dieObject) { Log.Error(nameof(SetDiedIfInDungeon), e); } - } } private void RemoveDungeonsAfterCertainNumber(int amount) { - if (_trackingController.IsMainWindowNull() || _mainWindowViewModel.TrackingDungeons == null) - { - return; - } + if (_trackingController.IsMainWindowNull() || _mainWindowViewModel.TrackingDungeons == null) return; try { while (true) { - if (_mainWindowViewModel.TrackingNotifications?.Count <= amount) - { - break; - } + if (_mainWindowViewModel.TrackingNotifications?.Count <= amount) break; var dateTime = GetLowestDate(_mainWindowViewModel.TrackingDungeons); if (dateTime != null) @@ -256,16 +230,9 @@ private void RemoveDungeonsAfterCertainNumber(int amount) if (removableItem != null) { if (_mainWindow.Dispatcher.CheckAccess()) - { _mainWindowViewModel.TrackingDungeons.Remove(removableItem); - } else - { - _mainWindow.Dispatcher.Invoke(delegate - { - _mainWindowViewModel.TrackingDungeons.Remove(removableItem); - }); - } + _mainWindow.Dispatcher.Invoke(delegate { _mainWindowViewModel.TrackingDungeons.Remove(removableItem); }); } } } @@ -278,32 +245,24 @@ private void RemoveDungeonsAfterCertainNumber(int amount) private void SetCurrentDungeonActive(Guid guid, bool allToFalse = false) { - if (_mainWindowViewModel.TrackingDungeons.Count <= 0) - { - return; - } + if (_mainWindowViewModel.TrackingDungeons.Count <= 0) return; if (_mainWindow.Dispatcher.CheckAccess()) { _mainWindowViewModel.TrackingDungeons.Where(x => x.Status != DungeonStatus.Done).ToList().ForEach(x => x.Status = DungeonStatus.Done); var dun = _mainWindowViewModel.TrackingDungeons?.First(x => x.MapsGuid.Contains(guid)); - if (!allToFalse) - { - dun.Status = DungeonStatus.Active; - } + if (!allToFalse) dun.Status = DungeonStatus.Active; } else { _mainWindow.Dispatcher.Invoke(delegate { - _mainWindowViewModel.TrackingDungeons.Where(x => x.Status != DungeonStatus.Done).ToList().ForEach(x => x.Status = DungeonStatus.Done); + _mainWindowViewModel.TrackingDungeons.Where(x => x.Status != DungeonStatus.Done).ToList() + .ForEach(x => x.Status = DungeonStatus.Done); var dun = _mainWindowViewModel.TrackingDungeons?.First(x => x.MapsGuid.Contains(guid)); - if (!allToFalse) - { - dun.Status = DungeonStatus.Active; - } + if (!allToFalse) dun.Status = DungeonStatus.Active; }); } } @@ -312,15 +271,14 @@ private void SetBestDungeonTime() { if (_mainWindow.Dispatcher.CheckAccess()) { - if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.DungeonChests.Any(y => y?.IsBossChest == true)) == true) + if (_mainWindowViewModel?.TrackingDungeons?.Any(x => + x?.Status == DungeonStatus.Done && x.DungeonChests.Any(y => y?.IsBossChest == true)) == true) { _mainWindowViewModel.TrackingDungeons.Where(x => x?.IsBestTime == true).ToList().ForEach(x => x.IsBestTime = false); - var min = _mainWindowViewModel?.TrackingDungeons?.Where(x => x?.DungeonChests.Any(y => y.IsBossChest) == true).Select(x => x.TotalTime).Min(); + var min = _mainWindowViewModel?.TrackingDungeons?.Where(x => x?.DungeonChests.Any(y => y.IsBossChest) == true) + .Select(x => x.TotalTime).Min(); var bestTimeDungeon = _mainWindowViewModel?.TrackingDungeons?.SingleOrDefault(x => x.TotalTime == min); - if (bestTimeDungeon != null) - { - bestTimeDungeon.IsBestTime = true; - } + if (bestTimeDungeon != null) bestTimeDungeon.IsBestTime = true; } } else @@ -329,15 +287,14 @@ private void SetBestDungeonTime() { _mainWindowViewModel.TrackingDungeons.Where(x => x?.IsBestTime == true).ToList().ForEach(x => x.IsBestTime = false); - if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.DungeonChests.Any(y => y?.IsBossChest == true)) == true) + if (_mainWindowViewModel?.TrackingDungeons?.Any(x => + x?.Status == DungeonStatus.Done && x.DungeonChests.Any(y => y?.IsBossChest == true)) == true) { _mainWindowViewModel.TrackingDungeons.Where(x => x?.IsBestTime == true).ToList().ForEach(x => x.IsBestTime = false); - var min = _mainWindowViewModel?.TrackingDungeons?.Where(x => x?.DungeonChests.Any(y => y.IsBossChest) == true).Select(x => x.TotalTime).Min(); + var min = _mainWindowViewModel?.TrackingDungeons?.Where(x => x?.DungeonChests.Any(y => y.IsBossChest) == true) + .Select(x => x.TotalTime).Min(); var bestTimeDungeon = _mainWindowViewModel?.TrackingDungeons?.SingleOrDefault(x => x.TotalTime == min); - if (bestTimeDungeon != null) - { - bestTimeDungeon.IsBestTime = true; - } + if (bestTimeDungeon != null) bestTimeDungeon.IsBestTime = true; } }); } @@ -346,13 +303,9 @@ private void SetBestDungeonTime() private void SetBestDungeonValuesWithDispatcher() { if (_mainWindow.Dispatcher.CheckAccess()) - { CalculateBestDungeonValues(); - } else - { _mainWindow.Dispatcher.Invoke(CalculateBestDungeonValues); - } } private void CalculateBestDungeonValues() @@ -378,68 +331,59 @@ private void CalculateBestDungeonValues() if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.Fame > 0) == true) { - var highestFame = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.Fame > 0).Select(x => x.Fame).Max(); + var highestFame = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.Fame > 0) + .Select(x => x.Fame).Max(); var bestDungeonFame = _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.Fame.CompareTo(highestFame) == 0); - if (bestDungeonFame != null) - { - bestDungeonFame.IsBestFame = true; - } + if (bestDungeonFame != null) bestDungeonFame.IsBestFame = true; } if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.ReSpec > 0) == true) { - var highestReSpec = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.ReSpec > 0).Select(x => x.ReSpec).Max(); + var highestReSpec = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.ReSpec > 0) + .Select(x => x.ReSpec).Max(); var bestDungeonReSpec = _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.ReSpec.CompareTo(highestReSpec) == 0); - if (bestDungeonReSpec != null) - { - bestDungeonReSpec.IsBestReSpec = true; - } + if (bestDungeonReSpec != null) bestDungeonReSpec.IsBestReSpec = true; } if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.Silver > 0) == true) { - var highestSilver = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.Silver > 0).Select(x => x.Silver).Max(); + var highestSilver = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.Silver > 0) + .Select(x => x.Silver).Max(); var bestDungeonSilver = _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.Silver.CompareTo(highestSilver) == 0); - if (bestDungeonSilver != null) - { - bestDungeonSilver.IsBestSilver = true; - } + if (bestDungeonSilver != null) bestDungeonSilver.IsBestSilver = true; } if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.FamePerHour > 0) == true) { - var highestFamePerHour = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.FamePerHour > 0).Select(x => x.FamePerHour).Max(); - var bestDungeonFamePerHour = _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.FamePerHour.CompareTo(highestFamePerHour) == 0); + var highestFamePerHour = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.FamePerHour > 0) + .Select(x => x.FamePerHour).Max(); + var bestDungeonFamePerHour = + _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.FamePerHour.CompareTo(highestFamePerHour) == 0); - if (bestDungeonFamePerHour != null) - { - bestDungeonFamePerHour.IsBestFamePerHour = true; - } + if (bestDungeonFamePerHour != null) bestDungeonFamePerHour.IsBestFamePerHour = true; } if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.ReSpecPerHour > 0) == true) { - var highestReSpecPerHour = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.ReSpecPerHour > 0).Select(x => x.ReSpecPerHour).Max(); - var bestDungeonReSpecPerHour = _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.ReSpecPerHour.CompareTo(highestReSpecPerHour) == 0); + var highestReSpecPerHour = _mainWindowViewModel.TrackingDungeons + .Where(x => x?.Status == DungeonStatus.Done && x.ReSpecPerHour > 0).Select(x => x.ReSpecPerHour).Max(); + var bestDungeonReSpecPerHour = + _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.ReSpecPerHour.CompareTo(highestReSpecPerHour) == 0); - if (bestDungeonReSpecPerHour != null) - { - bestDungeonReSpecPerHour.IsBestReSpecPerHour = true; - } + if (bestDungeonReSpecPerHour != null) bestDungeonReSpecPerHour.IsBestReSpecPerHour = true; } if (_mainWindowViewModel?.TrackingDungeons?.Any(x => x?.Status == DungeonStatus.Done && x.SilverPerHour > 0) == true) { - var highestSilverPerHour = _mainWindowViewModel.TrackingDungeons.Where(x => x?.Status == DungeonStatus.Done && x.SilverPerHour > 0).Select(x => x.SilverPerHour).Max(); - var bestDungeonSilverPerHour = _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.SilverPerHour.CompareTo(highestSilverPerHour) == 0); + var highestSilverPerHour = _mainWindowViewModel.TrackingDungeons + .Where(x => x?.Status == DungeonStatus.Done && x.SilverPerHour > 0).Select(x => x.SilverPerHour).Max(); + var bestDungeonSilverPerHour = + _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => x.SilverPerHour.CompareTo(highestSilverPerHour) == 0); - if (bestDungeonSilverPerHour != null) - { - bestDungeonSilverPerHour.IsBestSilverPerHour = true; - } + if (bestDungeonSilverPerHour != null) bestDungeonSilverPerHour.IsBestSilverPerHour = true; } } catch (Exception e) @@ -450,7 +394,8 @@ private void CalculateBestDungeonValues() private void AddDungeonRunIfNextMap(Guid currentGuid) { - if (_lastGuid != null && _mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains(currentGuid) && x.MapsGuid.Contains((Guid)_lastGuid))) + if (_lastGuid != null && + _mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains(currentGuid) && x.MapsGuid.Contains((Guid) _lastGuid))) { var dun = _mainWindowViewModel.TrackingDungeons?.First(x => x.MapsGuid.Contains(currentGuid)); dun.AddDungeonRunTime(DateTime.UtcNow); @@ -496,45 +441,43 @@ private void AddMapToExistDungeon(Guid currentGuid, Guid lastGuid) private void LeaveDungeonCheck(MapType mapType) { - if (_lastGuid != null && _mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains((Guid)_lastGuid)) && mapType != MapType.RandomDungeon) + if (_lastGuid != null && _mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains((Guid) _lastGuid)) && + mapType != MapType.RandomDungeon) { - var dun = _mainWindowViewModel.TrackingDungeons?.First(x => x.MapsGuid.Contains((Guid)_lastGuid)); + var dun = _mainWindowViewModel.TrackingDungeons?.First(x => x.MapsGuid.Contains((Guid) _lastGuid)); dun.AddDungeonRunTime(DateTime.UtcNow); } } private void IsDungeonDoneCheck(MapType mapType) { - if (_lastGuid != null && _mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains((Guid)_lastGuid)) && mapType != MapType.RandomDungeon) + if (_lastGuid != null && _mainWindowViewModel.TrackingDungeons.Any(x => x.MapsGuid.Contains((Guid) _lastGuid)) && + mapType != MapType.RandomDungeon) { var dun = _mainWindowViewModel?.TrackingDungeons?.FirstOrDefault(x => - x.MapsGuid.Contains((Guid)_lastGuid) && x.DungeonChests.Any(y => y.IsBossChest)); - if (dun != null) - { - dun.Status = DungeonStatus.Done; - } + x.MapsGuid.Contains((Guid) _lastGuid) && x.DungeonChests.Any(y => y.IsBossChest)); + if (dun != null) dun.Status = DungeonStatus.Done; } } public void AddValueToDungeon(double value, ValueType valueType) { - if (_currentGuid == null) - { - return; - } + if (_currentGuid == null) return; try { if (_mainWindow.Dispatcher.CheckAccess()) { - var dun = _mainWindowViewModel.TrackingDungeons?.FirstOrDefault(x => x.MapsGuid.Contains((Guid)_currentGuid) && x.Status == DungeonStatus.Active); + var dun = _mainWindowViewModel.TrackingDungeons?.FirstOrDefault(x => + x.MapsGuid.Contains((Guid) _currentGuid) && x.Status == DungeonStatus.Active); dun?.Add(value, valueType); } else { _mainWindow.Dispatcher.Invoke(delegate { - var dun = _mainWindowViewModel.TrackingDungeons?.FirstOrDefault(x => x.MapsGuid.Contains((Guid)_currentGuid) && x.Status == DungeonStatus.Active); + var dun = _mainWindowViewModel.TrackingDungeons?.FirstOrDefault(x => + x.MapsGuid.Contains((Guid) _currentGuid) && x.Status == DungeonStatus.Active); dun?.Add(value, valueType); }); } @@ -547,10 +490,7 @@ public void AddValueToDungeon(double value, ValueType valueType) public static DateTime? GetLowestDate(ObservableCollection items) { - if (items.IsNullOrEmpty()) - { - return null; - } + if (items.IsNullOrEmpty()) return null; try { @@ -568,7 +508,6 @@ public ObservableCollection LoadDungeonFromFile() var localFilePath = $"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.DungeonRunsFileName}"; if (File.Exists(localFilePath)) - { try { var localItemString = File.ReadAllText(localFilePath, Encoding.UTF8); @@ -579,7 +518,7 @@ public ObservableCollection LoadDungeonFromFile() Log.Error(nameof(LoadDungeonFromFile), e); return new ObservableCollection(); } - } + return new ObservableCollection(); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/EntityController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/EntityController.cs index dfcb60589..cc9ad8326 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/EntityController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/EntityController.cs @@ -15,13 +15,15 @@ namespace StatisticsAnalysisTool.Network.Controller { public class EntityController { - private readonly MainWindow _mainWindow; - private readonly MainWindowViewModel _mainWindowViewModel; private readonly ConcurrentDictionary _knownEntities = new ConcurrentDictionary(); private readonly ConcurrentDictionary _knownPartyEntities = new ConcurrentDictionary(); + private readonly MainWindow _mainWindow; + private readonly MainWindowViewModel _mainWindowViewModel; private readonly ObservableCollection _newEquipmentItems = new ObservableCollection(); private readonly ObservableCollection _spellEffects = new ObservableCollection(); - private readonly ConcurrentDictionary _tempCharacterEquipmentData = new ConcurrentDictionary(); + + private readonly ConcurrentDictionary _tempCharacterEquipmentData = + new ConcurrentDictionary(); public EntityController(MainWindow mainWindow, MainWindowViewModel mainWindowViewModel) { @@ -38,7 +40,6 @@ public void AddEntity(long objectId, Guid userGuid, string name, GameObjectType PlayerGameObject gameObject; if (_knownEntities.TryRemove(userGuid, out var oldEntity)) - { gameObject = new PlayerGameObject(objectId) { Name = name, @@ -50,9 +51,7 @@ public void AddEntity(long objectId, Guid userGuid, string name, GameObjectType CombatTime = oldEntity.CombatTime, Damage = oldEntity.Damage }; - } else - { gameObject = new PlayerGameObject(objectId) { Name = name, @@ -60,7 +59,6 @@ public void AddEntity(long objectId, Guid userGuid, string name, GameObjectType UserGuid = userGuid, ObjectSubType = objectSubType }; - } if (_tempCharacterEquipmentData.TryGetValue(objectId, out var characterEquipmentData)) { @@ -75,15 +73,12 @@ public void AddEntity(long objectId, Guid userGuid, string name, GameObjectType public void RemoveAllEntities() { - foreach (var entity in _knownEntities.Where(x => x.Value.ObjectSubType != GameObjectSubType.LocalPlayer && !_knownPartyEntities.ContainsKey(x.Key))) - { + foreach (var entity in _knownEntities.Where(x => + x.Value.ObjectSubType != GameObjectSubType.LocalPlayer && !_knownPartyEntities.ContainsKey(x.Key))) _knownEntities.TryRemove(entity.Key, out _); - } - foreach (var entity in _knownEntities.Where(x => x.Value.ObjectSubType == GameObjectSubType.LocalPlayer || _knownPartyEntities.ContainsKey(x.Key))) - { - entity.Value.ObjectId = null; - } + foreach (var entity in _knownEntities.Where(x => + x.Value.ObjectSubType == GameObjectSubType.LocalPlayer || _knownPartyEntities.ContainsKey(x.Key))) entity.Value.ObjectId = null; } public KeyValuePair? GetEntity(long objectId) @@ -102,10 +97,7 @@ public List> GetAllEntities(bool onlyInPart public void AddToParty(Guid guid, string username) { - if (_knownPartyEntities.All(x => x.Key != guid)) - { - _knownPartyEntities.TryAdd(guid, username); - } + if (_knownPartyEntities.All(x => x.Key != guid)) _knownPartyEntities.TryAdd(guid, username); SetPartyMemberUi(); } @@ -114,10 +106,7 @@ public void RemoveFromParty(string username) { var partyMember = _knownPartyEntities.FirstOrDefault(x => x.Value == username); - if (partyMember.Value != null) - { - _knownPartyEntities.TryRemove(partyMember.Key, out _); - } + if (partyMember.Value != null) _knownPartyEntities.TryRemove(partyMember.Key, out _); SetPartyMemberUi(); } @@ -127,22 +116,14 @@ public void ResetPartyMember() _knownPartyEntities.Clear(); foreach (var member in _knownEntities.Where(x => x.Value.ObjectSubType == GameObjectSubType.LocalPlayer)) - { _knownPartyEntities.TryAdd(member.Key, member.Value.Name); - } } public void SetParty(Dictionary party, bool resetPartyBefore = false) { - if (resetPartyBefore) - { - ResetPartyMember(); - } + if (resetPartyBefore) ResetPartyMember(); - foreach (var member in party) - { - AddToParty(member.Key, member.Value); - } + foreach (var member in party) AddToParty(member.Key, member.Value); SetPartyMemberUi(); } @@ -152,10 +133,7 @@ private void SetPartyMemberUi() _mainWindow.Dispatcher.Invoke(() => { _mainWindowViewModel.PartyMemberCircles.Clear(); - foreach (var member in _knownPartyEntities) - { - _mainWindowViewModel.PartyMemberCircles.Add(new PartyMemberCircle() { Name = member.Value }); - } + foreach (var member in _knownPartyEntities) _mainWindowViewModel.PartyMemberCircles.Add(new PartyMemberCircle {Name = member.Value}); }); } @@ -167,10 +145,7 @@ public bool IsUserInParty(string name) public bool IsUserInParty(long objectId) { var entity = _knownEntities.FirstOrDefault(x => x.Value.ObjectId == objectId); - if (entity.Value == null) - { - return false; - } + if (entity.Value == null) return false; return _knownPartyEntities.Any(x => x.Value == entity.Value.Name); } @@ -183,36 +158,26 @@ public void SetCharacterEquipment(long objectId, CharacterEquipment equipment) { var entity = _knownEntities?.FirstOrDefault(x => x.Value.ObjectId == objectId); if (entity?.Value != null) - { entity.Value.Value.CharacterEquipment = equipment; - } else - { - _tempCharacterEquipmentData.TryAdd(objectId, new CharacterEquipmentData() + _tempCharacterEquipmentData.TryAdd(objectId, new CharacterEquipmentData { CharacterEquipment = equipment, TimeStamp = DateTime.UtcNow }); - } } public void ResetTempCharacterEquipment() { foreach (var characterEquipment in _tempCharacterEquipmentData) - { if (Utilities.IsBlockingTimeExpired(characterEquipment.Value.TimeStamp, 30)) - { _tempCharacterEquipmentData.TryRemove(characterEquipment.Key, out _); - } - } } public void AddEquipmentItem(EquipmentItem item) { - if (_newEquipmentItems.Any(x => x.ItemIndex.Equals(item.ItemIndex) && x.SpellDictionary.Values == item.SpellDictionary.Values) || item.SpellDictionary.Count <= 0) - { - return; - } + if (_newEquipmentItems.Any(x => x.ItemIndex.Equals(item.ItemIndex) && x.SpellDictionary.Values == item.SpellDictionary.Values) || + item.SpellDictionary.Count <= 0) return; lock (item) { @@ -224,15 +189,9 @@ public void AddEquipmentItem(EquipmentItem item) public void AddSpellEffect(SpellEffect spell) { - if (!IsUserInParty(spell.CauserId)) - { - return; - } + if (!IsUserInParty(spell.CauserId)) return; - if (_spellEffects.Any(x => x.CauserId.Equals(spell.CauserId) && x.SpellIndex.Equals(spell.SpellIndex))) - { - return; - } + if (_spellEffects.Any(x => x.CauserId.Equals(spell.CauserId) && x.SpellIndex.Equals(spell.SpellIndex))) return; lock (spell) { @@ -247,40 +206,30 @@ public void DetectUsedWeapon() var playerItemList = new Dictionary(); foreach (var item in _newEquipmentItems.ToList()) + foreach (var spell in from itemSpell in item.SpellDictionary + from spell in _spellEffects + where spell.SpellIndex.Equals(itemSpell.Value) + select spell) { - foreach (var spell in from itemSpell in item.SpellDictionary from spell in _spellEffects where spell.SpellIndex.Equals(itemSpell.Value) select spell) - { - if (playerItemList.Any(x => x.Key.Equals(spell.CauserId))) - { - continue; - } + if (playerItemList.Any(x => x.Key.Equals(spell.CauserId))) continue; - playerItemList.Add(spell.CauserId, item.ItemIndex); - } + playerItemList.Add(spell.CauserId, item.ItemIndex); } - foreach (var playerItem in playerItemList.ToList()) - { - SetCharacterMainHand(playerItem.Key, playerItem.Value); - } + foreach (var playerItem in playerItemList.ToList()) SetCharacterMainHand(playerItem.Key, playerItem.Value); } private void SetCharacterMainHand(long objectId, int itemIndex) { var entity = _knownEntities?.FirstOrDefault(x => x.Value.ObjectId == objectId); - if (entity?.Value == null) - { - return; - } + if (entity?.Value == null) return; if (entity.Value.Value?.CharacterEquipment == null) - { - entity.Value.Value.CharacterEquipment = new CharacterEquipment() + entity.Value.Value.CharacterEquipment = new CharacterEquipment { MainHand = itemIndex }; - } //if (entity.Value.Value != null) //{ @@ -291,20 +240,16 @@ private void SetCharacterMainHand(long objectId, int itemIndex) private void RemoveSpellAndEquipmentObjects() { foreach (var item in _newEquipmentItems.Where(x => x?.TimeStamp < DateTime.UtcNow.AddSeconds(-15)).ToList()) - { lock (item) { _newEquipmentItems.Remove(item); } - } foreach (var spell in _spellEffects.Where(x => x?.TimeStamp < DateTime.UtcNow.AddSeconds(-15)).ToList()) - { lock (spell) { _spellEffects.Remove(spell); } - } } public class CharacterEquipmentData @@ -319,26 +264,17 @@ public class CharacterEquipmentData public void ResetEntitiesDamageStartTime() { - foreach (var entity in _knownEntities) - { - entity.Value.CombatStart = null; - } + foreach (var entity in _knownEntities) entity.Value.CombatStart = null; } public void ResetEntitiesDamageTimes() { - foreach (var entity in _knownEntities) - { - entity.Value.ResetCombatTimes(); - } + foreach (var entity in _knownEntities) entity.Value.ResetCombatTimes(); } public void ResetEntitiesDamage() { - foreach (var entity in _knownEntities) - { - entity.Value.Damage = 0; - } + foreach (var entity in _knownEntities) entity.Value.Damage = 0; } #endregion diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/TrackingController.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/TrackingController.cs index edbee5eb2..a4870a31d 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/TrackingController.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Controller/TrackingController.cs @@ -18,21 +18,15 @@ namespace StatisticsAnalysisTool.Network.Controller { public class TrackingController { - public EntityController EntityController; - public DungeonController DungeonController; - public CombatController CombatController; - private const int _maxNotifications = 50; private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private readonly MainWindowViewModel _mainWindowViewModel; private readonly MainWindow _mainWindow; + private readonly MainWindowViewModel _mainWindowViewModel; private string _lastClusterHash; - - public ClusterInfo CurrentCluster { - get; - private set; - } + public CombatController CombatController; + public DungeonController DungeonController; + public EntityController EntityController; public TrackingController(MainWindowViewModel mainWindowViewModel, MainWindow mainWindow) { @@ -43,6 +37,8 @@ public TrackingController(MainWindowViewModel mainWindowViewModel, MainWindow ma CombatController = new CombatController(this, _mainWindow, mainWindowViewModel); } + public ClusterInfo CurrentCluster { get; private set; } + public void RegisterEvents() { EntityController.OnHealthUpdate += DamageMeterUpdate; @@ -52,26 +48,39 @@ public void UnregisterEvents() { EntityController.OnHealthUpdate -= DamageMeterUpdate; } - + + #region Trigger events + + public void DamageMeterUpdate(long objectId, GameTimeStamp timeStamp, double healthChange, double newHealthValue, EffectType effectType, + EffectOrigin effectOrigin, long causerId, int causingSpellType) + { + CombatController.AddDamage(causerId, healthChange); + } + + #endregion + + public bool IsMainWindowNull() + { + if (_mainWindow != null) return false; + + Log.Error($"{nameof(AddNotification)}: _mainWindow is null."); + return true; + } + #region Cluster - + public event Action OnChangeCluster; public void SetNewCluster(MapType mapType, Guid? mapGuid, string clusterIndex, string mainClusterIndex) { CurrentCluster = WorldData.GetClusterInfoByIndex(clusterIndex, mainClusterIndex, mapType, mapGuid); - if (!TryChangeCluster(CurrentCluster.Index, CurrentCluster.UniqueName)) - { - return; - } + if (!TryChangeCluster(CurrentCluster.Index, CurrentCluster.UniqueName)) return; - if (_mainWindowViewModel.IsDamageMeterResetByMapChangeActive) - { - CombatController.ResetDamageMeter(); - } + if (_mainWindowViewModel.IsDamageMeterResetByMapChangeActive) CombatController.ResetDamageMeter(); - Debug.Print($"[StateHandler] Changed cluster to: Index: '{CurrentCluster.Index}' UniqueName: '{CurrentCluster.UniqueName}' ClusterType: '{CurrentCluster.ClusterType}' MapType: '{CurrentCluster.MapType}'"); + Debug.Print( + $"[StateHandler] Changed cluster to: Index: '{CurrentCluster.Index}' UniqueName: '{CurrentCluster.UniqueName}' ClusterType: '{CurrentCluster.ClusterType}' MapType: '{CurrentCluster.MapType}'"); OnChangeCluster?.Invoke(CurrentCluster); } @@ -79,17 +88,14 @@ private bool TryChangeCluster(string index, string mapName) { var newClusterHash = index + mapName; - if (_lastClusterHash == newClusterHash) - { - return false; - } + if (_lastClusterHash == newClusterHash) return false; _lastClusterHash = newClusterHash; return true; } #endregion - + #region Set Main Window values public void SetTotalPlayerFame(double value) @@ -108,46 +114,30 @@ public void SetTotalPlayerReSpecPoints(double value) } #endregion - + #region Notifications public void AddNotification(TrackingNotification item) { - if (IsMainWindowNull() || _mainWindowViewModel.TrackingNotifications == null) - { - return; - } + if (IsMainWindowNull() || _mainWindowViewModel.TrackingNotifications == null) return; if (_mainWindow.Dispatcher.CheckAccess()) - { _mainWindowViewModel.TrackingNotifications.Insert(0, item); - } else - { - _mainWindow.Dispatcher.Invoke(delegate - { - _mainWindowViewModel.TrackingNotifications.Insert(0, item); - }); - } + _mainWindow.Dispatcher.Invoke(delegate { _mainWindowViewModel.TrackingNotifications.Insert(0, item); }); RemovesUnnecessaryNotifications(); } public void RemovesUnnecessaryNotifications() { - if (IsMainWindowNull() || _mainWindowViewModel.TrackingNotifications == null) - { - return; - } + if (IsMainWindowNull() || _mainWindowViewModel.TrackingNotifications == null) return; try { while (true) { - if (_mainWindowViewModel.TrackingNotifications?.Count <= _maxNotifications) - { - break; - } + if (_mainWindowViewModel.TrackingNotifications?.Count <= _maxNotifications) break; var dateTime = GetLowestDate(_mainWindowViewModel.TrackingNotifications); if (dateTime != null) @@ -156,16 +146,9 @@ public void RemovesUnnecessaryNotifications() if (removableItem != null) { if (_mainWindow.Dispatcher.CheckAccess()) - { _mainWindowViewModel.TrackingNotifications.Remove(removableItem); - } else - { - _mainWindow.Dispatcher.Invoke(delegate - { - _mainWindowViewModel.TrackingNotifications.Remove(removableItem); - }); - } + _mainWindow.Dispatcher.Invoke(delegate { _mainWindowViewModel.TrackingNotifications.Remove(removableItem); }); } } } @@ -178,10 +161,7 @@ public void RemovesUnnecessaryNotifications() private static DateTime? GetLowestDate(ObservableCollection items) { - if (items.IsNullOrEmpty()) - { - return null; - } + if (items.IsNullOrEmpty()) return null; try { @@ -194,33 +174,11 @@ public void RemovesUnnecessaryNotifications() return null; } } - - #endregion - - #region Dungeon - - #endregion - #region Trigger events - - public void DamageMeterUpdate(long objectId, GameTimeStamp timeStamp, double healthChange, double newHealthValue, EffectType effectType, EffectOrigin effectOrigin, long causerId, int causingSpellType) - { - CombatController.AddDamage(causerId, healthChange); - } + #region Dungeon #endregion - - public bool IsMainWindowNull() - { - if (_mainWindow != null) - { - return false; - } - - Log.Error($"{nameof(AddNotification)}: _mainWindow is null."); - return true; - } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/ActiveSpellEffectsUpdateEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/ActiveSpellEffectsUpdateEvent.cs index 826768ea9..9f0aec3d4 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/ActiveSpellEffectsUpdateEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/ActiveSpellEffectsUpdateEvent.cs @@ -1,8 +1,8 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Events { @@ -12,17 +12,14 @@ public ActiveSpellEffectsUpdateEvent(Dictionary parameters) : base { try { - if (parameters.ContainsKey(0)) - { - CauserId = parameters[0].ObjectToLong(); - } + if (parameters.ContainsKey(0)) CauserId = parameters[0].ObjectToLong(); if (parameters.ContainsKey(1)) { var valueType = parameters[1].GetType(); if (valueType.IsArray && typeof(short[]).Name == valueType.Name) { - var spells = ((short[])parameters[1]).ToDictionary(); + var spells = ((short[]) parameters[1]).ToDictionary(); SpellIndex = spells[0].ObjectToInt(); } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/CharacterEquipmentChangedEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/CharacterEquipmentChangedEvent.cs index beca74599..9de04e80d 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/CharacterEquipmentChangedEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/CharacterEquipmentChangedEvent.cs @@ -1,9 +1,9 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Models.NetworkModel; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Models.NetworkModel; namespace StatisticsAnalysisTool.Network.Events { @@ -13,17 +13,14 @@ public CharacterEquipmentChangedEvent(Dictionary parameters) : bas { try { - if (parameters.ContainsKey(0)) - { - ObjectId = parameters[0].ObjectToLong(); - } + if (parameters.ContainsKey(0)) ObjectId = parameters[0].ObjectToLong(); if (parameters.ContainsKey(2)) { var valueType = parameters[2].GetType(); if (valueType.IsArray && typeof(short[]).Name == valueType.Name) { - var equipment = ((short[])parameters[2]).ToDictionary(); + var equipment = ((short[]) parameters[2]).ToDictionary(); CharacterEquipment.MainHand = equipment[0].ObjectToInt(); CharacterEquipment.OffHand = equipment[1].ObjectToInt(); CharacterEquipment.Head = equipment[2].ObjectToInt(); diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/DiedEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/DiedEvent.cs index d1a22161d..a6b45285f 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/DiedEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/DiedEvent.cs @@ -1,7 +1,7 @@ -using Albion.Network; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Events { @@ -16,20 +16,12 @@ public DiedEvent(Dictionary parameters) : base(parameters) // Debug.Print($"{parameter}"); //} - if (parameters.ContainsKey(2)) - { - Died = string.IsNullOrEmpty(parameters[2].ToString()) ? string.Empty : parameters[2].ToString(); - } + if (parameters.ContainsKey(2)) Died = string.IsNullOrEmpty(parameters[2].ToString()) ? string.Empty : parameters[2].ToString(); - if (parameters.ContainsKey(4)) - { - KilledBy = string.IsNullOrEmpty(parameters[4].ToString()) ? string.Empty : parameters[4].ToString(); - } + if (parameters.ContainsKey(4)) KilledBy = string.IsNullOrEmpty(parameters[4].ToString()) ? string.Empty : parameters[4].ToString(); if (parameters.ContainsKey(5)) - { KilledByGuild = string.IsNullOrEmpty(parameters[5].ToString()) ? string.Empty : parameters[5].ToString(); - } } catch (Exception e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/HealthUpdateEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/HealthUpdateEvent.cs index aeb90cd9e..4a9663b8c 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/HealthUpdateEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/HealthUpdateEvent.cs @@ -1,17 +1,26 @@ -using Albion.Network; +using System; +using System.Collections.Generic; +using System.Reflection; +using Albion.Network; using log4net; using StatisticsAnalysisTool.Common; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Time; -using System; -using System.Collections.Generic; -using System.Reflection; namespace StatisticsAnalysisTool.Network.Handler { public class HealthUpdateEvent : BaseEvent { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public long CauserId; + public int CausingSpellType; + public EffectOrigin EffectOrigin; + public EffectType EffectType; + public double HealthChange; + public double NewHealthValue; + + public long ObjectId; + public GameTimeStamp TimeStamp; public HealthUpdateEvent(Dictionary parameters) : base(parameters) { @@ -23,59 +32,26 @@ public HealthUpdateEvent(Dictionary parameters) : base(parameters) // Debug.Print($"{parameter}"); //} - if (parameters.ContainsKey(0)) - { - ObjectId = parameters[0].ObjectToLong() ?? throw new ArgumentNullException(); - } + if (parameters.ContainsKey(0)) ObjectId = parameters[0].ObjectToLong() ?? throw new ArgumentNullException(); - if (parameters.ContainsKey(1)) - { - TimeStamp = new GameTimeStamp(parameters[1].ObjectToLong() ?? 0); - } + if (parameters.ContainsKey(1)) TimeStamp = new GameTimeStamp(parameters[1].ObjectToLong() ?? 0); - if (parameters.ContainsKey(2)) - { - HealthChange = parameters[2].ObjectToDouble(); - } + if (parameters.ContainsKey(2)) HealthChange = parameters[2].ObjectToDouble(); - if (parameters.ContainsKey(3)) - { - NewHealthValue = parameters[3].ObjectToDouble(); - } + if (parameters.ContainsKey(3)) NewHealthValue = parameters[3].ObjectToDouble(); - if (parameters.ContainsKey(4)) - { - EffectType = (EffectType) (parameters[4] as byte? ?? 0); - } + if (parameters.ContainsKey(4)) EffectType = (EffectType) (parameters[4] as byte? ?? 0); - if (parameters.ContainsKey(5)) - { - EffectOrigin = (EffectOrigin) (parameters[5] as byte? ?? 0); - } + if (parameters.ContainsKey(5)) EffectOrigin = (EffectOrigin) (parameters[5] as byte? ?? 0); - if (parameters.ContainsKey(6)) - { - CauserId = parameters[6].ObjectToLong() ?? throw new ArgumentNullException(); - } + if (parameters.ContainsKey(6)) CauserId = parameters[6].ObjectToLong() ?? throw new ArgumentNullException(); - if (parameters.ContainsKey(7)) - { - CausingSpellType = parameters[7].ObjectToShort(); - } + if (parameters.ContainsKey(7)) CausingSpellType = parameters[7].ObjectToShort(); } catch (Exception e) { Log.Error(nameof(UpdateMoneyEvent), e); } } - - public long ObjectId; - public GameTimeStamp TimeStamp; - public double HealthChange; - public double NewHealthValue; - public EffectType EffectType; - public EffectOrigin EffectOrigin; - public long CauserId; - public int CausingSpellType; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/InCombatStateUpdateEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/InCombatStateUpdateEvent.cs index 89e163f2f..e0bce332b 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/InCombatStateUpdateEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/InCombatStateUpdateEvent.cs @@ -1,43 +1,34 @@ -using Albion.Network; -using log4net; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Reflection; +using Albion.Network; +using log4net; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Handler { public class InCombatStateUpdateEvent : BaseEvent { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public bool InActiveCombat; + public bool InPassiveCombat; + + public long? ObjectId; public InCombatStateUpdateEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(0)) - { - ObjectId = parameters[0].ObjectToLong(); - } + if (parameters.ContainsKey(0)) ObjectId = parameters[0].ObjectToLong(); - if (parameters.ContainsKey(1)) - { - InActiveCombat = parameters[1] as bool? ?? false; - } + if (parameters.ContainsKey(1)) InActiveCombat = parameters[1] as bool? ?? false; - if (parameters.ContainsKey(2)) - { - InPassiveCombat = parameters[2] as bool? ?? false; - } + if (parameters.ContainsKey(2)) InPassiveCombat = parameters[2] as bool? ?? false; } - catch(Exception e) + catch (Exception e) { Log.Error(nameof(UpdateMoneyEvent), e); } } - - public long? ObjectId; - public bool InActiveCombat; - public bool InPassiveCombat; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LeaveEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LeaveEvent.cs index 1ab3a4566..f1393bbe7 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LeaveEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LeaveEvent.cs @@ -1,8 +1,8 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Events { @@ -12,10 +12,7 @@ public LeaveEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(0)) - { - ObjectId = parameters[0].ObjectToLong(); - } + if (parameters.ContainsKey(0)) ObjectId = parameters[0].ObjectToLong(); } catch (Exception e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LootChestOpenedEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LootChestOpenedEvent.cs index 2f4c0a180..457ad8d63 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LootChestOpenedEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/LootChestOpenedEvent.cs @@ -1,7 +1,7 @@ -using Albion.Network; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Events { @@ -11,11 +11,7 @@ public LootChestOpenedEvent(Dictionary parameters) : base(paramete { try { - if (parameters.ContainsKey(0) && int.TryParse(parameters[0].ToString(), out var id)) - { - Id = id; - } - + if (parameters.ContainsKey(0) && int.TryParse(parameters[0].ToString(), out var id)) Id = id; } catch (Exception e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewCharacterEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewCharacterEvent.cs index 14da90355..78b6dacc2 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewCharacterEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewCharacterEvent.cs @@ -1,8 +1,8 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Events { @@ -12,30 +12,15 @@ public NewCharacterEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(0)) - { - ObjectId = parameters[0].ObjectToLong(); - } + if (parameters.ContainsKey(0)) ObjectId = parameters[0].ObjectToLong(); - if (parameters.ContainsKey(1)) - { - Name = parameters[1].ToString(); - } + if (parameters.ContainsKey(1)) Name = parameters[1].ToString(); - if (parameters.ContainsKey(7)) - { - Guid = parameters[7].ObjectToGuid(); - } + if (parameters.ContainsKey(7)) Guid = parameters[7].ObjectToGuid(); - if (parameters.ContainsKey(8)) - { - GuildName = parameters[8].ToString(); - } + if (parameters.ContainsKey(8)) GuildName = parameters[8].ToString(); - if (parameters.ContainsKey(12)) - { - Position = (float[])parameters[12]; - } + if (parameters.ContainsKey(12)) Position = (float[]) parameters[12]; } catch (Exception e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewEquipmentItemEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewEquipmentItemEvent.cs index 006ec08e9..2d70bd7c5 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewEquipmentItemEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewEquipmentItemEvent.cs @@ -1,9 +1,8 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Events { @@ -13,37 +12,25 @@ public NewEquipmentItemEvent(Dictionary parameters) : base(paramet { try { - if (parameters.ContainsKey(1)) - { - ItemIndex = parameters[1].ObjectToInt(); - } + if (parameters.ContainsKey(1)) ItemIndex = parameters[1].ObjectToInt(); if (parameters.ContainsKey(8)) { var valueType = parameters[8].GetType(); if (valueType.IsArray && typeof(byte[]).Name == valueType.Name) { - var spells = ((byte[])parameters[8]).ToDictionary(); - foreach (var spell in spells) - { - SpellDictionary.Add(spell.Key, spell.Value.ObjectToInt()); - } + var spells = ((byte[]) parameters[8]).ToDictionary(); + foreach (var spell in spells) SpellDictionary.Add(spell.Key, spell.Value.ObjectToInt()); } - else if(valueType.IsArray && typeof(short[]).Name == valueType.Name) + else if (valueType.IsArray && typeof(short[]).Name == valueType.Name) { - var spells = ((short[])parameters[8]).ToDictionary(); - foreach (var spell in spells) - { - SpellDictionary.Add(spell.Key, spell.Value.ObjectToInt()); - } + var spells = ((short[]) parameters[8]).ToDictionary(); + foreach (var spell in spells) SpellDictionary.Add(spell.Key, spell.Value.ObjectToInt()); } else if (valueType.IsArray && typeof(int[]).Name == valueType.Name) { - var spells = ((int[])parameters[8]).ToDictionary(); - foreach (var spell in spells) - { - SpellDictionary.Add(spell.Key, spell.Value.ObjectToInt()); - } + var spells = ((int[]) parameters[8]).ToDictionary(); + foreach (var spell in spells) SpellDictionary.Add(spell.Key, spell.Value.ObjectToInt()); } } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootChestEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootChestEvent.cs index 2aa5294a2..2ced43fa6 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootChestEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootChestEvent.cs @@ -1,7 +1,7 @@ -using Albion.Network; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Events { @@ -11,22 +11,16 @@ public NewLootChestEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(0) && int.TryParse(parameters[0].ToString(), out var id)) - { - Id = id; - } + if (parameters.ContainsKey(0) && int.TryParse(parameters[0].ToString(), out var id)) Id = id; - if (parameters.ContainsKey(3)) - { - UniqueName = string.IsNullOrEmpty(parameters[3].ToString()) ? string.Empty : parameters[3].ToString(); - } + if (parameters.ContainsKey(3)) UniqueName = string.IsNullOrEmpty(parameters[3].ToString()) ? string.Empty : parameters[3].ToString(); //if (parameters.ContainsKey(4)) //{ // UniqueNameArea? = string.IsNullOrEmpty(parameters[4].ToString()) ? string.Empty : parameters[4].ToString(); //} } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootEvent.cs index e76310a79..a1a521ca2 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewLootEvent.cs @@ -1,7 +1,7 @@ -using Albion.Network; -using StatisticsAnalysisTool.Models.NetworkModel; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Models.NetworkModel; namespace StatisticsAnalysisTool.Network.Events { @@ -15,11 +15,11 @@ public NewLootEvent(Dictionary parameters) : base(parameters) var containerId = parameters[0].ToString(); // 2 = mob id? - var bodyName = (string)parameters[3]; + var bodyName = (string) parameters[3]; var container = new Container { - Id = containerId, Owner = bodyName, + Id = containerId, Owner = bodyName, Type = BodyName.StartsWith("@MOB") ? ContainerType.Monster : ContainerType.Player }; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewMobEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewMobEvent.cs index b4b53b9b7..ed8ec0337 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewMobEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewMobEvent.cs @@ -1,8 +1,8 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Events { @@ -10,7 +10,7 @@ public class NewMobEvent : BaseEvent { public NewMobEvent(Dictionary parameters) : base(parameters) { - Debug.Print($"--- NewMob (Event) ---"); + Debug.Print("--- NewMob (Event) ---"); //foreach (var parameter in parameters) //{ // Debug.Print($"{parameter}"); @@ -18,15 +18,9 @@ public NewMobEvent(Dictionary parameters) : base(parameters) try { - if (parameters.ContainsKey(0)) - { - ObjectId = parameters[0].ObjectToLong(); - } + if (parameters.ContainsKey(0)) ObjectId = parameters[0].ObjectToLong(); - if (parameters.ContainsKey(1)) - { - Type = parameters[1].ObjectToLong() ?? 0; - } + if (parameters.ContainsKey(1)) Type = parameters[1].ObjectToLong() ?? 0; Debug.Print($"ObjectId: {ObjectId} | Type: {Type}"); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewShrineEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewShrineEvent.cs index 5f31ca8fc..3ec8c76c3 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewShrineEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/NewShrineEvent.cs @@ -1,9 +1,9 @@ -using Albion.Network; -using log4net; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; +using Albion.Network; +using log4net; namespace StatisticsAnalysisTool.Network.Handler { @@ -11,34 +11,25 @@ public class NewShrineEvent : BaseEvent { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public bool InActiveCombat; + public bool InPassiveCombat; + public NewShrineEvent(Dictionary parameters) : base(parameters) { try { - Debug.Print($"----- NewShrineEvent (Event) -----"); + Debug.Print("----- NewShrineEvent (Event) -----"); - foreach (var parameter in parameters) - { - Debug.Print($"{parameter}"); - } + foreach (var parameter in parameters) Debug.Print($"{parameter}"); - if (parameters.ContainsKey(1)) - { - InActiveCombat = parameters[1] as bool? ?? false; - } + if (parameters.ContainsKey(1)) InActiveCombat = parameters[1] as bool? ?? false; - if (parameters.ContainsKey(2)) - { - InPassiveCombat = parameters[2] as bool? ?? false; - } + if (parameters.ContainsKey(2)) InPassiveCombat = parameters[2] as bool? ?? false; } - catch(Exception e) + catch (Exception e) { Log.Error(nameof(UpdateMoneyEvent), e); } } - - public bool InActiveCombat; - public bool InPassiveCombat; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyChangedOrderEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyChangedOrderEvent.cs index 4a1b0ff59..05a1da32d 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyChangedOrderEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyChangedOrderEvent.cs @@ -1,34 +1,28 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Handler { public class PartyChangedOrderEvent : BaseEvent { + public Guid? UserGuid; + public string Username; + public PartyChangedOrderEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(1)) - { - UserGuid = parameters[1].ObjectToGuid(); - } + if (parameters.ContainsKey(1)) UserGuid = parameters[1].ObjectToGuid(); - if (parameters.ContainsKey(2)) - { - Username = string.IsNullOrEmpty(parameters[2].ToString()) ? string.Empty : parameters[2].ToString(); - } + if (parameters.ContainsKey(2)) Username = string.IsNullOrEmpty(parameters[2].ToString()) ? string.Empty : parameters[2].ToString(); } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } } - - public Guid? UserGuid; - public string Username; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyDisbandedEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyDisbandedEvent.cs index 7898cd5b9..d61246405 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyDisbandedEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartyDisbandedEvent.cs @@ -1,40 +1,36 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Handler { public class PartyDisbandedEvent : BaseEvent { + public Dictionary PartyUsersGuid = new Dictionary(); + public PartyDisbandedEvent(Dictionary parameters) : base(parameters) { try { if (parameters.ContainsKey(0) && parameters[0] != null) { - var partyUsersByteArrays = ((object[])parameters[4]).ToDictionary(); - var partyUserNameArray = ((string[])parameters[5]).ToDictionary(); + var partyUsersByteArrays = ((object[]) parameters[4]).ToDictionary(); + var partyUserNameArray = ((string[]) parameters[5]).ToDictionary(); for (var i = 0; i < partyUsersByteArrays.Count; i++) { var guid = partyUsersByteArrays[i].ObjectToGuid(); var name = partyUserNameArray[i]; - if (guid != null && !string.IsNullOrEmpty(name)) - { - PartyUsersGuid.Add((Guid)guid, name); - } + if (guid != null && !string.IsNullOrEmpty(name)) PartyUsersGuid.Add((Guid) guid, name); } } } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } } - - public Dictionary PartyUsersGuid = new Dictionary(); } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartySilverGainedEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartySilverGainedEvent.cs index 81b8e21cf..b8c2f4438 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartySilverGainedEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/PartySilverGainedEvent.cs @@ -1,53 +1,39 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Network.Time; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Network.Time; namespace StatisticsAnalysisTool.Network.Events { public class PartySilverGainedEvent : BaseEvent { + public FixPoint SilverNet; + public FixPoint SilverPreTax; + public long? TargetEntityId; + + public GameTimeStamp TimeStamp; + public PartySilverGainedEvent(Dictionary parameters) : base(parameters) { try { - Debug.Print($"--- PartySilverGained (Event) ---"); - foreach (var parameter in parameters) - { - Debug.Print($"{parameter}"); - } + Debug.Print("--- PartySilverGained (Event) ---"); + foreach (var parameter in parameters) Debug.Print($"{parameter}"); - if (parameters.ContainsKey(0)) - { - TimeStamp = new GameTimeStamp(parameters[0].ObjectToLong()?? 0); - } + if (parameters.ContainsKey(0)) TimeStamp = new GameTimeStamp(parameters[0].ObjectToLong() ?? 0); - if (parameters.ContainsKey(1)) - { - TargetEntityId = parameters[1].ObjectToLong(); - } + if (parameters.ContainsKey(1)) TargetEntityId = parameters[1].ObjectToLong(); - if (parameters.ContainsKey(2)) - { - SilverNet = FixPoint.FromInternalValue(parameters[2].ObjectToLong()?? 0); - } + if (parameters.ContainsKey(2)) SilverNet = FixPoint.FromInternalValue(parameters[2].ObjectToLong() ?? 0); - if (parameters.ContainsKey(3)) - { - SilverPreTax = FixPoint.FromInternalValue(parameters[3].ObjectToLong()?? 0); - } + if (parameters.ContainsKey(3)) SilverPreTax = FixPoint.FromInternalValue(parameters[3].ObjectToLong() ?? 0); } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } } - - public GameTimeStamp TimeStamp; - public long? TargetEntityId; - public FixPoint SilverNet; - public FixPoint SilverPreTax; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/SiegeCampClaimStartEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/SiegeCampClaimStartEvent.cs index 8068954f5..51b7a30fc 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/SiegeCampClaimStartEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/SiegeCampClaimStartEvent.cs @@ -1,27 +1,24 @@ -using Albion.Network; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Handler { public class SiegeCampClaimStartEvent : BaseEvent { + public string Username; + public SiegeCampClaimStartEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(2)) - { - Username = string.IsNullOrEmpty(parameters[2].ToString()) ? string.Empty : parameters[2].ToString(); - } + if (parameters.ContainsKey(2)) Username = string.IsNullOrEmpty(parameters[2].ToString()) ? string.Empty : parameters[2].ToString(); } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } } - - public string Username; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TakeSilverEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TakeSilverEvent.cs index af394fa0e..74090d4be 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TakeSilverEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TakeSilverEvent.cs @@ -1,26 +1,32 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Handler { public class TakeSilverEvent : BaseEvent { + public bool ClusterBonus; // 9? + public FixPoint ClusterTax; + public FixPoint GuildTax; + public FixPoint Multiplier; + public bool PremiumBonus; + public long? TargetEntityId; + + public long TimeStamp; + + public FixPoint YieldAfterTax; + public FixPoint YieldPreTax; + public TakeSilverEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(1)) - { - TimeStamp = parameters[1].ObjectToLong() ?? 0; - } + if (parameters.ContainsKey(1)) TimeStamp = parameters[1].ObjectToLong() ?? 0; - if (parameters.ContainsKey(2)) - { - TargetEntityId = parameters[2].ObjectToLong(); - } + if (parameters.ContainsKey(2)) TargetEntityId = parameters[2].ObjectToLong(); if (parameters.ContainsKey(3)) { @@ -40,10 +46,7 @@ public TakeSilverEvent(Dictionary parameters) : base(parameters) ClusterTax = FixPoint.FromInternalValue(clusterTax ?? 0); } - if (parameters.ContainsKey(7)) - { - PremiumBonus = parameters[7] as bool? ?? false; - } + if (parameters.ContainsKey(7)) PremiumBonus = parameters[7] as bool? ?? false; if (parameters.ContainsKey(8)) { @@ -53,21 +56,10 @@ public TakeSilverEvent(Dictionary parameters) : base(parameters) YieldAfterTax = YieldPreTax - GuildTax; } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } } - - public long TimeStamp; - public long? TargetEntityId; - public FixPoint YieldPreTax; - public FixPoint GuildTax; - public FixPoint ClusterTax; - public bool PremiumBonus; - public FixPoint Multiplier; - public bool ClusterBonus; // 9? - - public FixPoint YieldAfterTax; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent.cs index ffadc5061..d48de10e5 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent.cs @@ -1,47 +1,37 @@ -using Albion.Network; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Events { public class TestEvent : BaseOperation { + public string ClusterMap; + + public string ClusterName; + + public string ClusterOwner; + public TestEvent(Dictionary parameters) : base(parameters) { - Debug.Print($"----- ChangeCluster -----"); + Debug.Print("----- ChangeCluster -----"); try { - foreach (var parameter in parameters) - { - Debug.Print($"{parameter}"); - } + foreach (var parameter in parameters) Debug.Print($"{parameter}"); - if (parameters.ContainsKey(0)) - { - ClusterName = string.IsNullOrEmpty(parameters[0].ToString()) ? string.Empty : parameters[0].ToString(); - } + if (parameters.ContainsKey(0)) ClusterName = string.IsNullOrEmpty(parameters[0].ToString()) ? string.Empty : parameters[0].ToString(); if (parameters.ContainsKey(255)) - { ClusterMap = string.IsNullOrEmpty(parameters[255].ToString()) ? string.Empty : parameters[255].ToString(); - } if (parameters.ContainsKey(253)) - { ClusterOwner = string.IsNullOrEmpty(parameters[253].ToString()) ? string.Empty : parameters[253].ToString(); - } } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } } - - public string ClusterName; - - public string ClusterMap; - - public string ClusterOwner; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent2.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent2.cs index bdad6470b..3127ac218 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent2.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent2.cs @@ -1,7 +1,7 @@ -using Albion.Network; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Events { @@ -9,16 +9,13 @@ public class TestEvent2 : BaseEvent { public TestEvent2(Dictionary parameters) : base(parameters) { - Debug.Print($"----- NewMob (Events) -----"); + Debug.Print("----- NewMob (Events) -----"); try { - foreach (var parameter in parameters) - { - Debug.Print($"{parameter}"); - } + foreach (var parameter in parameters) Debug.Print($"{parameter}"); } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent3.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent3.cs index 98f4f152d..bdb25a023 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent3.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/TestEvent3.cs @@ -1,7 +1,7 @@ -using Albion.Network; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Events { @@ -9,16 +9,13 @@ public class TestEvent3 : BaseOperation { public TestEvent3(Dictionary parameters) : base(parameters) { - Debug.Print($"----- Join (Operations) -----"); + Debug.Print("----- Join (Operations) -----"); try { - foreach (var parameter in parameters) - { - Debug.Print($"{parameter}"); - } + foreach (var parameter in parameters) Debug.Print($"{parameter}"); } - catch(Exception e) + catch (Exception e) { Debug.Print(e.Message); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateFameEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateFameEvent.cs index f7d68eed8..22d7515e5 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateFameEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateFameEvent.cs @@ -1,13 +1,20 @@ -using Albion.Network; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; +using Albion.Network; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Handler { public class UpdateFameEvent : BaseEvent { + public float BonusFactor; + public FixPoint Change; // Fame with Zone Multiplier and without Premium + public byte GroupSize; + public bool IsPremiumBonus; + public FixPoint SatchelFame; + public int UsedItemType; + public UpdateFameEvent(Dictionary parameters) : base(parameters) { // Array[10] exist only by Crafting... @@ -24,41 +31,20 @@ public UpdateFameEvent(Dictionary parameters) : base(parameters) var totalPlayerFame = parameters[1] as long? ?? 0; TotalPlayerFame = FixPoint.FromInternalValue(totalPlayerFame); } - - if (parameters.ContainsKey(2)) - { - Change = FixPoint.FromInternalValue(parameters[2].ObjectToLong() ?? 0); - } - if (parameters.ContainsKey(3)) - { - GroupSize = parameters[3] as byte? ?? 0; - } + if (parameters.ContainsKey(2)) Change = FixPoint.FromInternalValue(parameters[2].ObjectToLong() ?? 0); - if (parameters.ContainsKey(4)) - { - Multiplier = FixPoint.FromInternalValue(parameters[4].ObjectToLong() ?? 0); - } + if (parameters.ContainsKey(3)) GroupSize = parameters[3] as byte? ?? 0; - if (parameters.ContainsKey(5)) - { - IsPremiumBonus = parameters[5] as bool? ?? false; - } + if (parameters.ContainsKey(4)) Multiplier = FixPoint.FromInternalValue(parameters[4].ObjectToLong() ?? 0); - if (parameters.ContainsKey(6)) - { - BonusFactor = parameters[6] as float? ?? 0; - } + if (parameters.ContainsKey(5)) IsPremiumBonus = parameters[5] as bool? ?? false; - if (parameters.ContainsKey(9)) - { - SatchelFame = FixPoint.FromInternalValue(parameters[9].ObjectToLong() ?? 0); - } + if (parameters.ContainsKey(6)) BonusFactor = parameters[6] as float? ?? 0; - if (parameters.ContainsKey(252)) - { - UsedItemType = parameters[252].ObjectToInt(); - } + if (parameters.ContainsKey(9)) SatchelFame = FixPoint.FromInternalValue(parameters[9].ObjectToLong() ?? 0); + + if (parameters.ContainsKey(252)) UsedItemType = parameters[252].ObjectToInt(); if (Change.DoubleValue > 0 && Multiplier.DoubleValue > 0) { @@ -70,13 +56,9 @@ public UpdateFameEvent(Dictionary parameters) : base(parameters) if (Change.DoubleValue > 0) { if (IsPremiumBonus) - { fameWithZoneAndPremium = Change.DoubleValue * 1.5f; - } else - { fameWithZoneAndPremium = Change.DoubleValue; - } } if (fameWithZoneAndPremium > 0 && Change.DoubleValue > 0) @@ -86,9 +68,7 @@ public UpdateFameEvent(Dictionary parameters) : base(parameters) } if (Change.InternalValue >= NormalFame.InternalValue) - { ZoneFame = FixPoint.FromInternalValue(Change.InternalValue - NormalFame.InternalValue); - } TotalGainedFame = NormalFame + ZoneFame + PremiumFame + SatchelFame; } @@ -99,13 +79,7 @@ public UpdateFameEvent(Dictionary parameters) : base(parameters) } public FixPoint TotalPlayerFame { get; } - public FixPoint Change; // Fame with Zone Multiplier and without Premium - public byte GroupSize; public FixPoint Multiplier { get; } - public bool IsPremiumBonus; - public float BonusFactor; - public FixPoint SatchelFame; - public int UsedItemType; public FixPoint NormalFame { get; } public FixPoint PremiumFame { get; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateMoneyEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateMoneyEvent.cs index 12b851b57..69177d694 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateMoneyEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateMoneyEvent.cs @@ -1,9 +1,9 @@ -using Albion.Network; -using log4net; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; +using Albion.Network; +using log4net; namespace StatisticsAnalysisTool.Network { @@ -15,15 +15,11 @@ public UpdateMoneyEvent(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(1) && long.TryParse(parameters[1].ToString(), out long currentPlayerSilver)) - { + if (parameters.ContainsKey(1) && long.TryParse(parameters[1].ToString(), out var currentPlayerSilver)) CurrentPlayerSilver = currentPlayerSilver / 10000d; - } - if (parameters.ContainsKey(2) && long.TryParse(parameters[2].ToString(), out long currentPlayerGold)) - { + if (parameters.ContainsKey(2) && long.TryParse(parameters[2].ToString(), out var currentPlayerGold)) CurrentPlayerGold = currentPlayerGold / 10000d; - } } catch (ArgumentNullException e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateReSpecPointsEvent.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateReSpecPointsEvent.cs index fe9f17169..c60910985 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateReSpecPointsEvent.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Events/UpdateReSpecPointsEvent.cs @@ -1,12 +1,11 @@ -using Albion.Network; -using log4net; -using PcapDotNet.Base; -using StatisticsAnalysisTool.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Reflection; +using Albion.Network; +using log4net; +using PcapDotNet.Base; +using StatisticsAnalysisTool.Common; namespace StatisticsAnalysisTool.Network.Events { @@ -20,20 +19,19 @@ public UpdateReSpecPointsEvent(Dictionary parameters) : base(param { if (parameters.ContainsKey(0) && parameters[0] != null) { - var reSpecPointsArray = ((long[])parameters[0]).ToDictionary(); + var reSpecPointsArray = ((long[]) parameters[0]).ToDictionary(); - if (!reSpecPointsArray.IsNullOrEmpty() && reSpecPointsArray.ContainsKey(1) && long.TryParse(reSpecPointsArray[1].ToString(), out long currentReSpecPoints)) - { + if (!reSpecPointsArray.IsNullOrEmpty() && reSpecPointsArray.ContainsKey(1) && + long.TryParse(reSpecPointsArray[1].ToString(), out var currentReSpecPoints)) CurrentReSpecPoints = currentReSpecPoints / 10000d; - } } } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Log.Error(nameof(UpdateReSpecPointsEvent), e); Debug.Print(e.Message); } - catch(InvalidCastException e) + catch (InvalidCastException e) { Log.Error(nameof(UpdateReSpecPointsEvent), e); Debug.Print(e.Message); diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/FameCountUpTimer.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/FameCountUpTimer.cs index 2b1d743b6..6e617b46d 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/FameCountUpTimer.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/FameCountUpTimer.cs @@ -1,26 +1,26 @@ -using log4net; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Models.NetworkModel; -using StatisticsAnalysisTool.ViewModels; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; +using log4net; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Models.NetworkModel; +using StatisticsAnalysisTool.ViewModels; namespace StatisticsAnalysisTool.Network { public class FameCountUpTimer : ICountUpTimer { - private readonly MainWindowViewModel _mainWindowViewModel; private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private readonly List _famePerHourList = new List(); + private readonly MainWindowViewModel _mainWindowViewModel; private bool _isCurrentTimerUpdateActive; private DateTime _startTime; - private double _totalGainedFame; private int? _taskId; - - private readonly List _famePerHourList = new List(); + private double _totalGainedFame; public FameCountUpTimer(MainWindowViewModel mainWindowViewModel) { @@ -29,7 +29,7 @@ public FameCountUpTimer(MainWindowViewModel mainWindowViewModel) public void Add(double value) { - _famePerHourList.Add(new ValuePerHour() { DateTime = DateTime.Now, Value = value }); + _famePerHourList.Add(new ValuePerHour {DateTime = DateTime.Now, Value = value}); _famePerHourList.RemoveAll(x => x.DateTime < DateTime.Now.AddHours(-1)); _totalGainedFame = _famePerHourList.Sum(x => x.Value); @@ -38,15 +38,9 @@ public void Add(double value) public void Start() { - if (_isCurrentTimerUpdateActive) - { - return; - } + if (_isCurrentTimerUpdateActive) return; - if (_startTime.Millisecond <= 0) - { - _startTime = DateTime.Now; - } + if (_startTime.Millisecond <= 0) _startTime = DateTime.Now; CurrentTimerUpdate(); } @@ -67,10 +61,7 @@ public void Reset() private void CurrentTimerUpdate() { - if (_isCurrentTimerUpdateActive) - { - return; - } + if (_isCurrentTimerUpdateActive) return; _isCurrentTimerUpdateActive = true; @@ -87,17 +78,11 @@ private void CurrentTimerUpdate() private void KillTimerTask(int? taskId) { - if (taskId == null) - { - return; - } + if (taskId == null) return; try { - if (Process.GetProcesses().Any(x => x.Id == (int)taskId)) - { - Process.GetProcessById((int)taskId).Kill(); - } + if (Process.GetProcesses().Any(x => x.Id == (int) taskId)) Process.GetProcessById((int) taskId).Kill(); } catch (Exception e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ActiveSpellEffectsUpdateEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ActiveSpellEffectsUpdateEventHandler.cs index 73747c655..8ee01fb3b 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ActiveSpellEffectsUpdateEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ActiveSpellEffectsUpdateEventHandler.cs @@ -1,16 +1,17 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Common; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Models; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class ActiveSpellEffectsUpdateEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public ActiveSpellEffectsUpdateEventHandler(TrackingController trackingController) : base((int) EventCodes.ActiveSpellEffectsUpdate) { _trackingController = trackingController; @@ -20,7 +21,7 @@ protected override async Task OnActionAsync(ActiveSpellEffectsUpdateEvent value) { if (value.CauserId != null) { - var spellEffect = new SpellEffect() + var spellEffect = new SpellEffect { CauserId = value.CauserId.ObjectToLong() ?? 0, SpellIndex = value.SpellIndex diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ChangeClusterResponseHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ChangeClusterResponseHandler.cs index 1c84a6ad4..f9bda804e 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ChangeClusterResponseHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/ChangeClusterResponseHandler.cs @@ -1,15 +1,16 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Operations.Responses; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class ChangeClusterResponseHandler : ResponsePacketHandler { private readonly TrackingController _trackingController; - public ChangeClusterResponseHandler(TrackingController trackingController) : base((int)OperationCodes.ChangeCluster) + + public ChangeClusterResponseHandler(TrackingController trackingController) : base((int) OperationCodes.ChangeCluster) { _trackingController = trackingController; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/CharacterEquipmentChangedEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/CharacterEquipmentChangedEventHandler.cs index 7790c4922..47ed2b860 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/CharacterEquipmentChangedEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/CharacterEquipmentChangedEventHandler.cs @@ -1,14 +1,15 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class CharacterEquipmentChangedEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public CharacterEquipmentChangedEventHandler(TrackingController trackingController) : base((int) EventCodes.CharacterEquipmentChanged) { _trackingController = trackingController; @@ -16,10 +17,7 @@ public CharacterEquipmentChangedEventHandler(TrackingController trackingControll protected override async Task OnActionAsync(CharacterEquipmentChangedEvent value) { - if (value.ObjectId != null) - { - _trackingController.EntityController.SetCharacterEquipment((long)value.ObjectId, value.CharacterEquipment); - } + if (value.ObjectId != null) _trackingController.EntityController.SetCharacterEquipment((long) value.ObjectId, value.CharacterEquipment); await Task.CompletedTask; } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/DiedEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/DiedEventHandler.cs index 3ee5e8a0a..5bb5f4a59 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/DiedEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/DiedEventHandler.cs @@ -1,8 +1,8 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Models.NetworkModel; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/HealthUpdateEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/HealthUpdateEventHandler.cs index fb3e24416..550383253 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/HealthUpdateEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/HealthUpdateEventHandler.cs @@ -1,13 +1,14 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class HealthUpdateEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public HealthUpdateEventHandler(TrackingController trackingController) : base((int) EventCodes.HealthUpdate) { _trackingController = trackingController; @@ -15,7 +16,8 @@ public HealthUpdateEventHandler(TrackingController trackingController) : base((i protected override async Task OnActionAsync(HealthUpdateEvent value) { - _trackingController.EntityController.HealthUpdate(value.ObjectId, value.TimeStamp, value.HealthChange, value.NewHealthValue, value.EffectType, value.EffectOrigin, value.CauserId, value.CausingSpellType); + _trackingController.EntityController.HealthUpdate(value.ObjectId, value.TimeStamp, value.HealthChange, value.NewHealthValue, + value.EffectType, value.EffectOrigin, value.CauserId, value.CausingSpellType); await Task.CompletedTask; } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/InCombatStateUpdateEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/InCombatStateUpdateEventHandler.cs index 9d310d4ae..858c6d8ba 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/InCombatStateUpdateEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/InCombatStateUpdateEventHandler.cs @@ -1,13 +1,14 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class InCombatStateUpdateEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public InCombatStateUpdateEventHandler(TrackingController trackingController) : base((int) EventCodes.InCombatStateUpdate) { _trackingController = trackingController; @@ -16,9 +17,7 @@ public InCombatStateUpdateEventHandler(TrackingController trackingController) : protected override async Task OnActionAsync(InCombatStateUpdateEvent value) { if (value.ObjectId != null) - { - _trackingController.CombatController.UpdateCombatMode((long)value.ObjectId, value.InActiveCombat, value.InPassiveCombat); - } + _trackingController.CombatController.UpdateCombatMode((long) value.ObjectId, value.InActiveCombat, value.InPassiveCombat); await Task.CompletedTask; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/JoinResponseHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/JoinResponseHandler.cs index 89a7bcfa6..250d8e11e 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/JoinResponseHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/JoinResponseHandler.cs @@ -1,20 +1,21 @@ -using Albion.Network; +using System; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.GameData; using StatisticsAnalysisTool.Models.NetworkModel; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Operations.Responses; using StatisticsAnalysisTool.ViewModels; -using System; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class JoinResponseHandler : ResponsePacketHandler { - private readonly TrackingController _trackingController; private readonly MainWindowViewModel _mainWindowViewModel; - public JoinResponseHandler(TrackingController trackingController, MainWindowViewModel mainWindowViewModel) : base((int)OperationCodes.Join) + private readonly TrackingController _trackingController; + + public JoinResponseHandler(TrackingController trackingController, MainWindowViewModel mainWindowViewModel) : base((int) OperationCodes.Join) { _trackingController = trackingController; _mainWindowViewModel = mainWindowViewModel; @@ -24,7 +25,7 @@ protected override async Task OnActionAsync(JoinResponse value) { _trackingController.SetNewCluster(value.MapType, value.DungeonGuid, value.MapIndex, value.MainMapIndex); - _trackingController.DungeonController.LocalUserData = new LocalUserData() + _trackingController.DungeonController.LocalUserData = new LocalUserData { UserObjectId = value.UserObjectId, Guid = value.Guid, @@ -48,8 +49,9 @@ protected override async Task OnActionAsync(JoinResponse value) if (value.Guid != null && value.UserObjectId != null) { - _trackingController.EntityController.AddEntity((long)value.UserObjectId, (Guid)value.Guid, value.Username, GameObjectType.Player, GameObjectSubType.LocalPlayer); - _trackingController.EntityController.AddToParty((Guid)value.Guid, value.Username); + _trackingController.EntityController.AddEntity((long) value.UserObjectId, (Guid) value.Guid, value.Username, GameObjectType.Player, + GameObjectSubType.LocalPlayer); + _trackingController.EntityController.AddToParty((Guid) value.Guid, value.Username); } _trackingController.SetTotalPlayerSilver(value.Silver.IntegerValue); @@ -62,10 +64,7 @@ protected override async Task OnActionAsync(JoinResponse value) private void ResetFameCounterByMapChangeIfActive() { - if (_mainWindowViewModel.IsTrackingResetByMapChangeActive) - { - _mainWindowViewModel.ResetMainCounters(true, true, true); - } + if (_mainWindowViewModel.IsTrackingResetByMapChangeActive) _mainWindowViewModel.ResetMainCounters(true, true, true); } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LeaveEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LeaveEventHandler.cs index 2e64594c5..70e97d003 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LeaveEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LeaveEventHandler.cs @@ -1,14 +1,15 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class LeaveEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public LeaveEventHandler(TrackingController trackingController) : base((int) EventCodes.NewMob) { _trackingController = trackingController; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LootChestOpenedEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LootChestOpenedEventHandler.cs index 6e48a6cd7..3c73dd1b9 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LootChestOpenedEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/LootChestOpenedEventHandler.cs @@ -1,15 +1,16 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class LootChestOpenedEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; - public LootChestOpenedEventHandler(TrackingController trackingController) : base((int)EventCodes.LootChestOpened) + + public LootChestOpenedEventHandler(TrackingController trackingController) : base((int) EventCodes.LootChestOpened) { _trackingController = trackingController; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewCharacterEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewCharacterEventHandler.cs index 8254c598d..39afcde98 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewCharacterEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewCharacterEventHandler.cs @@ -1,15 +1,16 @@ -using Albion.Network; +using System; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class NewCharacterEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public NewCharacterEventHandler(TrackingController trackingController) : base((int) EventCodes.NewCharacter) { _trackingController = trackingController; @@ -18,9 +19,8 @@ public NewCharacterEventHandler(TrackingController trackingController) : base((i protected override async Task OnActionAsync(NewCharacterEvent value) { if (value.Guid != null && value.ObjectId != null) - { - _trackingController.EntityController.AddEntity((long)value.ObjectId, (Guid)value.Guid, value.Name, GameObjectType.Player, GameObjectSubType.Player); - } + _trackingController.EntityController.AddEntity((long) value.ObjectId, (Guid) value.Guid, value.Name, GameObjectType.Player, + GameObjectSubType.Player); await Task.CompletedTask; } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewEquipmentItemEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewEquipmentItemEventHandler.cs index 91ba18a82..4277f49cb 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewEquipmentItemEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewEquipmentItemEventHandler.cs @@ -1,15 +1,16 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Models; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class NewEquipmentItemEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public NewEquipmentItemEventHandler(TrackingController trackingController) : base((int) EventCodes.NewEquipmentItem) { _trackingController = trackingController; @@ -17,7 +18,7 @@ public NewEquipmentItemEventHandler(TrackingController trackingController) : bas protected override async Task OnActionAsync(NewEquipmentItemEvent value) { - _trackingController.EntityController.AddEquipmentItem(new EquipmentItem() + _trackingController.EntityController.AddEquipmentItem(new EquipmentItem { ItemIndex = value.ItemIndex, SpellDictionary = value.SpellDictionary diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootChestEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootChestEventHandler.cs index 4f0938559..5be8cf427 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootChestEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootChestEventHandler.cs @@ -1,15 +1,16 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class NewLootChestEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; - public NewLootChestEventHandler(TrackingController trackingController) : base((int)EventCodes.NewLootChest) + + public NewLootChestEventHandler(TrackingController trackingController) : base((int) EventCodes.NewLootChest) { _trackingController = trackingController; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootEventHandler.cs index 3ce0bdfed..601b2d1e9 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewLootEventHandler.cs @@ -1,17 +1,19 @@ -using Albion.Network; -using StatisticsAnalysisTool.Network.Events; -using System.Diagnostics; +using System.Diagnostics; using System.Threading.Tasks; +using Albion.Network; +using StatisticsAnalysisTool.Network.Events; namespace StatisticsAnalysisTool.Network.Handler { public class NewLootEventHandler : EventPacketHandler { - public NewLootEventHandler() : base(88) { } + public NewLootEventHandler() : base(88) + { + } protected override async Task OnActionAsync(NewLootEvent value) { - Debug.Print($"NewLoot"); + Debug.Print("NewLoot"); await Task.CompletedTask; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewMobEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewMobEventHandler.cs index 9bdbe1106..0296e9c3c 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewMobEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewMobEventHandler.cs @@ -1,14 +1,15 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class NewMobEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public NewMobEventHandler(TrackingController trackingController) : base((int) EventCodes.NewMob) { _trackingController = trackingController; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewShrineEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewShrineEventHandler.cs index 99705de8c..dbd2cf021 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewShrineEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/NewShrineEventHandler.cs @@ -1,13 +1,14 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class NewShrineEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public NewShrineEventHandler(TrackingController trackingController) : base((int) EventCodes.NewShrine) { _trackingController = trackingController; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyChangedOrderEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyChangedOrderEventHandler.cs index 63c693cca..7593c400e 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyChangedOrderEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyChangedOrderEventHandler.cs @@ -1,14 +1,15 @@ -using Albion.Network; +using System; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; -using System; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class PartyChangedOrderEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public PartyChangedOrderEventHandler(TrackingController trackingController) : base((int) EventCodes.PartyChangedOrder) { _trackingController = trackingController; @@ -16,10 +17,7 @@ public PartyChangedOrderEventHandler(TrackingController trackingController) : ba protected override async Task OnActionAsync(PartyChangedOrderEvent value) { - if (value?.UserGuid != null) - { - _trackingController.EntityController.AddToParty((Guid)value.UserGuid, value.Username); - } + if (value?.UserGuid != null) _trackingController.EntityController.AddToParty((Guid) value.UserGuid, value.Username); await Task.CompletedTask; } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyDisbandedEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyDisbandedEventHandler.cs index 9afb71625..98a2cd85d 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyDisbandedEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyDisbandedEventHandler.cs @@ -1,13 +1,14 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class PartyDisbandedEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public PartyDisbandedEventHandler(TrackingController trackingController) : base((int) EventCodes.PartyDisbanded) { _trackingController = trackingController; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyMakeLeaderEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyMakeLeaderEventHandler.cs index 509f7b80e..e95ea3efc 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyMakeLeaderEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartyMakeLeaderEventHandler.cs @@ -1,14 +1,15 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Operations.Responses; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class PartyMakeLeaderEventHandler : ResponsePacketHandler { private readonly TrackingController _trackingController; + public PartyMakeLeaderEventHandler(TrackingController trackingController) : base((int) OperationCodes.PartyMakeLeader) { _trackingController = trackingController; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartySilverGainedEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartySilverGainedEventHandler.cs index 4ea90608c..1c02c7bca 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartySilverGainedEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/PartySilverGainedEventHandler.cs @@ -1,13 +1,15 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class PartySilverGainedEventHandler : EventPacketHandler { - public PartySilverGainedEventHandler() : base((int) EventCodes.PartySilverGained) { } + public PartySilverGainedEventHandler() : base((int) EventCodes.PartySilverGained) + { + } protected override async Task OnActionAsync(PartySilverGainedEvent value) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/SiegeCampClaimStartEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/SiegeCampClaimStartEventHandler.cs index 5da4ac20c..cc7ebd4ea 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/SiegeCampClaimStartEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/SiegeCampClaimStartEventHandler.cs @@ -1,16 +1,17 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { /// - /// Triggered when silver is picked up. Each party member gets their own event. + /// Triggered when silver is picked up. Each party member gets their own event. /// public class SiegeCampClaimStartEventHandler : EventPacketHandler { private readonly TrackingController _trackingController; + public SiegeCampClaimStartEventHandler(TrackingController trackingController) : base((int) EventCodes.SiegeCampClaimStart) { _trackingController = trackingController; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TakeSilverEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TakeSilverEventHandler.cs index cf2cac56e..5be64ad80 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TakeSilverEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TakeSilverEventHandler.cs @@ -1,12 +1,14 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class TakeSilverEventHandler : EventPacketHandler { - public TakeSilverEventHandler() : base((int) EventCodes.TakeSilver) { } + public TakeSilverEventHandler() : base((int) EventCodes.TakeSilver) + { + } protected override async Task OnActionAsync(TakeSilverEvent value) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler.cs index 92aaf7c7e..c7d19ee8d 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler.cs @@ -1,13 +1,15 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class TestHandler : ResponsePacketHandler { - public TestHandler() : base((int) OperationCodes.Join) { } + public TestHandler() : base((int) OperationCodes.Join) + { + } protected override async Task OnActionAsync(TestEvent testEvent) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler2.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler2.cs index b4a2f6c97..35fc1ca5c 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler2.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler2.cs @@ -1,12 +1,14 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class TestHandler2 : EventPacketHandler { - public TestHandler2() : base(115) { } + public TestHandler2() : base(115) + { + } protected override async Task OnActionAsync(TestEvent2 value) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler3.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler3.cs index 7d0975631..a450fd5e2 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler3.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/TestHandler3.cs @@ -1,13 +1,15 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class TestHandler3 : RequestPacketHandler { - public TestHandler3() : base((int) OperationCodes.ChangeCluster) { } + public TestHandler3() : base((int) OperationCodes.ChangeCluster) + { + } protected override async Task OnActionAsync(TestEvent3 value) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateFameEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateFameEventHandler.cs index 0390c15a4..0b09ae687 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateFameEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateFameEventHandler.cs @@ -1,19 +1,19 @@ -using Albion.Network; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Common; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Notification; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using ValueType = StatisticsAnalysisTool.Enumerations.ValueType; namespace StatisticsAnalysisTool.Network.Handler { public class UpdateFameEventHandler : EventPacketHandler { - private readonly TrackingController _trackingController; private readonly FameCountUpTimer _fameCountUpTimer; + private readonly TrackingController _trackingController; public UpdateFameEventHandler(TrackingController trackingController, FameCountUpTimer fameCountUpTimer) : base((int) EventCodes.UpdateFame) { @@ -23,19 +23,23 @@ public UpdateFameEventHandler(TrackingController trackingController, FameCountUp protected override async Task OnActionAsync(UpdateFameEvent value) { - _trackingController.AddNotification(SetPveFameNotification(value.TotalPlayerFame.DoubleValue, value.TotalGainedFame.DoubleValue, value.ZoneFame.DoubleValue, value.PremiumFame.DoubleValue, value.SatchelFame.DoubleValue, value.IsPremiumBonus)); + _trackingController.AddNotification(SetPveFameNotification(value.TotalPlayerFame.DoubleValue, value.TotalGainedFame.DoubleValue, + value.ZoneFame.DoubleValue, value.PremiumFame.DoubleValue, value.SatchelFame.DoubleValue, value.IsPremiumBonus)); _fameCountUpTimer.Add(value.TotalGainedFame.DoubleValue); _trackingController.DungeonController?.AddValueToDungeon(value.TotalGainedFame.DoubleValue, ValueType.Fame); _trackingController.SetTotalPlayerFame(value.TotalPlayerFame.DoubleValue); await Task.CompletedTask; } - - private TrackingNotification SetPveFameNotification(double totalPlayerFame, double totalGainedFame, double zoneFame, double premiumFame, double satchelFame, bool isMobFame) + + private TrackingNotification SetPveFameNotification(double totalPlayerFame, double totalGainedFame, double zoneFame, double premiumFame, + double satchelFame, bool isMobFame) { return new TrackingNotification(DateTime.Now, new List { - new FameNotificationFragment(LanguageController.Translation("YOU_HAVE"), AttributeStatOperator.Plus, totalPlayerFame, totalGainedFame, LanguageController.Translation("FAME"), FameTypeOperator.Pve, zoneFame, premiumFame, satchelFame, LanguageController.Translation("GAINED")), + new FameNotificationFragment(LanguageController.Translation("YOU_HAVE"), AttributeStatOperator.Plus, totalPlayerFame, totalGainedFame, + LanguageController.Translation("FAME"), FameTypeOperator.Pve, zoneFame, premiumFame, satchelFame, + LanguageController.Translation("GAINED")) }); } } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateMoneyEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateMoneyEventHandler.cs index fb316a5c7..09e3e9394 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateMoneyEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateMoneyEventHandler.cs @@ -1,16 +1,17 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class UpdateMoneyEventHandler : EventPacketHandler { - private readonly TrackingController _trackingController; private readonly SilverCountUpTimer _silverCountUpTimer; + private readonly TrackingController _trackingController; - public UpdateMoneyEventHandler(TrackingController trackingController, SilverCountUpTimer silverCountUpTimer) : base((int) EventCodes.UpdateMoney) + public UpdateMoneyEventHandler(TrackingController trackingController, SilverCountUpTimer silverCountUpTimer) : base( + (int) EventCodes.UpdateMoney) { _trackingController = trackingController; _silverCountUpTimer = silverCountUpTimer; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateReSpecPointsEventHandler.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateReSpecPointsEventHandler.cs index 455e7abff..b4c94707b 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateReSpecPointsEventHandler.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Handler/UpdateReSpecPointsEventHandler.cs @@ -1,17 +1,18 @@ -using Albion.Network; +using System.Threading.Tasks; +using Albion.Network; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Events; -using System.Threading.Tasks; namespace StatisticsAnalysisTool.Network.Handler { public class UpdateReSpecPointsEventHandler : EventPacketHandler { - private readonly TrackingController _trackingController; private readonly ReSpecPointsCountUpTimer _reSpecPointsCountUpTimer; + private readonly TrackingController _trackingController; - public UpdateReSpecPointsEventHandler(TrackingController trackingController, ReSpecPointsCountUpTimer reSpecPointsCountUpTimer) : base((int) EventCodes.UpdateReSpecPoints) + public UpdateReSpecPointsEventHandler(TrackingController trackingController, ReSpecPointsCountUpTimer reSpecPointsCountUpTimer) : base( + (int) EventCodes.UpdateReSpecPoints) { _trackingController = trackingController; _reSpecPointsCountUpTimer = reSpecPointsCountUpTimer; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/NetworkManager.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/NetworkManager.cs index fe95db6f8..bc0ceafdb 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/NetworkManager.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/NetworkManager.cs @@ -1,3 +1,9 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using System.Windows; using Albion.Network; using log4net; using PacketDotNet; @@ -6,12 +12,6 @@ using StatisticsAnalysisTool.Network.Controller; using StatisticsAnalysisTool.Network.Handler; using StatisticsAnalysisTool.ViewModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; -using System.Windows; namespace StatisticsAnalysisTool.Network { @@ -23,7 +23,10 @@ public static class NetworkManager private static readonly List _capturedDevices = new List(); private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public static bool StartNetworkCapture(MainWindowViewModel mainWindowViewModel, TrackingController trackingController, ValueCountUpTimer valueCountUpTimerTimer) + public static bool IsNetworkCaptureRunning => _capturedDevices.Where(device => device.Started).Any(device => device.Started); + + public static bool StartNetworkCapture(MainWindowViewModel mainWindowViewModel, TrackingController trackingController, + ValueCountUpTimer valueCountUpTimerTimer) { try { @@ -52,7 +55,7 @@ public static bool StartNetworkCapture(MainWindowViewModel mainWindowViewModel, builder.AddEventHandler(new NewEquipmentItemEventHandler(trackingController)); builder.AddEventHandler(new ActiveSpellEffectsUpdateEventHandler(trackingController)); builder.AddEventHandler(new PartySilverGainedEventHandler()); - + //builder.AddResponseHandler(new TestHandler()); //builder.AddEventHandler(new TestHandler2()); //builder.AddRequestHandler(new TestHandler3()); @@ -75,17 +78,11 @@ public static bool StartNetworkCapture(MainWindowViewModel mainWindowViewModel, private static bool StartDeviceCapture() { - if (_capturedDevices.Count <= 0) - { - return false; - } + if (_capturedDevices.Count <= 0) return false; try { - foreach (var device in _capturedDevices) - { - PacketEvent(device); - } + foreach (var device in _capturedDevices) PacketEvent(device); } catch (Exception e) { @@ -94,21 +91,19 @@ private static bool StartDeviceCapture() _mainWindowViewModel.StopTracking(); return false; } - + return true; } public static void StopNetworkCapture() { foreach (var device in _capturedDevices.Where(device => device.Started)) - { Task.Run(() => { device.StopCapture(); device.Close(); builder = null; }); - } _capturedDevices.Clear(); } @@ -125,17 +120,12 @@ await Task.Run(() => }); } - public static bool IsNetworkCaptureRunning => _capturedDevices.Where(device => device.Started).Any(device => device.Started); - private static void PacketHandler(object sender, CaptureEventArgs e) { try { var packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data).Extract(); - if (packet != null && (packet.SourcePort == 5056 || packet.DestinationPort == 5056)) - { - _receiver.ReceivePacket(packet.PayloadData); - } + if (packet != null && (packet.SourcePort == 5056 || packet.DestinationPort == 5056)) _receiver.ReceivePacket(packet.PayloadData); } catch (OverflowException ex) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DamageMeterFragment.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DamageMeterFragment.cs index 5dd4f50e4..7770942b1 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DamageMeterFragment.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DamageMeterFragment.cs @@ -1,98 +1,116 @@ -using StatisticsAnalysisTool.Annotations; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Models; -using System; +using System; using System.ComponentModel; using System.Runtime.CompilerServices; +using StatisticsAnalysisTool.Annotations; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Models; namespace StatisticsAnalysisTool.Network.Notification { public class DamageMeterFragment : INotifyPropertyChanged { - private string _name; + private string _categoryId; private Guid _causerGuid; + private Item _causerMainHand; private string _damage; private double _damageInPercent; - private Item _causerMainHand; - private string _categoryId; - private string _dpsString; - private double _dps; private double _damagePercentage; + private double _dps; + private string _dpsString; + private string _name; - public string Name { + public string Name + { get => _name; - set { + set + { _name = value; OnPropertyChanged(); } } - public Guid CauserGuid { + public Guid CauserGuid + { get => _causerGuid; - set { + set + { _causerGuid = value; OnPropertyChanged(); } } - public string Damage { + public string Damage + { get => _damage; - set { + set + { _damage = value; OnPropertyChanged(); } } - public string DpsString { + public string DpsString + { get => _dpsString; - private set { + private set + { _dpsString = value; OnPropertyChanged(); } } - public double Dps { + public double Dps + { get => _dps; - set { + set + { _dps = value; DpsString = _dps.ToShortNumberString(); OnPropertyChanged(); } } - public double DamageInPercent { + public double DamageInPercent + { get => _damageInPercent; - set { + set + { _damageInPercent = value; OnPropertyChanged(); } } - - public double DamagePercentage { + + public double DamagePercentage + { get => _damagePercentage; - set { + set + { _damagePercentage = value; OnPropertyChanged(); } } - - public Item CauserMainHand { + + public Item CauserMainHand + { get => _causerMainHand; - set { + set + { _causerMainHand = value; CategoryId = _causerMainHand?.FullItemInformation?.CategoryId; OnPropertyChanged(); } } - - public string CategoryId { + + public string CategoryId + { get => _categoryId; - set { + set + { _categoryId = value; OnPropertyChanged(); } } - + public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonChestFragment.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonChestFragment.cs index 76acc6e72..f0997ff64 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonChestFragment.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonChestFragment.cs @@ -1,44 +1,50 @@ -using Newtonsoft.Json; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using Newtonsoft.Json; using StatisticsAnalysisTool.Annotations; using StatisticsAnalysisTool.Common; using StatisticsAnalysisTool.Enumerations; using StatisticsAnalysisTool.GameData; -using System; -using System.ComponentModel; -using System.Runtime.CompilerServices; namespace StatisticsAnalysisTool.Network.Notification { public class DungeonChestFragment : INotifyPropertyChanged { private int _id; - private DateTime _opened; - private string _uniqueName; - private ChestType _type; - private ChestRarity _rarity; private bool _isBossChest; private bool _isChestOpen; + private DateTime _opened; + private ChestRarity _rarity; private ChestStatus _status; + private ChestType _type; + private string _uniqueName; - public int Id { + public int Id + { get => _id; - set { + set + { _id = value; OnPropertyChanged(); } } - public DateTime Opened { + public DateTime Opened + { get => _opened; - set { + set + { _opened = value; OnPropertyChanged(); } } - public string UniqueName { + public string UniqueName + { get => _uniqueName; - set { + set + { _uniqueName = value; Type = LootChestData.GetChestType(_uniqueName); Rarity = LootChestData.GetChestRarity(UniqueName); @@ -46,65 +52,75 @@ public string UniqueName { } } - public ChestType Type { + public ChestType Type + { get => _type; - set { + set + { _type = value; OnPropertyChanged(); } } - public ChestRarity Rarity { + public ChestRarity Rarity + { get => _rarity; - set { + set + { _rarity = value; Status = SetStatus(); OnPropertyChanged(); } } - public ChestStatus Status { + public ChestStatus Status + { get => _status; - set { + set + { _status = value; OnPropertyChanged(); } } - public bool IsBossChest { + public bool IsBossChest + { get => _isBossChest; - set { + set + { _isBossChest = value; OnPropertyChanged(); } } - public bool IsChestOpen { + public bool IsChestOpen + { get => _isChestOpen; - set { + set + { _isChestOpen = value; Status = SetStatus(); OnPropertyChanged(); } } - [JsonIgnore] - public string TranslationStandard => LanguageController.Translation("STANDARD"); - [JsonIgnore] - public string TranslationUncommon => LanguageController.Translation("UNCOMMON"); - [JsonIgnore] - public string TranslationRare => LanguageController.Translation("RARE"); - [JsonIgnore] - public string TranslationLegendary => LanguageController.Translation("LEGENDARY"); - [JsonIgnore] - public string TranslationBossChest => LanguageController.Translation("BOSS_CHEST"); - [JsonIgnore] - public string TranslationBookChest => LanguageController.Translation("BOOK_CHEST"); + [JsonIgnore] public string TranslationStandard => LanguageController.Translation("STANDARD"); + + [JsonIgnore] public string TranslationUncommon => LanguageController.Translation("UNCOMMON"); + + [JsonIgnore] public string TranslationRare => LanguageController.Translation("RARE"); + + [JsonIgnore] public string TranslationLegendary => LanguageController.Translation("LEGENDARY"); + + [JsonIgnore] public string TranslationBossChest => LanguageController.Translation("BOSS_CHEST"); + + [JsonIgnore] public string TranslationBookChest => LanguageController.Translation("BOOK_CHEST"); + + public event PropertyChangedEventHandler PropertyChanged; private ChestStatus SetStatus() { if (IsChestOpen) - { switch (Rarity) { case ChestRarity.Standard: @@ -116,9 +132,7 @@ private ChestStatus SetStatus() case ChestRarity.Legendary: return ChestStatus.LegendaryChestOpen; } - } else - { switch (Rarity) { case ChestRarity.Standard: @@ -130,12 +144,9 @@ private ChestStatus SetStatus() case ChestRarity.Legendary: return ChestStatus.LegendaryChestClose; } - } return ChestStatus.Unknown; } - - public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonNotificationFragment.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonNotificationFragment.cs index d80a041f0..43944b2fb 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonNotificationFragment.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/DungeonNotificationFragment.cs @@ -1,48 +1,56 @@ -using Newtonsoft.Json; -using StatisticsAnalysisTool.Annotations; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Enumerations; -using StatisticsAnalysisTool.GameData; -using System; +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; +using Newtonsoft.Json; +using StatisticsAnalysisTool.Annotations; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Enumerations; +using StatisticsAnalysisTool.GameData; using ValueType = StatisticsAnalysisTool.Enumerations.ValueType; namespace StatisticsAnalysisTool.Network.Notification { public class DungeonNotificationFragment : LineFragment, INotifyPropertyChanged { - private int _dungeonCounter; - private List _mapsGuid; - private double _fame; - private string _runTimeString; - private DateTime _enterDungeonMap; private readonly List _dungeonRuns = new List(); - private DungeonStatus _status; - private bool _isBestTime; - private bool _isBestFame; - private TimeSpan _totalTime; - private string _mainMapIndex; private bool _diedInDungeon; + private string _diedName; private ObservableCollection _dungeonChests = new ObservableCollection(); - private DungeonMode _mode = DungeonMode.Unknown; + private int _dungeonCounter; + private DateTime _enterDungeonMap; private Faction _faction; - private string _diedName; + private double _fame; + private double _famePerHour; + private bool _isBestFame; + private bool _isBestFamePerHour; + private bool _isBestReSpec; + private bool _isBestReSpecPerHour; + private bool _isBestSilver; + private bool _isBestSilverPerHour; + private bool _isBestTime; private string _killedBy; + + private double? _lastReSpecValue; + private double? _lastSilverValue; + private string _mainMapIndex; private string _mainMapName; + private List _mapsGuid; + private DungeonMode _mode = DungeonMode.Unknown; private double _reSpec; - private double _silver; - private double _famePerHour; private double _reSpecPerHour; + private string _runTimeString; + private double _silver; private double _silverPerHour; + private DungeonStatus _status; + private TimeSpan _totalTime; public DungeonNotificationFragment(Guid firstMap, int count, string mainMapIndex, DateTime startDungeon) { MainMapIndex = mainMapIndex; FirstMap = firstMap; - MapsGuid = new List { firstMap }; + MapsGuid = new List {firstMap}; StartDungeon = startDungeon; EnterDungeonMap = DateTime.UtcNow; DungeonCounter = count; @@ -52,7 +60,8 @@ public DungeonNotificationFragment(Guid firstMap, int count, string mainMapIndex public ObservableCollection DungeonChests { get => _dungeonChests; - set { + set + { _dungeonChests = value; OnPropertyChanged(); } @@ -61,7 +70,8 @@ public ObservableCollection DungeonChests public Faction Faction { get => _faction; - set { + set + { _faction = value; OnPropertyChanged(); } @@ -70,7 +80,8 @@ public Faction Faction public DungeonMode Mode { get => _mode; - set { + set + { _mode = value; OnPropertyChanged(); } @@ -79,7 +90,8 @@ public DungeonMode Mode public string MainMapIndex { get => _mainMapIndex; - set { + set + { _mainMapIndex = value; MainMapName = WorldData.GetUniqueNameOrDefault(value); OnPropertyChanged(); @@ -89,91 +101,89 @@ public string MainMapIndex public string MainMapName { get => _mainMapName; - set { + set + { _mainMapName = value; OnPropertyChanged(); } } - public int DungeonCounter { + public int DungeonCounter + { get => _dungeonCounter; - set { + set + { _dungeonCounter = value; OnPropertyChanged(); } } [JsonProperty] - public bool DiedInDungeon { + public bool DiedInDungeon + { get => _diedInDungeon; - set { + set + { _diedInDungeon = value; OnPropertyChanged(); } } - [JsonIgnore] - public string DiedMessage => $"{DiedName} {LanguageController.Translation("KILLED_BY")} {KilledBy}"; + [JsonIgnore] public string DiedMessage => $"{DiedName} {LanguageController.Translation("KILLED_BY")} {KilledBy}"; [JsonProperty] - public string DiedName { + public string DiedName + { get => _diedName; - set { + set + { _diedName = value; OnPropertyChanged(); } } [JsonProperty] - public string KilledBy { + public string KilledBy + { get => _killedBy; - set { + set + { _killedBy = value; OnPropertyChanged(); } } - [JsonProperty] - public DateTime StartDungeon { get; } + [JsonProperty] public DateTime StartDungeon { get; } - [JsonProperty] - private TimeSpan RunTimeInSeconds => TotalTime.TotalSeconds <= 0 ? (DateTime.UtcNow - StartDungeon) : TotalTime; + [JsonProperty] private TimeSpan RunTimeInSeconds => TotalTime.TotalSeconds <= 0 ? DateTime.UtcNow - StartDungeon : TotalTime; [JsonProperty] - public DateTime EnterDungeonMap { + public DateTime EnterDungeonMap + { get => _enterDungeonMap; - set { + set + { _enterDungeonMap = value; OnPropertyChanged(); } } - public void AddDungeonRunTime(DateTime dungeonEnd) - { - _dungeonRuns.Add(new DungeonRun() { Start = EnterDungeonMap, End = dungeonEnd }); - - TotalTime = new TimeSpan(); - foreach (var dunRun in _dungeonRuns) - { - TotalTime = TotalTime.Add(dunRun.Run); - } - - RunTimeString = (TotalTime.Ticks <= 0) ? "00:00:00" : $"{TotalTime.Hours:D2}:{TotalTime.Minutes:D2}:{TotalTime.Seconds:D2}"; - } - public string RunTimeString { get => _runTimeString; - set { + set + { _runTimeString = value; OnPropertyChanged(); } } [JsonProperty] - public TimeSpan TotalTime { + public TimeSpan TotalTime + { get => _totalTime; - set { + set + { _totalTime = value; OnPropertyChanged(); } @@ -183,20 +193,21 @@ public TimeSpan TotalTime { public List MapsGuid { get => _mapsGuid; - set { + set + { _mapsGuid = value; OnPropertyChanged(); } } - [JsonProperty] - public Guid FirstMap { get; } + [JsonProperty] public Guid FirstMap { get; } [JsonProperty] public double Fame { get => _fame; - private set { + private set + { _fame = value; FamePerHour = Utilities.GetValuePerHourToDouble(value, RunTimeInSeconds); OnPropertyChanged(); @@ -207,7 +218,8 @@ private set { public double ReSpec { get => _reSpec; - private set { + private set + { _reSpec = value; ReSpecPerHour = Utilities.GetValuePerHourToDouble(value, RunTimeInSeconds); OnPropertyChanged(); @@ -218,7 +230,8 @@ private set { public double Silver { get => _silver; - private set { + private set + { _silver = value; SilverPerHour = Utilities.GetValuePerHourToDouble(value, RunTimeInSeconds); OnPropertyChanged(); @@ -229,7 +242,8 @@ private set { public double FamePerHour { get => _famePerHour; - private set { + private set + { _famePerHour = value; OnPropertyChanged(); } @@ -239,7 +253,8 @@ private set { public double ReSpecPerHour { get => _reSpecPerHour; - private set { + private set + { _reSpecPerHour = value; OnPropertyChanged(); } @@ -249,144 +264,162 @@ private set { public double SilverPerHour { get => _silverPerHour; - private set { + private set + { _silverPerHour = value; OnPropertyChanged(); } } - private double? _lastReSpecValue; - private double? _lastSilverValue; - private bool _isBestReSpec; - private bool _isBestFamePerHour; - private bool _isBestSilver; - private bool _isBestReSpecPerHour; - private bool _isBestSilverPerHour; - - public void Add(double value, ValueType type) - { - switch (type) - { - case ValueType.Fame: - Fame += value; - return; - case ValueType.ReSpec: - ReSpec += AddValue(value, _lastReSpecValue, out _lastReSpecValue); - return; - case ValueType.Silver: - Silver += AddValue(value, _lastSilverValue, out _lastSilverValue); - return; - } - } - - private double AddValue(double value, double? lastValue, out double? newLastValue) - { - if (lastValue == null) - { - newLastValue = value; - return 0; - } - - var newSilverValue = (double)(value - lastValue); - - if (newSilverValue == 0) - { - newLastValue = value; - return 0; - } - - newLastValue = value; - - return newSilverValue; - } - [JsonProperty] - public DungeonStatus Status { + public DungeonStatus Status + { get => _status; - set { + set + { _status = value; OnPropertyChanged(); } } [JsonProperty] - public bool IsBestTime { + public bool IsBestTime + { get => _isBestTime; - set { + set + { _isBestTime = value; OnPropertyChanged(); } } [JsonProperty] - public bool IsBestFame { + public bool IsBestFame + { get => _isBestFame; - set { + set + { _isBestFame = value; OnPropertyChanged(); } } [JsonProperty] - public bool IsBestReSpec { + public bool IsBestReSpec + { get => _isBestReSpec; - set { + set + { _isBestReSpec = value; OnPropertyChanged(); } } [JsonProperty] - public bool IsBestSilver { + public bool IsBestSilver + { get => _isBestSilver; - set { + set + { _isBestSilver = value; OnPropertyChanged(); } } [JsonProperty] - public bool IsBestFamePerHour { + public bool IsBestFamePerHour + { get => _isBestFamePerHour; - set { + set + { _isBestFamePerHour = value; OnPropertyChanged(); } } [JsonProperty] - public bool IsBestReSpecPerHour { + public bool IsBestReSpecPerHour + { get => _isBestReSpecPerHour; - set { + set + { _isBestReSpecPerHour = value; OnPropertyChanged(); } } [JsonProperty] - public bool IsBestSilverPerHour { + public bool IsBestSilverPerHour + { get => _isBestSilverPerHour; - set { + set + { _isBestSilverPerHour = value; OnPropertyChanged(); } } - [JsonIgnore] - public string TranslationDungeonFame => LanguageController.Translation("DUNGEON_FAME"); - [JsonIgnore] - public string TranslationDungeonRunTime => LanguageController.Translation("DUNGEON_RUN_TIME"); - [JsonIgnore] - public string TranslationSolo => LanguageController.Translation("SOLO"); - [JsonIgnore] - public string TranslationStandard => LanguageController.Translation("STANDARD"); - [JsonIgnore] - public string TranslationAvalon => LanguageController.Translation("AVALON"); - [JsonIgnore] - public string TranslationUnknown => LanguageController.Translation("UNKNOWN"); + [JsonIgnore] public string TranslationDungeonFame => LanguageController.Translation("DUNGEON_FAME"); + + [JsonIgnore] public string TranslationDungeonRunTime => LanguageController.Translation("DUNGEON_RUN_TIME"); + + [JsonIgnore] public string TranslationSolo => LanguageController.Translation("SOLO"); + + [JsonIgnore] public string TranslationStandard => LanguageController.Translation("STANDARD"); + + [JsonIgnore] public string TranslationAvalon => LanguageController.Translation("AVALON"); + + [JsonIgnore] public string TranslationUnknown => LanguageController.Translation("UNKNOWN"); public event PropertyChangedEventHandler PropertyChanged; + public void AddDungeonRunTime(DateTime dungeonEnd) + { + _dungeonRuns.Add(new DungeonRun {Start = EnterDungeonMap, End = dungeonEnd}); + + TotalTime = new TimeSpan(); + foreach (var dunRun in _dungeonRuns) TotalTime = TotalTime.Add(dunRun.Run); + + RunTimeString = TotalTime.Ticks <= 0 ? "00:00:00" : $"{TotalTime.Hours:D2}:{TotalTime.Minutes:D2}:{TotalTime.Seconds:D2}"; + } + + public void Add(double value, ValueType type) + { + switch (type) + { + case ValueType.Fame: + Fame += value; + return; + case ValueType.ReSpec: + ReSpec += AddValue(value, _lastReSpecValue, out _lastReSpecValue); + return; + case ValueType.Silver: + Silver += AddValue(value, _lastSilverValue, out _lastSilverValue); + return; + } + } + + private double AddValue(double value, double? lastValue, out double? newLastValue) + { + if (lastValue == null) + { + newLastValue = value; + return 0; + } + + var newSilverValue = (double) (value - lastValue); + + if (newSilverValue == 0) + { + newLastValue = value; + return 0; + } + + newLastValue = value; + + return newSilverValue; + } + [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/FameNotificationFragment.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/FameNotificationFragment.cs index 7c9ab8000..a4e291b39 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/FameNotificationFragment.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Notification/FameNotificationFragment.cs @@ -4,7 +4,8 @@ namespace StatisticsAnalysisTool.Network.Notification { public class FameNotificationFragment : LineFragment { - public FameNotificationFragment(string startText, AttributeStatOperator statOperator, double totalPlayerFame, double totalGainedFame, string fameText, FameTypeOperator fameTypeOperator, double zone, double premium, double satchel, string endText) + public FameNotificationFragment(string startText, AttributeStatOperator statOperator, double totalPlayerFame, double totalGainedFame, + string fameText, FameTypeOperator fameTypeOperator, double zone, double premium, double satchel, string endText) { StartText = startText; Operator = statOperator; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/MoveOperation.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/MoveOperation.cs index d44b422c8..b7fb961f2 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/MoveOperation.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/MoveOperation.cs @@ -1,5 +1,5 @@ -using Albion.Network; -using System.Collections.Generic; +using System.Collections.Generic; +using Albion.Network; namespace StatisticsAnalysisTool.Network.Operations { @@ -7,11 +7,11 @@ public class MoveOperation : BaseOperation { public MoveOperation(Dictionary parameters) : base(parameters) { - Time = (int)parameters[0]; - Position = (float[])parameters[1]; - Direction = (float)parameters[2]; - NewPosition = (float[])parameters[3]; - Speed = (float)parameters[4]; + Time = (int) parameters[0]; + Position = (float[]) parameters[1]; + Direction = (float) parameters[2]; + NewPosition = (float[]) parameters[3]; + Speed = (float) parameters[4]; } public int Time { get; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/ChangeClusterResponse.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/ChangeClusterResponse.cs index 849ac52e6..73aad7242 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/ChangeClusterResponse.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/ChangeClusterResponse.cs @@ -1,8 +1,8 @@ -using Albion.Network; -using log4net; -using System; +using System; using System.Collections.Generic; using System.Reflection; +using Albion.Network; +using log4net; namespace StatisticsAnalysisTool.Network.Operations.Responses { @@ -10,35 +10,28 @@ public class ChangeClusterResponse : BaseOperation { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public string ClusterMap; + + public string ClusterOwner; + + public string Index; + public ChangeClusterResponse(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(0)) - { - Index = string.IsNullOrEmpty(parameters[0].ToString()) ? string.Empty : parameters[0].ToString(); - } + if (parameters.ContainsKey(0)) Index = string.IsNullOrEmpty(parameters[0].ToString()) ? string.Empty : parameters[0].ToString(); if (parameters.ContainsKey(253)) - { ClusterOwner = string.IsNullOrEmpty(parameters[253].ToString()) ? string.Empty : parameters[253].ToString(); - } if (parameters.ContainsKey(255)) - { ClusterMap = string.IsNullOrEmpty(parameters[255].ToString()) ? string.Empty : parameters[255].ToString(); - } } catch (Exception e) { Log.Debug(nameof(ChangeClusterResponse), e); } } - - public string Index; - - public string ClusterMap; - - public string ClusterOwner; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/JoinResponse.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/JoinResponse.cs index 3e77847ed..102ebecd5 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/JoinResponse.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/JoinResponse.cs @@ -1,11 +1,11 @@ -using Albion.Network; -using log4net; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.GameData; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; +using Albion.Network; +using log4net; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.GameData; namespace StatisticsAnalysisTool.Network.Operations.Responses { @@ -13,11 +13,13 @@ public class JoinResponse : BaseOperation { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public long? UserObjectId; + public JoinResponse(Dictionary parameters) : base(parameters) { try { - Debug.Print($"---------- UserInformation (Response) ----------"); + Debug.Print("---------- UserInformation (Response) ----------"); //foreach (var parameter in parameters) //{ // Debug.Print($"{parameter}"); @@ -36,10 +38,7 @@ public JoinResponse(Dictionary parameters) : base(parameters) Debug.Print($"Local user Guid: {Guid}"); } - if (parameters.ContainsKey(2)) - { - Username = parameters[2].ToString(); - } + if (parameters.ContainsKey(2)) Username = parameters[2].ToString(); if (parameters.ContainsKey(8)) { @@ -48,65 +47,33 @@ public JoinResponse(Dictionary parameters) : base(parameters) DungeonGuid = WorldData.GetDungeonGuid(MapIndex); } - if (parameters.ContainsKey(23)) - { - CurrentFocusPoints = parameters[23].ObjectToDouble(); - } + if (parameters.ContainsKey(23)) CurrentFocusPoints = parameters[23].ObjectToDouble(); - if (parameters.ContainsKey(24)) - { - MaxCurrentFocusPoints = parameters[24].ObjectToDouble(); - } + if (parameters.ContainsKey(24)) MaxCurrentFocusPoints = parameters[24].ObjectToDouble(); - if (parameters.ContainsKey(28)) - { - Silver = FixPoint.FromInternalValue(parameters[28].ObjectToLong() ?? 0); - } + if (parameters.ContainsKey(28)) Silver = FixPoint.FromInternalValue(parameters[28].ObjectToLong() ?? 0); - if (parameters.ContainsKey(29)) - { - Gold = FixPoint.FromInternalValue(parameters[29].ObjectToLong() ?? 0); - } + if (parameters.ContainsKey(29)) Gold = FixPoint.FromInternalValue(parameters[29].ObjectToLong() ?? 0); - if (parameters.ContainsKey(32)) - { - LearningPoints = FixPoint.FromInternalValue(parameters[32].ObjectToLong() ?? 0); - } + if (parameters.ContainsKey(32)) LearningPoints = FixPoint.FromInternalValue(parameters[32].ObjectToLong() ?? 0); - if (parameters.ContainsKey(36)) - { - Reputation = parameters[36].ObjectToDouble(); - } + if (parameters.ContainsKey(36)) Reputation = parameters[36].ObjectToDouble(); if (parameters.ContainsKey(38) && parameters[38] != null && parameters[38] is long[] reSpecArray && reSpecArray.Length > 1) - { ReSpecPoints = FixPoint.FromInternalValue(reSpecArray[1]); - } if (parameters.ContainsKey(51)) - { GuildName = string.IsNullOrEmpty(parameters[51].ToString()) ? string.Empty : parameters[51].ToString(); - } if (parameters.ContainsKey(58)) - { MainMapIndex = string.IsNullOrEmpty(parameters[58].ToString()) ? string.Empty : parameters[58].ToString(); - } - if (parameters.ContainsKey(61)) - { - PlayTimeInSeconds = parameters[61].ObjectToInt(); - } + if (parameters.ContainsKey(61)) PlayTimeInSeconds = parameters[61].ObjectToInt(); if (parameters.ContainsKey(69)) - { AllianceName = string.IsNullOrEmpty(parameters[69].ToString()) ? string.Empty : parameters[69].ToString(); - } - - if (parameters.ContainsKey(92)) - { - CurrentDailyBonusPoints = parameters[92].ObjectToLong(); - } + + if (parameters.ContainsKey(92)) CurrentDailyBonusPoints = parameters[92].ObjectToLong(); } catch (Exception e) { @@ -114,7 +81,6 @@ public JoinResponse(Dictionary parameters) : base(parameters) } } - public long? UserObjectId; public Guid? Guid { get; } public string Username { get; } public string MapIndex { get; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/PartyMakeLeaderResponse.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/PartyMakeLeaderResponse.cs index 62fd1c2e7..5d7118b69 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/PartyMakeLeaderResponse.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Operations/Responses/PartyMakeLeaderResponse.cs @@ -1,8 +1,8 @@ -using Albion.Network; -using log4net; -using System; +using System; using System.Collections.Generic; using System.Reflection; +using Albion.Network; +using log4net; namespace StatisticsAnalysisTool.Network.Operations.Responses { @@ -10,22 +10,18 @@ public class PartyMakeLeaderResponse : BaseOperation { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public string Username; + public PartyMakeLeaderResponse(Dictionary parameters) : base(parameters) { try { - if (parameters.ContainsKey(0)) - { - Username = string.IsNullOrEmpty(parameters[0].ToString()) ? string.Empty : parameters[0].ToString(); - } - + if (parameters.ContainsKey(0)) Username = string.IsNullOrEmpty(parameters[0].ToString()) ? string.Empty : parameters[0].ToString(); } catch (Exception e) { Log.Debug(nameof(PartyMakeLeaderResponse), e); } } - - public string Username; } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ReSpecPointsCountUpTimer.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ReSpecPointsCountUpTimer.cs index 779400d0c..8061aba40 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ReSpecPointsCountUpTimer.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ReSpecPointsCountUpTimer.cs @@ -1,27 +1,27 @@ -using log4net; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Models.NetworkModel; -using StatisticsAnalysisTool.ViewModels; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; +using log4net; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Models.NetworkModel; +using StatisticsAnalysisTool.ViewModels; namespace StatisticsAnalysisTool.Network { public class ReSpecPointsCountUpTimer : ICountUpTimer { - private readonly MainWindowViewModel _mainWindowViewModel; private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private readonly MainWindowViewModel _mainWindowViewModel; + + private readonly List _valuePerHourList = new List(); private bool _isCurrentTimerUpdateActive; + private double? _lastValue; private DateTime _startTime; - private double _totalGained; private int? _taskId; - private double? _lastValue; - - private readonly List _valuePerHourList = new List(); + private double _totalGained; public ReSpecPointsCountUpTimer(MainWindowViewModel mainWindowViewModel) { @@ -36,16 +36,13 @@ public void Add(double value) return; } - var newValue = (double)(value - _lastValue); + var newValue = (double) (value - _lastValue); - if (newValue == 0) - { - return; - } + if (newValue == 0) return; _lastValue = value; - _valuePerHourList.Add(new ValuePerHour() { DateTime = DateTime.Now, Value = newValue }); + _valuePerHourList.Add(new ValuePerHour {DateTime = DateTime.Now, Value = newValue}); _valuePerHourList.RemoveAll(x => x.DateTime < DateTime.Now.AddHours(-1)); _totalGained = _valuePerHourList.Sum(x => x.Value); @@ -54,15 +51,9 @@ public void Add(double value) public void Start() { - if (_isCurrentTimerUpdateActive) - { - return; - } + if (_isCurrentTimerUpdateActive) return; - if (_startTime.Millisecond <= 0) - { - _startTime = DateTime.Now; - } + if (_startTime.Millisecond <= 0) _startTime = DateTime.Now; CurrentTimerUpdate(); } @@ -81,13 +72,10 @@ public void Reset() _valuePerHourList.Clear(); CurrentTimerUpdate(); } - + private void CurrentTimerUpdate() { - if (_isCurrentTimerUpdateActive) - { - return; - } + if (_isCurrentTimerUpdateActive) return; _isCurrentTimerUpdateActive = true; @@ -104,17 +92,11 @@ private void CurrentTimerUpdate() private void KillTimerTask(int? taskId) { - if (taskId == null) - { - return; - } + if (taskId == null) return; try { - if (Process.GetProcesses().Any(x => x.Id == (int)taskId)) - { - Process.GetProcessById((int)taskId).Kill(); - } + if (Process.GetProcesses().Any(x => x.Id == (int) taskId)) Process.GetProcessById((int) taskId).Kill(); } catch (Exception e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/SilverCountUpTimer.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/SilverCountUpTimer.cs index 9df128f1d..3df92724b 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/SilverCountUpTimer.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/SilverCountUpTimer.cs @@ -1,27 +1,27 @@ -using log4net; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Models.NetworkModel; -using StatisticsAnalysisTool.ViewModels; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; +using log4net; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Models.NetworkModel; +using StatisticsAnalysisTool.ViewModels; namespace StatisticsAnalysisTool.Network { public class SilverCountUpTimer : ICountUpTimer { - private readonly MainWindowViewModel _mainWindowViewModel; private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private readonly MainWindowViewModel _mainWindowViewModel; + + private readonly List _silverPerHourList = new List(); private bool _isCurrentTimerUpdateActive; + private double? _lastValue; private DateTime _startTime; - private double _totalGainedSilver; private int? _taskId; - private double? _lastValue; - - private readonly List _silverPerHourList = new List(); + private double _totalGainedSilver; public SilverCountUpTimer(MainWindowViewModel mainWindowViewModel) { @@ -36,16 +36,13 @@ public void Add(double value) return; } - var newSilverValue = (double)(value - _lastValue); + var newSilverValue = (double) (value - _lastValue); - if (newSilverValue == 0) - { - return; - } + if (newSilverValue == 0) return; _lastValue = value; - _silverPerHourList.Add(new ValuePerHour() { DateTime = DateTime.Now, Value = newSilverValue }); + _silverPerHourList.Add(new ValuePerHour {DateTime = DateTime.Now, Value = newSilverValue}); _silverPerHourList.RemoveAll(x => x.DateTime < DateTime.Now.AddHours(-1)); _totalGainedSilver = _silverPerHourList.Sum(x => x.Value); @@ -54,15 +51,9 @@ public void Add(double value) public void Start() { - if (_isCurrentTimerUpdateActive) - { - return; - } + if (_isCurrentTimerUpdateActive) return; - if (_startTime.Millisecond <= 0) - { - _startTime = DateTime.Now; - } + if (_startTime.Millisecond <= 0) _startTime = DateTime.Now; CurrentTimerUpdate(); } @@ -80,13 +71,10 @@ public void Reset() _silverPerHourList.Clear(); CurrentTimerUpdate(); } - + private void CurrentTimerUpdate() { - if (_isCurrentTimerUpdateActive) - { - return; - } + if (_isCurrentTimerUpdateActive) return; _isCurrentTimerUpdateActive = true; @@ -103,17 +91,11 @@ private void CurrentTimerUpdate() private void KillTimerTask(int? taskId) { - if (taskId == null) - { - return; - } + if (taskId == null) return; try { - if (Process.GetProcesses().Any(x => x.Id == (int)taskId)) - { - Process.GetProcessById((int)taskId).Kill(); - } + if (Process.GetProcesses().Any(x => x.Id == (int) taskId)) Process.GetProcessById((int) taskId).Kill(); } catch (Exception e) { diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeSpan.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeSpan.cs index 2e057dbb4..7e317b666 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeSpan.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeSpan.cs @@ -35,20 +35,14 @@ public GameTimeSpan(long ticks) public static GameTimeSpan FromSeconds(double fSeconds) { - return new GameTimeSpan((long)(fSeconds * TicksPerSecond + 0.5)); + return new GameTimeSpan((long) (fSeconds * TicksPerSecond + 0.5)); } public string ToStringVerbose() { - if (Ticks < TicksPerMinute) - { - return $"{Seconds:0}.{Milliseconds:000}s"; - } - - if (Ticks < TicksPerHour) - { - return $"{Minutes:0}:{Seconds:00}.{Milliseconds:000}"; - } + if (Ticks < TicksPerMinute) return $"{Seconds:0}.{Milliseconds:000}s"; + + if (Ticks < TicksPerHour) return $"{Minutes:0}:{Seconds:00}.{Milliseconds:000}"; return $"{Hours + Days * 24L:0}:{Minutes:00}:{Seconds:00}.{Milliseconds:000}"; } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeStamp.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeStamp.cs index c05ab1989..4a953d723 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeStamp.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/Time/GameTimeStamp.cs @@ -18,7 +18,8 @@ public GameTimeStamp(long iTicks) Ticks = iTicks; } - public static TimeSourceDelegate TimeSource { + public static TimeSourceDelegate TimeSource + { get => pTimeSource; set => pTimeSource = value; } @@ -37,8 +38,7 @@ public static GameTimeStamp DefaultTimeSource() public static readonly GameTimeStamp Zero = new GameTimeStamp(0L); public readonly long Ticks; - [ThreadStatic] - private static TimeSourceDelegate pTimeSource; + [ThreadStatic] private static TimeSourceDelegate pTimeSource; public delegate GameTimeStamp TimeSourceDelegate(); @@ -117,7 +117,7 @@ public int CompareTo(object obj) { if (!(obj is GameTimeStamp)) throw new ArgumentException(); - var gameTimeStamp = (GameTimeStamp)obj; + var gameTimeStamp = (GameTimeStamp) obj; if (Ticks > gameTimeStamp.Ticks) return 1; if (Ticks == gameTimeStamp.Ticks) @@ -137,7 +137,7 @@ public int CompareTo(GameTimeStamp xOther) public override bool Equals(object value) { if (value is GameTimeStamp) - return ((GameTimeStamp)value).Ticks == Ticks; + return ((GameTimeStamp) value).Ticks == Ticks; throw new ArgumentException(); } @@ -148,7 +148,7 @@ public bool Equals(GameTimeStamp other) public override int GetHashCode() { - return (int)Ticks; + return (int) Ticks; } public override string ToString() diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ValueCountUpTimer.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ValueCountUpTimer.cs index b15b370cf..f2029e5a5 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ValueCountUpTimer.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Network/ValueCountUpTimer.cs @@ -2,8 +2,8 @@ { public class ValueCountUpTimer { - public FameCountUpTimer FameCountUpTimer { get; set; } - public SilverCountUpTimer SilverCountUpTimer { get; set; } - public ReSpecPointsCountUpTimer ReSpecPointsCountUpTimer { get; set; } + public FameCountUpTimer FameCountUpTimer { get; set; } + public SilverCountUpTimer SilverCountUpTimer { get; set; } + public ReSpecPointsCountUpTimer ReSpecPointsCountUpTimer { get; set; } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/Annotations.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/Annotations.cs index 623d27408..ccb299feb 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/Annotations.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/Annotations.cs @@ -21,6 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; + // ReSharper disable InheritdocConsiderUsage #pragma warning disable 1591 @@ -33,1131 +34,1318 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE namespace StatisticsAnalysisTool.Annotations { - /// - /// Indicates that the value of the marked element could be null sometimes, - /// so checking for null is required before its usage. - /// - /// - /// [CanBeNull] object Test() => null; - /// - /// void UseTest() { - /// var p = Test(); - /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' - /// } - /// - [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] - public sealed class CanBeNullAttribute : Attribute { } - - /// - /// Indicates that the value of the marked element can never be null. - /// - /// - /// [NotNull] object Foo() { - /// return null; // Warning: Possible 'null' assignment - /// } - /// - [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] - public sealed class NotNullAttribute : Attribute { } - - /// - /// Can be applied to symbols of types derived from IEnumerable as well as to symbols of Task - /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property - /// or of the Lazy.Value property can never be null. - /// - /// - /// public void Foo([ItemNotNull]List<string> books) - /// { - /// foreach (var book in books) { - /// if (book != null) // Warning: Expression is always true - /// Console.WriteLine(book.ToUpper()); - /// } - /// } - /// - [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field)] - public sealed class ItemNotNullAttribute : Attribute { } - - /// - /// Can be applied to symbols of types derived from IEnumerable as well as to symbols of Task - /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property - /// or of the Lazy.Value property can be null. - /// - /// - /// public void Foo([ItemCanBeNull]List<string> books) - /// { - /// foreach (var book in books) - /// { - /// // Warning: Possible 'System.NullReferenceException' - /// Console.WriteLine(book.ToUpper()); - /// } - /// } - /// - [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field)] - public sealed class ItemCanBeNullAttribute : Attribute { } - - /// - /// Indicates that the marked method builds string by the format pattern and (optional) arguments. - /// The parameter, which contains the format string, should be given in constructor. The format string - /// should be in -like form. - /// - /// - /// [StringFormatMethod("message")] - /// void ShowError(string message, params object[] args) { /* do something */ } - /// - /// void Foo() { - /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string - /// } - /// - [AttributeUsage( - AttributeTargets.Constructor | AttributeTargets.Method | - AttributeTargets.Property | AttributeTargets.Delegate)] - public sealed class StringFormatMethodAttribute : Attribute - { - /// - /// Specifies which parameter of an annotated method should be treated as the format string - /// - public StringFormatMethodAttribute([NotNull] string formatParameterName) - { - FormatParameterName = formatParameterName; - } - - [NotNull] public string FormatParameterName { get; } - } - - /// - /// Use this annotation to specify a type that contains static or const fields - /// with values for the annotated property/field/parameter. - /// The specified type will be used to improve completion suggestions. - /// - /// - /// namespace TestNamespace - /// { - /// public class Constants - /// { - /// public static int INT_CONST = 1; - /// public const string STRING_CONST = "1"; - /// } - /// - /// public class Class1 - /// { - /// [ValueProvider("TestNamespace.Constants")] public int myField; - /// public void Foo([ValueProvider("TestNamespace.Constants")] string str) { } - /// - /// public void Test() - /// { - /// Foo(/*try completion here*/);// - /// myField = /*try completion here*/ - /// } - /// } - /// } - /// - [AttributeUsage( - AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, - AllowMultiple = true)] - public sealed class ValueProviderAttribute : Attribute - { - public ValueProviderAttribute([NotNull] string name) - { - Name = name; - } - - [NotNull] public string Name { get; } - } - - /// - /// Indicates that the function argument should be a string literal and match one - /// of the parameters of the caller function. For example, ReSharper annotates - /// the parameter of . - /// - /// - /// void Foo(string param) { - /// if (param == null) - /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol - /// } - /// - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class InvokerParameterNameAttribute : Attribute { } - - /// - /// Indicates that the method is contained in a type that implements - /// System.ComponentModel.INotifyPropertyChanged interface and this method - /// is used to notify that some property value changed. - /// - /// - /// The method should be non-static and conform to one of the supported signatures: - /// - /// NotifyChanged(string) - /// NotifyChanged(params string[]) - /// NotifyChanged{T}(Expression{Func{T}}) - /// NotifyChanged{T,U}(Expression{Func{T,U}}) - /// SetProperty{T}(ref T, T, string) - /// - /// - /// - /// public class Foo : INotifyPropertyChanged { - /// public event PropertyChangedEventHandler PropertyChanged; - /// - /// [NotifyPropertyChangedInvocator] - /// protected virtual void NotifyChanged(string propertyName) { ... } - /// - /// string _name; - /// - /// public string Name { - /// get { return _name; } - /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } - /// } - /// } - /// - /// Examples of generated notifications: - /// - /// NotifyChanged("Property") - /// NotifyChanged(() => Property) - /// NotifyChanged((VM x) => x.Property) - /// SetProperty(ref myField, value, "Property") - /// - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute - { - public NotifyPropertyChangedInvocatorAttribute() { } - public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) - { - ParameterName = parameterName; - } - - [CanBeNull] public string ParameterName { get; } - } - - /// - /// Describes dependency between method input and output. - /// - /// - ///

Function Definition Table syntax:

- /// - /// FDT ::= FDTRow [;FDTRow]* - /// FDTRow ::= Input => Output | Output <= Input - /// Input ::= ParameterName: Value [, Input]* - /// Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value} - /// Value ::= true | false | null | notnull | canbenull - /// - /// If the method has a single input parameter, its name could be omitted.
- /// Using halt (or void/nothing, which is the same) for the method output - /// means that the method doesn't return normally (throws or terminates the process).
- /// Value canbenull is only applicable for output parameters.
- /// You can use multiple [ContractAnnotation] for each FDT row, or use single attribute - /// with rows separated by semicolon. There is no notion of order rows, all rows are checked - /// for applicability and applied per each program state tracked by the analysis engine.
- ///
- /// - /// - /// [ContractAnnotation("=> halt")] - /// public void TerminationMethod() - /// - /// - /// [ContractAnnotation("null <= param:null")] // reverse condition syntax - /// public string GetName(string surname) - /// - /// - /// [ContractAnnotation("s:null => true")] - /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() - /// - /// - /// // A method that returns null if the parameter is null, - /// // and not null if the parameter is not null - /// [ContractAnnotation("null => null; notnull => notnull")] - /// public object Transform(object data) - /// - /// - /// [ContractAnnotation("=> true, result: notnull; => false, result: null")] - /// public bool TryParse(string s, out Person result) - /// - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] - public sealed class ContractAnnotationAttribute : Attribute - { - public ContractAnnotationAttribute([NotNull] string contract) - : this(contract, false) { } - - public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) - { - Contract = contract; - ForceFullStates = forceFullStates; - } - - [NotNull] public string Contract { get; } - - public bool ForceFullStates { get; } - } - - /// - /// Indicates whether the marked element should be localized. - /// - /// - /// [LocalizationRequiredAttribute(true)] - /// class Foo { - /// string str = "my string"; // Warning: Localizable string - /// } - /// - [AttributeUsage(AttributeTargets.All)] - public sealed class LocalizationRequiredAttribute : Attribute - { - public LocalizationRequiredAttribute() : this(true) { } - - public LocalizationRequiredAttribute(bool required) - { - Required = required; - } - - public bool Required { get; } - } - - /// - /// Indicates that the value of the marked type (or its derivatives) - /// cannot be compared using '==' or '!=' operators and Equals() - /// should be used instead. However, using '==' or '!=' for comparison - /// with null is always permitted. - /// - /// - /// [CannotApplyEqualityOperator] - /// class NoEquality { } - /// - /// class UsesNoEquality { - /// void Test() { - /// var ca1 = new NoEquality(); - /// var ca2 = new NoEquality(); - /// if (ca1 != null) { // OK - /// bool condition = ca1 == ca2; // Warning - /// } - /// } - /// } - /// - [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] - public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } - - /// - /// When applied to a target attribute, specifies a requirement for any type marked - /// with the target attribute to implement or inherit specific type or types. - /// - /// - /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement - /// class ComponentAttribute : Attribute { } - /// - /// [Component] // ComponentAttribute requires implementing IComponent interface - /// class MyComponent : IComponent { } - /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - [BaseTypeRequired(typeof(Attribute))] - public sealed class BaseTypeRequiredAttribute : Attribute - { - public BaseTypeRequiredAttribute([NotNull] Type baseType) - { - BaseType = baseType; - } - - [NotNull] public Type BaseType { get; } - } - - /// - /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), - /// so this symbol will not be reported as unused (as well as by other usage inspections). - /// - [AttributeUsage(AttributeTargets.All, Inherited = false)] - public sealed class UsedImplicitlyAttribute : Attribute - { - public UsedImplicitlyAttribute() - : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } - - public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) - : this(useKindFlags, ImplicitUseTargetFlags.Default) { } - - public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) - : this(ImplicitUseKindFlags.Default, targetFlags) { } - - public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) - { - UseKindFlags = useKindFlags; - TargetFlags = targetFlags; - } - - public ImplicitUseKindFlags UseKindFlags { get; } - - public ImplicitUseTargetFlags TargetFlags { get; } - } - - /// - /// Can be applied to attributes, type parameters, and parameters of a type assignable from . - /// When applied to an attribute, the decorated attribute behaves the same as . - /// When applied to a type parameter or to a parameter of type , indicates that the corresponding type - /// is used implicitly. - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter | AttributeTargets.Parameter)] - public sealed class MeansImplicitUseAttribute : Attribute - { - public MeansImplicitUseAttribute() - : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } - - public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) - : this(useKindFlags, ImplicitUseTargetFlags.Default) { } - - public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) - : this(ImplicitUseKindFlags.Default, targetFlags) { } - - public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) - { - UseKindFlags = useKindFlags; - TargetFlags = targetFlags; - } - - [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; } - - [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; } - } - - /// - /// Specify the details of implicitly used symbol when it is marked - /// with or . - /// - [Flags] - public enum ImplicitUseKindFlags - { - Default = Access | Assign | InstantiatedWithFixedConstructorSignature, - /// Only entity marked with attribute considered used. - Access = 1, - /// Indicates implicit assignment to a member. - Assign = 2, /// - /// Indicates implicit instantiation of a type with fixed constructor signature. - /// That means any unused constructor parameters won't be reported as such. + /// Indicates that the value of the marked element could be null sometimes, + /// so checking for null is required before its usage. /// - InstantiatedWithFixedConstructorSignature = 4, - /// Indicates implicit instantiation of a type. - InstantiatedNoFixedConstructorSignature = 8, - } - - /// - /// Specify what is considered to be used implicitly when marked - /// with or . - /// - [Flags] - public enum ImplicitUseTargetFlags - { - Default = Itself, - Itself = 1, - /// Members of entity marked with attribute are considered used. - Members = 2, - /// Entity marked with attribute and all its members considered used. - WithMembers = Itself | Members - } - - /// - /// This attribute is intended to mark publicly available API - /// which should not be removed and so is treated as used. - /// - [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] - [AttributeUsage(AttributeTargets.All, Inherited = false)] - public sealed class PublicAPIAttribute : Attribute - { - public PublicAPIAttribute() { } - - public PublicAPIAttribute([NotNull] string comment) - { - Comment = comment; - } - - [CanBeNull] public string Comment { get; } - } - - /// - /// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. - /// If the parameter is a delegate, indicates that delegate is executed while the method is executed. - /// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. - /// - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class InstantHandleAttribute : Attribute { } - - /// - /// Indicates that a method does not make any observable state changes. - /// The same as System.Diagnostics.Contracts.PureAttribute. - /// - /// - /// [Pure] int Multiply(int x, int y) => x * y; - /// - /// void M() { - /// Multiply(123, 42); // Waring: Return value of pure method is not used - /// } - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class PureAttribute : Attribute { } - - /// - /// Indicates that the return value of the method invocation must be used. - /// - /// - /// Methods decorated with this attribute (in contrast to pure methods) might change state, - /// but make no sense without using their return value.
- /// Similarly to , this attribute - /// will help detecting usages of the method when the return value in not used. - /// Additionally, you can optionally specify a custom message, which will be used when showing warnings, e.g. - /// [MustUseReturnValue("Use the return value to...")]. - ///
- [AttributeUsage(AttributeTargets.Method)] - public sealed class MustUseReturnValueAttribute : Attribute - { - public MustUseReturnValueAttribute() { } - - public MustUseReturnValueAttribute([NotNull] string justification) - { - Justification = justification; - } - - [CanBeNull] public string Justification { get; } - } - - /// - /// Indicates the type member or parameter of some type, that should be used instead of all other ways - /// to get the value of that type. This annotation is useful when you have some "context" value evaluated - /// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one. - /// - /// - /// class Foo { - /// [ProvidesContext] IBarService _barService = ...; - /// - /// void ProcessNode(INode node) { - /// DoSomething(node, node.GetGlobalServices().Bar); - /// // ^ Warning: use value of '_barService' field - /// } - /// } - /// - [AttributeUsage( - AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] - public sealed class ProvidesContextAttribute : Attribute { } - - /// - /// Indicates that a parameter is a path to a file or a folder within a web project. - /// Path can be relative or absolute, starting from web root (~). - /// - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class PathReferenceAttribute : Attribute - { - public PathReferenceAttribute() { } - - public PathReferenceAttribute([NotNull, PathReference] string basePath) - { - BasePath = basePath; - } - - [CanBeNull] public string BasePath { get; } - } - - /// - /// An extension method marked with this attribute is processed by code completion - /// as a 'Source Template'. When the extension method is completed over some expression, its source code - /// is automatically expanded like a template at call site. - /// - /// - /// Template method body can contain valid source code and/or special comments starting with '$'. - /// Text inside these comments is added as source code when the template is applied. Template parameters - /// can be used either as additional method parameters or as identifiers wrapped in two '$' signs. - /// Use the attribute to specify macros for parameters. - /// - /// - /// In this example, the 'forEach' method is a source template available over all values - /// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block: - /// - /// [SourceTemplate] - /// public static void forEach<T>(this IEnumerable<T> xs) { - /// foreach (var x in xs) { - /// //$ $END$ - /// } - /// } - /// - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class SourceTemplateAttribute : Attribute { } - - /// - /// Allows specifying a macro for a parameter of a source template. - /// - /// - /// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression - /// is defined in the property. When applied on a method, the target - /// template parameter is defined in the property. To apply the macro silently - /// for the parameter, set the property value = -1. - /// - /// - /// Applying the attribute on a source template method: - /// - /// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] - /// public static void forEach<T>(this IEnumerable<T> collection) { - /// foreach (var item in collection) { - /// //$ $END$ - /// } - /// } - /// - /// Applying the attribute on a template method parameter: - /// - /// [SourceTemplate] - /// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { - /// /*$ var $x$Id = "$newguid$" + x.ToString(); - /// x.DoSomething($x$Id); */ - /// } - /// - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] - public sealed class MacroAttribute : Attribute - { + /// + /// + /// [CanBeNull] object Test() => null; + /// + /// void UseTest() { + /// var p = Test(); + /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | + AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] + public sealed class CanBeNullAttribute : Attribute + { + } + /// - /// Allows specifying a macro that will be executed for a source template - /// parameter when the template is expanded. + /// Indicates that the value of the marked element can never be null. /// - [CanBeNull] public string Expression { get; set; } + /// + /// + /// [NotNull] object Foo() { + /// return null; // Warning: Possible 'null' assignment + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | + AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] + public sealed class NotNullAttribute : Attribute + { + } + + /// + /// Can be applied to symbols of types derived from IEnumerable as well as to symbols of Task + /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property + /// or of the Lazy.Value property can never be null. + /// + /// + /// + /// public void Foo([ItemNotNull]List<string> books) + /// { + /// foreach (var book in books) { + /// if (book != null) // Warning: Expression is always true + /// Console.WriteLine(book.ToUpper()); + /// } + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | + AttributeTargets.Delegate | AttributeTargets.Field)] + public sealed class ItemNotNullAttribute : Attribute + { + } + + /// + /// Can be applied to symbols of types derived from IEnumerable as well as to symbols of Task + /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property + /// or of the Lazy.Value property can be null. + /// + /// + /// + /// public void Foo([ItemCanBeNull]List<string> books) + /// { + /// foreach (var book in books) + /// { + /// // Warning: Possible 'System.NullReferenceException' + /// Console.WriteLine(book.ToUpper()); + /// } + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | + AttributeTargets.Delegate | AttributeTargets.Field)] + public sealed class ItemCanBeNullAttribute : Attribute + { + } + + /// + /// Indicates that the marked method builds string by the format pattern and (optional) arguments. + /// The parameter, which contains the format string, should be given in constructor. The format string + /// should be in -like form. + /// + /// + /// + /// [StringFormatMethod("message")] + /// void ShowError(string message, params object[] args) { /* do something */ } + /// + /// void Foo() { + /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Constructor | AttributeTargets.Method | + AttributeTargets.Property | AttributeTargets.Delegate)] + public sealed class StringFormatMethodAttribute : Attribute + { + /// + /// Specifies which parameter of an annotated method should be treated as the format string + /// + public StringFormatMethodAttribute([NotNull] string formatParameterName) + { + FormatParameterName = formatParameterName; + } + + [NotNull] public string FormatParameterName { get; } + } /// - /// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed. + /// Use this annotation to specify a type that contains static or const fields + /// with values for the annotated property/field/parameter. + /// The specified type will be used to improve completion suggestions. + /// + /// + /// + /// namespace TestNamespace + /// { + /// public class Constants + /// { + /// public static int INT_CONST = 1; + /// public const string STRING_CONST = "1"; + /// } + /// + /// public class Class1 + /// { + /// [ValueProvider("TestNamespace.Constants")] public int myField; + /// public void Foo([ValueProvider("TestNamespace.Constants")] string str) { } + /// + /// public void Test() + /// { + /// Foo(/*try completion here*/);// + /// myField = /*try completion here*/ + /// } + /// } + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, + AllowMultiple = true)] + public sealed class ValueProviderAttribute : Attribute + { + public ValueProviderAttribute([NotNull] string name) + { + Name = name; + } + + [NotNull] public string Name { get; } + } + + /// + /// Indicates that the function argument should be a string literal and match one + /// of the parameters of the caller function. For example, ReSharper annotates + /// the parameter of . + /// + /// + /// + /// void Foo(string param) { + /// if (param == null) + /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol + /// } + /// + /// + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class InvokerParameterNameAttribute : Attribute + { + } + + /// + /// Indicates that the method is contained in a type that implements + /// System.ComponentModel.INotifyPropertyChanged interface and this method + /// is used to notify that some property value changed. /// /// - /// If the target parameter is used several times in the template, only one occurrence becomes editable; - /// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence, - /// use values >= 0. To make the parameter non-editable when the template is expanded, use -1. + /// The method should be non-static and conform to one of the supported signatures: + /// + /// + /// NotifyChanged(string) + /// + /// + /// NotifyChanged(params string[]) + /// + /// + /// NotifyChanged{T}(Expression{Func{T}}) + /// + /// + /// NotifyChanged{T,U}(Expression{Func{T,U}}) + /// + /// + /// SetProperty{T}(ref T, T, string) + /// + /// /// - public int Editable { get; set; } + /// + /// + /// public class Foo : INotifyPropertyChanged { + /// public event PropertyChangedEventHandler PropertyChanged; + /// + /// [NotifyPropertyChangedInvocator] + /// protected virtual void NotifyChanged(string propertyName) { ... } + /// + /// string _name; + /// + /// public string Name { + /// get { return _name; } + /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } + /// } + /// } + /// + /// Examples of generated notifications: + /// + /// + /// NotifyChanged("Property") + /// + /// + /// NotifyChanged(() => Property) + /// + /// + /// NotifyChanged((VM x) => x.Property) + /// + /// + /// SetProperty(ref myField, value, "Property") + /// + /// + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute + { + public NotifyPropertyChangedInvocatorAttribute() + { + } + + public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) + { + ParameterName = parameterName; + } + + [CanBeNull] public string ParameterName { get; } + } + + /// + /// Describes dependency between method input and output. + /// + /// + ///

Function Definition Table syntax:

+ /// + /// FDT ::= FDTRow [;FDTRow]* + /// FDTRow ::= Input => Output | Output <= Input + /// Input ::= ParameterName: Value [, Input]* + /// Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value} + /// Value ::= true | false | null | notnull | canbenull + /// + /// If the method has a single input parameter, its name could be omitted.
+ /// Using halt (or void/nothing, which is the same) for the method output + /// means that the method doesn't return normally (throws or terminates the process).
+ /// Value canbenull is only applicable for output parameters.
+ /// You can use multiple [ContractAnnotation] for each FDT row, or use single attribute + /// with rows separated by semicolon. There is no notion of order rows, all rows are checked + /// for applicability and applied per each program state tracked by the analysis engine.
+ ///
+ /// + /// + /// + /// + /// [ContractAnnotation("=> halt")] + /// public void TerminationMethod() + /// + /// + /// + /// + /// [ContractAnnotation("null <= param:null")] // reverse condition syntax + /// public string GetName(string surname) + /// + /// + /// + /// + /// [ContractAnnotation("s:null => true")] + /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() + /// + /// + /// + /// + /// // A method that returns null if the parameter is null, + /// // and not null if the parameter is not null + /// [ContractAnnotation("null => null; notnull => notnull")] + /// public object Transform(object data) + /// + /// + /// + /// + /// [ContractAnnotation("=> true, result: notnull; => false, result: null")] + /// public bool TryParse(string s, out Person result) + /// + /// + /// + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + public sealed class ContractAnnotationAttribute : Attribute + { + public ContractAnnotationAttribute([NotNull] string contract) + : this(contract, false) + { + } + + public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) + { + Contract = contract; + ForceFullStates = forceFullStates; + } + + [NotNull] public string Contract { get; } + + public bool ForceFullStates { get; } + } + + /// + /// Indicates whether the marked element should be localized. + /// + /// + /// + /// [LocalizationRequiredAttribute(true)] + /// class Foo { + /// string str = "my string"; // Warning: Localizable string + /// } + /// + /// + [AttributeUsage(AttributeTargets.All)] + public sealed class LocalizationRequiredAttribute : Attribute + { + public LocalizationRequiredAttribute() : this(true) + { + } + + public LocalizationRequiredAttribute(bool required) + { + Required = required; + } + + public bool Required { get; } + } + + /// + /// Indicates that the value of the marked type (or its derivatives) + /// cannot be compared using '==' or '!=' operators and Equals() + /// should be used instead. However, using '==' or '!=' for comparison + /// with null is always permitted. + /// + /// + /// + /// [CannotApplyEqualityOperator] + /// class NoEquality { } + /// + /// class UsesNoEquality { + /// void Test() { + /// var ca1 = new NoEquality(); + /// var ca2 = new NoEquality(); + /// if (ca1 != null) { // OK + /// bool condition = ca1 == ca2; // Warning + /// } + /// } + /// } + /// + /// + [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] + public sealed class CannotApplyEqualityOperatorAttribute : Attribute + { + } + + /// + /// When applied to a target attribute, specifies a requirement for any type marked + /// with the target attribute to implement or inherit specific type or types. + /// + /// + /// + /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement + /// class ComponentAttribute : Attribute { } + /// + /// [Component] // ComponentAttribute requires implementing IComponent interface + /// class MyComponent : IComponent { } + /// + /// + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + [BaseTypeRequired(typeof(Attribute))] + public sealed class BaseTypeRequiredAttribute : Attribute + { + public BaseTypeRequiredAttribute([NotNull] Type baseType) + { + BaseType = baseType; + } + + [NotNull] public Type BaseType { get; } + } + + /// + /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), + /// so this symbol will not be reported as unused (as well as by other usage inspections). + /// + [AttributeUsage(AttributeTargets.All, Inherited = false)] + public sealed class UsedImplicitlyAttribute : Attribute + { + public UsedImplicitlyAttribute() + : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) + { + } + + public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) + : this(useKindFlags, ImplicitUseTargetFlags.Default) + { + } + + public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) + : this(ImplicitUseKindFlags.Default, targetFlags) + { + } + + public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) + { + UseKindFlags = useKindFlags; + TargetFlags = targetFlags; + } + + public ImplicitUseKindFlags UseKindFlags { get; } + + public ImplicitUseTargetFlags TargetFlags { get; } + } + + /// + /// Can be applied to attributes, type parameters, and parameters of a type assignable from + /// . + /// When applied to an attribute, the decorated attribute behaves the same as . + /// When applied to a type parameter or to a parameter of type , indicates that the + /// corresponding type + /// is used implicitly. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter | AttributeTargets.Parameter)] + public sealed class MeansImplicitUseAttribute : Attribute + { + public MeansImplicitUseAttribute() + : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) + { + } + + public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) + : this(useKindFlags, ImplicitUseTargetFlags.Default) + { + } + + public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) + : this(ImplicitUseKindFlags.Default, targetFlags) + { + } + + public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) + { + UseKindFlags = useKindFlags; + TargetFlags = targetFlags; + } + + [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; } + + [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; } + } + + /// + /// Specify the details of implicitly used symbol when it is marked + /// with or . + /// + [Flags] + public enum ImplicitUseKindFlags + { + Default = Access | Assign | InstantiatedWithFixedConstructorSignature, + + /// Only entity marked with attribute considered used. + Access = 1, + + /// Indicates implicit assignment to a member. + Assign = 2, + + /// + /// Indicates implicit instantiation of a type with fixed constructor signature. + /// That means any unused constructor parameters won't be reported as such. + /// + InstantiatedWithFixedConstructorSignature = 4, + + /// Indicates implicit instantiation of a type. + InstantiatedNoFixedConstructorSignature = 8 + } + + /// + /// Specify what is considered to be used implicitly when marked + /// with or . + /// + [Flags] + public enum ImplicitUseTargetFlags + { + Default = Itself, + Itself = 1, + + /// Members of entity marked with attribute are considered used. + Members = 2, + + /// Entity marked with attribute and all its members considered used. + WithMembers = Itself | Members + } + + /// + /// This attribute is intended to mark publicly available API + /// which should not be removed and so is treated as used. + /// + [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] + [AttributeUsage(AttributeTargets.All, Inherited = false)] + public sealed class PublicAPIAttribute : Attribute + { + public PublicAPIAttribute() + { + } + + public PublicAPIAttribute([NotNull] string comment) + { + Comment = comment; + } + + [CanBeNull] public string Comment { get; } + } + + /// + /// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. + /// If the parameter is a delegate, indicates that delegate is executed while the method is executed. + /// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. + /// + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class InstantHandleAttribute : Attribute + { + } + + /// + /// Indicates that a method does not make any observable state changes. + /// The same as System.Diagnostics.Contracts.PureAttribute. + /// + /// + /// + /// [Pure] int Multiply(int x, int y) => x * y; + /// + /// void M() { + /// Multiply(123, 42); // Waring: Return value of pure method is not used + /// } + /// + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class PureAttribute : Attribute + { + } + + /// + /// Indicates that the return value of the method invocation must be used. + /// + /// + /// Methods decorated with this attribute (in contrast to pure methods) might change state, + /// but make no sense without using their return value.
+ /// Similarly to , this attribute + /// will help detecting usages of the method when the return value in not used. + /// Additionally, you can optionally specify a custom message, which will be used when showing warnings, e.g. + /// [MustUseReturnValue("Use the return value to...")]. + ///
+ [AttributeUsage(AttributeTargets.Method)] + public sealed class MustUseReturnValueAttribute : Attribute + { + public MustUseReturnValueAttribute() + { + } + + public MustUseReturnValueAttribute([NotNull] string justification) + { + Justification = justification; + } + + [CanBeNull] public string Justification { get; } + } + + /// + /// Indicates the type member or parameter of some type, that should be used instead of all other ways + /// to get the value of that type. This annotation is useful when you have some "context" value evaluated + /// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one. + /// + /// + /// + /// class Foo { + /// [ProvidesContext] IBarService _barService = ...; + /// + /// void ProcessNode(INode node) { + /// DoSomething(node, node.GetGlobalServices().Bar); + /// // ^ Warning: use value of '_barService' field + /// } + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] + public sealed class ProvidesContextAttribute : Attribute + { + } + + /// + /// Indicates that a parameter is a path to a file or a folder within a web project. + /// Path can be relative or absolute, starting from web root (~). + /// + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class PathReferenceAttribute : Attribute + { + public PathReferenceAttribute() + { + } + + public PathReferenceAttribute([NotNull] [PathReference] string basePath) + { + BasePath = basePath; + } + + [CanBeNull] public string BasePath { get; } + } + + /// + /// An extension method marked with this attribute is processed by code completion + /// as a 'Source Template'. When the extension method is completed over some expression, its source code + /// is automatically expanded like a template at call site. + /// + /// + /// Template method body can contain valid source code and/or special comments starting with '$'. + /// Text inside these comments is added as source code when the template is applied. Template parameters + /// can be used either as additional method parameters or as identifiers wrapped in two '$' signs. + /// Use the attribute to specify macros for parameters. + /// + /// + /// In this example, the 'forEach' method is a source template available over all values + /// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block: + /// + /// [SourceTemplate] + /// public static void forEach<T>(this IEnumerable<T> xs) { + /// foreach (var x in xs) { + /// //$ $END$ + /// } + /// } + /// + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class SourceTemplateAttribute : Attribute + { + } + + /// + /// Allows specifying a macro for a parameter of a source template. + /// + /// + /// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression + /// is defined in the property. When applied on a method, the target + /// template parameter is defined in the property. To apply the macro silently + /// for the parameter, set the property value = -1. + /// + /// + /// Applying the attribute on a source template method: + /// + /// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] + /// public static void forEach<T>(this IEnumerable<T> collection) { + /// foreach (var item in collection) { + /// //$ $END$ + /// } + /// } + /// + /// Applying the attribute on a template method parameter: + /// + /// [SourceTemplate] + /// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { + /// /*$ var $x$Id = "$newguid$" + x.ToString(); + /// x.DoSomething($x$Id); */ + /// } + /// + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] + public sealed class MacroAttribute : Attribute + { + /// + /// Allows specifying a macro that will be executed for a source template + /// parameter when the template is expanded. + /// + [CanBeNull] + public string Expression { get; set; } + + /// + /// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed. + /// + /// + /// If the target parameter is used several times in the template, only one occurrence becomes editable; + /// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence, + /// use values >= 0. To make the parameter non-editable when the template is expanded, use -1. + /// + public int Editable { get; set; } + + /// + /// Identifies the target parameter of a source template if the + /// is applied on a template method. + /// + [CanBeNull] + public string Target { get; set; } + } + + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] + public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute + { + public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) + { + Format = format; + } + + [NotNull] public string Format { get; } + } + + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] + public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute + { + public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) + { + Format = format; + } + + [NotNull] public string Format { get; } + } + + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] + public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute + { + public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) + { + Format = format; + } + + [NotNull] public string Format { get; } + } + + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] + public sealed class AspMvcMasterLocationFormatAttribute : Attribute + { + public AspMvcMasterLocationFormatAttribute([NotNull] string format) + { + Format = format; + } + + [NotNull] public string Format { get; } + } + + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] + public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute + { + public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) + { + Format = format; + } + + [NotNull] public string Format { get; } + } + + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] + public sealed class AspMvcViewLocationFormatAttribute : Attribute + { + public AspMvcViewLocationFormatAttribute([NotNull] string format) + { + Format = format; + } + + [NotNull] public string Format { get; } + } /// - /// Identifies the target parameter of a source template if the - /// is applied on a template method. + /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter + /// is an MVC action. If applied to a method, the MVC action name is calculated + /// implicitly from the context. Use this attribute for custom wrappers similar to + /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String). /// - [CanBeNull] public string Target { get; set; } - } + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcActionAttribute : Attribute + { + public AspMvcActionAttribute() + { + } + + public AspMvcActionAttribute([NotNull] string anonymousProperty) + { + AnonymousProperty = anonymousProperty; + } - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] - public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute - { - public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) + [CanBeNull] public string AnonymousProperty { get; } + } + + /// + /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC area. + /// Use this attribute for custom wrappers similar to + /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcAreaAttribute : Attribute { - Format = format; + public AspMvcAreaAttribute() + { + } + + public AspMvcAreaAttribute([NotNull] string anonymousProperty) + { + AnonymousProperty = anonymousProperty; + } + + [CanBeNull] public string AnonymousProperty { get; } } - [NotNull] public string Format { get; } - } + /// + /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is + /// an MVC controller. If applied to a method, the MVC controller name is calculated + /// implicitly from the context. Use this attribute for custom wrappers similar to + /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcControllerAttribute : Attribute + { + public AspMvcControllerAttribute() + { + } + + public AspMvcControllerAttribute([NotNull] string anonymousProperty) + { + AnonymousProperty = anonymousProperty; + } - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] - public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute - { - public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) + [CanBeNull] public string AnonymousProperty { get; } + } + + /// + /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC Master. Use this attribute + /// for custom wrappers similar to System.Web.Mvc.Controller.View(String, String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcMasterAttribute : Attribute { - Format = format; } - [NotNull] public string Format { get; } - } + /// + /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC model type. Use this attribute + /// for custom wrappers similar to System.Web.Mvc.Controller.View(String, Object). + /// + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class AspMvcModelTypeAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] - public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute - { - public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) + /// + /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC + /// partial view. If applied to a method, the MVC partial view name is calculated implicitly + /// from the context. Use this attribute for custom wrappers similar to + /// System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcPartialViewAttribute : Attribute { - Format = format; } - [NotNull] public string Format { get; } - } + /// + /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] + public sealed class AspMvcSuppressViewErrorAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] - public sealed class AspMvcMasterLocationFormatAttribute : Attribute - { - public AspMvcMasterLocationFormatAttribute([NotNull] string format) + /// + /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. + /// Use this attribute for custom wrappers similar to + /// System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcDisplayTemplateAttribute : Attribute { - Format = format; } - [NotNull] public string Format { get; } - } + /// + /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC editor template. + /// Use this attribute for custom wrappers similar to + /// System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcEditorTemplateAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] - public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute - { - public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) + /// + /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC template. + /// Use this attribute for custom wrappers similar to + /// System.ComponentModel.DataAnnotations.UIHintAttribute(System.String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcTemplateAttribute : Attribute { - Format = format; } - [NotNull] public string Format { get; } - } + /// + /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter + /// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly + /// from the context. Use this attribute for custom wrappers similar to + /// System.Web.Mvc.Controller.View(Object). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcViewAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] - public sealed class AspMvcViewLocationFormatAttribute : Attribute - { - public AspMvcViewLocationFormatAttribute([NotNull] string format) + /// + /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter + /// is an MVC view component name. + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcViewComponentAttribute : Attribute { - Format = format; } - [NotNull] public string Format { get; } - } + /// + /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter + /// is an MVC view component view. If applied to a method, the MVC view component view name is default. + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class AspMvcViewComponentViewAttribute : Attribute + { + } - /// - /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter - /// is an MVC action. If applied to a method, the MVC action name is calculated - /// implicitly from the context. Use this attribute for custom wrappers similar to - /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcActionAttribute : Attribute - { - public AspMvcActionAttribute() { } + /// + /// ASP.NET MVC attribute. When applied to a parameter of an attribute, + /// indicates that this parameter is an MVC action name. + /// + /// + /// + /// [ActionName("Foo")] + /// public ActionResult Login(string returnUrl) { + /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK + /// return RedirectToAction("Bar"); // Error: Cannot resolve action + /// } + /// + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] + public sealed class AspMvcActionSelectorAttribute : Attribute + { + } - public AspMvcActionAttribute([NotNull] string anonymousProperty) + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] + public sealed class HtmlElementAttributesAttribute : Attribute { - AnonymousProperty = anonymousProperty; + public HtmlElementAttributesAttribute() + { + } + + public HtmlElementAttributesAttribute([NotNull] string name) + { + Name = name; + } + + [CanBeNull] public string Name { get; } } - [CanBeNull] public string AnonymousProperty { get; } - } + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] + public sealed class HtmlAttributeValueAttribute : Attribute + { + public HtmlAttributeValueAttribute([NotNull] string name) + { + Name = name; + } - /// - /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC area. - /// Use this attribute for custom wrappers similar to - /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcAreaAttribute : Attribute - { - public AspMvcAreaAttribute() { } + [NotNull] public string Name { get; } + } - public AspMvcAreaAttribute([NotNull] string anonymousProperty) - { - AnonymousProperty = anonymousProperty; + /// + /// Razor attribute. Indicates that the marked parameter or method is a Razor section. + /// Use this attribute for custom wrappers similar to + /// System.Web.WebPages.WebPageBase.RenderSection(String). + /// + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] + public sealed class RazorSectionAttribute : Attribute + { } - [CanBeNull] public string AnonymousProperty { get; } - } - - /// - /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is - /// an MVC controller. If applied to a method, the MVC controller name is calculated - /// implicitly from the context. Use this attribute for custom wrappers similar to - /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcControllerAttribute : Attribute - { - public AspMvcControllerAttribute() { } - - public AspMvcControllerAttribute([NotNull] string anonymousProperty) - { - AnonymousProperty = anonymousProperty; - } - - [CanBeNull] public string AnonymousProperty { get; } - } - - /// - /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC Master. Use this attribute - /// for custom wrappers similar to System.Web.Mvc.Controller.View(String, String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcMasterAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC model type. Use this attribute - /// for custom wrappers similar to System.Web.Mvc.Controller.View(String, Object). - /// - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class AspMvcModelTypeAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC - /// partial view. If applied to a method, the MVC partial view name is calculated implicitly - /// from the context. Use this attribute for custom wrappers similar to - /// System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcPartialViewAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method. - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] - public sealed class AspMvcSuppressViewErrorAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. - /// Use this attribute for custom wrappers similar to - /// System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcDisplayTemplateAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC editor template. - /// Use this attribute for custom wrappers similar to - /// System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcEditorTemplateAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. Indicates that the marked parameter is an MVC template. - /// Use this attribute for custom wrappers similar to - /// System.ComponentModel.DataAnnotations.UIHintAttribute(System.String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcTemplateAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter - /// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly - /// from the context. Use this attribute for custom wrappers similar to - /// System.Web.Mvc.Controller.View(Object). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcViewAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter - /// is an MVC view component name. - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcViewComponentAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter - /// is an MVC view component view. If applied to a method, the MVC view component view name is default. - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class AspMvcViewComponentViewAttribute : Attribute { } - - /// - /// ASP.NET MVC attribute. When applied to a parameter of an attribute, - /// indicates that this parameter is an MVC action name. - /// - /// - /// [ActionName("Foo")] - /// public ActionResult Login(string returnUrl) { - /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK - /// return RedirectToAction("Bar"); // Error: Cannot resolve action - /// } - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] - public sealed class AspMvcActionSelectorAttribute : Attribute { } - - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] - public sealed class HtmlElementAttributesAttribute : Attribute - { - public HtmlElementAttributesAttribute() { } - - public HtmlElementAttributesAttribute([NotNull] string name) - { - Name = name; - } - - [CanBeNull] public string Name { get; } - } - - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] - public sealed class HtmlAttributeValueAttribute : Attribute - { - public HtmlAttributeValueAttribute([NotNull] string name) - { - Name = name; - } - - [NotNull] public string Name { get; } - } - - /// - /// Razor attribute. Indicates that the marked parameter or method is a Razor section. - /// Use this attribute for custom wrappers similar to - /// System.Web.WebPages.WebPageBase.RenderSection(String). - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] - public sealed class RazorSectionAttribute : Attribute { } - - /// - /// Indicates how method, constructor invocation, or property access - /// over collection type affects the contents of the collection. - /// Use to specify the access type. - /// - /// - /// Using this attribute only makes sense if all collection methods are marked with this attribute. - /// - /// - /// public class MyStringCollection : List<string> - /// { - /// [CollectionAccess(CollectionAccessType.Read)] - /// public string GetFirstString() - /// { - /// return this.ElementAt(0); - /// } - /// } - /// class Test - /// { - /// public void Foo() - /// { - /// // Warning: Contents of the collection is never updated - /// var col = new MyStringCollection(); - /// string x = col.GetFirstString(); - /// } - /// } - /// - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] - public sealed class CollectionAccessAttribute : Attribute - { - public CollectionAccessAttribute(CollectionAccessType collectionAccessType) - { - CollectionAccessType = collectionAccessType; - } - - public CollectionAccessType CollectionAccessType { get; } - } - - /// - /// Provides a value for the to define - /// how the collection method invocation affects the contents of the collection. - /// - [Flags] - public enum CollectionAccessType - { - /// Method does not use or modify content of the collection. - None = 0, - /// Method only reads content of the collection but does not modify it. - Read = 1, - /// Method can change content of the collection but does not add new elements. - ModifyExistingContent = 2, - /// Method can add new elements to the collection. - UpdatedContent = ModifyExistingContent | 4 - } - - /// - /// Indicates that the marked method is assertion method, i.e. it halts the control flow if - /// one of the conditions is satisfied. To set the condition, mark one of the parameters with - /// attribute. - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class AssertionMethodAttribute : Attribute { } - - /// - /// Indicates the condition parameter of the assertion method. The method itself should be - /// marked by attribute. The mandatory argument of - /// the attribute is the assertion type. - /// - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class AssertionConditionAttribute : Attribute - { - public AssertionConditionAttribute(AssertionConditionType conditionType) - { - ConditionType = conditionType; - } - - public AssertionConditionType ConditionType { get; } - } - - /// - /// Specifies assertion type. If the assertion method argument satisfies the condition, - /// then the execution continues. Otherwise, execution is assumed to be halted. - /// - public enum AssertionConditionType - { - /// Marked parameter should be evaluated to true. - IS_TRUE = 0, - /// Marked parameter should be evaluated to false. - IS_FALSE = 1, - /// Marked parameter should be evaluated to null value. - IS_NULL = 2, - /// Marked parameter should be evaluated to not null value. - IS_NOT_NULL = 3, - } - - /// - /// Indicates that the marked method unconditionally terminates control flow execution. - /// For example, it could unconditionally throw exception. - /// - [Obsolete("Use [ContractAnnotation('=> halt')] instead")] - [AttributeUsage(AttributeTargets.Method)] - public sealed class TerminatesProgramAttribute : Attribute { } - - /// - /// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select, - /// .Where). This annotation allows inference of [InstantHandle] annotation for parameters - /// of delegate type by analyzing LINQ method chains. - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class LinqTunnelAttribute : Attribute { } - - /// - /// Indicates that IEnumerable passed as a parameter is not enumerated. - /// Use this annotation to suppress the 'Possible multiple enumeration of IEnumerable' inspection. - /// - /// - /// static void ThrowIfNull<T>([NoEnumeration] T v, string n) where T : class - /// { - /// // custom check for null but no enumeration - /// } - /// - /// void Foo(IEnumerable<string> values) - /// { - /// ThrowIfNull(values, nameof(values)); - /// var x = values.ToList(); // No warnings about multiple enumeration - /// } - /// - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class NoEnumerationAttribute : Attribute { } - - /// - /// Indicates that the marked parameter is a regular expression pattern. - /// - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class RegexPatternAttribute : Attribute { } - - /// - /// Prevents the Member Reordering feature from tossing members of the marked class. - /// - /// - /// The attribute must be mentioned in your member reordering patterns. - /// - [AttributeUsage( - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] - public sealed class NoReorderAttribute : Attribute { } - - /// - /// XAML attribute. Indicates the type that has ItemsSource property and should be treated - /// as ItemsControl-derived type, to enable inner items DataContext type resolve. - /// - [AttributeUsage(AttributeTargets.Class)] - public sealed class XamlItemsControlAttribute : Attribute { } - - /// - /// XAML attribute. Indicates the property of some BindingBase-derived type, that - /// is used to bind some item of ItemsControl-derived type. This annotation will - /// enable the DataContext type resolve for XAML bindings for such properties. - /// - /// - /// Property should have the tree ancestor of the ItemsControl type or - /// marked with the attribute. - /// - [AttributeUsage(AttributeTargets.Property)] - public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } - - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - public sealed class AspChildControlTypeAttribute : Attribute - { - public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) - { - TagName = tagName; - ControlType = controlType; - } - - [NotNull] public string TagName { get; } - - [NotNull] public Type ControlType { get; } - } - - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] - public sealed class AspDataFieldAttribute : Attribute { } - - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] - public sealed class AspDataFieldsAttribute : Attribute { } - - [AttributeUsage(AttributeTargets.Property)] - public sealed class AspMethodPropertyAttribute : Attribute { } - - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - public sealed class AspRequiredAttributeAttribute : Attribute - { - public AspRequiredAttributeAttribute([NotNull] string attribute) - { - Attribute = attribute; - } - - [NotNull] public string Attribute { get; } - } - - [AttributeUsage(AttributeTargets.Property)] - public sealed class AspTypePropertyAttribute : Attribute - { - public bool CreateConstructorReferences { get; } - - public AspTypePropertyAttribute(bool createConstructorReferences) - { - CreateConstructorReferences = createConstructorReferences; - } - } - - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public sealed class RazorImportNamespaceAttribute : Attribute - { - public RazorImportNamespaceAttribute([NotNull] string name) + /// + /// Indicates how method, constructor invocation, or property access + /// over collection type affects the contents of the collection. + /// Use to specify the access type. + /// + /// + /// Using this attribute only makes sense if all collection methods are marked with this attribute. + /// + /// + /// + /// public class MyStringCollection : List<string> + /// { + /// [CollectionAccess(CollectionAccessType.Read)] + /// public string GetFirstString() + /// { + /// return this.ElementAt(0); + /// } + /// } + /// class Test + /// { + /// public void Foo() + /// { + /// // Warning: Contents of the collection is never updated + /// var col = new MyStringCollection(); + /// string x = col.GetFirstString(); + /// } + /// } + /// + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] + public sealed class CollectionAccessAttribute : Attribute { - Name = name; + public CollectionAccessAttribute(CollectionAccessType collectionAccessType) + { + CollectionAccessType = collectionAccessType; + } + + public CollectionAccessType CollectionAccessType { get; } } - [NotNull] public string Name { get; } - } + /// + /// Provides a value for the to define + /// how the collection method invocation affects the contents of the collection. + /// + [Flags] + public enum CollectionAccessType + { + /// Method does not use or modify content of the collection. + None = 0, + + /// Method only reads content of the collection but does not modify it. + Read = 1, + + /// Method can change content of the collection but does not add new elements. + ModifyExistingContent = 2, + + /// Method can add new elements to the collection. + UpdatedContent = ModifyExistingContent | 4 + } - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public sealed class RazorInjectionAttribute : Attribute - { - public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) + /// + /// Indicates that the marked method is assertion method, i.e. it halts the control flow if + /// one of the conditions is satisfied. To set the condition, mark one of the parameters with + /// attribute. + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class AssertionMethodAttribute : Attribute { - Type = type; - FieldName = fieldName; } - [NotNull] public string Type { get; } + /// + /// Indicates the condition parameter of the assertion method. The method itself should be + /// marked by attribute. The mandatory argument of + /// the attribute is the assertion type. + /// + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class AssertionConditionAttribute : Attribute + { + public AssertionConditionAttribute(AssertionConditionType conditionType) + { + ConditionType = conditionType; + } - [NotNull] public string FieldName { get; } - } + public AssertionConditionType ConditionType { get; } + } - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public sealed class RazorDirectiveAttribute : Attribute - { - public RazorDirectiveAttribute([NotNull] string directive) + /// + /// Specifies assertion type. If the assertion method argument satisfies the condition, + /// then the execution continues. Otherwise, execution is assumed to be halted. + /// + public enum AssertionConditionType { - Directive = directive; + /// Marked parameter should be evaluated to true. + IS_TRUE = 0, + + /// Marked parameter should be evaluated to false. + IS_FALSE = 1, + + /// Marked parameter should be evaluated to null value. + IS_NULL = 2, + + /// Marked parameter should be evaluated to not null value. + IS_NOT_NULL = 3 } - [NotNull] public string Directive { get; } - } + /// + /// Indicates that the marked method unconditionally terminates control flow execution. + /// For example, it could unconditionally throw exception. + /// + [Obsolete("Use [ContractAnnotation('=> halt')] instead")] + [AttributeUsage(AttributeTargets.Method)] + public sealed class TerminatesProgramAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public sealed class RazorPageBaseTypeAttribute : Attribute - { - public RazorPageBaseTypeAttribute([NotNull] string baseType) - { - BaseType = baseType; - } - public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName) - { - BaseType = baseType; - PageName = pageName; - } + /// + /// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select, + /// .Where). This annotation allows inference of [InstantHandle] annotation for parameters + /// of delegate type by analyzing LINQ method chains. + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class LinqTunnelAttribute : Attribute + { + } - [NotNull] public string BaseType { get; } - [CanBeNull] public string PageName { get; } - } + /// + /// Indicates that IEnumerable passed as a parameter is not enumerated. + /// Use this annotation to suppress the 'Possible multiple enumeration of IEnumerable' inspection. + /// + /// + /// + /// static void ThrowIfNull<T>([NoEnumeration] T v, string n) where T : class + /// { + /// // custom check for null but no enumeration + /// } + /// + /// void Foo(IEnumerable<string> values) + /// { + /// ThrowIfNull(values, nameof(values)); + /// var x = values.ToList(); // No warnings about multiple enumeration + /// } + /// + /// + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class NoEnumerationAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Method)] - public sealed class RazorHelperCommonAttribute : Attribute { } + /// + /// Indicates that the marked parameter is a regular expression pattern. + /// + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class RegexPatternAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Property)] - public sealed class RazorLayoutAttribute : Attribute { } + /// + /// Prevents the Member Reordering feature from tossing members of the marked class. + /// + /// + /// The attribute must be mentioned in your member reordering patterns. + /// + [AttributeUsage( + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] + public sealed class NoReorderAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Method)] - public sealed class RazorWriteLiteralMethodAttribute : Attribute { } + /// + /// XAML attribute. Indicates the type that has ItemsSource property and should be treated + /// as ItemsControl-derived type, to enable inner items DataContext type resolve. + /// + [AttributeUsage(AttributeTargets.Class)] + public sealed class XamlItemsControlAttribute : Attribute + { + } + + /// + /// XAML attribute. Indicates the property of some BindingBase-derived type, that + /// is used to bind some item of ItemsControl-derived type. This annotation will + /// enable the DataContext type resolve for XAML bindings for such properties. + /// + /// + /// Property should have the tree ancestor of the ItemsControl type or + /// marked with the attribute. + /// + [AttributeUsage(AttributeTargets.Property)] + public sealed class XamlItemBindingOfItemsControlAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + public sealed class AspChildControlTypeAttribute : Attribute + { + public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) + { + TagName = tagName; + ControlType = controlType; + } + + [NotNull] public string TagName { get; } + + [NotNull] public Type ControlType { get; } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] + public sealed class AspDataFieldAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Method)] - public sealed class RazorWriteMethodAttribute : Attribute { } + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] + public sealed class AspDataFieldsAttribute : Attribute + { + } - [AttributeUsage(AttributeTargets.Parameter)] - public sealed class RazorWriteMethodParameterAttribute : Attribute { } + [AttributeUsage(AttributeTargets.Property)] + public sealed class AspMethodPropertyAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + public sealed class AspRequiredAttributeAttribute : Attribute + { + public AspRequiredAttributeAttribute([NotNull] string attribute) + { + Attribute = attribute; + } + + [NotNull] public string Attribute { get; } + } + + [AttributeUsage(AttributeTargets.Property)] + public sealed class AspTypePropertyAttribute : Attribute + { + public AspTypePropertyAttribute(bool createConstructorReferences) + { + CreateConstructorReferences = createConstructorReferences; + } + + public bool CreateConstructorReferences { get; } + } + + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public sealed class RazorImportNamespaceAttribute : Attribute + { + public RazorImportNamespaceAttribute([NotNull] string name) + { + Name = name; + } + + [NotNull] public string Name { get; } + } + + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public sealed class RazorInjectionAttribute : Attribute + { + public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) + { + Type = type; + FieldName = fieldName; + } + + [NotNull] public string Type { get; } + + [NotNull] public string FieldName { get; } + } + + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public sealed class RazorDirectiveAttribute : Attribute + { + public RazorDirectiveAttribute([NotNull] string directive) + { + Directive = directive; + } + + [NotNull] public string Directive { get; } + } + + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public sealed class RazorPageBaseTypeAttribute : Attribute + { + public RazorPageBaseTypeAttribute([NotNull] string baseType) + { + BaseType = baseType; + } + + public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName) + { + BaseType = baseType; + PageName = pageName; + } + + [NotNull] public string BaseType { get; } + [CanBeNull] public string PageName { get; } + } + + [AttributeUsage(AttributeTargets.Method)] + public sealed class RazorHelperCommonAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Property)] + public sealed class RazorLayoutAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Method)] + public sealed class RazorWriteLiteralMethodAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Method)] + public sealed class RazorWriteMethodAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class RazorWriteMethodParameterAttribute : Attribute + { + } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/AssemblyInfo.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/AssemblyInfo.cs index 56444fcbb..f3da9e4ca 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/AssemblyInfo.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/Properties/AssemblyInfo.cs @@ -1,6 +1,7 @@ using System.Reflection; using System.Runtime.InteropServices; using System.Windows; +using log4net.Config; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, @@ -15,7 +16,7 @@ [assembly: AssemblyCulture("")] // Log4net -[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] +[assembly: XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von @@ -33,12 +34,12 @@ [assembly: ThemeInfo( - ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher - //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird, - // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.) - ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs - //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird, - // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.) + ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher + //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird, + // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.) + ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs + //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird, + // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.) )] @@ -53,4 +54,4 @@ // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.4.0.*")] -[assembly: AssemblyFileVersion("3.4.0.0")] +[assembly: AssemblyFileVersion("3.4.0.0")] \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/InfoWindowViewModel.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/InfoWindowViewModel.cs index 979045330..a28549b94 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/InfoWindowViewModel.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/InfoWindowViewModel.cs @@ -1,7 +1,7 @@ -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Properties; -using System.ComponentModel; +using System.ComponentModel; using System.Runtime.CompilerServices; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; namespace StatisticsAnalysisTool.ViewModels { @@ -22,17 +22,21 @@ private void Init() #region Bindings - public InfoWindowTranslation Translation { + public InfoWindowTranslation Translation + { get => _translation; - set { + set + { _translation = value; OnPropertyChanged(); } } - public bool ShowNotAgainChecked { + public bool ShowNotAgainChecked + { get => _showNotAgainChecked; - set { + set + { _showNotAgainChecked = value; Settings.Default.ShowInfoWindowOnStartChecked = !_showNotAgainChecked; OnPropertyChanged(); diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemAlertWindowViewModel.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemAlertWindowViewModel.cs index 6c8274315..5aa65aced 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemAlertWindowViewModel.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemAlertWindowViewModel.cs @@ -1,20 +1,20 @@ -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Models; -using System.ComponentModel; +using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Media; using System.Windows.Media.Imaging; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Models; namespace StatisticsAnalysisTool.ViewModels { public class ItemAlertWindowViewModel : INotifyPropertyChanged { private readonly AlertInfos _alertInfos; - private ItemAlertWindowTranslation _translation; - private string _itemName; + private Color _cityColor; private string _cityName; private BitmapImage _icon; - private Color _cityColor; + private string _itemName; + private ItemAlertWindowTranslation _translation; public ItemAlertWindowViewModel(AlertInfos alertInfos) { @@ -33,7 +33,8 @@ private void Init() #region Bindings - public string ItemName { + public string ItemName + { get => _itemName; set { @@ -42,7 +43,8 @@ public string ItemName { } } - public string CityName { + public string CityName + { get => _cityName; set { @@ -51,7 +53,8 @@ public string CityName { } } - public BitmapImage Icon { + public BitmapImage Icon + { get => _icon; set { @@ -60,7 +63,8 @@ public BitmapImage Icon { } } - public Color CityColor { + public Color CityColor + { get => _cityColor; set { @@ -69,9 +73,11 @@ public Color CityColor { } } - public ItemAlertWindowTranslation Translation { + public ItemAlertWindowTranslation Translation + { get => _translation; - set { + set + { _translation = value; OnPropertyChanged(); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemWindowViewModel.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemWindowViewModel.cs index 6001e317e..ab23a1c31 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemWindowViewModel.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/ItemWindowViewModel.cs @@ -1,13 +1,7 @@ -using FontAwesome5; -using log4net; -using StatisticsAnalysisTool.Common; -using StatisticsAnalysisTool.Exceptions; -using StatisticsAnalysisTool.Models; -using StatisticsAnalysisTool.Properties; -using StatisticsAnalysisTool.Views; -using System; +using System; using System.Collections.Generic; using System.ComponentModel; +using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; @@ -16,52 +10,63 @@ using System.Windows.Controls; using System.Windows.Markup; using System.Windows.Media.Imaging; +using FontAwesome5; +using LiveCharts; +using LiveCharts.Wpf; +using log4net; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Exceptions; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; +using StatisticsAnalysisTool.Views; namespace StatisticsAnalysisTool.ViewModels { - using LiveCharts; - using LiveCharts.Wpf; - using System.Globalization; - public class ItemWindowViewModel : INotifyPropertyChanged { + public enum Error + { + NoPrices, + NoItemInfo, + GeneralError, + ToManyRequests + } + + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly ItemWindow _mainWindow; - private Item _item; - private ItemInformation _itemInformation; - private bool _runUpdate = true; - private Visibility _errorBarVisibility; + private List _allQualityPricesList; + private string _averagePrices; + private List _currentCityPrices; + private GoldResponseModel _currentGoldPrice; private string _errorBarText; - private BitmapImage _icon; - private string _itemName; - private bool _masterpieceQualityChecked; + private Visibility _errorBarVisibility; private bool _excellentQualityChecked; - private bool _outstandingQualityChecked; private bool _goodQualityChecked; - private bool _normalQualityChecked; - private ItemWindowTranslation _translation; private bool _hasItemPrices; - private bool _showBlackZoneOutpostsChecked; - private bool _showVillagesChecked; - private SeriesCollection _seriesCollectionHistory; - private string[] _labelsHistory; - private bool _refreshSpin; + private BitmapImage _icon; + private Visibility _informationLoadingImageVisibility; private bool _isAutoUpdateActive; - private string _refreshIconTooltipText; - private List _allQualityPricesList; - private string _itemTierLevel; - private List _marketCurrentPricesItemList; + private Item _item; + private ItemInformation _itemInformation; private XmlLanguage _itemListViewLanguage; - private Visibility _loadingImageVisibility; + private string _itemName; + private string _itemTierLevel; + private string[] _labelsHistory; private EFontAwesomeIcon _loadingImageIcon; private bool _loadingImageSpin; - private string _averagePrices; + private Visibility _loadingImageVisibility; + private List _marketCurrentPricesItemList; + private bool _masterpieceQualityChecked; + private bool _normalQualityChecked; + private bool _outstandingQualityChecked; private List _realMoneyPriceList; - private GoldResponseModel _currentGoldPrice; - private List _currentCityPrices; - private Visibility _informationLoadingImageVisibility; - - public enum Error { NoPrices, NoItemInfo, GeneralError, ToManyRequests } - private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private string _refreshIconTooltipText; + private bool _refreshSpin; + private bool _runUpdate = true; + private SeriesCollection _seriesCollectionHistory; + private bool _showBlackZoneOutpostsChecked; + private bool _showVillagesChecked; + private ItemWindowTranslation _translation; public ItemWindowViewModel(ItemWindow mainWindow, Item item) { @@ -97,7 +102,7 @@ private async void InitializeItemData(Item item) return; } - ItemTierLevel = (Item?.Tier != -1 && Item?.Level != -1) ? $"T{Item?.Tier}.{Item?.Level}" : string.Empty; + ItemTierLevel = Item?.Tier != -1 && Item?.Level != -1 ? $"T{Item?.Tier}.{Item?.Level}" : string.Empty; SetFullItemInformationAsync(item); await _mainWindow.Dispatcher.InvokeAsync(() => @@ -122,7 +127,7 @@ await _mainWindow.Dispatcher.InvokeAsync(() => _mainWindow.Icon = item.Icon; _mainWindow.Title = $"{localizedName} (T{item.Tier})"; }); - + StartAutoUpdater(); RefreshSpin = IsAutoUpdateActive; } @@ -254,9 +259,7 @@ private List GetQualities() private void SetDefaultQualityIfNoOneChecked() { if (!NormalQualityChecked && !GoodQualityChecked && !OutstandingQualityChecked && !ExcellentQualityChecked && !MasterpieceQualityChecked) - { NormalQualityChecked = true; - } } public async void SetHistoryChartPricesAsync() @@ -266,12 +269,10 @@ public async void SetHistoryChartPricesAsync() try { var locations = Locations.GetLocationsListByArea(ShowBlackZoneOutpostsChecked, ShowVillagesChecked, true, true); - historyItemPrices = await ApiController.GetHistoryItemPricesFromJsonAsync(Item.UniqueName, locations, DateTime.Now.AddDays(-30), GetQualities()).ConfigureAwait(true); + historyItemPrices = await ApiController + .GetHistoryItemPricesFromJsonAsync(Item.UniqueName, locations, DateTime.Now.AddDays(-30), GetQualities()).ConfigureAwait(true); - if (historyItemPrices == null) - { - return; - } + if (historyItemPrices == null) return; } catch (TooManyRequestsException) { @@ -293,9 +294,7 @@ private void SetHistoryChart(List historyItemPrices) foreach (var data in marketHistory?.Data?.OrderBy(x => x.Timestamp).ToList() ?? new List()) { if (!date.Exists(x => x.Contains(data.Timestamp.ToString("g", CultureInfo.CurrentCulture)))) - { date.Add(data.Timestamp.ToString("g", CultureInfo.CurrentCulture)); - } amount.Add(data.AveragePrice); } @@ -324,7 +323,6 @@ public async void GetItemPricesInRealMoneyAsync() var filteredCityPrices = GetFilteredCityPrices(ShowBlackZoneOutpostsChecked, ShowVillagesChecked, true, true, true); foreach (var stat in filteredCityPrices) - { if (realMoneyMarketObject.Exists(x => x.Location == stat.City)) { var marketQualityObject = realMoneyMarketObject.Find(x => x.LocationName == stat.City); @@ -332,11 +330,11 @@ public async void GetItemPricesInRealMoneyAsync() } else { - var marketQualityObject = new MarketQualityObject { Location = stat.City }; + var marketQualityObject = new MarketQualityObject {Location = stat.City}; await SetRealMoneyQualityStat(stat, marketQualityObject); realMoneyMarketObject.Add(marketQualityObject); } - } + RealMoneyPriceList = realMoneyMarketObject; } @@ -349,7 +347,6 @@ public void SetQualityPriceStatsOnListView() var marketQualityObjectList = new List(); foreach (var stat in filteredCityPrices) - { if (marketQualityObjectList.Exists(x => x.Location == stat.City)) { var marketQualityObject = marketQualityObjectList.Find(x => x.LocationName == stat.City); @@ -357,11 +354,11 @@ public void SetQualityPriceStatsOnListView() } else { - var marketQualityObject = new MarketQualityObject { Location = stat.City }; + var marketQualityObject = new MarketQualityObject {Location = stat.City}; SetQualityStat(stat, ref marketQualityObject); marketQualityObjectList.Add(marketQualityObject); } - } + AllQualityPricesList = marketQualityObjectList; } @@ -375,36 +372,41 @@ private async Task SetRealMoneyQualityStat(MarketResponse marketResponse, Market var getGoldPricesObjectList = await ApiController.GetGoldPricesFromJsonAsync(null, 1); _currentGoldPrice = getGoldPricesObjectList?.FirstOrDefault(); } - + switch (ItemController.GetQuality(marketResponse.QualityLevel)) { case ItemQuality.Normal: - marketQualityObject.SellPriceMinNormalStringInRalMoney = Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); + marketQualityObject.SellPriceMinNormalStringInRalMoney = + Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); marketQualityObject.SellPriceMinNormalDate = marketResponse.SellPriceMinDate; return; case ItemQuality.Good: - marketQualityObject.SellPriceMinGoodStringInRalMoney = Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); + marketQualityObject.SellPriceMinGoodStringInRalMoney = + Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); marketQualityObject.SellPriceMinGoodDate = marketResponse.SellPriceMinDate; return; case ItemQuality.Outstanding: - marketQualityObject.SellPriceMinOutstandingStringInRalMoney = Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); + marketQualityObject.SellPriceMinOutstandingStringInRalMoney = + Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); marketQualityObject.SellPriceMinOutstandingDate = marketResponse.SellPriceMinDate; return; case ItemQuality.Excellent: - marketQualityObject.SellPriceMinExcellentStringInRalMoney = Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); + marketQualityObject.SellPriceMinExcellentStringInRalMoney = + Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); marketQualityObject.SellPriceMinExcellentDate = marketResponse.SellPriceMinDate; return; case ItemQuality.Masterpiece: - marketQualityObject.SellPriceMinMasterpieceStringInRalMoney = Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); + marketQualityObject.SellPriceMinMasterpieceStringInRalMoney = + Converter.GoldToDollar(marketResponse.SellPriceMin, _currentGoldPrice?.Price ?? 0); marketQualityObject.SellPriceMinMasterpieceDate = marketResponse.SellPriceMinDate; return; } } - + private static void SetQualityStat(MarketResponse marketResponse, ref MarketQualityObject marketQualityObject) { if (marketQualityObject == null) @@ -439,10 +441,11 @@ private static void SetQualityStat(MarketResponse marketResponse, ref MarketQual } } - private List GetFilteredCityPrices(bool blackZoneOutposts, bool villages, bool cities, bool blackMarket, bool getAllQualities = false) + private List GetFilteredCityPrices(bool blackZoneOutposts, bool villages, bool cities, bool blackMarket, + bool getAllQualities = false) { return CurrentCityPrices?.Where(x => - Locations.GetLocationsListByArea(blackZoneOutposts, villages, cities, blackMarket).Contains(x.City) + Locations.GetLocationsListByArea(blackZoneOutposts, villages, cities, blackMarket).Contains(x.City) && (GetQualities().Contains(x.QualityLevel) || getAllQualities)).ToList(); } @@ -458,10 +461,7 @@ public void GetMainPriceStats() var marketCurrentPricesItemList = statsPricesTotalList.Select(item => new MarketCurrentPricesItem(item)).ToList(); - if (LoadingImageVisibility != Visibility.Hidden) - { - LoadingImageVisibility = Visibility.Hidden; - } + if (LoadingImageVisibility != Visibility.Hidden) LoadingImageVisibility = Visibility.Hidden; MarketCurrentPricesItemList = marketCurrentPricesItemList; SetAveragePricesString(); @@ -475,7 +475,6 @@ private List PriceUpdate(List newStatsPrice var currentStatsPricesTotalList = new List(); foreach (var newStats in newStatsPricesList) - { try { if (currentStatsPricesTotalList.Exists(s => Locations.GetParameterName(s.City) == newStats.City)) @@ -515,7 +514,6 @@ private List PriceUpdate(List newStatsPrice { return currentStatsPricesTotalList; } - } return currentStatsPricesTotalList; } @@ -529,10 +527,7 @@ private void FindBestPrice(ref List list) try { - if (list.Exists(s => s.BuyPriceMax == max)) - { - list.Find(s => s.BuyPriceMax == max).BestBuyMaxPrice = true; - } + if (list.Exists(s => s.BuyPriceMax == max)) list.Find(s => s.BuyPriceMax == max).BestBuyMaxPrice = true; } catch { @@ -543,10 +538,7 @@ private void FindBestPrice(ref List list) try { - if (list.Exists(s => s.SellPriceMin == min)) - { - list.First(s => s.SellPriceMin == min).BestSellMinPrice = true; - } + if (list.Exists(s => s.SellPriceMin == min)) list.First(s => s.SellPriceMin == min).BestSellMinPrice = true; } catch { @@ -595,27 +587,15 @@ private void SetAveragePricesString() foreach (var price in cityPrices) { - if (price.SellPriceMin != 0) - { - sellPriceMin.Add(price.SellPriceMin); - } + if (price.SellPriceMin != 0) sellPriceMin.Add(price.SellPriceMin); - if (price.SellPriceMax != 0) - { - sellPriceMax.Add(price.SellPriceMax); - } + if (price.SellPriceMax != 0) sellPriceMax.Add(price.SellPriceMax); - if (price.BuyPriceMin != 0) - { - buyPriceMin.Add(price.BuyPriceMin); - } + if (price.BuyPriceMin != 0) buyPriceMin.Add(price.BuyPriceMin); - if (price.BuyPriceMax != 0) - { - buyPriceMax.Add(price.BuyPriceMax); - } + if (price.BuyPriceMax != 0) buyPriceMax.Add(price.BuyPriceMax); } - + var sellPriceMinAverage = Average(sellPriceMin.ToArray()); var sellPriceMaxAverage = Average(sellPriceMax.ToArray()); var buyPriceMinAverage = Average(buyPriceMin.ToArray()); @@ -628,260 +608,324 @@ private void SetAveragePricesString() } #endregion Prices - + #region Bindings - public Item Item { + public Item Item + { get => _item; - set { + set + { _item = value; OnPropertyChanged(); } } - public ItemInformation ItemInformation { + public ItemInformation ItemInformation + { get => _itemInformation; - set { + set + { _itemInformation = value; OnPropertyChanged(); } } - public string ItemName { + public string ItemName + { get => _itemName; - set { + set + { _itemName = value; OnPropertyChanged(); } } - public string ItemTierLevel { + public string ItemTierLevel + { get => _itemTierLevel; - set { + set + { _itemTierLevel = value; OnPropertyChanged(); } } - public BitmapImage Icon { + public BitmapImage Icon + { get => _icon; - set { + set + { _icon = value; OnPropertyChanged(); } } - public List CurrentCityPrices { + public List CurrentCityPrices + { get => _currentCityPrices; - set { + set + { _currentCityPrices = value; OnPropertyChanged(); } } - public string AveragePrices { + public string AveragePrices + { get => _averagePrices; - set { + set + { _averagePrices = value; OnPropertyChanged(); } } - public Visibility LoadingImageVisibility { + public Visibility LoadingImageVisibility + { get => _loadingImageVisibility; - set { + set + { _loadingImageVisibility = value; OnPropertyChanged(); } } - public Visibility InformationLoadingImageVisibility { + public Visibility InformationLoadingImageVisibility + { get => _informationLoadingImageVisibility; - set { + set + { _informationLoadingImageVisibility = value; OnPropertyChanged(); } } - public EFontAwesomeIcon LoadingImageIcon { + public EFontAwesomeIcon LoadingImageIcon + { get => _loadingImageIcon; - set { + set + { _loadingImageIcon = value; OnPropertyChanged(); } } - public bool LoadingImageSpin { + public bool LoadingImageSpin + { get => _loadingImageSpin; - set { + set + { _loadingImageSpin = value; OnPropertyChanged(); } } - public List MarketCurrentPricesItemList { + public List MarketCurrentPricesItemList + { get => _marketCurrentPricesItemList; - set { + set + { _marketCurrentPricesItemList = value; OnPropertyChanged(); } } - public XmlLanguage ItemListViewLanguage { + public XmlLanguage ItemListViewLanguage + { get => _itemListViewLanguage; - set { + set + { _itemListViewLanguage = value; OnPropertyChanged(); } } - public bool RunUpdate { + public bool RunUpdate + { get => _runUpdate; - set { + set + { _runUpdate = value; OnPropertyChanged(); } } - public string ErrorBarText { + public string ErrorBarText + { get => _errorBarText; - set { + set + { _errorBarText = value; OnPropertyChanged(); } } - public Visibility ErrorBarVisibility { + public Visibility ErrorBarVisibility + { get => _errorBarVisibility; - set { + set + { _errorBarVisibility = value; OnPropertyChanged(); } } - public ItemWindowTranslation Translation { + public ItemWindowTranslation Translation + { get => _translation; - set { + set + { _translation = value; OnPropertyChanged(); } } - public bool NormalQualityChecked { + public bool NormalQualityChecked + { get => _normalQualityChecked; - set { + set + { _normalQualityChecked = !_normalQualityChecked && value; OnPropertyChanged(); } } - public bool GoodQualityChecked { + public bool GoodQualityChecked + { get => _goodQualityChecked; - set { + set + { _goodQualityChecked = !_goodQualityChecked && value; OnPropertyChanged(); } } - public bool OutstandingQualityChecked { + public bool OutstandingQualityChecked + { get => _outstandingQualityChecked; - set { + set + { _outstandingQualityChecked = !_outstandingQualityChecked && value; OnPropertyChanged(); } } - public bool ExcellentQualityChecked { + public bool ExcellentQualityChecked + { get => _excellentQualityChecked; - set { + set + { _excellentQualityChecked = !_excellentQualityChecked && value; OnPropertyChanged(); } } - public bool MasterpieceQualityChecked { + public bool MasterpieceQualityChecked + { get => _masterpieceQualityChecked; - set { + set + { _masterpieceQualityChecked = !_masterpieceQualityChecked && value; OnPropertyChanged(); } } - public bool ShowBlackZoneOutpostsChecked { + public bool ShowBlackZoneOutpostsChecked + { get => _showBlackZoneOutpostsChecked; - set { + set + { _showBlackZoneOutpostsChecked = value; OnPropertyChanged(); } } - public bool ShowVillagesChecked { + public bool ShowVillagesChecked + { get => _showVillagesChecked; - set { + set + { _showVillagesChecked = value; OnPropertyChanged(); } } - public bool IsAutoUpdateActive { + public bool IsAutoUpdateActive + { get => _isAutoUpdateActive; - set { + set + { _isAutoUpdateActive = value; OnPropertyChanged(); } } - public bool HasItemPrices { + public bool HasItemPrices + { get => _hasItemPrices; - set { + set + { _hasItemPrices = value; OnPropertyChanged(); } } - public SeriesCollection SeriesCollectionHistory { + public SeriesCollection SeriesCollectionHistory + { get => _seriesCollectionHistory; - set { + set + { _seriesCollectionHistory = value; OnPropertyChanged(); } } - public string[] LabelsHistory { + public string[] LabelsHistory + { get => _labelsHistory; - set { + set + { _labelsHistory = value; OnPropertyChanged(); } } - public bool RefreshSpin { + public bool RefreshSpin + { get => _refreshSpin; - set { + set + { _refreshSpin = value; OnPropertyChanged(); } } - public string RefreshIconTooltipText { + public string RefreshIconTooltipText + { get => _refreshIconTooltipText; - set { + set + { _refreshIconTooltipText = value; OnPropertyChanged(); } } - public List AllQualityPricesList { + public List AllQualityPricesList + { get => _allQualityPricesList; - set { + set + { _allQualityPricesList = value; OnPropertyChanged(); } } - public List RealMoneyPriceList { + public List RealMoneyPriceList + { get => _realMoneyPriceList; - set { + set + { _realMoneyPriceList = value; OnPropertyChanged(); } @@ -900,14 +944,11 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName public void CopyTextToClipboard(object sender) { - if (sender == null) - { - return; - } + if (sender == null) return; try { - var label = (Label)sender; + var label = (Label) sender; Clipboard.SetText(label.Content.ToString()); } catch (Exception ex) @@ -923,10 +964,7 @@ public ulong Sum(params ulong[] values) public ulong Average(params ulong[] values) { - if (values.Length == 0) - { - return 0; - } + if (values.Length == 0) return 0; var sum = Sum(values); var result = sum / (ulong) values.Length; diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/MainWindowViewModel.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/MainWindowViewModel.cs index 88f3a44ff..945d0c100 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/MainWindowViewModel.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/MainWindowViewModel.cs @@ -1,5 +1,6 @@ using FontAwesome5; using LiveCharts; +using LiveCharts.Wpf; using log4net; using PcapDotNet.Base; using StatisticsAnalysisTool.Annotations; @@ -25,12 +26,10 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Data; +using System.Windows.Media; namespace StatisticsAnalysisTool.ViewModels { - using LiveCharts.Wpf; - using System.Windows.Media; - public class MainWindowViewModel : INotifyPropertyChanged { private static MainWindow _mainWindow; @@ -38,88 +37,88 @@ public class MainWindowViewModel : INotifyPropertyChanged private static PlayerModeInformationModel _playerModeInformationLocal; private static PlayerModeInformationModel _playerModeInformation; - private ObservableCollection _modes = new ObservableCollection(); - private ModeStruct _modeSelection; + private readonly Dictionary viewModeGrid = new Dictionary(); + private Visibility _allianceInformationVisibility; + private double _allianceInfoWidth; private int _currentGoldPrice; private string _currentGoldPriceTimestamp; - private SeriesCollection _seriesCollection; - private string[] _labels; - private string _textBoxGoldModeNumberOfValues; - private string _updateTranslation; - private string _numberOfValuesTranslation; - private string _loadTranslation; - private PlayerModeTranslation _playerModeTranslation = new PlayerModeTranslation(); - private bool _isTxtSearchEnabled; - private string _itemCounterString; - private int _localImageCounter; + private Visibility _currentMapInformationVisibility; + private double _currentMapInfoWidth; + private ObservableCollection _damageMeter = new ObservableCollection(); + private List _damageMeterSort = new List(); + private DamageMeterSortStruct _damageMeterSortSelection; + private DungeonStats _dungeonStatsDay = new DungeonStats(); + private DungeonStats _dungeonStatsTotal = new DungeonStats(); + private string _errorBarText; + private Visibility _errorBarVisibility; + private string _famePerHour = "0"; private string _fullItemInformationExistLocal; + private Visibility _goldPriceVisibility; + private Visibility _guildInformationVisibility; + private double _guildInfoWidth; + private Visibility _isDamageMeterPopupVisible = Visibility.Hidden; + private bool _isDamageMeterResetByMapChangeActive; + private bool _isFullItemInfoLoading; + private bool _isFullItemInfoSearchActive; + private bool _isLoadFullItemInfoButtonEnabled; + private bool _isShowOnlyItemsWithAlertOnActive; + private bool _isTrackingActive; + private bool _isTrackingResetByMapChangeActive; + private bool _isTxtSearchEnabled; private Dictionary _itemCategories = new Dictionary(); - private Category _selectedItemCategories; - private Dictionary _itemParentCategories = new Dictionary(); - private ParentCategory _selectedItemParentCategories; - private Dictionary _itemTiers = new Dictionary(); - private ItemTier _selectedItemTier; + private Visibility _itemCategoriesVisibility; + private string _itemCounterString; private Dictionary _itemLevels = new Dictionary(); - private ItemLevel _selectedItemLevel; - private string _searchText; - private bool _isFullItemInfoSearchActive; private Visibility _itemLevelsVisibility; - private Visibility _itemTiersVisibility; - private Visibility _itemCategoriesVisibility; + private Dictionary _itemParentCategories = new Dictionary(); private Visibility _itemParentCategoriesVisibility; - private MainWindowTranslation _translation; - private string _savedPlayerInformationName; + private ICollectionView _itemsView; + private Dictionary _itemTiers = new Dictionary(); + private Visibility _itemTiersVisibility; + private string[] _labels; private Visibility _loadFullItemInfoButtonVisibility; - private bool _isLoadFullItemInfoButtonEnabled; - private int _loadFullItemInfoProBarValue; + private string _loadFullItemInfoProBarCounter; + private Visibility _loadFullItemInfoProBarGridVisibility; private int _loadFullItemInfoProBarMax; private int _loadFullItemInfoProBarMin; - private Visibility _loadFullItemInfoProBarGridVisibility; + private int _loadFullItemInfoProBarValue; private Visibility _loadIconVisibility; - private string _loadFullItemInfoProBarCounter; - private bool _isFullItemInfoLoading; - private ICollectionView _itemsView; - public AlertController AlertManager; - private bool _isShowOnlyItemsWithAlertOnActive; - private bool _isTrackingActive; - private Brush _trackerActivationToggleColor; - private string _famePerHour = "0"; - private string _totalPlayerFame = "0"; + private string _loadTranslation; + private int _localImageCounter; + private ObservableCollection _modes = new ObservableCollection(); + private ModeStruct _modeSelection; + private string _numberOfValuesTranslation; + private ObservableCollection _partyMemberCircles = new ObservableCollection(); + private PlayerModeTranslation _playerModeTranslation = new PlayerModeTranslation(); private string _reSpecPointsPerHour = "0"; - private TrackingController _trackingController; - private DateTime? activateWaitTimer; - private readonly Dictionary viewModeGrid = new Dictionary(); + private string _savedPlayerInformationName; + private string _searchText; + private Category _selectedItemCategories; + private ItemLevel _selectedItemLevel; + private ParentCategory _selectedItemParentCategories; + private ItemTier _selectedItemTier; + private SeriesCollection _seriesCollection; + private string _silverPerHour = "0"; + private string _textBoxGoldModeNumberOfValues; + private string _totalPlayerFame = "0"; + private string _totalPlayerReSpecPoints = "0"; + private string _totalPlayerSilver = "0"; + private Brush _trackerActivationToggleColor; private EFontAwesomeIcon _trackerActivationToggleIcon = EFontAwesomeIcon.Solid_ToggleOff; + private string _trackingAllianceName; + private TrackingController _trackingController; + private string _trackingCurrentMapName; + private ObservableCollection _trackingDungeons = new ObservableCollection(); + private string _trackingGuildName; private ObservableCollection _trackingNotifications = new ObservableCollection(); private string _trackingUsername; - private string _trackingGuildName; - private string _trackingAllianceName; - private string _errorBarText; - private Visibility _errorBarVisibility; + private MainWindowTranslation _translation; + private string _updateTranslation; private Visibility _usernameInformationVisibility; - private Visibility _guildInformationVisibility; - private Visibility _allianceInformationVisibility; - private bool _isTrackingResetByMapChangeActive; - private string _silverPerHour = "0"; - private string _totalPlayerSilver = "0"; - private string _totalPlayerReSpecPoints = "0"; - private ValueCountUpTimer _valueCountUpTimer; - private Visibility _goldPriceVisibility; - private Visibility _currentMapInformationVisibility; - private string _trackingCurrentMapName; private double _usernameInfoWidth; - private double _guildInfoWidth; - private double _allianceInfoWidth; - private double _currentMapInfoWidth; - private Visibility _isDamageMeterPopupVisible = Visibility.Hidden; - private ObservableCollection _trackingDungeons = new ObservableCollection(); - private ObservableCollection _damageMeter = new ObservableCollection(); - private DungeonStats _dungeonStatsDay = new DungeonStats(); - private DungeonStats _dungeonStatsTotal = new DungeonStats(); - private ObservableCollection _partyMemberCircles = new ObservableCollection(); - private bool _isDamageMeterResetByMapChangeActive; - private DamageMeterSortStruct _damageMeterSortSelection; - private List _damageMeterSort = new List(); + private ValueCountUpTimer _valueCountUpTimer; + private DateTime? activateWaitTimer; + public AlertController AlertManager; public MainWindowViewModel(MainWindow mainWindow) { @@ -131,22 +130,161 @@ public MainWindowViewModel(MainWindow mainWindow) InitWindowSettings(); Utilities.AutoUpdate(); - if (!LanguageController.InitializeLanguage()) - { - _mainWindow.Close(); - } + if (!LanguageController.InitializeLanguage()) _mainWindow.Close(); InitMainWindowData(); InitTracking(); } + public async void SetUiElements() + { + #region Error bar + + ErrorBarVisibility = Visibility.Hidden; + + #endregion + + #region Set Modes to combobox + + Modes.Clear(); + Modes.Add(new ModeStruct {Name = LanguageController.Translation("NORMAL"), ViewMode = ViewMode.Normal}); + Modes.Add(new ModeStruct {Name = LanguageController.Translation("TRACKING"), ViewMode = ViewMode.Tracking}); + Modes.Add(new ModeStruct {Name = LanguageController.Translation("PLAYER"), ViewMode = ViewMode.Player}); + Modes.Add(new ModeStruct {Name = LanguageController.Translation("GOLD"), ViewMode = ViewMode.Gold}); + ModeSelection = Modes.FirstOrDefault(x => x.ViewMode == ViewMode.Normal); + + #endregion Set Modes to combobox + + #region Full Item Info elements + + LoadFullItemInfoButtonVisibility = Visibility.Hidden; + + IsFullItemInfoSearchActive = Settings.Default.IsFullItemInfoSearchActive; + + ItemParentCategories = CategoryController.ParentCategoryNames; + SelectedItemParentCategory = ParentCategory.Unknown; + + ItemTiers = FrequentlyValues.ItemTiers; + SelectedItemTier = ItemTier.Unknown; + + ItemLevels = FrequentlyValues.ItemLevels; + SelectedItemLevel = ItemLevel.Unknown; + + if (!IsFullItemInfoLoading) LoadFullItemInfoProBarGridVisibility = Visibility.Hidden; + + #endregion Full Item Info elements + + #region Gold price + + var currentGoldPrice = await ApiController.GetGoldPricesFromJsonAsync(null, 1).ConfigureAwait(true); + CurrentGoldPrice = currentGoldPrice.FirstOrDefault()?.Price ?? 0; + if (!currentGoldPrice.IsNullOrEmpty()) + { + CurrentGoldPriceTimestamp = currentGoldPrice.FirstOrDefault()?.Timestamp.ToString(CultureInfo.CurrentCulture) ?? + new DateTime(0, 0, 0, 0, 0, 0).ToString(CultureInfo.CurrentCulture); + GoldPriceVisibility = Visibility.Visible; + } + else + { + GoldPriceVisibility = Visibility.Hidden; + } + + #endregion Gold price + + #region Player information + + SavedPlayerInformationName = Settings.Default.SavedPlayerInformationName; + + #endregion Player information + + #region Tracking + + UsernameInformationVisibility = Visibility.Hidden; + GuildInformationVisibility = Visibility.Hidden; + AllianceInformationVisibility = Visibility.Hidden; + CurrentMapInformationVisibility = Visibility.Hidden; + + IsTrackingResetByMapChangeActive = Settings.Default.IsTrackingResetByMapChangeActive; + + var sortByDamageStruct = new DamageMeterSortStruct + { + Name = Translation.SortByDamage, + DamageMeterSortType = DamageMeterSortType.Damage + }; + var sortByDpsStruct = new DamageMeterSortStruct + { + Name = Translation.SortByDps, + DamageMeterSortType = DamageMeterSortType.Dps + }; + var sortByNameStruct = new DamageMeterSortStruct + { + Name = Translation.SortByName, + DamageMeterSortType = DamageMeterSortType.Name + }; + + DamageMeterSort.Clear(); + DamageMeterSort.Add(sortByDamageStruct); + DamageMeterSort.Add(sortByDpsStruct); + DamageMeterSort.Add(sortByNameStruct); + DamageMeterSortSelection = sortByDamageStruct; + + #endregion + } + + #region Alert + + public void ToggleAlertSender(object sender) + { + if (sender == null) return; + + try + { + var imageAwesome = (ImageAwesome) sender; + var item = (Item) imageAwesome.DataContext; + + if (item.AlertModeMinSellPriceIsUndercutPrice <= 0) return; + + item.IsAlertActive = AlertManager.ToggleAlert(ref item); + ItemsView.Refresh(); + } + catch (Exception e) + { + Log.Error(nameof(ToggleAlertSender), e); + } + } + + #endregion + + #region Item list (Normal Mode) + + public void ItemFilterReset() + { + SearchText = string.Empty; + SelectedItemCategory = Category.Unknown; + SelectedItemParentCategory = ParentCategory.Unknown; + SelectedItemLevel = ItemLevel.Unknown; + SelectedItemTier = ItemTier.Unknown; + } + + #endregion Item list (Normal Mode) + + #region Helper methods + + public void SetErrorBar(Visibility visibility, string errorMessage) + { + ErrorBarText = errorMessage; + ErrorBarVisibility = visibility; + } + + #endregion + #region Inits - void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) + private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { try { - Log.Fatal(nameof(OnUnhandledException), (Exception)e.ExceptionObject); + Log.Fatal(nameof(OnUnhandledException), (Exception) e.ExceptionObject); } catch (Exception ex) { @@ -173,10 +311,7 @@ public void SelectViewModeGrid() { Log.Warn($"SelectViewModeGrid: Grid for [{ModeSelection.ViewMode}] is not existing"); - if (viewModeGrid.FirstOrDefault().Value != null) - { - viewModeGrid.FirstOrDefault().Value.Visibility = Visibility.Visible; - } + if (viewModeGrid.FirstOrDefault().Value != null) viewModeGrid.FirstOrDefault().Value.Visibility = Visibility.Visible; return; } @@ -187,15 +322,9 @@ public void SelectViewModeGrid() private void HideAllGrids() { - if (viewModeGrid == null) - { - return; - } + if (viewModeGrid == null) return; - foreach (var grid in viewModeGrid) - { - grid.Value.Visibility = Visibility.Hidden; - } + foreach (var grid in viewModeGrid) grid.Value.Visibility = Visibility.Hidden; } #endregion @@ -224,10 +353,7 @@ private void InitWindowSettings() _mainWindow.Height = Settings.Default.MainWindowHeight; _mainWindow.Width = Settings.Default.MainWindowWidth; - if (Settings.Default.MainWindowMaximized) - { - _mainWindow.WindowState = WindowState.Maximized; - } + if (Settings.Default.MainWindowMaximized) _mainWindow.WindowState = WindowState.Maximized; CenterWindowOnScreen(); @@ -246,9 +372,7 @@ private async void InitMainWindowData() var isItemListLoaded = await ItemController.GetItemListFromJsonAsync().ConfigureAwait(true); if (!isItemListLoaded) - { MessageBox.Show(LanguageController.Translation("ITEM_LIST_CAN_NOT_BE_LOADED"), LanguageController.Translation("ERROR")); - } if (isItemListLoaded) { @@ -261,10 +385,7 @@ private async void InitMainWindowData() LoadIconVisibility = Visibility.Hidden; IsTxtSearchEnabled = true; - _mainWindow.Dispatcher?.Invoke(() => - { - _mainWindow.TxtSearch.Focus(); - }); + _mainWindow.Dispatcher?.Invoke(() => { _mainWindow.TxtSearch.Focus(); }); } ShowInfoWindow(); @@ -276,110 +397,10 @@ private async void InitTracking() await WorldData.GetDataListFromJsonAsync(); await LootChestData.GetDataListFromJsonAsync(); - if (Settings.Default.IsTrackingActiveAtToolStart) - { - StartTracking(); - } + if (Settings.Default.IsTrackingActiveAtToolStart) StartTracking(); } #endregion - - public async void SetUiElements() - { - #region Error bar - - ErrorBarVisibility = Visibility.Hidden; - - #endregion - - #region Set Modes to combobox - - Modes.Clear(); - Modes.Add(new ModeStruct { Name = LanguageController.Translation("NORMAL"), ViewMode = ViewMode.Normal }); - Modes.Add(new ModeStruct { Name = LanguageController.Translation("TRACKING"), ViewMode = ViewMode.Tracking }); - Modes.Add(new ModeStruct { Name = LanguageController.Translation("PLAYER"), ViewMode = ViewMode.Player }); - Modes.Add(new ModeStruct { Name = LanguageController.Translation("GOLD"), ViewMode = ViewMode.Gold }); - ModeSelection = Modes.FirstOrDefault(x => x.ViewMode == ViewMode.Normal); - - #endregion Set Modes to combobox - - #region Full Item Info elements - - LoadFullItemInfoButtonVisibility = Visibility.Hidden; - - IsFullItemInfoSearchActive = Settings.Default.IsFullItemInfoSearchActive; - - ItemParentCategories = CategoryController.ParentCategoryNames; - SelectedItemParentCategory = ParentCategory.Unknown; - - ItemTiers = FrequentlyValues.ItemTiers; - SelectedItemTier = ItemTier.Unknown; - - ItemLevels = FrequentlyValues.ItemLevels; - SelectedItemLevel = ItemLevel.Unknown; - - if (!IsFullItemInfoLoading) - { - LoadFullItemInfoProBarGridVisibility = Visibility.Hidden; - } - - #endregion Full Item Info elements - - #region Gold price - - var currentGoldPrice = await ApiController.GetGoldPricesFromJsonAsync(null, 1).ConfigureAwait(true); - CurrentGoldPrice = currentGoldPrice.FirstOrDefault()?.Price ?? 0; - if (!currentGoldPrice.IsNullOrEmpty()) - { - CurrentGoldPriceTimestamp = currentGoldPrice.FirstOrDefault()?.Timestamp.ToString(CultureInfo.CurrentCulture) ?? new DateTime(0, 0, 0, 0, 0, 0).ToString(CultureInfo.CurrentCulture); - GoldPriceVisibility = Visibility.Visible; - } - else - { - GoldPriceVisibility = Visibility.Hidden; - } - - #endregion Gold price - - #region Player information - - SavedPlayerInformationName = Settings.Default.SavedPlayerInformationName; - - #endregion Player information - - #region Tracking - - UsernameInformationVisibility = Visibility.Hidden; - GuildInformationVisibility = Visibility.Hidden; - AllianceInformationVisibility = Visibility.Hidden; - CurrentMapInformationVisibility = Visibility.Hidden; - - IsTrackingResetByMapChangeActive = Settings.Default.IsTrackingResetByMapChangeActive; - - var sortByDamageStruct = new DamageMeterSortStruct() - { - Name = Translation.SortByDamage, - DamageMeterSortType = DamageMeterSortType.Damage - }; - var sortByDpsStruct = new DamageMeterSortStruct() - { - Name = Translation.SortByDps, - DamageMeterSortType = DamageMeterSortType.Dps - }; - var sortByNameStruct = new DamageMeterSortStruct() - { - Name = Translation.SortByName, - DamageMeterSortType = DamageMeterSortType.Name - }; - - DamageMeterSort.Clear(); - DamageMeterSort.Add(sortByDamageStruct); - DamageMeterSort.Add(sortByDpsStruct); - DamageMeterSort.Add(sortByNameStruct); - DamageMeterSortSelection = sortByDamageStruct; - - #endregion - } #region Ui utility methods @@ -389,8 +410,8 @@ public void CenterWindowOnScreen() var screenHeight = SystemParameters.PrimaryScreenHeight; var windowWidth = _mainWindow.Width; var windowHeight = _mainWindow.Height; - _mainWindow.Left = (screenWidth / 2) - (windowWidth / 2); - _mainWindow.Top = (screenHeight / 2) - (windowHeight / 2); + _mainWindow.Left = screenWidth / 2 - windowWidth / 2; + _mainWindow.Top = screenHeight / 2 - windowHeight / 2; } private void ShowInfoWindow() @@ -429,7 +450,6 @@ public static void OpenItemWindow(Item item) } } - #endregion #region Full Item Information @@ -462,10 +482,7 @@ public async void LoadAllFullItemInformationFromWeb() foreach (var item in ItemController.Items) { - if (!IsFullItemInfoLoading) - { - break; - } + if (!IsFullItemInfoLoading) break; item.FullItemInformation = await ItemController.GetFullItemInformationAsync(item); LoadFullItemInfoProBarValue++; @@ -487,49 +504,6 @@ public async void LoadAllFullItemInformationFromWeb() #endregion - #region Alert - - public void ToggleAlertSender(object sender) - { - if (sender == null) - { - return; - } - - try - { - var imageAwesome = (ImageAwesome)sender; - var item = (Item)imageAwesome.DataContext; - - if (item.AlertModeMinSellPriceIsUndercutPrice <= 0) - { - return; - } - - item.IsAlertActive = AlertManager.ToggleAlert(ref item); - ItemsView.Refresh(); - } - catch (Exception e) - { - Log.Error(nameof(ToggleAlertSender), e); - } - } - - #endregion - - #region Item list (Normal Mode) - - public void ItemFilterReset() - { - SearchText = string.Empty; - SelectedItemCategory = Category.Unknown; - SelectedItemParentCategory = ParentCategory.Unknown; - SelectedItemLevel = ItemLevel.Unknown; - SelectedItemTier = ItemTier.Unknown; - } - - #endregion Item list (Normal Mode) - #region Player information (Player Mode) public async Task SetComparedPlayerModeInfoValues() @@ -552,7 +526,7 @@ private async Task GetPlayerModeInformationByApi() var searchPlayer = gameInfoSearch.SearchPlayer?.FirstOrDefault(); var gameInfoPlayers = await ApiController.GetGameInfoPlayersFromJsonAsync(gameInfoSearch.SearchPlayer?.FirstOrDefault()?.Id); - return new PlayerModeInformationModel() + return new PlayerModeInformationModel { Timestamp = DateTime.UtcNow, GameInfoSearch = gameInfoSearch, @@ -561,17 +535,21 @@ private async Task GetPlayerModeInformationByApi() }; } - public PlayerModeInformationModel PlayerModeInformation { + public PlayerModeInformationModel PlayerModeInformation + { get => _playerModeInformation; - set { + set + { _playerModeInformation = value; OnPropertyChanged(); } } - public PlayerModeInformationModel PlayerModeInformationLocal { + public PlayerModeInformationModel PlayerModeInformationLocal + { get => _playerModeInformationLocal; - set { + set + { _playerModeInformationLocal = value; OnPropertyChanged(); } @@ -602,23 +580,27 @@ public async void SetGoldChart(int count) { Title = "Gold", Values = amount, - Fill = (Brush)Application.Current.Resources["Solid.Color.Gold.Fill"], - Stroke = (Brush)Application.Current.Resources["Solid.Color.Text.Gold"] + Fill = (Brush) Application.Current.Resources["Solid.Color.Gold.Fill"], + Stroke = (Brush) Application.Current.Resources["Solid.Color.Text.Gold"] } }; } - public SeriesCollection SeriesCollection { + public SeriesCollection SeriesCollection + { get => _seriesCollection; - set { + set + { _seriesCollection = value; OnPropertyChanged(); } } - public string[] Labels { + public string[] Labels + { get => _labels; - set { + set + { _labels = value; OnPropertyChanged(); } @@ -630,58 +612,40 @@ public string[] Labels { public void TrackerActivationToggle() { - if (!IsReadyToTracking()) - { - return; - } + if (!IsReadyToTracking()) return; IsTrackingActive = !IsTrackingActive; if (IsTrackingActive) - { StartTracking(); - } else - { StopTracking(); - } } public void StartTracking() { - if (NetworkManager.IsNetworkCaptureRunning) - { - return; - } + if (NetworkManager.IsNetworkCaptureRunning) return; - if (_trackingController == null) - { - _trackingController = new TrackingController(this, _mainWindow); - } + if (_trackingController == null) _trackingController = new TrackingController(this, _mainWindow); _trackingController?.RegisterEvents(); TrackingDungeons = _trackingController?.DungeonController?.LoadDungeonFromFile(); _trackingController?.DungeonController?.SetDungeonStatsDay(); _trackingController?.DungeonController?.SetDungeonStatsTotal(); - DungeonStatsDay.EnteredDungeon = _trackingController.DungeonController.GetDungeonsCount(DateTime.UtcNow.AddDays(-1)); - DungeonStatsTotal.EnteredDungeon = _trackingController.DungeonController.GetDungeonsCount(DateTime.UtcNow.AddYears(-10)); + if (_trackingController.DungeonController != null) + { + DungeonStatsDay.EnteredDungeon = _trackingController.DungeonController.GetDungeonsCount(DateTime.UtcNow.AddDays(-1)); + DungeonStatsTotal.EnteredDungeon = _trackingController.DungeonController.GetDungeonsCount(DateTime.UtcNow.AddYears(-10)); + } _valueCountUpTimer = new ValueCountUpTimer(); - if (_valueCountUpTimer?.FameCountUpTimer == null) - { - _valueCountUpTimer.FameCountUpTimer = new FameCountUpTimer(this); - } + if (_valueCountUpTimer?.FameCountUpTimer == null) _valueCountUpTimer.FameCountUpTimer = new FameCountUpTimer(this); - if (_valueCountUpTimer?.SilverCountUpTimer == null) - { - _valueCountUpTimer.SilverCountUpTimer = new SilverCountUpTimer(this); - } + if (_valueCountUpTimer?.SilverCountUpTimer == null) _valueCountUpTimer.SilverCountUpTimer = new SilverCountUpTimer(this); if (_valueCountUpTimer?.ReSpecPointsCountUpTimer == null) - { _valueCountUpTimer.ReSpecPointsCountUpTimer = new ReSpecPointsCountUpTimer(this); - } _valueCountUpTimer?.FameCountUpTimer.Start(); _valueCountUpTimer?.SilverCountUpTimer.Start(); @@ -715,20 +679,11 @@ private bool IsReadyToTracking() public void ResetMainCounters(bool fame, bool silver, bool reSpec) { - if (fame) - { - _valueCountUpTimer?.FameCountUpTimer?.Reset(); - } + if (fame) _valueCountUpTimer?.FameCountUpTimer?.Reset(); - if (silver) - { - _valueCountUpTimer?.SilverCountUpTimer?.Reset(); - } + if (silver) _valueCountUpTimer?.SilverCountUpTimer?.Reset(); - if (reSpec) - { - _valueCountUpTimer?.ReSpecPointsCountUpTimer?.Reset(); - } + if (reSpec) _valueCountUpTimer?.ReSpecPointsCountUpTimer?.Reset(); } public void ResetDamageMeter() @@ -764,10 +719,9 @@ public void SetDamageMeterSort() DamageMeter.OrderByReference(DamageMeter.OrderByDescending(x => x.Dps).ToList()); return; } + if (DamageMeterSortSelection.DamageMeterSortType == DamageMeterSortType.Name) - { DamageMeter.OrderByReference(DamageMeter.OrderBy(x => x.Name).ToList()); - } } #endregion @@ -776,53 +730,40 @@ public void SetDamageMeterSort() private void ItemsViewFilter() { - if (ItemsView == null) - { - return; - } + if (ItemsView == null) return; if (IsFullItemInfoSearchActive) - { ItemsView.Filter = i => { var item = i as Item; if (IsShowOnlyItemsWithAlertOnActive) - { - return item?.FullItemInformation != null && - item.LocalizedNameAndEnglish.ToLower().Contains(SearchText?.ToLower() ?? string.Empty) - && (item.FullItemInformation?.CategoryObject?.ParentCategory == SelectedItemParentCategory || SelectedItemParentCategory == ParentCategory.Unknown) - && (item.FullItemInformation?.CategoryObject?.Category == SelectedItemCategory || SelectedItemCategory == Category.Unknown) - && ((ItemTier)item.FullItemInformation?.Tier == SelectedItemTier || SelectedItemTier == ItemTier.Unknown) - && ((ItemLevel)item.FullItemInformation?.Level == SelectedItemLevel || SelectedItemLevel == ItemLevel.Unknown) - && item.IsAlertActive; - } - else - { return item?.FullItemInformation != null && item.LocalizedNameAndEnglish.ToLower().Contains(SearchText?.ToLower() ?? string.Empty) - && (item.FullItemInformation?.CategoryObject?.ParentCategory == SelectedItemParentCategory || SelectedItemParentCategory == ParentCategory.Unknown) - && (item.FullItemInformation?.CategoryObject?.Category == SelectedItemCategory || SelectedItemCategory == Category.Unknown) + && (item.FullItemInformation?.CategoryObject?.ParentCategory == SelectedItemParentCategory || + SelectedItemParentCategory == ParentCategory.Unknown) + && (item.FullItemInformation?.CategoryObject?.Category == SelectedItemCategory || + SelectedItemCategory == Category.Unknown) && ((ItemTier) item.FullItemInformation?.Tier == SelectedItemTier || SelectedItemTier == ItemTier.Unknown) - && ((ItemLevel) item.FullItemInformation?.Level == SelectedItemLevel || SelectedItemLevel == ItemLevel.Unknown); - } + && ((ItemLevel) item.FullItemInformation?.Level == SelectedItemLevel || SelectedItemLevel == ItemLevel.Unknown) + && item.IsAlertActive; + return item?.FullItemInformation != null && + item.LocalizedNameAndEnglish.ToLower().Contains(SearchText?.ToLower() ?? string.Empty) + && (item.FullItemInformation?.CategoryObject?.ParentCategory == SelectedItemParentCategory || + SelectedItemParentCategory == ParentCategory.Unknown) + && (item.FullItemInformation?.CategoryObject?.Category == SelectedItemCategory || SelectedItemCategory == Category.Unknown) + && ((ItemTier) item.FullItemInformation?.Tier == SelectedItemTier || SelectedItemTier == ItemTier.Unknown) + && ((ItemLevel) item.FullItemInformation?.Level == SelectedItemLevel || SelectedItemLevel == ItemLevel.Unknown); }; - } else - { ItemsView.Filter = i => { var item = i as Item; if (IsShowOnlyItemsWithAlertOnActive) - { - return (item?.LocalizedNameAndEnglish.ToLower().Contains(SearchText?.ToLower() ?? string.Empty) ?? false) && item.IsAlertActive; - } - else - { - return item?.LocalizedNameAndEnglish.ToLower().Contains(SearchText?.ToLower() ?? string.Empty) ?? false; - } + return (item?.LocalizedNameAndEnglish.ToLower().Contains(SearchText?.ToLower() ?? string.Empty) ?? false) && + item.IsAlertActive; + return item?.LocalizedNameAndEnglish.ToLower().Contains(SearchText?.ToLower() ?? string.Empty) ?? false; }; - } SetItemCounterAsync(); } @@ -832,7 +773,7 @@ private async void SetItemCounterAsync() try { LocalImageCounter = await ImageController.LocalImagesCounterAsync(); - ItemCounterString = $"{((ListCollectionView)ItemsView)?.Count ?? 0}/{ItemController.Items?.Count ?? 0}"; + ItemCounterString = $"{((ListCollectionView) ItemsView)?.Count ?? 0}/{ItemController.Items?.Count ?? 0}"; } catch (Exception e) { @@ -840,26 +781,17 @@ private async void SetItemCounterAsync() } } - - #endregion - - #region Helper methods - - public void SetErrorBar(Visibility visibility, string errorMessage) - { - ErrorBarText = errorMessage; - ErrorBarVisibility = visibility; - } - #endregion #region Bindings - public string SearchText { + public string SearchText + { get => _searchText; - set { + set + { _searchText = value; - + ItemsViewFilter(); ItemsView?.Refresh(); @@ -877,17 +809,21 @@ public ICollectionView ItemsView } } - public Visibility IsDamageMeterPopupVisible { + public Visibility IsDamageMeterPopupVisible + { get => _isDamageMeterPopupVisible; - set { + set + { _isDamageMeterPopupVisible = value; OnPropertyChanged(); } } - public DamageMeterSortStruct DamageMeterSortSelection { + public DamageMeterSortStruct DamageMeterSortSelection + { get => _damageMeterSortSelection; - set { + set + { _damageMeterSortSelection = value; SetDamageMeterSort(); @@ -895,235 +831,289 @@ public DamageMeterSortStruct DamageMeterSortSelection { } } - public List DamageMeterSort { + public List DamageMeterSort + { get => _damageMeterSort; - set { + set + { _damageMeterSort = value; OnPropertyChanged(); } } - public ObservableCollection DamageMeter { + public ObservableCollection DamageMeter + { get => _damageMeter; - set { + set + { _damageMeter = value; OnPropertyChanged(); } } - public Visibility UsernameInformationVisibility { + public Visibility UsernameInformationVisibility + { get => _usernameInformationVisibility; - set { + set + { _usernameInformationVisibility = value; OnPropertyChanged(); } } - public Visibility GuildInformationVisibility { + public Visibility GuildInformationVisibility + { get => _guildInformationVisibility; - set { + set + { _guildInformationVisibility = value; OnPropertyChanged(); } } - public Visibility AllianceInformationVisibility { + public Visibility AllianceInformationVisibility + { get => _allianceInformationVisibility; - set { + set + { _allianceInformationVisibility = value; OnPropertyChanged(); } } - - public Visibility CurrentMapInformationVisibility { + + public Visibility CurrentMapInformationVisibility + { get => _currentMapInformationVisibility; - set { + set + { _currentMapInformationVisibility = value; OnPropertyChanged(); } } - - public Visibility GoldPriceVisibility { + + public Visibility GoldPriceVisibility + { get => _goldPriceVisibility; - set { + set + { _goldPriceVisibility = value; OnPropertyChanged(); } } - public DungeonStats DungeonStatsDay { + public DungeonStats DungeonStatsDay + { get => _dungeonStatsDay; - set { + set + { _dungeonStatsDay = value; OnPropertyChanged(); } } - public DungeonStats DungeonStatsTotal { + public DungeonStats DungeonStatsTotal + { get => _dungeonStatsTotal; - set { + set + { _dungeonStatsTotal = value; OnPropertyChanged(); } } - public string TrackingUsername { + public string TrackingUsername + { get => _trackingUsername; - set { + set + { _trackingUsername = value; UsernameInformationVisibility = !string.IsNullOrEmpty(_trackingUsername) ? Visibility.Visible : Visibility.Hidden; - UsernameInfoWidth = (string.IsNullOrEmpty(_trackingUsername)) ? 0 : double.NaN; + UsernameInfoWidth = string.IsNullOrEmpty(_trackingUsername) ? 0 : double.NaN; OnPropertyChanged(); } } - public string TrackingGuildName { + public string TrackingGuildName + { get => _trackingGuildName; - set { + set + { _trackingGuildName = value; GuildInformationVisibility = !string.IsNullOrEmpty(_trackingGuildName) ? Visibility.Visible : Visibility.Hidden; - GuildInfoWidth = (string.IsNullOrEmpty(_trackingGuildName)) ? 0 : double.NaN; + GuildInfoWidth = string.IsNullOrEmpty(_trackingGuildName) ? 0 : double.NaN; OnPropertyChanged(); } } - public string TrackingAllianceName { + public string TrackingAllianceName + { get => _trackingAllianceName; - set { + set + { _trackingAllianceName = value; AllianceInformationVisibility = !string.IsNullOrEmpty(_trackingAllianceName) ? Visibility.Visible : Visibility.Hidden; - AllianceInfoWidth = (string.IsNullOrEmpty(_trackingAllianceName)) ? 0 : double.NaN; + AllianceInfoWidth = string.IsNullOrEmpty(_trackingAllianceName) ? 0 : double.NaN; OnPropertyChanged(); } } - public string TrackingCurrentMapName { + public string TrackingCurrentMapName + { get => _trackingCurrentMapName; - set { + set + { _trackingCurrentMapName = value; CurrentMapInformationVisibility = !string.IsNullOrEmpty(_trackingCurrentMapName) ? Visibility.Visible : Visibility.Hidden; - CurrentMapInfoWidth = (string.IsNullOrEmpty(_trackingCurrentMapName)) ? 0 : double.NaN; + CurrentMapInfoWidth = string.IsNullOrEmpty(_trackingCurrentMapName) ? 0 : double.NaN; OnPropertyChanged(); } } - public double UsernameInfoWidth { + public double UsernameInfoWidth + { get => _usernameInfoWidth; - set { + set + { _usernameInfoWidth = value; OnPropertyChanged(); } } - public double GuildInfoWidth { + public double GuildInfoWidth + { get => _guildInfoWidth; - set { + set + { _guildInfoWidth = value; OnPropertyChanged(); } } - public double AllianceInfoWidth { + public double AllianceInfoWidth + { get => _allianceInfoWidth; - set { + set + { _allianceInfoWidth = value; OnPropertyChanged(); } } - public double CurrentMapInfoWidth { + public double CurrentMapInfoWidth + { get => _currentMapInfoWidth; - set { + set + { _currentMapInfoWidth = value; OnPropertyChanged(); } } - public string FamePerHour { + public string FamePerHour + { get => _famePerHour; - set { + set + { _famePerHour = value; OnPropertyChanged(); } } - public string SilverPerHour { + public string SilverPerHour + { get => _silverPerHour; - set { + set + { _silverPerHour = value; OnPropertyChanged(); } } - public string ReSpecPointsPerHour { + public string ReSpecPointsPerHour + { get => _reSpecPointsPerHour; - set { + set + { _reSpecPointsPerHour = value; OnPropertyChanged(); } } - public string TotalPlayerFame { + public string TotalPlayerFame + { get => _totalPlayerFame; - set { + set + { _totalPlayerFame = value; OnPropertyChanged(); } } - public string TotalPlayerSilver { + public string TotalPlayerSilver + { get => _totalPlayerSilver; - set { + set + { _totalPlayerSilver = value; OnPropertyChanged(); } } - public string TotalPlayerReSpecPoints { + public string TotalPlayerReSpecPoints + { get => _totalPlayerReSpecPoints; - set { + set + { _totalPlayerReSpecPoints = value; OnPropertyChanged(); } } - public bool IsTrackingResetByMapChangeActive { + public bool IsTrackingResetByMapChangeActive + { get => _isTrackingResetByMapChangeActive; - set { + set + { _isTrackingResetByMapChangeActive = value; OnPropertyChanged(); } } - public ObservableCollection TrackingNotifications { + public ObservableCollection TrackingNotifications + { get => _trackingNotifications; - set { + set + { _trackingNotifications = value; OnPropertyChanged(); } } - public ObservableCollection TrackingDungeons { + public ObservableCollection TrackingDungeons + { get => _trackingDungeons; - set { + set + { _trackingDungeons = value; OnPropertyChanged(); } } - public bool IsTrackingActive { + public bool IsTrackingActive + { get => _isTrackingActive; - set { + set + { _isTrackingActive = value; - TrackerActivationToggleIcon = (_isTrackingActive) ? EFontAwesomeIcon.Solid_ToggleOn : EFontAwesomeIcon.Solid_ToggleOff; + TrackerActivationToggleIcon = _isTrackingActive ? EFontAwesomeIcon.Solid_ToggleOn : EFontAwesomeIcon.Solid_ToggleOff; - var colorOn = new SolidColorBrush((Color)Application.Current.Resources["Color.Blue.2"]); - var colorOff = new SolidColorBrush((Color)Application.Current.Resources["Color.Text.Normal"]); + var colorOn = new SolidColorBrush((Color) Application.Current.Resources["Color.Blue.2"]); + var colorOff = new SolidColorBrush((Color) Application.Current.Resources["Color.Text.Normal"]); TrackerActivationToggleColor = _isTrackingActive ? colorOn : colorOff; - var trackingIconColorOn = new SolidColorBrush((Color)Application.Current.Resources["Tracking.On"]); - var trackingIconColorOff = new SolidColorBrush((Color)Application.Current.Resources["Tracking.Off"]); + var trackingIconColorOn = new SolidColorBrush((Color) Application.Current.Resources["Tracking.On"]); + var trackingIconColorOff = new SolidColorBrush((Color) Application.Current.Resources["Tracking.Off"]); TrackingIconColor = _isTrackingActive ? trackingIconColorOn : trackingIconColorOff; OnPropertyChanged(); } @@ -1139,28 +1129,31 @@ public EFontAwesomeIcon TrackerActivationToggleIcon } } - public Brush TrackerActivationToggleColor + public Brush TrackerActivationToggleColor { - get => _trackerActivationToggleColor ?? new SolidColorBrush((Color)Application.Current.Resources["Color.Text.Normal"]); + get => _trackerActivationToggleColor ?? new SolidColorBrush((Color) Application.Current.Resources["Color.Text.Normal"]); set { _trackerActivationToggleColor = value; OnPropertyChanged(); } } - - public Brush TrackingIconColor { - get => _trackerActivationToggleColor ?? new SolidColorBrush((Color)Application.Current.Resources["Tracking.Off"]); + + public Brush TrackingIconColor + { + get => _trackerActivationToggleColor ?? new SolidColorBrush((Color) Application.Current.Resources["Tracking.Off"]); set { _trackerActivationToggleColor = value; OnPropertyChanged(); } } - - public bool IsShowOnlyItemsWithAlertOnActive { + + public bool IsShowOnlyItemsWithAlertOnActive + { get => _isShowOnlyItemsWithAlertOnActive; - set { + set + { _isShowOnlyItemsWithAlertOnActive = value; ItemsViewFilter(); ItemsView?.Refresh(); @@ -1168,92 +1161,108 @@ public bool IsShowOnlyItemsWithAlertOnActive { } } - public bool IsFullItemInfoLoading { + public bool IsFullItemInfoLoading + { get => _isFullItemInfoLoading; - set { + set + { _isFullItemInfoLoading = value; OnPropertyChanged(); } } - public string LoadFullItemInfoProBarCounter { + public string LoadFullItemInfoProBarCounter + { get => _loadFullItemInfoProBarCounter; - set { + set + { _loadFullItemInfoProBarCounter = value; OnPropertyChanged(); } } - public Visibility LoadIconVisibility { + public Visibility LoadIconVisibility + { get => _loadIconVisibility; - set { + set + { _loadIconVisibility = value; OnPropertyChanged(); } } - public Visibility LoadFullItemInfoProBarGridVisibility { + public Visibility LoadFullItemInfoProBarGridVisibility + { get => _loadFullItemInfoProBarGridVisibility; - set { + set + { _loadFullItemInfoProBarGridVisibility = value; OnPropertyChanged(); } } - public int LoadFullItemInfoProBarValue { + public int LoadFullItemInfoProBarValue + { get => _loadFullItemInfoProBarValue; - set { + set + { _loadFullItemInfoProBarValue = value; LoadFullItemInfoProBarCounter = $"{_loadFullItemInfoProBarValue}/{LoadFullItemInfoProBarMax}"; OnPropertyChanged(); } } - public int LoadFullItemInfoProBarMax { + public int LoadFullItemInfoProBarMax + { get => _loadFullItemInfoProBarMax; - set { + set + { _loadFullItemInfoProBarMax = value; OnPropertyChanged(); } } - public int LoadFullItemInfoProBarMin { + public int LoadFullItemInfoProBarMin + { get => _loadFullItemInfoProBarMin; - set { + set + { _loadFullItemInfoProBarMin = value; OnPropertyChanged(); } } - public bool IsLoadFullItemInfoButtonEnabled { + public bool IsLoadFullItemInfoButtonEnabled + { get => _isLoadFullItemInfoButtonEnabled; - set { + set + { _isLoadFullItemInfoButtonEnabled = value; OnPropertyChanged(); } } - public Visibility LoadFullItemInfoButtonVisibility { + public Visibility LoadFullItemInfoButtonVisibility + { get => _loadFullItemInfoButtonVisibility; - set { + set + { _loadFullItemInfoButtonVisibility = value; OnPropertyChanged(); } } - public bool IsFullItemInfoSearchActive { + public bool IsFullItemInfoSearchActive + { get => _isFullItemInfoSearchActive; - set { + set + { _isFullItemInfoSearchActive = value; if (_isFullItemInfoSearchActive) - { ItemLevelsVisibility = ItemTiersVisibility = ItemCategoriesVisibility = ItemParentCategoriesVisibility = Visibility.Visible; - } else - { ItemLevelsVisibility = ItemTiersVisibility = ItemCategoriesVisibility = ItemParentCategoriesVisibility = Visibility.Hidden; - } ItemsViewFilter(); ItemsView?.Refresh(); @@ -1263,59 +1272,74 @@ public bool IsFullItemInfoSearchActive { } } - public ObservableCollection PartyMemberCircles { + public ObservableCollection PartyMemberCircles + { get => _partyMemberCircles; - set { + set + { _partyMemberCircles = value; OnPropertyChanged(); } } - public Visibility ItemLevelsVisibility { + public Visibility ItemLevelsVisibility + { get => _itemLevelsVisibility; - set { + set + { _itemLevelsVisibility = value; OnPropertyChanged(); } } - public Visibility ItemTiersVisibility { + public Visibility ItemTiersVisibility + { get => _itemTiersVisibility; - set { + set + { _itemTiersVisibility = value; OnPropertyChanged(); } } - public Visibility ItemCategoriesVisibility { + public Visibility ItemCategoriesVisibility + { get => _itemCategoriesVisibility; - set { + set + { _itemCategoriesVisibility = value; OnPropertyChanged(); } } - public Visibility ItemParentCategoriesVisibility { + public Visibility ItemParentCategoriesVisibility + { get => _itemParentCategoriesVisibility; - set { + set + { _itemParentCategoriesVisibility = value; OnPropertyChanged(); } } - public Dictionary ItemCategories { + public Dictionary ItemCategories + { get => _itemCategories; - set { + set + { var categories = value; - categories = (new Dictionary { { Category.Unknown, string.Empty } }).Concat(categories).ToDictionary(k => k.Key, v => v.Value); + categories = new Dictionary {{Category.Unknown, string.Empty}}.Concat(categories) + .ToDictionary(k => k.Key, v => v.Value); _itemCategories = categories; OnPropertyChanged(); } } - public Category SelectedItemCategory { + public Category SelectedItemCategory + { get => _selectedItemCategories; - set { + set + { _selectedItemCategories = value; ItemsViewFilter(); ItemsView?.Refresh(); @@ -1323,17 +1347,21 @@ public Category SelectedItemCategory { } } - public Dictionary ItemParentCategories { + public Dictionary ItemParentCategories + { get => _itemParentCategories; - set { + set + { _itemParentCategories = value; OnPropertyChanged(); } } - public ParentCategory SelectedItemParentCategory { + public ParentCategory SelectedItemParentCategory + { get => _selectedItemParentCategories; - set { + set + { _selectedItemParentCategories = value; ItemCategories = CategoryController.GetCategoriesByParentCategory(SelectedItemParentCategory); SelectedItemCategory = Category.Unknown; @@ -1343,17 +1371,21 @@ public ParentCategory SelectedItemParentCategory { } } - public Dictionary ItemTiers { + public Dictionary ItemTiers + { get => _itemTiers; - set { + set + { _itemTiers = value; OnPropertyChanged(); } } - public ItemTier SelectedItemTier { + public ItemTier SelectedItemTier + { get => _selectedItemTier; - set { + set + { _selectedItemTier = value; ItemsViewFilter(); ItemsView?.Refresh(); @@ -1361,17 +1393,21 @@ public ItemTier SelectedItemTier { } } - public Dictionary ItemLevels { + public Dictionary ItemLevels + { get => _itemLevels; - set { + set + { _itemLevels = value; OnPropertyChanged(); } } - public ItemLevel SelectedItemLevel { + public ItemLevel SelectedItemLevel + { get => _selectedItemLevel; - set { + set + { _selectedItemLevel = value; ItemsView?.Refresh(); SetItemCounterAsync(); @@ -1379,146 +1415,182 @@ public ItemLevel SelectedItemLevel { } } - public int LocalImageCounter { + public int LocalImageCounter + { get => _localImageCounter; - set { + set + { _localImageCounter = value; OnPropertyChanged(); } } - public string ItemCounterString { + public string ItemCounterString + { get => _itemCounterString; - set { + set + { _itemCounterString = value; OnPropertyChanged(); } } - public bool IsTxtSearchEnabled { + public bool IsTxtSearchEnabled + { get => _isTxtSearchEnabled; - set { + set + { _isTxtSearchEnabled = value; OnPropertyChanged(); } } - public bool IsDamageMeterResetByMapChangeActive { + public bool IsDamageMeterResetByMapChangeActive + { get => _isDamageMeterResetByMapChangeActive; - set { + set + { _isDamageMeterResetByMapChangeActive = value; OnPropertyChanged(); } } - public ObservableCollection Modes { + public ObservableCollection Modes + { get => _modes; - set { + set + { _modes = value; OnPropertyChanged(); } } - public ModeStruct ModeSelection { + public ModeStruct ModeSelection + { get => _modeSelection; - set { + set + { _modeSelection = value; OnPropertyChanged(); } } - public int CurrentGoldPrice { + public int CurrentGoldPrice + { get => _currentGoldPrice; - set { + set + { _currentGoldPrice = value; OnPropertyChanged(); } } - public string CurrentGoldPriceTimestamp { + public string CurrentGoldPriceTimestamp + { get => _currentGoldPriceTimestamp; - set { + set + { _currentGoldPriceTimestamp = value; OnPropertyChanged(); } } - public string TextBoxGoldModeNumberOfValues { + public string TextBoxGoldModeNumberOfValues + { get => _textBoxGoldModeNumberOfValues; - set { + set + { _textBoxGoldModeNumberOfValues = value; OnPropertyChanged(); } } - public PlayerModeTranslation PlayerModeTranslation { + public PlayerModeTranslation PlayerModeTranslation + { get => _playerModeTranslation; - set { + set + { _playerModeTranslation = value; OnPropertyChanged(); } } - public string LoadTranslation { + public string LoadTranslation + { get => _loadTranslation; - set { + set + { _loadTranslation = value; OnPropertyChanged(); } } - public string FullItemInformationExistLocal { + public string FullItemInformationExistLocal + { get => _fullItemInformationExistLocal; - set { + set + { _fullItemInformationExistLocal = value; OnPropertyChanged(); } } - public string NumberOfValuesTranslation { + public string NumberOfValuesTranslation + { get => _numberOfValuesTranslation; - set { + set + { _numberOfValuesTranslation = value; OnPropertyChanged(); } } - public string SavedPlayerInformationName { + public string SavedPlayerInformationName + { get => _savedPlayerInformationName; - set { + set + { _savedPlayerInformationName = value; Settings.Default.SavedPlayerInformationName = _savedPlayerInformationName; OnPropertyChanged(); } } - public string ErrorBarText { + public string ErrorBarText + { get => _errorBarText; - set { + set + { _errorBarText = value; OnPropertyChanged(); } } - public Visibility ErrorBarVisibility { + public Visibility ErrorBarVisibility + { get => _errorBarVisibility; - set { + set + { _errorBarVisibility = value; OnPropertyChanged(); } } - public string UpdateTranslation { + public string UpdateTranslation + { get => _updateTranslation; - set { + set + { _updateTranslation = value; OnPropertyChanged(); } } - - public MainWindowTranslation Translation { + + public MainWindowTranslation Translation + { get => _translation; - set { + set + { _translation = value; OnPropertyChanged(); } diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/SettingsWindowViewModel.cs b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/SettingsWindowViewModel.cs index 70fe2db10..dc6d6c514 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/SettingsWindowViewModel.cs +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/ViewModels/SettingsWindowViewModel.cs @@ -1,22 +1,20 @@ -using log4net; -using StatisticsAnalysisTool.Models; +using System.Collections.ObjectModel; +using System.ComponentModel; using System.Globalization; +using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; +using log4net; +using StatisticsAnalysisTool.Common; +using StatisticsAnalysisTool.Models; +using StatisticsAnalysisTool.Properties; +using StatisticsAnalysisTool.Views; namespace StatisticsAnalysisTool.ViewModels { - using Common; - using Properties; - using System.Collections.ObjectModel; - using System.ComponentModel; - using System.Linq; - using System.Runtime.CompilerServices; - using Views; - public class SettingsWindowViewModel : INotifyPropertyChanged { private static SettingsWindow _settingsWindow; - private readonly MainWindowViewModel _mainWindowViewModel; private static string _itemListSourceUrl; private static ObservableCollection _languages = new ObservableCollection(); private static FileInformation _languagesSelection; @@ -24,13 +22,14 @@ public class SettingsWindowViewModel : INotifyPropertyChanged private static FileSettingInformation _refreshRatesSelection; private static ObservableCollection _updateItemListByDays = new ObservableCollection(); private static FileSettingInformation _settingByDaysSelection; - private SettingsWindowTranslation _translation; - private bool _isOpenItemWindowInNewWindowChecked; - private bool _showInfoWindowOnStartChecked; - private int _fullItemInformationUpdateCycleDays; + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private readonly MainWindowViewModel _mainWindowViewModel; private ObservableCollection _alertSounds = new ObservableCollection(); private FileInformation _alertSoundSelection; - private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private int _fullItemInformationUpdateCycleDays; + private bool _isOpenItemWindowInNewWindowChecked; + private bool _showInfoWindowOnStartChecked; + private SettingsWindowTranslation _translation; public SettingsWindowViewModel(SettingsWindow settingsWindow, MainWindowViewModel mainWindowViewModel) { @@ -45,11 +44,11 @@ private void InitializeSettings() #region Refrash rate RefreshRates.Clear(); - RefreshRates.Add(new FileSettingInformation() { Name = LanguageController.Translation("5_SECONDS"), Value = 5000 }); - RefreshRates.Add(new FileSettingInformation() { Name = LanguageController.Translation("10_SECONDS"), Value = 10000 }); - RefreshRates.Add(new FileSettingInformation() { Name = LanguageController.Translation("30_SECONDS"), Value = 30000 }); - RefreshRates.Add(new FileSettingInformation() { Name = LanguageController.Translation("60_SECONDS"), Value = 60000 }); - RefreshRates.Add(new FileSettingInformation() { Name = LanguageController.Translation("5_MINUTES"), Value = 300000 }); + RefreshRates.Add(new FileSettingInformation {Name = LanguageController.Translation("5_SECONDS"), Value = 5000}); + RefreshRates.Add(new FileSettingInformation {Name = LanguageController.Translation("10_SECONDS"), Value = 10000}); + RefreshRates.Add(new FileSettingInformation {Name = LanguageController.Translation("30_SECONDS"), Value = 30000}); + RefreshRates.Add(new FileSettingInformation {Name = LanguageController.Translation("60_SECONDS"), Value = 60000}); + RefreshRates.Add(new FileSettingInformation {Name = LanguageController.Translation("5_MINUTES"), Value = 300000}); RefreshRatesSelection = RefreshRates.FirstOrDefault(x => x.Value == Settings.Default.RefreshRate); #endregion @@ -58,7 +57,6 @@ private void InitializeSettings() Languages.Clear(); foreach (var langInfo in LanguageController.LanguageFiles) - { try { var cultureInfo = CultureInfo.CreateSpecificCulture(langInfo.FileName); @@ -72,7 +70,6 @@ private void InitializeSettings() { Log.Error(nameof(InitializeSettings), e); } - } LanguagesSelection = Languages.FirstOrDefault(x => x.FileName == LanguageController.CurrentCultureInfo.TextInfo.CultureName); @@ -81,11 +78,11 @@ private void InitializeSettings() #region Update item list by days UpdateItemListByDays.Clear(); - UpdateItemListByDays.Add(new FileSettingInformation() { Name = LanguageController.Translation("EVERY_DAY"), Value = 1 }); - UpdateItemListByDays.Add(new FileSettingInformation() { Name = LanguageController.Translation("EVERY_3_DAYS"), Value = 3 }); - UpdateItemListByDays.Add(new FileSettingInformation() { Name = LanguageController.Translation("EVERY_7_DAYS"), Value = 7 }); - UpdateItemListByDays.Add(new FileSettingInformation() { Name = LanguageController.Translation("EVERY_14_DAYS"), Value = 14 }); - UpdateItemListByDays.Add(new FileSettingInformation() { Name = LanguageController.Translation("EVERY_28_DAYS"), Value = 28 }); + UpdateItemListByDays.Add(new FileSettingInformation {Name = LanguageController.Translation("EVERY_DAY"), Value = 1}); + UpdateItemListByDays.Add(new FileSettingInformation {Name = LanguageController.Translation("EVERY_3_DAYS"), Value = 3}); + UpdateItemListByDays.Add(new FileSettingInformation {Name = LanguageController.Translation("EVERY_7_DAYS"), Value = 7}); + UpdateItemListByDays.Add(new FileSettingInformation {Name = LanguageController.Translation("EVERY_14_DAYS"), Value = 14}); + UpdateItemListByDays.Add(new FileSettingInformation {Name = LanguageController.Translation("EVERY_28_DAYS"), Value = 28}); SettingByDaysSelection = UpdateItemListByDays.FirstOrDefault(x => x.Value == Settings.Default.UpdateItemListByDays); ItemListSourceUrl = Settings.Default.ItemListSourceUrl; @@ -98,10 +95,7 @@ private void InitializeSettings() #region Alert Sounds AlertSounds.Clear(); - foreach (var sound in SoundController.AlertSounds) - { - AlertSounds.Add(new FileInformation(sound.FileName, sound.FilePath)); - } + foreach (var sound in SoundController.AlertSounds) AlertSounds.Add(new FileInformation(sound.FileName, sound.FilePath)); AlertSoundSelection = AlertSounds.FirstOrDefault(x => x.FileName == Settings.Default.SelectedAlertSound); #endregion @@ -137,107 +131,139 @@ private void SetAppSettingsAndTranslations() _mainWindowViewModel.UpdateTranslation = LanguageController.Translation("UPDATE"); } + public struct FileSettingInformation + { + public string Name { get; set; } + public int Value { get; set; } + } + #region Bindings - public ObservableCollection AlertSounds { + public ObservableCollection AlertSounds + { get => _alertSounds; - set { + set + { _alertSounds = value; OnPropertyChanged(); } } - public FileInformation AlertSoundSelection { + public FileInformation AlertSoundSelection + { get => _alertSoundSelection; - set { + set + { _alertSoundSelection = value; OnPropertyChanged(); } } - public int FullItemInformationUpdateCycleDays { + public int FullItemInformationUpdateCycleDays + { get => _fullItemInformationUpdateCycleDays; - set { + set + { _fullItemInformationUpdateCycleDays = value; OnPropertyChanged(); } } - public FileSettingInformation SettingByDaysSelection { + public FileSettingInformation SettingByDaysSelection + { get => _settingByDaysSelection; - set { + set + { _settingByDaysSelection = value; OnPropertyChanged(); } } - public ObservableCollection UpdateItemListByDays { + public ObservableCollection UpdateItemListByDays + { get => _updateItemListByDays; - set { + set + { _updateItemListByDays = value; OnPropertyChanged(); } } - public FileSettingInformation RefreshRatesSelection { + public FileSettingInformation RefreshRatesSelection + { get => _refreshRatesSelection; - set { + set + { _refreshRatesSelection = value; OnPropertyChanged(); } } - public ObservableCollection RefreshRates { + public ObservableCollection RefreshRates + { get => _refreshRates; - set { + set + { _refreshRates = value; OnPropertyChanged(); } } - public FileInformation LanguagesSelection { + public FileInformation LanguagesSelection + { get => _languagesSelection; - set { + set + { _languagesSelection = value; OnPropertyChanged(); } } - public ObservableCollection Languages { + public ObservableCollection Languages + { get => _languages; - set { + set + { _languages = value; OnPropertyChanged(); } } - public string ItemListSourceUrl { + public string ItemListSourceUrl + { get => _itemListSourceUrl; - set { + set + { _itemListSourceUrl = value; OnPropertyChanged(); } } - public SettingsWindowTranslation Translation { + public SettingsWindowTranslation Translation + { get => _translation; - set { + set + { _translation = value; OnPropertyChanged(); } } - public bool IsOpenItemWindowInNewWindowChecked { + public bool IsOpenItemWindowInNewWindowChecked + { get => _isOpenItemWindowInNewWindowChecked; - set { + set + { _isOpenItemWindowInNewWindowChecked = value; OnPropertyChanged(); } } - public bool ShowInfoWindowOnStartChecked { + public bool ShowInfoWindowOnStartChecked + { get => _showInfoWindowOnStartChecked; - set { + set + { _showInfoWindowOnStartChecked = value; OnPropertyChanged(); } @@ -251,11 +277,5 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName } #endregion Bindings - - public struct FileSettingInformation - { - public string Name { get; set; } - public int Value { get; set; } - } } } \ No newline at end of file diff --git a/StatisticsAnalysisTool/StatisticsAnalysisTool/packages.config b/StatisticsAnalysisTool/StatisticsAnalysisTool/packages.config index 238c8263f..524cdce27 100644 --- a/StatisticsAnalysisTool/StatisticsAnalysisTool/packages.config +++ b/StatisticsAnalysisTool/StatisticsAnalysisTool/packages.config @@ -1,4 +1,5 @@  +