Refactoring

Extract some logic, suppress some compiler messages
This commit is contained in:
Kurt 2020-09-18 22:11:13 -07:00
parent b90419ba63
commit 2b7e06e217
28 changed files with 172 additions and 68 deletions

View file

@ -170,7 +170,10 @@ namespace PKHeX.Core
if (pi.IsValueEqual(obj, cmd.PropertyValue) == cmd.Evaluator)
continue;
}
#pragma warning disable CA1031 // Do not catch general exception types
// User provided inputs can mismatch the type's required value format, and fail to be compared.
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
Debug.WriteLine($"Unable to compare {cmd.PropertyName} to {cmd.PropertyValue}.");
Debug.WriteLine(e.Message);
@ -214,7 +217,10 @@ namespace PKHeX.Core
if (!IsFilterMatch(cmd, info, pi))
return ModifyResult.Filtered;
}
#pragma warning disable CA1031 // Do not catch general exception types
// Swallow any error because this can be malformed user input.
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
Debug.WriteLine(MsgBEModifyFailCompare + " " + ex.Message, cmd.PropertyName, cmd.PropertyValue);
return ModifyResult.Error;

View file

@ -59,7 +59,9 @@ namespace PKHeX.Core
{
AddLinesPKM(gift, strings, result);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch { result.Add(MsgMysteryGiftParseFail); }
#pragma warning restore CA1031 // Do not catch general exception types
}
else if (gift.IsBP)
{

View file

@ -1075,15 +1075,14 @@ namespace PKHeX.Core
public int GetMove(int index)
{
switch (index)
return index switch
{
case 0: return Move1;
case 1: return Move2;
case 2: return Move3;
case 3: return Move4;
default:
throw new IndexOutOfRangeException(nameof(index));
}
0 => Move1,
1 => Move2,
2 => Move3,
3 => Move4,
_ => throw new IndexOutOfRangeException(nameof(index)),
};
}
public void SetMove(int index, int value)

View file

@ -94,7 +94,9 @@ namespace PKHeX.Core
url = url.Substring(payloadBegin + 1); // Trim URL to right after #
return Convert.FromBase64String(url);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch
#pragma warning restore CA1031 // Do not catch general exception types
{
return null;
}

View file

@ -16,10 +16,17 @@ namespace PKHeX.Core
// Binary Search doesn't require extra memory like a Dictionary would; also, we only need to find a few blocks.
public SCBlock GetBlock(uint key) => BinarySearch(BlockInfo, key);
/// <summary>
/// Tries to grab the actual block, and returns a new dummy if the block does not exist.
/// </summary>
/// <param name="key">Block Key</param>
/// <returns>Block if exists, dummy if not. Dummy key will not match requested key.</returns>
public SCBlock GetBlockSafe(uint key)
{
try { return GetBlock(key); }
#pragma warning disable CA1031 // Do not catch general exception types
catch (KeyNotFoundException) { return new SCBlock(0); }
#pragma warning restore CA1031 // Do not catch general exception types
}
private static SCBlock BinarySearch(IReadOnlyList<SCBlock> arr, uint key)

View file

@ -85,7 +85,9 @@ namespace PKHeX.Core
var data = File.ReadAllBytes(f);
data.CopyTo(block.Data, 0);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch
#pragma warning restore CA1031 // Do not catch general exception types
{
failed.Add(fn);
}

View file

@ -198,5 +198,32 @@ namespace PKHeX.Core
}
}
}
/// <summary>
/// Gets box names for all boxes in the save file.
/// </summary>
/// <param name="sav"><see cref="SaveFile"/> that box names are being dumped for.</param>
/// <returns>Returns default English box names in the event the save file does not have names (not exportable), or fails to return a box name.</returns>
public static string[] GetBoxNames(SaveFile sav)
{
int count = sav.BoxCount;
var result = new string[count];
if (!sav.Exportable)
{
for (int i = 0; i < count; i++)
result[i] = $"Box {i + 1}";
return result;
}
for (int i = 0; i < count; i++)
{
try { result[i] = sav.GetBoxName(i); }
#pragma warning disable CA1031 // Do not catch general exception types
catch { result[i] = $"Box {i + 1}"; }
#pragma warning restore CA1031 // Do not catch general exception types
}
return result;
}
}
}

View file

@ -691,15 +691,12 @@ namespace PKHeX.Core
// force evaluation so that an invalid path will throw before we return true/false.
// EnumerateFiles throws an exception while iterating, which won't be caught by the try-catch here.
var files = Directory.GetFiles(folderPath, "*", searchOption);
static int GetFileSize(string file)
{
try { return (int) new FileInfo(file).Length; }
catch { return -1; } // Bad File / Locked
}
result = files.Where(f => IsSizeValid(GetFileSize(f)));
result = files.Where(f => IsSizeValid(FileUtil.GetFileSize(f)));
return true;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (ArgumentException)
#pragma warning restore CA1031 // Do not catch general exception types
{
result = new[] { MsgFileLoadFailAuto + Environment.NewLine + folderPath, MsgFileLoadFailAutoAdvise + Environment.NewLine + MsgFileLoadFailAutoCause };
return false;

View file

@ -248,7 +248,10 @@ namespace PKHeX.Core
{
ReflectUtil.SetValue(t, prop, value);
}
#pragma warning disable CA1031 // Do not catch general exception types
// Malformed translation files, log
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
Debug.WriteLine($"Property not present: {prop} || Value written: {value}");
Debug.WriteLine(e.Message);

View file

@ -28,7 +28,10 @@ namespace PKHeX.Core
var ext = Path.GetExtension(path);
return GetSupportedFile(data, ext, reference);
}
#pragma warning disable CA1031 // Do not catch general exception types
// User input data can be fuzzed; if anything blows up, just fail safely.
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
Debug.WriteLine(MessageStrings.MsgFileInUse);
Debug.WriteLine(e.Message);
@ -62,6 +65,28 @@ namespace PKHeX.Core
return null;
}
public static bool IsFileLocked(string path)
{
try { return (File.GetAttributes(path) & FileAttributes.ReadOnly) != 0; }
#pragma warning disable CA1031 // Do not catch general exception types
catch { return true; }
#pragma warning restore CA1031 // Do not catch general exception types
}
public static int GetFileSize(string path)
{
try
{
var size = new FileInfo(path).Length;
if (size > int.MaxValue)
return -1;
return (int)size;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch { return -1; } // Bad File / Locked
#pragma warning restore CA1031 // Do not catch general exception types
}
private static bool TryGetGP1(byte[] data, out GP1? gp1)
{
gp1 = null;
@ -77,7 +102,7 @@ namespace PKHeX.Core
/// <param name="length">File size</param>
public static bool IsFileTooBig(long length)
{
if (length <= 0x100000)
if (length <= 0x10_0000) // 10 MB
return false;
if (length == SaveUtil.SIZE_G4BR || length == SaveUtil.SIZE_G8SWSH || length == SaveUtil.SIZE_G8SWSH_1 || length == SaveUtil.SIZE_G8SWSH_2 || length == SaveUtil.SIZE_G8SWSH_2B)
return false;
@ -90,7 +115,7 @@ namespace PKHeX.Core
/// Checks if the length is too small to be a detectable file.
/// </summary>
/// <param name="length">File size</param>
public static bool IsFileTooSmall(long length) => length < 0x20;
public static bool IsFileTooSmall(long length) => length < 0x20; // bigger than PK1
/// <summary>
/// Tries to get an <see cref="SaveFile"/> object from the input parameters.

View file

@ -16,7 +16,10 @@ namespace PKHeX.Core
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
#pragma warning disable CA1031 // Do not catch general exception types
// No internet?
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
Debug.WriteLine(e.Message);
return null;

View file

@ -113,6 +113,13 @@ namespace PKHeX.Core
}
}
/// <summary>
/// Checks if the <see cref="obj"/> has the requested property <see cref="name"/>.
/// </summary>
/// <param name="obj">Object to check for property existence.</param>
/// <param name="name">Name of the property.</param>
/// <param name="pi">Reference to the property info for the object, if it exists.</param>
/// <returns>True if has property, and false if does not have property. <see cref="pi"/> is null when returning false.</returns>
public static bool HasProperty(object obj, string name, out PropertyInfo? pi) => (pi = GetPropertyInfo(obj.GetType().GetTypeInfo(), name)) != null;
public static PropertyInfo? GetPropertyInfo(this TypeInfo typeInfo, string name)

View file

@ -36,7 +36,9 @@ namespace PKHeX.Drawing
if (data.Contains("filetype not supported"))
return QRDecodeResult.BadType;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch { return QRDecodeResult.BadConnection; }
#pragma warning restore CA1031 // Do not catch general exception types
// Quickly convert the json response to a data string
try
@ -44,7 +46,9 @@ namespace PKHeX.Drawing
result = DecodeQRJson(data);
return QRDecodeResult.Success;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
Debug.WriteLine(e.Message);
return QRDecodeResult.BadConversion;

View file

@ -145,33 +145,14 @@ namespace PKHeX.WinForms.Controls
{
if (!SAV.HasBox)
return;
if (!SAV.Exportable)
{
getBoxNamesDefault();
}
else
{
try { getBoxNamesFromSave(); }
catch { getBoxNamesDefault(); }
}
CB_BoxSelect.Items.Clear();
CB_BoxSelect.Items.AddRange(BoxUtil.GetBoxNames(SAV));
if (box < 0 && (uint)SAV.CurrentBox < CB_BoxSelect.Items.Count)
CurrentBox = SAV.CurrentBox; // restore selected box
else
CurrentBox = box;
void getBoxNamesFromSave()
{
CB_BoxSelect.Items.Clear();
for (int i = 0; i < SAV.BoxCount; i++)
CB_BoxSelect.Items.Add(SAV.GetBoxName(i));
}
void getBoxNamesDefault()
{
CB_BoxSelect.Items.Clear();
for (int i = 0; i < SAV.BoxCount; i++)
CB_BoxSelect.Items.Add($"Box {i+1}");
}
}
public void ResetSlots()

View file

@ -172,9 +172,12 @@ namespace PKHeX.WinForms.Controls
var data = encrypt ? pk.EncryptedPartyData : pk.DecryptedPartyData;
external = TryMakeDragDropPKM(pb, data, newfile);
}
#pragma warning disable CA1031 // Do not catch general exception types
// Tons of things can happen with drag & drop; don't try to handle things, just indicate failure.
catch (Exception x)
#pragma warning restore CA1031 // Do not catch general exception types
{
WinFormsUtil.Error("Drag & Drop Error", x);
WinFormsUtil.Error("Drag && Drop Error", x);
external = false;
}

View file

@ -21,7 +21,9 @@ namespace PKHeX.WinForms.Controls
Sounds.SoundLocation = path;
try { Sounds.Play(); }
#pragma warning disable CA1031 // Do not catch general exception types
catch { Debug.WriteLine("Failed to play sound."); }
#pragma warning restore CA1031 // Do not catch general exception types
}
public void Stop() => Sounds.Stop();

View file

@ -837,19 +837,13 @@ namespace PKHeX.WinForms
if (sav.Exportable && Directory.Exists(BackupPath) && !File.Exists(backupName))
File.WriteAllBytes(backupName, sav.BAK);
if (!IsFileLocked(path))
if (!FileUtil.IsFileLocked(path))
return true;
WinFormsUtil.Alert(MsgFileWriteProtected + Environment.NewLine + path, MsgFileWriteProtectedAdvice);
return false;
}
private static bool IsFileLocked(string path)
{
try { return (File.GetAttributes(path) & FileAttributes.ReadOnly) != 0; }
catch { return true; }
}
private static bool SanityCheckSAV(ref SaveFile sav)
{
ParseSettings.InitFromSaveFileData(sav); // physical GB, no longer used in logic
@ -1121,7 +1115,10 @@ namespace PKHeX.WinForms
C_SAV.M.Drag.Info.Cursor = Cursor = new Cursor(((Bitmap)pb.Image).GetHicon());
DoDragDrop(new DataObject(DataFormats.FileDrop, new[] { newfile }), DragDropEffects.Move);
}
#pragma warning disable CA1031 // Do not catch general exception types
// Tons of things can happen with drag & drop; don't try to handle things, just indicate failure.
catch (Exception x)
#pragma warning restore CA1031 // Do not catch general exception types
{ WinFormsUtil.Error("Drag && Drop Error", x); }
C_SAV.M.Drag.ResetCursor(this);
File.Delete(newfile);
@ -1174,7 +1171,10 @@ namespace PKHeX.WinForms
settings.Draw = Draw.ToString();
settings.Save();
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception x)
// Config might be corrupted, or their dotnet runtime is insufficient (<4.6?)
#pragma warning restore CA1031 // Do not catch general exception types
{
File.WriteAllLines("config error.txt", new[] {x.ToString()});
}
@ -1191,11 +1191,11 @@ namespace PKHeX.WinForms
private void ClickExportSAV(object sender, EventArgs e)
{
if (Menu_ExportSAV.Enabled)
{
C_SAV.ExportSaveFile();
Text = GetProgramTitle(C_SAV.SAV);
}
if (!Menu_ExportSAV.Enabled)
return; // hot-keys can't cheat the system!
C_SAV.ExportSaveFile();
Text = GetProgramTitle(C_SAV.SAV);
}
private void ClickSaveFileName(object sender, EventArgs e)
@ -1227,7 +1227,11 @@ namespace PKHeX.WinForms
Directory.CreateDirectory(BackupPath);
WinFormsUtil.Alert(MsgBackupSuccess, string.Format(MsgBackupDelete, BackupPath));
}
catch (Exception ex) { WinFormsUtil.Error($"{MsgBackupUnable} @ {BackupPath}", ex); }
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
// Maybe they put their exe in a folder that we can't create files/folders to.
#pragma warning restore CA1031 // Do not catch general exception types
{ WinFormsUtil.Error($"{MsgBackupUnable} @ {BackupPath}", ex); }
}
private void ClickUndo(object sender, EventArgs e) => C_SAV.ClickUndo();

View file

@ -49,7 +49,10 @@ namespace PKHeX.WinForms
var types = z.GetTypes();
return types.Where(type => IsTypePlugin(type, pluginType));
}
#pragma warning disable CA1031 // Do not catch general exception types
// User plugins can be out of date, with mismatching API surfaces.
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
System.Diagnostics.Debug.WriteLine($"Unable to load plugin [{pluginType.Name}]: {z.FullName}", ex.Message);
return Enumerable.Empty<Type>();

View file

@ -77,7 +77,10 @@ namespace PKHeX.WinForms
if (DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, MsgQRClipboardImage))
return;
try { Clipboard.SetImage(PB_QR.Image); }
#pragma warning disable CA1031 // Do not catch general exception types
// Clipboard can be locked periodically, just notify on failure.
catch { WinFormsUtil.Alert(MsgQRClipboardFail); }
#pragma warning restore CA1031 // Do not catch general exception types
}
private void UpdateBoxSlotCopies(object sender, EventArgs e)

View file

@ -321,7 +321,9 @@ namespace PKHeX.WinForms
while (!IsHandleCreated) { }
BeginInvoke(new MethodInvoker(() => SetResults(RawDB)));
}
#pragma warning disable CA1031 // Do not catch general exception types
catch { /* Window Closed? */ }
#pragma warning restore CA1031 // Do not catch general exception types
}
private static List<PKM> LoadPKMSaves(string pkmdb, string savdb, string EXTERNAL_SAV, SaveFile SAV)
@ -635,8 +637,14 @@ namespace PKHeX.WinForms
var clones = SearchUtil.GetExtraClones(db);
foreach (var pk in clones)
{
try { File.Delete(pk.Identifier); ++deleted; }
var path = pk.Identifier;
if (path == null || !File.Exists(path))
continue;
try { File.Delete(path); ++deleted; }
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex) { WinFormsUtil.Error(MsgDBDeleteCloneFail + Environment.NewLine + ex.Message + Environment.NewLine + pk.Identifier); }
#pragma warning restore CA1031 // Do not catch general exception types
}
if (deleted == 0)

View file

@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using PKHeX.Core;
@ -278,19 +277,16 @@ namespace PKHeX.WinForms
private void SetFlagsFromFileName(string inpFileName)
{
if (new FileInfo(inpFileName).Length > 2058) return; // 24*20*4(ARGB)=1920
Bitmap bmp;
FileStream fs = new FileStream(inpFileName, FileMode.Open, FileAccess.Read);
try
{
bmp = (Bitmap)Image.FromStream(fs);
}
catch
{
bmp = null;
}
fs.Close();
if (bmp == null || bmp.Width != 24 || bmp.Height != 20) return;
if (FileUtil.GetFileSize(inpFileName) > 2058)
return; // 24*20*4(ARGB)=1920
Bitmap bmp; try { bmp = (Bitmap)Image.FromFile(inpFileName); }
#pragma warning disable CA1031 // Do not catch general exception types
catch { return; }
#pragma warning restore CA1031 // Do not catch general exception types
if (bmp.Width != 24 || bmp.Height != 20)
return;
byte[] BrightMap = new byte[480];
byte[] BrightCount = new byte[0x100];
@ -306,7 +302,8 @@ namespace PKHeX.WinForms
}
int ColorCount = BrightCount.Count(v => v > 0);
if (ColorCount > 4 || ColorCount == 0) return;
if (ColorCount > 4 || ColorCount == 0)
return;
int errmin = int.MaxValue;
byte[] LCT = new byte[4];
byte[] mLCT = new byte[4];

View file

@ -45,7 +45,9 @@ namespace PKHeX.WinForms
bg = CGearImage.GetCGearBackground(img);
PB_Background.Image = CGearImage.GetBitmap(bg);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
WinFormsUtil.Error(ex.Message);
}

View file

@ -100,7 +100,9 @@ namespace PKHeX.WinForms
ComboBox comboBox = (ComboBox)dataGridView1.EditingControl;
comboBox.DroppedDown = true;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch { Console.WriteLine("Failed to modify item."); }
#pragma warning restore CA1031 // Do not catch general exception types
}
private bool loading = true;

View file

@ -129,7 +129,10 @@ namespace PKHeX.WinForms
NUD_Y.Value = (decimal)SAV.Situation.Y;
NUD_R.Value = (decimal)SAV.Situation.R;
}
#pragma warning disable CA1031 // Do not catch general exception types
// Sometimes the coordinates aren't really decimal/float coordinates?
catch { GB_Map.Enabled = false; }
#pragma warning restore CA1031 // Do not catch general exception types
// Load Play Time
MT_Hours.Text = SAV.PlayedHours.ToString();

View file

@ -223,11 +223,13 @@ namespace PKHeX.WinForms
desc.Add(split[1]);
enums.Add(split.Length == 3 ? split[2] : string.Empty);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch
{
// Ignore bad user values
Debug.WriteLine(string.Concat(split));
}
#pragma warning restore CA1031 // Do not catch general exception types
}
if (num.Count == 0)
{

View file

@ -111,7 +111,9 @@ namespace PKHeX.WinForms
System.Diagnostics.Process.Start(Application.ExecutablePath);
Environment.Exit(0);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
WinFormsUtil.Error("Failed to delete settings.", ex.Message);
}

View file

@ -61,7 +61,9 @@ namespace PKHeX.WinForms
if (File.Exists(externalLangPath))
{
try { return File.ReadAllLines(externalLangPath); }
#pragma warning disable CA1031 // Do not catch general exception types
catch { /* In use? Just return the internal resource. */ }
#pragma warning restore CA1031 // Do not catch general exception types
}
if (Util.IsStringListCached(file, out var result))
@ -174,7 +176,10 @@ namespace PKHeX.WinForms
{
var _ = (Form)System.Activator.CreateInstance(t, new object[argCount]);
}
#pragma warning disable CA1031 // Do not catch general exception types
// This is a debug utility method, will always be logging. Shouldn't ever fail.
catch
#pragma warning restore CA1031 // Do not catch general exception types
{
Debug.Write($"Failed to create a new form {t}");
}

View file

@ -139,7 +139,10 @@ namespace PKHeX.WinForms
{
Error(MsgClipboardFailWrite, x);
}
#pragma warning disable CA1031 // Do not catch general exception types
// Clipboard might be locked sometimes
catch
#pragma warning restore CA1031 // Do not catch general exception types
{
Error(MsgClipboardFailWrite);
}