Code refactoring

This commit is contained in:
Jaex 2021-06-10 01:14:01 +03:00
parent d2576ae5fa
commit e8ad4b8553
90 changed files with 258 additions and 565 deletions

View file

@ -96,9 +96,7 @@ private void CreateFirstInstance(EventHandler<InstanceCallbackEventArgs> callbac
{
try
{
bool createdNew;
using (EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, EventName, out createdNew))
using (EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, EventName, out bool createdNew))
{
// Mixing single instance and multi instance (via command line parameter) copies of the program can
// result in CreateFirstInstance being called if it isn't really the first one. Make sure this is
@ -151,9 +149,7 @@ private void UpdateRemoteObject(string uri)
IpcClientChannel clientChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(clientChannel, true);
InstanceProxy proxy = Activator.GetObject(typeof(InstanceProxy), string.Format("ipc://{0}{1}{2}/{2}", Environment.MachineName, Environment.UserName, uri)) as InstanceProxy;
if (proxy != null)
if (Activator.GetObject(typeof(InstanceProxy), string.Format("ipc://{0}{1}{2}/{2}", Environment.MachineName, Environment.UserName, uri)) is InstanceProxy proxy)
{
proxy.SetCommandLineArgs(InstanceProxy.CommandLineArgs);
}
@ -171,9 +167,7 @@ private void RegisterRemoteType(string uri)
private void WaitOrTimerCallback(object state, bool timedOut)
{
EventHandler<InstanceCallbackEventArgs> callback = state as EventHandler<InstanceCallbackEventArgs>;
if (callback != null)
if (state is EventHandler<InstanceCallbackEventArgs> callback)
{
try
{

View file

@ -71,9 +71,7 @@ private void ExecuteAction(string parameter)
}
else if (NumberAction != null)
{
int num;
if (int.TryParse(parameter, out num))
if (int.TryParse(parameter, out int num))
{
NumberAction(num);
}

View file

@ -91,10 +91,7 @@ private void cli_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
if (OutputDataReceived != null)
{
OutputDataReceived(sender, e);
}
OutputDataReceived?.Invoke(sender, e);
}
}
@ -102,10 +99,7 @@ private void cli_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
if (ErrorDataReceived != null)
{
ErrorDataReceived(sender, e);
}
ErrorDataReceived?.Invoke(sender, e);
}
}

View file

@ -74,7 +74,7 @@ public ColorBgra(Color color) : this(color.B, color.G, color.R, color.A)
public override bool Equals(object obj)
{
return obj is ColorBgra && ((ColorBgra)obj).Bgra == Bgra;
return obj is ColorBgra color && color.Bgra == Bgra;
}
public override int GetHashCode()

View file

@ -114,10 +114,7 @@ public void ChangeColor(Color color, ColorType colorType = ColorType.None)
private void OnColorChanged(ColorType colorType = ColorType.None)
{
if (ColorChanged != null)
{
ColorChanged(this, new ColorEventArgs(SelectedColor, colorType));
}
ColorChanged?.Invoke(this, new ColorEventArgs(SelectedColor, colorType));
}
#region Component Designer generated code

View file

@ -205,10 +205,7 @@ private void MouseMoveTimer_Tick(object sender, EventArgs e)
protected void OnColorChanged()
{
if (ColorChanged != null)
{
ColorChanged(this, new ColorEventArgs(SelectedColor, DrawStyle));
}
ColorChanged?.Invoke(this, new ColorEventArgs(SelectedColor, DrawStyle));
}
protected void DrawColors()

View file

@ -163,10 +163,7 @@ protected override void OnClick(EventArgs e)
protected virtual void OnCheckedChanged(EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(this, e);
}
CheckedChanged?.Invoke(this, e);
}
private void DrawBackground(Graphics g)

View file

@ -97,10 +97,7 @@ protected override void OnPaint(PaintEventArgs e)
protected void OnDraw(Graphics g)
{
if (Draw != null)
{
Draw(g);
}
Draw?.Invoke(g);
}
}
}

View file

@ -70,10 +70,7 @@ public Color Color
protected void OnColorChanged(Color color)
{
if (ColorChanged != null)
{
ColorChanged(color);
}
ColorChanged?.Invoke(color);
}
protected override void OnMouseClick(MouseEventArgs mevent)

View file

@ -125,10 +125,7 @@ public DoubleLabeledNumericUpDown()
private void OnValueChanged(object sender, EventArgs e)
{
if (ValueChanged != null)
{
ValueChanged(sender, e);
}
ValueChanged?.Invoke(sender, e);
}
}
}

View file

@ -190,10 +190,7 @@ private void OnImportRequested(string json)
private void OnImportCompleted()
{
if (ImportCompleted != null)
{
ImportCompleted();
}
ImportCompleted?.Invoke();
}
private void ImportJson(string json)

View file

@ -187,10 +187,7 @@ protected override void OnKeyUp(KeyEventArgs kevent)
protected void OnHotkeyChanged()
{
if (HotkeyChanged != null)
{
HotkeyChanged(this, EventArgs.Empty);
}
HotkeyChanged?.Invoke(this, EventArgs.Empty);
}
}
}

View file

@ -112,10 +112,7 @@ public LabeledNumericUpDown()
private void OnValueChanged(object sender, EventArgs e)
{
if (ValueChanged != null)
{
ValueChanged(sender, e);
}
ValueChanged?.Invoke(sender, e);
}
}
}

View file

@ -234,9 +234,7 @@ protected override void OnDragOver(DragEventArgs drgevent)
{
base.OnDragOver(drgevent);
ListViewItem lvi = drgevent.Data.GetData(typeof(ListViewItem)) as ListViewItem;
if (lvi != null && lvi.ListView == this)
if (drgevent.Data.GetData(typeof(ListViewItem)) is ListViewItem lvi && lvi.ListView == this)
{
drgevent.Effect = DragDropEffects.Move;
@ -265,9 +263,7 @@ protected override void OnDragDrop(DragEventArgs drgevent)
{
base.OnDragDrop(drgevent);
ListViewItem lvi = drgevent.Data.GetData(typeof(ListViewItem)) as ListViewItem;
if (lvi != null && lvi.ListView == this && lvi != dragOverItem)
if (drgevent.Data.GetData(typeof(ListViewItem)) is ListViewItem lvi && lvi.ListView == this && lvi != dragOverItem)
{
int oldIndex = lvi.Index;
int newIndex;

View file

@ -167,9 +167,7 @@ private void tvMain_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
private void tvMain_AfterSelect(object sender, TreeViewEventArgs e)
{
TabPage tabPage = e.Node.Tag as TabPage;
if (tabPage != null)
if (e.Node.Tag is TabPage tabPage)
{
if (AutoSelectChild && tabPage.Controls.Count == 1 && tabPage.Controls[0] is TabControl)
{
@ -224,10 +222,7 @@ public void SelectChildNode()
protected void OnTabChanged(TabPage tabPage)
{
if (TabChanged != null)
{
TabChanged(tabPage);
}
TabChanged?.Invoke(tabPage);
}
protected override void ScaleControl(SizeF factor, BoundsSpecified specified)

View file

@ -62,10 +62,7 @@ protected override void OnUnsubscribeControlEvents(Control control)
public void OnValueChanged(object sender, EventArgs e)
{
if (ValueChanged != null)
{
ValueChanged(this, e);
}
ValueChanged?.Invoke(this, e);
}
}
}

View file

@ -88,9 +88,7 @@ protected override void OnCheckedChanged(EventArgs e)
// Clear the checked state for all siblings.
foreach (ToolStripItem item in Parent.Items)
{
ToolStripRadioButtonMenuItem radioItem = item as ToolStripRadioButtonMenuItem;
if (radioItem != null && radioItem != this && radioItem.Checked)
if (item is ToolStripRadioButtonMenuItem radioItem && radioItem != this && radioItem.Checked)
{
radioItem.Checked = false;
@ -210,11 +208,9 @@ public override bool Enabled
{
get
{
ToolStripMenuItem ownerMenuItem = OwnerItem as ToolStripMenuItem;
// Use the base value in design mode to prevent the designer
// from setting the base value to the calculated value.
if (!DesignMode && ownerMenuItem != null && ownerMenuItem.CheckOnClick)
if (!DesignMode && OwnerItem is ToolStripMenuItem ownerMenuItem && ownerMenuItem.CheckOnClick)
{
return base.Enabled && ownerMenuItem.Checked;
}
@ -232,9 +228,7 @@ public override bool Enabled
// CheckedChanged event.
protected override void OnOwnerChanged(EventArgs e)
{
ToolStripMenuItem ownerMenuItem = OwnerItem as ToolStripMenuItem;
if (ownerMenuItem != null && ownerMenuItem.CheckOnClick)
if (OwnerItem is ToolStripMenuItem ownerMenuItem && ownerMenuItem.CheckOnClick)
{
ownerMenuItem.CheckedChanged += OwnerMenuItem_CheckedChanged;
}

View file

@ -111,7 +111,7 @@ private static uint[] InitializeTable(uint polynomial)
}
else
{
entry = entry >> 1;
entry >>= 1;
}
}
createTable[i] = entry;

View file

@ -183,8 +183,7 @@ public static string ASCIIToText(string ascii)
{
foreach (string number in numbers)
{
byte b;
if (byte.TryParse(number, out b))
if (byte.TryParse(number, out byte b))
{
stream.WriteByte(b);
}

View file

@ -61,9 +61,7 @@ public void UpdateCursorData()
if (iconHandle != IntPtr.Zero)
{
IconInfo iconInfo;
if (NativeMethods.GetIconInfo(iconHandle, out iconInfo))
if (NativeMethods.GetIconInfo(iconHandle, out IconInfo iconInfo))
{
Position = new Point(Position.X - iconInfo.xHotspot, Position.Y - iconInfo.yHotspot);

View file

@ -109,25 +109,25 @@ public static bool IsValidIndex<T>(this List<T> list, int index)
public static T ReturnIfValidIndex<T>(this T[] array, int index)
{
if (array.IsValidIndex(index)) return array[index];
return default(T);
return default;
}
public static T ReturnIfValidIndex<T>(this List<T> list, int index)
{
if (list.IsValidIndex(index)) return list[index];
return default(T);
return default;
}
public static T Last<T>(this T[] array, int index = 0)
{
if (array.Length > index) return array[array.Length - index - 1];
return default(T);
return default;
}
public static T Last<T>(this List<T> list, int index = 0)
{
if (list.Count > index) return list[list.Count - index - 1];
return default(T);
return default;
}
public static double ToDouble(this Version value)
@ -445,8 +445,10 @@ public static void ApplyDefaultPropertyValues(this object self)
{
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self))
{
DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
if (attr != null) prop.SetValue(self, attr.Value);
if (prop.Attributes[typeof(DefaultValueAttribute)] is DefaultValueAttribute attr)
{
prop.SetValue(self, attr.Value);
}
}
}

View file

@ -52,7 +52,7 @@ public static class NumberExtensions
return MathHelpers.IsBetween(num, min, max);
}
public static T BetweenOrDefault<T>(this T num, T min, T max, T defaultValue = default(T)) where T : IComparable<T>
public static T BetweenOrDefault<T>(this T num, T min, T max, T defaultValue = default) where T : IComparable<T>
{
return MathHelpers.BetweenOrDefault(num, min, max, defaultValue);
}

View file

@ -277,8 +277,7 @@ public static string ParseQuoteString(this string str)
public static bool IsNumber(this string text)
{
int num;
return int.TryParse(text, out num);
return int.TryParse(text, out _);
}
public static string[] Lines(this string text)
@ -289,7 +288,7 @@ public static string[] Lines(this string text)
public static IEnumerable<Tuple<string, string>> ForEachBetween(this string text, string front, string back)
{
int f = 0;
int b = 0;
int b;
while (text.Length > f && (f = text.IndexOf(front, f)) >= 0 && (b = text.IndexOf(back, f + front.Length)) >= 0)
{
string result = text.Substring(f, (b + back.Length) - f);

View file

@ -195,9 +195,9 @@ public static XmlNode AppendElement(this XmlNode parent, string tagName, string
{
XmlDocument xd;
if (parent is XmlDocument)
if (parent is XmlDocument document)
{
xd = (XmlDocument)parent;
xd = document;
}
else
{
@ -230,9 +230,9 @@ public static XmlNode PrependElement(this XmlNode parent, string tagName, string
{
XmlDocument xd;
if (parent is XmlDocument)
if (parent is XmlDocument document)
{
xd = (XmlDocument)parent;
xd = document;
}
else
{

View file

@ -65,9 +65,7 @@ private void AddDNS(string name, string primary = null, string secondary = null)
private void cbAdapters_SelectedIndexChanged(object sender, EventArgs e)
{
AdapterInfo adapter = cbAdapters.SelectedItem as AdapterInfo;
if (adapter != null)
if (cbAdapters.SelectedItem is AdapterInfo adapter)
{
string[] dns = adapter.GetDNS();
@ -105,15 +103,10 @@ private void cbAutomatic_CheckedChanged(object sender, EventArgs e)
private void cbDNSType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbDNSType.SelectedIndex > 0)
if (cbDNSType.SelectedIndex > 0 && cbDNSType.SelectedItem is DNSInfo dnsInfo)
{
DNSInfo dnsInfo = cbDNSType.SelectedItem as DNSInfo;
if (dnsInfo != null)
{
txtPreferredDNS.Text = dnsInfo.PrimaryDNS;
txtAlternateDNS.Text = dnsInfo.SecondaryDNS;
}
txtPreferredDNS.Text = dnsInfo.PrimaryDNS;
txtAlternateDNS.Text = dnsInfo.SecondaryDNS;
}
UpdateControls();
@ -154,9 +147,7 @@ private async Task SendPing(string ip)
private void btnSave_Click(object sender, EventArgs e)
{
AdapterInfo adapter = cbAdapters.SelectedItem as AdapterInfo;
if (adapter != null)
if (cbAdapters.SelectedItem is AdapterInfo adapter)
{
uint result;

View file

@ -298,8 +298,7 @@ private void lvPresets_SelectedIndexChanged(object sender, EventArgs e)
if (isReady && lvPresets.SelectedItems.Count > 0)
{
ListViewItem lvi = lvPresets.SelectedItems[0];
GradientInfo gradientInfo = lvi.Tag as GradientInfo;
if (gradientInfo != null)
if (lvi.Tag is GradientInfo gradientInfo)
{
Gradient = gradientInfo.Copy();
UpdateGradientList(true);

View file

@ -198,14 +198,9 @@ private void tpFileHashCheck_DragEnter(object sender, DragEventArgs e)
private void tpFileHashCheck_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) && e.Data.GetData(DataFormats.FileDrop, false) is string[] files && files.Length > 0)
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null && files.Length > 0)
{
txtFilePath.Text = files[0];
}
txtFilePath.Text = files[0];
}
}

View file

@ -135,9 +135,7 @@ public static Rectangle ClientToScreen(Rectangle r)
public static Point GetCursorPosition()
{
POINT point;
if (NativeMethods.GetCursorPos(out point))
if (NativeMethods.GetCursorPos(out POINT point))
{
return (Point)point;
}
@ -311,14 +309,9 @@ public static Rectangle GetWindowRectangle(IntPtr handle)
{
Rectangle rect = Rectangle.Empty;
if (NativeMethods.IsDWMEnabled())
if (NativeMethods.IsDWMEnabled() && NativeMethods.GetExtendedFrameBounds(handle, out Rectangle tempRect))
{
Rectangle tempRect;
if (NativeMethods.GetExtendedFrameBounds(handle, out tempRect))
{
rect = tempRect;
}
rect = tempRect;
}
if (rect.IsEmpty)

View file

@ -85,8 +85,7 @@ public static byte[] ConvertToDib(Image image)
gr.DrawImage(image, new Rectangle(0, 0, bm32b.Width, bm32b.Height));
// Bitmap format has its lines reversed.
bm32b.RotateFlip(RotateFlipType.Rotate180FlipX);
int stride;
bm32bData = GetImageData(bm32b, out stride);
bm32bData = GetImageData(bm32b, out int stride);
}
// BITMAPINFOHEADER struct for DIB.
int hdrSize = 0x28;
@ -128,18 +127,16 @@ public static Bitmap GetClipboardImage(DataObject retrievedData)
{
Bitmap clipboardimage = null;
// Order: try PNG, move on to try 32-bit ARGB DIB, then try the normal Bitmap and Image types.
if (retrievedData.GetDataPresent("PNG"))
if (retrievedData.GetDataPresent("PNG") && retrievedData.GetData("PNG") is MemoryStream pngStream)
{
MemoryStream png_stream = retrievedData.GetData("PNG") as MemoryStream;
if (png_stream != null)
using (Bitmap bm = new Bitmap(png_stream))
clipboardimage = CloneImage(bm);
using (Bitmap bm = new Bitmap(pngStream))
{
clipboardimage = CloneImage(bm);
}
}
if (clipboardimage == null && retrievedData.GetDataPresent(DataFormats.Dib))
if (clipboardimage == null && retrievedData.GetDataPresent(DataFormats.Dib) && retrievedData.GetData(DataFormats.Dib) is MemoryStream dib)
{
MemoryStream dib = retrievedData.GetData(DataFormats.Dib) as MemoryStream;
if (dib != null)
clipboardimage = ImageFromClipboardDib(dib.ToArray());
clipboardimage = ImageFromClipboardDib(dib.ToArray());
}
if (clipboardimage == null && retrievedData.GetDataPresent(DataFormats.Bitmap))
clipboardimage = new Bitmap(retrievedData.GetData(DataFormats.Bitmap) as Image);

View file

@ -57,7 +57,7 @@ public static class MathHelpers
return num.CompareTo(min) >= 0 && num.CompareTo(max) <= 0;
}
public static T BetweenOrDefault<T>(T num, T min, T max, T defaultValue = default(T)) where T : IComparable<T>
public static T BetweenOrDefault<T>(T num, T min, T max, T defaultValue = default) where T : IComparable<T>
{
if (num.CompareTo(min) >= 0 && num.CompareTo(max) <= 0) return num;
return defaultValue;

View file

@ -119,10 +119,7 @@ protected override void WndProc(ref Message m)
protected void OnKeyPressed(ushort id, Keys key, Modifiers modifier)
{
if (HotkeyPress != null)
{
HotkeyPress(id, key, modifier);
}
HotkeyPress?.Invoke(id, key, modifier);
}
private bool CheckRepeatLimitTime()

View file

@ -62,10 +62,7 @@ public Logger(string logFilePath)
protected void OnMessageAdded(string message)
{
if (MessageAdded != null)
{
MessageAdded(message);
}
MessageAdded?.Invoke(message);
}
private void ProcessMessageQueue()

View file

@ -121,8 +121,7 @@ public static string Parse(string input, Color color, Point position)
int[] a = new int[o.Item2.Length];
for (int i = o.Item2.Length - 1; i >= 0; --i)
{
int n = 0;
if (int.TryParse(o.Item2[i], out n))
if (int.TryParse(o.Item2[i], out int n))
{
a[i] = n;
}

View file

@ -358,8 +358,7 @@ public string Parse(string pattern)
int[] a = new int[o.Item2.Length];
for (int i = o.Item2.Length - 1; i >= 0; --i)
{
int n = 0;
if (int.TryParse(o.Item2[i], out n))
if (int.TryParse(o.Item2[i], out int n))
{
a[i] = n;
}

View file

@ -88,8 +88,7 @@ public static Process GetProcessByWindowHandle(IntPtr hwnd)
{
try
{
uint processID;
GetWindowThreadProcessId(hwnd, out processID);
GetWindowThreadProcessId(hwnd, out uint processID);
return Process.GetProcessById((int)processID);
}
catch (Exception e)
@ -128,9 +127,7 @@ public static IntPtr GetClassLongPtrSafe(IntPtr hWnd, int nIndex)
private static Icon GetSmallApplicationIcon(IntPtr handle)
{
IntPtr iconHandle;
SendMessageTimeout(handle, (int)WindowsMessages.GETICON, NativeConstants.ICON_SMALL2, 0, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out iconHandle);
SendMessageTimeout(handle, (int)WindowsMessages.GETICON, NativeConstants.ICON_SMALL2, 0, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out IntPtr iconHandle);
if (iconHandle == IntPtr.Zero)
{
@ -157,9 +154,7 @@ private static Icon GetSmallApplicationIcon(IntPtr handle)
private static Icon GetBigApplicationIcon(IntPtr handle)
{
IntPtr iconHandle;
SendMessageTimeout(handle, (int)WindowsMessages.GETICON, NativeConstants.ICON_BIG, 0, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out iconHandle);
SendMessageTimeout(handle, (int)WindowsMessages.GETICON, NativeConstants.ICON_BIG, 0, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out IntPtr iconHandle);
if (iconHandle == IntPtr.Zero)
{
@ -212,16 +207,14 @@ public static bool IsDWMEnabled()
public static bool GetExtendedFrameBounds(IntPtr handle, out Rectangle rectangle)
{
RECT rect;
int result = DwmGetWindowAttribute(handle, (int)DwmWindowAttribute.DWMWA_EXTENDED_FRAME_BOUNDS, out rect, Marshal.SizeOf(typeof(RECT)));
int result = DwmGetWindowAttribute(handle, (int)DwmWindowAttribute.DWMWA_EXTENDED_FRAME_BOUNDS, out RECT rect, Marshal.SizeOf(typeof(RECT)));
rectangle = rect;
return result == 0;
}
public static bool GetNCRenderingEnabled(IntPtr handle)
{
bool enabled;
int result = DwmGetWindowAttribute(handle, (int)DwmWindowAttribute.DWMWA_NCRENDERING_ENABLED, out enabled, sizeof(bool));
int result = DwmGetWindowAttribute(handle, (int)DwmWindowAttribute.DWMWA_NCRENDERING_ENABLED, out bool enabled, sizeof(bool));
return result == 0 && enabled;
}
@ -255,15 +248,13 @@ public static bool UseImmersiveDarkMode(IntPtr handle, bool enabled)
public static Rectangle GetWindowRect(IntPtr handle)
{
RECT rect;
GetWindowRect(handle, out rect);
GetWindowRect(handle, out RECT rect);
return rect;
}
public static Rectangle GetClientRect(IntPtr handle)
{
RECT rect;
GetClientRect(handle, out rect);
GetClientRect(handle, out RECT rect);
Point position = rect.Location;
ClientToScreen(handle, ref position);
return new Rectangle(position, rect.Size);
@ -271,9 +262,7 @@ public static Rectangle GetClientRect(IntPtr handle)
public static Rectangle MaximizedWindowFix(IntPtr handle, Rectangle windowRect)
{
Size size;
if (GetBorderSize(handle, out size))
if (GetBorderSize(handle, out Size size))
{
windowRect = new Rectangle(windowRect.X + size.Width, windowRect.Y + size.Height, windowRect.Width - (size.Width * 2), windowRect.Height - (size.Height * 2));
}
@ -369,8 +358,7 @@ public static bool IsWindowCloaked(IntPtr handle)
{
if (IsDWMEnabled())
{
int cloaked;
int result = DwmGetWindowAttribute(handle, (int)DwmWindowAttribute.DWMWA_CLOAKED, out cloaked, sizeof(int));
int result = DwmGetWindowAttribute(handle, (int)DwmWindowAttribute.DWMWA_CLOAKED, out int cloaked, sizeof(int));
return result == 0 && cloaked != 0;
}
@ -485,8 +473,7 @@ public static bool Is64Bit()
private static bool Is32BitProcessOn64BitProcessor()
{
bool retVal;
IsWow64Process(Process.GetCurrentProcess().Handle, out retVal);
IsWow64Process(Process.GetCurrentProcess().Handle, out bool retVal);
return retVal;
}

View file

@ -153,14 +153,14 @@ public bool Equals(RECT r)
public override bool Equals(object obj)
{
if (obj is RECT)
if (obj is RECT rect)
{
return Equals((RECT)obj);
return Equals(rect);
}
if (obj is Rectangle)
if (obj is Rectangle rectangle)
{
return Equals(new RECT((Rectangle)obj));
return Equals(new RECT(rectangle));
}
return false;

View file

@ -69,9 +69,7 @@ public static PingResult PingHost(string host, int timeout = 1000, int pingCount
private static IPAddress GetIpFromHost(string host)
{
IPAddress address;
if (!IPAddress.TryParse(host, out address))
if (!IPAddress.TryParse(host, out IPAddress address))
{
try
{

View file

@ -86,7 +86,7 @@ public void Unlock()
public override bool Equals(object obj)
{
return obj is UnsafeBitmap && Compare((UnsafeBitmap)obj, this);
return obj is UnsafeBitmap unsafeBitmap && Compare(unsafeBitmap, this);
}
public override int GetHashCode()

View file

@ -66,9 +66,8 @@ public Vector2(float x, float y)
public override bool Equals(object obj)
{
if (obj is Vector2)
if (obj is Vector2 v)
{
Vector2 v = (Vector2)obj;
return v.x == x && v.y == y;
}

View file

@ -64,9 +64,7 @@ protected override List<HistoryItem> Load(string filePath)
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "HistoryItem")
{
XElement element = XNode.ReadFrom(reader) as XElement;
if (element != null)
if (XNode.ReadFrom(reader) is XElement element)
{
HistoryItem hi = ParseHistoryItem(element);
historyItemList.Add(hi);

View file

@ -343,7 +343,7 @@ private void GeneratePreviewImage(int padding)
padding = 0;
}
size = size - (padding * 2);
size -= padding * 2;
if (PreviewImage != null) PreviewImage.Dispose();
PreviewImage = new Bitmap(size, size);
@ -392,11 +392,8 @@ private void tsmiEffectClick(object sender, EventArgs e)
if (preset != null)
{
ToolStripMenuItem tsmi = sender as ToolStripMenuItem;
if (tsmi != null && tsmi.Tag is Type)
if (sender is ToolStripMenuItem tsmi && tsmi.Tag is Type type)
{
Type type = (Type)tsmi.Tag;
ImageEffect imageEffect = (ImageEffect)Activator.CreateInstance(type);
AddEffect(imageEffect, preset);
UpdatePreview();
@ -500,9 +497,7 @@ private void ImageEffectsForm_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null && files.Any(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxie")))
if (e.Data.GetData(DataFormats.FileDrop, false) is string[] files && files.Any(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxie")))
{
e.Effect = DragDropEffects.Copy;
}
@ -519,16 +514,11 @@ private void ImageEffectsForm_DragEnter(object sender, DragEventArgs e)
private void ImageEffectsForm_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) && e.Data.GetData(DataFormats.FileDrop, false) is string[] files)
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null)
foreach (string filePath in files.Where(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxie")))
{
foreach (string filePath in files.Where(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxie")))
{
ImportImageEffectFile(filePath);
}
ImportImageEffectFile(filePath);
}
}
}
@ -589,8 +579,7 @@ private void lvPresets_SelectedIndexChanged(object sender, EventArgs e)
private void txtPresetName_TextChanged(object sender, EventArgs e)
{
ListViewItem lvi;
ImageEffectPreset preset = GetSelectedPreset(out lvi);
ImageEffectPreset preset = GetSelectedPreset(out ListViewItem lvi);
if (preset != null)
{
@ -619,9 +608,8 @@ private void btnEffectDuplicate_Click(object sender, EventArgs e)
{
ListViewItem lvi = lvEffects.SelectedItems[0];
if (lvi.Tag is ImageEffect)
if (lvi.Tag is ImageEffect imageEffect)
{
ImageEffect imageEffect = (ImageEffect)lvi.Tag;
ImageEffect imageEffectClone = imageEffect.Copy();
AddEffect(imageEffectClone, preset);
UpdatePreview();
@ -682,9 +670,8 @@ private void lvEffects_SelectedIndexChanged(object sender, EventArgs e)
private void lvEffects_ItemChecked(object sender, ItemCheckedEventArgs e)
{
if (e.Item != null && e.Item.Focused && e.Item.Tag is ImageEffect)
if (e.Item != null && e.Item.Focused && e.Item.Tag is ImageEffect imageEffect)
{
ImageEffect imageEffect = (ImageEffect)e.Item.Tag;
imageEffect.Enabled = e.Item.Checked;
UpdatePreview();
}
@ -825,23 +812,16 @@ private void pbResult_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null && files.Length > 0)
if (e.Data.GetData(DataFormats.FileDrop, false) is string[] files && files.Length > 0 && Helpers.IsImageFile(files[0]))
{
if (Helpers.IsImageFile(files[0]))
{
if (PreviewImage != null) PreviewImage.Dispose();
PreviewImage = ImageHelpers.LoadImage(files[0]);
UpdatePreview();
}
if (PreviewImage != null) PreviewImage.Dispose();
PreviewImage = ImageHelpers.LoadImage(files[0]);
UpdatePreview();
}
}
else if (e.Data.GetDataPresent(DataFormats.Bitmap, false))
{
Bitmap bmp = e.Data.GetData(DataFormats.Bitmap, false) as Bitmap;
if (bmp != null)
if (e.Data.GetData(DataFormats.Bitmap, false) is Bitmap bmp)
{
if (PreviewImage != null) PreviewImage.Dispose();
PreviewImage = bmp;

View file

@ -131,10 +131,7 @@ private void btnUpload_Click(object sender, EventArgs e)
protected void OnUploadRequested(string source)
{
if (UploadRequested != null)
{
UploadRequested(source);
}
UploadRequested?.Invoke(source);
}
private void btnSaveAs_Click(object sender, EventArgs e)

View file

@ -128,7 +128,7 @@ private string GetFolderNameRow(FolderInfo dir, int level)
folderNameRow = " " + HtmlHelper.Tag("span", folderNameRow, "", "class=\"FolderInfo\"");
}
string pathTitle = "";
string pathTitle;
if (settings.DisplayPath)
{

View file

@ -152,14 +152,9 @@ private void UpdateEncodeProgress(string data)
// Duration: 00:00:15.32, start: 0.000000, bitrate: 1095 kb/s
Match match = Regex.Match(data, @"Duration:\s*(\d+:\d+:\d+\.\d+),\s*start:", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
if (match.Success)
if (match.Success && TimeSpan.TryParse(match.Groups[1].Value, out TimeSpan duration))
{
TimeSpan duration;
if (TimeSpan.TryParse(match.Groups[1].Value, out duration))
{
VideoDuration = duration;
}
VideoDuration = duration;
}
}
else
@ -167,17 +162,12 @@ private void UpdateEncodeProgress(string data)
//frame= 942 fps=187 q=35.0 size= 3072kB time=00:00:38.10 bitrate= 660.5kbits/s speed=7.55x
Match match = Regex.Match(data, @"time=\s*(\d+:\d+:\d+\.\d+)\s*bitrate=", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
if (match.Success)
if (match.Success && TimeSpan.TryParse(match.Groups[1].Value, out TimeSpan time))
{
TimeSpan time;
EncodeTime = time;
EncodePercentage = ((float)EncodeTime.Ticks / VideoDuration.Ticks) * 100;
if (TimeSpan.TryParse(match.Groups[1].Value, out time))
{
EncodeTime = time;
EncodePercentage = ((float)EncodeTime.Ticks / VideoDuration.Ticks) * 100;
OnEncodeProgressChanged(EncodePercentage);
}
OnEncodeProgressChanged(EncodePercentage);
}
}
}

View file

@ -223,10 +223,7 @@ private void btnCombine_Click(object sender, EventArgs e)
protected void OnProcessRequested(Bitmap bmp)
{
if (ProcessRequested != null)
{
ProcessRequested(bmp);
}
ProcessRequested?.Invoke(bmp);
}
private void ImageCombinerForm_DragEnter(object sender, DragEventArgs e)
@ -243,16 +240,11 @@ private void ImageCombinerForm_DragEnter(object sender, DragEventArgs e)
private void ImageCombinerForm_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) && e.Data.GetData(DataFormats.FileDrop, false) is string[] files)
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null)
foreach (string file in files)
{
foreach (string file in files)
{
lvImages.Items.Add(file);
}
lvImages.Items.Add(file);
}
}
}

View file

@ -105,19 +105,14 @@ private void lvImages_DragEnter(object sender, DragEventArgs e)
private void lvImages_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) && e.Data.GetData(DataFormats.FileDrop, false) is string[] files)
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null)
foreach (string file in files)
{
foreach (string file in files)
{
AddFile(file);
}
UpdateEnabled();
AddFile(file);
}
UpdateEnabled();
}
}

View file

@ -98,10 +98,7 @@ private void Thumbnailer_ProgressChanged(int current, int length)
protected void OnThumbnailsTaken(List<VideoThumbnailInfo> thumbnails)
{
if (ThumbnailsTaken != null)
{
ThumbnailsTaken(thumbnails);
}
ThumbnailsTaken?.Invoke(thumbnails);
}
private void btnBrowse_Click(object sender, EventArgs e)

View file

@ -154,10 +154,7 @@ private List<VideoThumbnailInfo> Finish(List<VideoThumbnailInfo> tempThumbnails)
protected void OnProgressChanged(int current, int length)
{
if (ProgressChanged != null)
{
ProgressChanged(current, length);
}
ProgressChanged?.Invoke(current, length);
}
private string GetOutputDirectory()

View file

@ -606,9 +606,7 @@ private object eiFFmpeg_ExportRequested()
private async void eiFFmpeg_ImportRequested(object obj)
{
FFmpegOptions ffmpegOptions = obj as FFmpegOptions;
if (ffmpegOptions != null)
if (obj is FFmpegOptions ffmpegOptions)
{
string tempFFmpegPath = Options.FFmpeg.CLIPath;
Options.FFmpeg = ffmpegOptions;

View file

@ -144,10 +144,7 @@ private void ScreenRecordForm_FormClosed(object sender, FormClosedEventArgs e)
protected void OnStopRequested()
{
if (StopRequested != null)
{
StopRequested();
}
StopRequested?.Invoke();
}
public void StartCountdown(int milliseconds)

View file

@ -100,10 +100,7 @@ protected override void Dispose(bool disposing)
protected void OnImageProcessRequested(Bitmap bmp)
{
if (ImageProcessRequested != null)
{
ImageProcessRequested(bmp);
}
ImageProcessRequested?.Invoke(bmp);
}
private void btnSelectHandle_Click(object sender, EventArgs e)
@ -161,9 +158,7 @@ private void SelectRectangle()
{
Thread.Sleep(250);
Rectangle rect;
if (RegionCaptureTasks.GetRectangleRegion(out rect, RegionCaptureOptions))
if (RegionCaptureTasks.GetRectangleRegion(out Rectangle rect, RegionCaptureOptions))
{
selectedRectangle = rect;
lblSelectedRectangle.Text = selectedRectangle.ToString();

View file

@ -89,9 +89,7 @@ private void LoadImageFiles()
imageFiles = null;
ilvStickers.Items.Clear();
StickerPackInfo stickerPack = tscbStickers.SelectedItem as StickerPackInfo;
if (stickerPack != null && !string.IsNullOrEmpty(stickerPack.FolderPath))
if (tscbStickers.SelectedItem is StickerPackInfo stickerPack && !string.IsNullOrEmpty(stickerPack.FolderPath))
{
string folderPath = Helpers.GetAbsolutePath(stickerPack.FolderPath);

View file

@ -85,38 +85,26 @@ public virtual void OnDraw(Graphics g)
public virtual void OnMouseEnter()
{
if (MouseEnter != null)
{
MouseEnter();
}
MouseEnter?.Invoke();
}
public virtual void OnMouseLeave()
{
if (MouseLeave != null)
{
MouseLeave();
}
MouseLeave?.Invoke();
}
public virtual void OnMouseDown(Point position)
{
IsDragging = true;
if (MouseDown != null)
{
MouseDown(this, new MouseEventArgs(MouseButtons.Left, 1, position.X, position.Y, 0));
}
MouseDown?.Invoke(this, new MouseEventArgs(MouseButtons.Left, 1, position.X, position.Y, 0));
}
public virtual void OnMouseUp(Point position)
{
IsDragging = false;
if (MouseUp != null)
{
MouseUp(this, new MouseEventArgs(MouseButtons.Left, 1, position.X, position.Y, 0));
}
MouseUp?.Invoke(this, new MouseEventArgs(MouseButtons.Left, 1, position.X, position.Y, 0));
}
}
}

View file

@ -2095,26 +2095,17 @@ private bool PickColor(Color currentColor, out Color newColor)
private void OnCurrentShapeChanged(BaseShape shape)
{
if (CurrentShapeChanged != null)
{
CurrentShapeChanged(shape);
}
CurrentShapeChanged?.Invoke(shape);
}
private void OnCurrentShapeTypeChanged(ShapeType shapeType)
{
if (CurrentShapeTypeChanged != null)
{
CurrentShapeTypeChanged(shapeType);
}
CurrentShapeTypeChanged?.Invoke(shapeType);
}
private void OnShapeCreated(BaseShape shape)
{
if (ShapeCreated != null)
{
ShapeCreated(shape);
}
ShapeCreated?.Invoke(shape);
}
public void Dispose()

View file

@ -57,10 +57,7 @@ public AccountTypeControl()
private void cbAccountType_SelectedIndexChanged(object sender, EventArgs e)
{
if (AccountTypeChanged != null)
{
AccountTypeChanged(SelectedAccountType);
}
AccountTypeChanged?.Invoke(SelectedAccountType);
}
}
}

View file

@ -117,10 +117,7 @@ public OAuthControl()
private void btnOpenAuthorizePage_Click(object sender, EventArgs e)
{
if (OpenButtonClicked != null)
{
OpenButtonClicked();
}
OpenButtonClicked?.Invoke();
}
private void txtVerificationCode_TextChanged(object sender, EventArgs e)
@ -140,10 +137,7 @@ private void btnCompleteAuthorization_Click(object sender, EventArgs e)
private void btnRefreshAuthorization_Click(object sender, EventArgs e)
{
if (RefreshButtonClicked != null)
{
RefreshButtonClicked();
}
RefreshButtonClicked?.Invoke();
}
private void btnClearAuthorization_Click(object sender, EventArgs e)
@ -151,10 +145,7 @@ private void btnClearAuthorization_Click(object sender, EventArgs e)
UserInfo = null;
Status = OAuthLoginStatus.LoginRequired;
if (ClearButtonClicked != null)
{
ClearButtonClicked();
}
ClearButtonClicked?.Invoke();
}
private void UpdateStatusLabel()

View file

@ -194,7 +194,7 @@ public BoxFileInfo GetFiles(string id)
public string CreateSharedLink(string id, BoxShareAccessLevel accessLevel)
{
string response = SendRequest(HttpMethod.PUT, "https://api.box.com/2.0/files/" + id, "{\"shared_link\": {\"access\": \"" + accessLevel.ToString().ToLower() +"\"}}", headers: GetAuthHeaders());
string response = SendRequest(HttpMethod.PUT, "https://api.box.com/2.0/files/" + id, "{\"shared_link\": {\"access\": \"" + accessLevel.ToString().ToLower() + "\"}}", headers: GetAuthHeaders());
if (!string.IsNullOrEmpty(response))
{

View file

@ -160,7 +160,7 @@ private void SetPermissions(string fileID, GoogleDrivePermissionRole role, Googl
allowFileDiscovery = allowFileDiscovery.ToString()
});
string response = SendRequest(HttpMethod.POST, url, json, RequestHelpers.ContentTypeJSON, null, GoogleAuth.GetAuthHeaders());
SendRequest(HttpMethod.POST, url, json, RequestHelpers.ContentTypeJSON, null, GoogleAuth.GetAuthHeaders());
}
public List<GoogleDriveFile> GetFolders(string driveID = "", bool trashed = false, bool writer = true)

View file

@ -89,8 +89,11 @@ public override UploadResult Upload(Stream stream, string fileName)
AllowReportProgress = true;
string key = SimpleUpload(stream, fileName);
AllowReportProgress = false;
string url = null;
while ((url = PollUpload(key, fileName)) == null) Thread.Sleep(pollInterval);
string url;
while ((url = PollUpload(key, fileName)) == null)
{
Thread.Sleep(pollInterval);
}
return new UploadResult() { IsSuccess = true, URL = url };
}

View file

@ -229,9 +229,9 @@ public override UploadResult Upload(Stream stream, string fileName)
{
if (!CheckAuthorization()) return null;
UploadResult result;
string sessionUrl = CreateSession(fileName);
long position = 0;
UploadResult result = new UploadResult();
do
{

View file

@ -42,10 +42,7 @@ public class PlikFileUploaderService : FileUploaderService
public override GenericUploader CreateUploader(UploadersConfig config, TaskReferenceHelper taskInfo)
{
return new Plik(config.PlikSettings)
{
Settings = config.PlikSettings
};
return new Plik(config.PlikSettings);
}
public override bool CheckConfig(UploadersConfig config)
@ -60,10 +57,11 @@ public override bool CheckConfig(UploadersConfig config)
public sealed class Plik : FileUploader
{
public PlikSettings Settings { get; set; }
public PlikSettings Settings { get; private set; }
public Plik(PlikSettings s)
public Plik(PlikSettings settings)
{
Settings = settings;
}
public override UploadResult Upload(Stream stream, string fileName)
@ -125,7 +123,7 @@ internal static void CalculateTTLValue(NumericUpDown ttlElement, int newUnit, in
{
ttlElement.Value = 1;
}
ttlElement.Value = ttlElement.Value * GetMultiplyIndex(newUnit, oldUnit);
ttlElement.Value *= GetMultiplyIndex(newUnit, oldUnit);
ttlElement.ReadOnly = false;
}
else

View file

@ -90,14 +90,9 @@ public string Login(string email, string password)
{
string[] values = response.Split(',');
if (values.Length > 1)
if (values.Length > 1 && int.TryParse(values[0], out int status) && status >= 0)
{
int status;
if (int.TryParse(values[0], out status) && status >= 0)
{
return values[1];
}
return values[1];
}
}
@ -121,9 +116,7 @@ public bool DeleteFile(string id)
if (lines.Length > 0)
{
int status;
return int.TryParse(lines[0], out status) && status >= 0;
return int.TryParse(lines[0], out int status) && status >= 0;
}
}
@ -146,9 +139,7 @@ public override UploadResult Upload(Stream stream, string fileName)
if (values.Length > 0)
{
int status;
if (!int.TryParse(values[0], out status))
if (!int.TryParse(values[0], out int status))
{
status = -2;
}

View file

@ -92,7 +92,7 @@ public Seafile(string apiurl, string authtoken, string repoid)
public string GetAuthToken(string username, string password)
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "auth-token/?format=json");
url = URLHelpers.CombineURL(url, "auth-token/?format=json");
Dictionary<string, string> args = new Dictionary<string, string>
{
@ -119,7 +119,7 @@ public string GetAuthToken(string username, string password)
public bool CheckAPIURL()
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "ping/?format=json");
url = URLHelpers.CombineURL(url, "ping/?format=json");
SSLBypassHelper sslBypassHelper = null;
@ -154,7 +154,7 @@ public bool CheckAPIURL()
public bool CheckAuthToken()
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "auth/ping/?format=json");
url = URLHelpers.CombineURL(url, "auth/ping/?format=json");
NameValueCollection headers = new NameValueCollection();
headers.Add("Authorization", "Token " + AuthToken);
@ -196,7 +196,7 @@ public bool CheckAuthToken()
public SeafileCheckAccInfoResponse GetAccountInfo()
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "account/info/?format=json");
url = URLHelpers.CombineURL(url, "account/info/?format=json");
NameValueCollection headers = new NameValueCollection();
headers.Add("Authorization", "Token " + AuthToken);
@ -237,10 +237,10 @@ public SeafileCheckAccInfoResponse GetAccountInfo()
public string GetOrMakeDefaultLibrary(string authtoken = null)
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "default-repo/?format=json");
url = URLHelpers.CombineURL(url, "default-repo/?format=json");
NameValueCollection headers = new NameValueCollection();
headers.Add("Authorization", "Token " + (authtoken == null ? AuthToken : authtoken));
headers.Add("Authorization", "Token " + (authtoken ?? AuthToken));
SSLBypassHelper sslBypassHelper = null;
@ -274,7 +274,7 @@ public string GetOrMakeDefaultLibrary(string authtoken = null)
public List<SeafileLibraryObj> GetLibraries()
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "repos/?format=json");
url = URLHelpers.CombineURL(url, "repos/?format=json");
NameValueCollection headers = new NameValueCollection();
headers.Add("Authorization", "Token " + AuthToken);
@ -311,7 +311,7 @@ public List<SeafileLibraryObj> GetLibraries()
public bool ValidatePath(string path)
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "repos/" + RepoID + "/dir/?p=" + path + "&format=json");
url = URLHelpers.CombineURL(url, "repos/" + RepoID + "/dir/?p=" + path + "&format=json");
NameValueCollection headers = new NameValueCollection();
headers.Add("Authorization", "Token " + AuthToken);
@ -350,7 +350,7 @@ public bool ValidatePath(string path)
public bool DecryptLibrary(string libraryPassword)
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "repos/" + RepoID + "/?format=json");
url = URLHelpers.CombineURL(url, "repos/" + RepoID + "/?format=json");
NameValueCollection headers = new NameValueCollection();
headers.Add("Authorization", "Token " + AuthToken);
@ -422,7 +422,7 @@ public override UploadResult Upload(Stream stream, string fileName)
}
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "repos/" + RepoID + "/upload-link/?format=json");
url = URLHelpers.CombineURL(url, "repos/" + RepoID + "/upload-link/?format=json");
NameValueCollection headers = new NameValueCollection();
headers.Add("Authorization", "Token " + AuthToken);
@ -482,7 +482,7 @@ public override UploadResult Upload(Stream stream, string fileName)
public string ShareFile(string path)
{
string url = URLHelpers.FixPrefix(APIURL);
url = URLHelpers.CombineURL(APIURL, "repos", RepoID, "file/shared-link/");
url = URLHelpers.CombineURL(url, "repos", RepoID, "file/shared-link/");
Dictionary<string, string> args = new Dictionary<string, string>();
args.Add("p", path);

View file

@ -548,7 +548,6 @@ private void DoWork(CancellationToken ct)
{
Thread.Sleep(1000);
ProgressInfo progressInfo = new ProgressInfo();
int progress, elapsed;
DateTime time;
while (!ct.IsCancellationRequested)
{
@ -561,7 +560,7 @@ private void DoWork(CancellationToken ct)
if (progressInfo.Status != "fail" && !string.IsNullOrEmpty(progressInfo.Meter))
{
if (int.TryParse(progressInfo.Meter, out progress))
if (int.TryParse(progressInfo.Meter, out int progress))
{
//sendSpace.OnProgressChanged(0, 0);
}
@ -570,7 +569,7 @@ private void DoWork(CancellationToken ct)
catch
{
}
elapsed = (int)(DateTime.Now - time).TotalMilliseconds;
int elapsed = (int)(DateTime.Now - time).TotalMilliseconds;
if (elapsed < interval)
{
Thread.Sleep(interval - elapsed);

View file

@ -23,6 +23,8 @@
#endregion License Information (GPL v3)
using Newtonsoft.Json;
using ShareX.HelpersLib;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
@ -30,8 +32,6 @@
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using ShareX.HelpersLib;
using Newtonsoft.Json;
namespace ShareX.UploadersLib.FileUploaders
{
@ -124,9 +124,9 @@ public override UploadResult Upload(Stream stream, string fileName)
byte[] encryptedBytes = EncryptBytes(cryptoData, plainBytes);
int prependSize = 0;
if(dumpStash.Count > 0)
if (dumpStash.Count > 0)
{
using(MemoryStream ms = new MemoryStream())
using (MemoryStream ms = new MemoryStream())
{
ms.Write(dumpStash.ToArray(), 0, dumpStash.Count);
ms.Write(encryptedBytes, 0, encryptedBytes.Length);
@ -137,7 +137,7 @@ public override UploadResult Upload(Stream stream, string fileName)
dumpStash.Clear();
}
if(encryptedBytes.Length + (i == 0 ? 16 : 0) > BYTE_CHUNK_SIZE) // 16 bytes for the salt header
if (encryptedBytes.Length + (i == 0 ? 16 : 0) > BYTE_CHUNK_SIZE) // 16 bytes for the salt header
{
dumpStash.AddRange(encryptedBytes.Skip(BYTE_CHUNK_SIZE - (i == 0 ? 16 : 0)));
encryptedBytes = encryptedBytes.Take(BYTE_CHUNK_SIZE - (i == 0 ? 16 : 0)).ToArray();

View file

@ -798,9 +798,7 @@ private void CustomUploaderSettingsForm_DragEnter(object sender, DragEventArgs e
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null && files.Any(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxcu")))
if (e.Data.GetData(DataFormats.FileDrop, false) is string[] files && files.Any(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxcu")))
{
e.Effect = DragDropEffects.Copy;
}
@ -817,25 +815,20 @@ private void CustomUploaderSettingsForm_DragEnter(object sender, DragEventArgs e
private void CustomUploaderSettingsForm_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) && e.Data.GetData(DataFormats.FileDrop, false) is string[] files)
{
string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
if (files != null)
foreach (string filePath in files.Where(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxcu")))
{
foreach (string filePath in files.Where(x => !string.IsNullOrEmpty(x) && x.EndsWith(".sxcu")))
CustomUploaderItem cui = JsonHelpers.DeserializeFromFile<CustomUploaderItem>(filePath);
if (cui != null)
{
CustomUploaderItem cui = JsonHelpers.DeserializeFromFile<CustomUploaderItem>(filePath);
if (cui != null)
{
cui.CheckBackwardCompatibility();
CustomUploaderAdd(cui);
}
cui.CheckBackwardCompatibility();
CustomUploaderAdd(cui);
}
eiCustomUploaders_ImportCompleted();
}
eiCustomUploaders_ImportCompleted();
}
}

View file

@ -54,12 +54,8 @@ public JiraUpload()
public JiraUpload(string issuePrefix, GetSummaryHandler getSummary) : this()
{
if (getSummary == null)
{
throw new ArgumentNullException(nameof(getSummary));
}
this.issuePrefix = issuePrefix;
this.getSummary = getSummary;
this.getSummary = getSummary ?? throw new ArgumentNullException(nameof(getSummary));
}
private void JiraUpload_Load(object sender, EventArgs e)

View file

@ -923,9 +923,9 @@ private void lvImgurAlbumList_SelectedIndexChanged(object sender, EventArgs e)
if (lvImgurAlbumList.SelectedItems.Count > 0)
{
ListViewItem lvi = lvImgurAlbumList.SelectedItems[0];
if (lvi.Tag is ImgurAlbumData)
if (lvi.Tag is ImgurAlbumData albumData)
{
Config.ImgurSelectedAlbum = (ImgurAlbumData)lvi.Tag;
Config.ImgurSelectedAlbum = albumData;
}
}
else
@ -1118,9 +1118,8 @@ private void lvPicasaAlbumList_SelectedIndexChanged(object sender, EventArgs e)
if (lvPicasaAlbumList.SelectedItems.Count > 0)
{
ListViewItem lvi = lvPicasaAlbumList.SelectedItems[0];
if (lvi.Tag is GooglePhotosAlbumInfo)
if (lvi.Tag is GooglePhotosAlbumInfo album)
{
GooglePhotosAlbumInfo album = (GooglePhotosAlbumInfo)lvi.Tag;
txtPicasaAlbumID.Text = album.ID;
}
}
@ -1710,8 +1709,7 @@ private void cbOneDriveCreateShareableLink_CheckedChanged(object sender, EventAr
private void tvOneDrive_AfterSelect(object sender, TreeViewEventArgs e)
{
OneDriveFileInfo file = e.Node.Tag as OneDriveFileInfo;
if (file != null)
if (e.Node.Tag is OneDriveFileInfo file)
{
lblOneDriveFolderID.Text = Resources.UploadersConfigForm_LoadSettings_Selected_folder_ + " " + file.name;
Config.OneDriveV2SelectedFolder = file;
@ -1720,8 +1718,7 @@ private void tvOneDrive_AfterSelect(object sender, TreeViewEventArgs e)
private void tvOneDrive_AfterExpand(object sender, TreeViewEventArgs e)
{
OneDriveFileInfo file = e.Node.Tag as OneDriveFileInfo;
if (file != null)
if (e.Node.Tag is OneDriveFileInfo file)
{
OneDriveListFolders(file, e.Node);
}
@ -1784,8 +1781,7 @@ private void lvGoogleDriveFoldersList_SelectedIndexChanged(object sender, EventA
if (lvGoogleDriveFoldersList.SelectedItems.Count > 0)
{
ListViewItem lvi = lvGoogleDriveFoldersList.SelectedItems[0];
GoogleDriveFile folder = lvi.Tag as GoogleDriveFile;
if (folder != null)
if (lvi.Tag is GoogleDriveFile folder)
{
txtGoogleDriveFolderID.Text = folder.id;
}
@ -1905,8 +1901,7 @@ private void lvBoxFolders_SelectedIndexChanged(object sender, EventArgs e)
if (lvBoxFolders.SelectedItems.Count > 0)
{
ListViewItem lvi = lvBoxFolders.SelectedItems[0];
BoxFileEntry file = lvi.Tag as BoxFileEntry;
if (file != null)
if (lvi.Tag is BoxFileEntry file)
{
lblBoxFolderID.Text = Resources.UploadersConfigForm_LoadSettings_Selected_folder_ + " " + file.name;
Config.BoxSelectedFolder = file;
@ -1919,8 +1914,7 @@ private void lvBoxFolders_MouseDoubleClick(object sender, MouseEventArgs e)
if (e.Button == MouseButtons.Left && lvBoxFolders.SelectedItems.Count > 0)
{
ListViewItem lvi = lvBoxFolders.SelectedItems[0];
BoxFileEntry file = lvi.Tag as BoxFileEntry;
if (file != null)
if (lvi.Tag is BoxFileEntry file)
{
lvBoxFolders.Items.Clear();
BoxListFolders(file);
@ -2148,8 +2142,7 @@ private void btnMegaLogin_Click(object sender, EventArgs e)
private void cbMegaFolder_SelectedIndexChanged(object sender, EventArgs e)
{
Mega.DisplayNode selectedNode = ((ComboBox)sender).SelectedItem as Mega.DisplayNode;
if (selectedNode != null)
if (((ComboBox)sender).SelectedItem is Mega.DisplayNode selectedNode)
{
Config.MegaParentNodeId = selectedNode == Mega.DisplayNode.EmptyNode ? null : selectedNode.Node.Id;
}
@ -2186,9 +2179,7 @@ private void txtAmazonS3SecretKey_TextChanged(object sender, EventArgs e)
private void cbAmazonS3Endpoints_SelectedIndexChanged(object sender, EventArgs e)
{
AmazonS3Endpoint endpoint = cbAmazonS3Endpoints.SelectedItem as AmazonS3Endpoint;
if (endpoint != null)
if (cbAmazonS3Endpoints.SelectedItem is AmazonS3Endpoint endpoint)
{
txtAmazonS3Region.Text = endpoint.Region;
txtAmazonS3Endpoint.Text = endpoint.Endpoint;
@ -2456,14 +2447,9 @@ private void txtLambdaApiKey_TextChanged(object sender, EventArgs e)
private void cbLambdaUploadURL_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbLambdaUploadURL.SelectedIndex > -1)
if (cbLambdaUploadURL.SelectedIndex > -1 && cbLambdaUploadURL.SelectedItem is string url)
{
string url = cbLambdaUploadURL.SelectedItem as string;
if (url != null)
{
Config.LambdaSettings.UploadURL = url;
}
Config.LambdaSettings.UploadURL = url;
}
}

View file

@ -41,9 +41,7 @@ public static string GetMimeType(string ext)
ext = ext.Substring(1);
}
string mime;
if (Mappings.TryGetValue(ext, out mime))
if (Mappings.TryGetValue(ext, out string mime))
{
return mime;
}

View file

@ -117,7 +117,7 @@ public override UploadResult Upload(Stream stream, string fileName)
if (!string.IsNullOrEmpty(Settings.ContentType)) args.Add("content_type", Settings.ContentType);
if (!string.IsNullOrEmpty(Settings.Hidden)) args.Add("hidden", Settings.Hidden);
string query = OAuthManager.GenerateQuery(url, args, HttpMethod.POST, AuthInfo, out Dictionary<string, string> parameters);
OAuthManager.GenerateQuery(url, args, HttpMethod.POST, AuthInfo, out Dictionary<string, string> parameters);
UploadResult result = SendRequestFile(url, stream, fileName, "photo", parameters);

View file

@ -140,7 +140,7 @@ private UploadResult ParseResult(UploadResult result)
string userid = xele.GetElementValue("userid");
string mediaid = xele.GetElementValue("mediaid");
string mediaurl = xele.GetElementValue("mediaurl");
if (Options.ShowFull) mediaurl = mediaurl + "/full";
if (Options.ShowFull) mediaurl += "/full";
result.URL = mediaurl;
result.ThumbnailURL = mediaurl + ".th.jpg";
break;

View file

@ -237,9 +237,7 @@ private static string GenerateNonce()
private static string NormalizeUrl(string url)
{
Uri uri;
if (Uri.TryCreate(url, UriKind.Absolute, out uri))
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
string port = "";

View file

@ -24,6 +24,7 @@
#endregion License Information (GPL v3)
using System;
using System.Diagnostics.Contracts;
namespace ShareX.UploadersLib
{
@ -33,29 +34,18 @@ public static bool Validate<T>(int index, UploadersConfig config)
{
Enum destination = (Enum)Enum.ToObject(typeof(T), index);
if (destination is ImageDestination)
switch (destination)
{
return Validate((ImageDestination)destination, config);
}
if (destination is TextDestination)
{
return Validate((TextDestination)destination, config);
}
if (destination is FileDestination)
{
return Validate((FileDestination)destination, config);
}
if (destination is UrlShortenerType)
{
return Validate((UrlShortenerType)destination, config);
}
if (destination is URLSharingServices)
{
return Validate((URLSharingServices)destination, config);
case ImageDestination imageDestination:
return Validate(imageDestination, config);
case TextDestination textDestination:
return Validate(textDestination, config);
case FileDestination fileDestination:
return Validate(fileDestination, config);
case UrlShortenerType urlShortenerType:
return Validate(urlShortenerType, config);
case URLSharingServices urlSharingServices:
return Validate(urlSharingServices, config);
}
return true;

View file

@ -81,11 +81,11 @@ public void Init(TaskInfo info)
{
if (info.TaskSettings.TextDestination != TextDestination.FileUploader)
{
x.Checked = x.Tag is TextDestination && (TextDestination)x.Tag == info.TaskSettings.TextDestination;
x.Checked = x.Tag is TextDestination textDestination && textDestination == info.TaskSettings.TextDestination;
}
else
{
x.Checked = x.Tag is FileDestination && (FileDestination)x.Tag == info.TaskSettings.TextFileDestination;
x.Checked = x.Tag is FileDestination fileDestination && fileDestination == info.TaskSettings.TextFileDestination;
}
});
break;
@ -104,7 +104,7 @@ public void Init(TaskInfo info)
flp.Controls.OfType<RadioButton>().ForEach(x =>
{
x.Checked = x.Tag is FileDestination && (FileDestination)x.Tag == info.TaskSettings.FileDestination;
x.Checked = x.Tag is FileDestination fileDestination && fileDestination == info.TaskSettings.FileDestination;
});
break;
case EDataType.URL:
@ -122,7 +122,7 @@ public void Init(TaskInfo info)
flp.Controls.OfType<RadioButton>().ForEach(x =>
{
x.Checked = x.Tag is UrlShortenerType && (UrlShortenerType)x.Tag == info.TaskSettings.URLShortenerDestination;
x.Checked = x.Tag is UrlShortenerType urlShortenerType && urlShortenerType == info.TaskSettings.URLShortenerDestination;
});
break;
@ -164,11 +164,11 @@ public void InitCapture(TaskSettings taskSettings)
{
if (taskSettings.ImageDestination != ImageDestination.FileUploader)
{
x.Checked = x.Tag is ImageDestination && (ImageDestination)x.Tag == taskSettings.ImageDestination;
x.Checked = x.Tag is ImageDestination imageDestination && imageDestination == taskSettings.ImageDestination;
}
else
{
x.Checked = x.Tag is FileDestination && (FileDestination)x.Tag == taskSettings.ImageFileDestination;
x.Checked = x.Tag is FileDestination fileDestination && fileDestination == taskSettings.ImageFileDestination;
}
});
}
@ -211,39 +211,39 @@ private void SetDestinations(bool isActive, EDataType dataType, object destinati
switch (dataType)
{
case EDataType.Image:
if (destination is ImageDestination)
if (destination is ImageDestination imageDestination)
{
taskSettings.ImageDestination = (ImageDestination)destination;
taskSettings.ImageDestination = imageDestination;
}
else if (destination is FileDestination)
else if (destination is FileDestination imageFileDestination)
{
taskSettings.ImageDestination = ImageDestination.FileUploader;
taskSettings.ImageFileDestination = (FileDestination)destination;
taskSettings.ImageFileDestination = imageFileDestination;
}
break;
case EDataType.Text:
if (destination is TextDestination)
if (destination is TextDestination textDestination)
{
taskSettings.TextDestination = (TextDestination)destination;
taskSettings.TextDestination = textDestination;
}
else if (destination is FileDestination)
else if (destination is FileDestination textFileDestination)
{
taskSettings.TextDestination = TextDestination.FileUploader;
taskSettings.TextFileDestination = (FileDestination)destination;
taskSettings.TextFileDestination = textFileDestination;
}
break;
case EDataType.File:
if (destination is FileDestination)
if (destination is FileDestination fileDestination)
{
taskSettings.ImageDestination = ImageDestination.FileUploader;
taskSettings.TextDestination = TextDestination.FileUploader;
taskSettings.ImageFileDestination = taskSettings.TextFileDestination = taskSettings.FileDestination = (FileDestination)destination;
taskSettings.ImageFileDestination = taskSettings.TextFileDestination = taskSettings.FileDestination = fileDestination;
}
break;
case EDataType.URL:
if (destination is UrlShortenerType)
if (destination is UrlShortenerType urlShortenerDestination)
{
taskSettings.URLShortenerDestination = (UrlShortenerType)destination;
taskSettings.URLShortenerDestination = urlShortenerDestination;
}
break;
}

View file

@ -281,26 +281,17 @@ private void StopEditing()
protected void OnHotkeyChanged()
{
if (HotkeyChanged != null)
{
HotkeyChanged(this, EventArgs.Empty);
}
HotkeyChanged?.Invoke(this, EventArgs.Empty);
}
protected void OnSelectedChanged()
{
if (SelectedChanged != null)
{
SelectedChanged(this, EventArgs.Empty);
}
SelectedChanged?.Invoke(this, EventArgs.Empty);
}
protected void OnEditRequested()
{
if (EditRequested != null)
{
EditRequested(this, EventArgs.Empty);
}
EditRequested?.Invoke(this, EventArgs.Empty);
}
private void btnEdit_Click(object sender, EventArgs e)

View file

@ -106,10 +106,7 @@ public void Start()
protected void OnNewsLoaded()
{
if (NewsLoaded != null)
{
NewsLoaded(this, EventArgs.Empty);
}
NewsLoaded?.Invoke(this, EventArgs.Empty);
}
public void MarkRead()
@ -167,8 +164,7 @@ private void UpdateUnreadStatus()
{
foreach (DataGridViewRow row in dgvNews.Rows)
{
NewsItem newsItem = row.Tag as NewsItem;
if (newsItem != null && newsItem.IsUnread)
if (row.Tag is NewsItem newsItem && newsItem.IsUnread)
{
row.Cells[0].Style.BackColor = row.Cells[0].Style.SelectionBackColor = Color.LimeGreen;
}
@ -184,8 +180,7 @@ private void dgvNews_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
if (e.ColumnIndex == 2)
{
DataGridViewRow row = dgvNews.Rows[e.RowIndex];
NewsItem newsItem = row.Tag as NewsItem;
if (newsItem != null && !string.IsNullOrEmpty(newsItem.URL))
if (row.Tag is NewsItem newsItem && !string.IsNullOrEmpty(newsItem.URL))
{
dgvNews.Cursor = Cursors.Hand;
row.Cells[e.ColumnIndex].Style.ForeColor = row.Cells[e.ColumnIndex].Style.SelectionForeColor =
@ -199,8 +194,7 @@ private void dgvNews_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
if (e.ColumnIndex == 2)
{
DataGridViewRow row = dgvNews.Rows[e.RowIndex];
NewsItem newsItem = row.Tag as NewsItem;
if (newsItem != null && !string.IsNullOrEmpty(newsItem.URL))
if (row.Tag is NewsItem newsItem && !string.IsNullOrEmpty(newsItem.URL))
{
row.Cells[e.ColumnIndex].Style.ForeColor = row.Cells[e.ColumnIndex].Style.SelectionForeColor =
ShareXResources.UseCustomTheme ? ShareXResources.Theme.TextColor : SystemColors.ControlText;
@ -215,8 +209,7 @@ private void dgvNews_CellMouseClick(object sender, DataGridViewCellMouseEventArg
if (e.Button == MouseButtons.Left && e.ColumnIndex == 2)
{
DataGridViewRow row = dgvNews.Rows[e.RowIndex];
NewsItem newsItem = row.Tag as NewsItem;
if (newsItem != null && URLHelpers.IsValidURL(newsItem.URL))
if (row.Tag is NewsItem newsItem && URLHelpers.IsValidURL(newsItem.URL))
{
URLHelpers.OpenURL(newsItem.URL);
}

View file

@ -307,7 +307,7 @@ private void UpdateToolbar(List<HotkeyType> actions)
tsMain.Items.Add(tslTitle);
foreach (HotkeyType action in Program.Settings.ActionsToolbarList)
foreach (HotkeyType action in actions)
{
if (action == HotkeyType.None)
{

View file

@ -146,7 +146,7 @@ private void btnCopyLink_Click(object sender, EventArgs e)
{
if (lvClipboardFormats.Items.Count > 0)
{
string url = null;
string url;
if (lvClipboardFormats.SelectedItems.Count == 0)
{

View file

@ -124,9 +124,7 @@ private void TakeScreenshot()
private void SelectRegion()
{
Rectangle rect;
if (RegionCaptureTasks.GetRectangleRegion(out rect, TaskSettings.CaptureSettings.SurfaceOptions))
if (RegionCaptureTasks.GetRectangleRegion(out Rectangle rect, TaskSettings.CaptureSettings.SurfaceOptions))
{
Program.Settings.AutoCaptureRegion = rect;
UpdateRegion();

View file

@ -1639,8 +1639,7 @@ private async void tsddbCapture_DropDownOpening(object sender, EventArgs e)
private void tsmiWindowItems_Click(object sender, EventArgs e)
{
ToolStripItem tsi = (ToolStripItem)sender;
WindowInfo wi = tsi.Tag as WindowInfo;
if (wi != null)
if (tsi.Tag is WindowInfo wi)
{
new CaptureWindow(wi.Handle).Capture(true);
}
@ -2092,9 +2091,7 @@ private void timerTraySingleClick_Tick(object sender, EventArgs e)
private void niTray_BalloonTipClicked(object sender, EventArgs e)
{
BalloonTipAction action = niTray.Tag as BalloonTipAction;
if (action != null)
if (niTray.Tag is BalloonTipAction action)
{
switch (action.ClickAction)
{
@ -2130,8 +2127,7 @@ private async void tsmiCapture_DropDownOpening(object sender, EventArgs e)
private void tsmiTrayWindowItems_Click(object sender, EventArgs e)
{
ToolStripItem tsi = (ToolStripItem)sender;
WindowInfo wi = tsi.Tag as WindowInfo;
if (wi != null)
if (tsi.Tag is WindowInfo wi)
{
new CaptureWindow(wi.Handle).Capture();
}

View file

@ -1042,9 +1042,7 @@ private void nudScreenRegionHeight_ValueChanged(object sender, EventArgs e)
private void btnCaptureCustomRegionSelectRectangle_Click(object sender, EventArgs e)
{
Rectangle rect;
if (RegionCaptureTasks.GetRectangleRegion(out rect, TaskSettings.CaptureSettings.SurfaceOptions))
if (RegionCaptureTasks.GetRectangleRegion(out Rectangle rect, TaskSettings.CaptureSettings.SurfaceOptions))
{
nudCaptureCustomRegionX.SetValue(rect.X);
nudCaptureCustomRegionY.SetValue(rect.Y);
@ -1374,9 +1372,7 @@ private void cbNameFormatCustomTimeZone_CheckedChanged(object sender, EventArgs
private void cbNameFormatTimeZone_SelectedIndexChanged(object sender, EventArgs e)
{
TimeZoneInfo timeZoneInfo = cbNameFormatTimeZone.SelectedItem as TimeZoneInfo;
if (timeZoneInfo != null)
if (cbNameFormatTimeZone.SelectedItem is TimeZoneInfo timeZoneInfo)
{
TaskSettings.UploadSettings.CustomTimeZone = timeZoneInfo;
}
@ -1428,9 +1424,7 @@ private void cbClipboardUploadAutoIndexFolder_CheckedChanged(object sender, Even
private UploaderFilter GetUploaderFilterFromFields()
{
IGenericUploaderService service = cbUploaderFiltersDestination.SelectedItem as IGenericUploaderService;
if (service != null)
if (cbUploaderFiltersDestination.SelectedItem is IGenericUploaderService service)
{
UploaderFilter filter = new UploaderFilter();
filter.Uploader = service.ServiceIdentifier;
@ -1462,9 +1456,8 @@ private void UpdateUploaderFilterFields(UploaderFilter filter)
for (int i = 0; i < cbUploaderFiltersDestination.Items.Count; i++)
{
IGenericUploaderService service = cbUploaderFiltersDestination.Items[i] as IGenericUploaderService;
if (service != null && service.ServiceIdentifier.Equals(filter.Uploader, StringComparison.InvariantCultureIgnoreCase))
if (cbUploaderFiltersDestination.Items[i] is IGenericUploaderService service &&
service.ServiceIdentifier.Equals(filter.Uploader, StringComparison.InvariantCultureIgnoreCase))
{
cbUploaderFiltersDestination.SelectedIndex = i;
break;

View file

@ -85,10 +85,7 @@ private void hotkeyForm_HotkeyPress(ushort id, Keys key, Modifiers modifier)
protected void OnHotkeyTrigger(HotkeySettings hotkeySetting)
{
if (HotkeyTrigger != null)
{
HotkeyTrigger(hotkeySetting);
}
HotkeyTrigger?.Invoke(hotkeySetting);
}
public void RegisterHotkey(HotkeySettings hotkeySetting)
@ -173,10 +170,7 @@ public void ToggleHotkeys(bool hotkeysDisabled)
UnregisterAllHotkeys(false, true);
}
if (HotkeysToggledTrigger != null)
{
HotkeysToggledTrigger(hotkeysDisabled);
}
HotkeysToggledTrigger?.Invoke(hotkeysDisabled);
}
public void ShowFailedHotkeys()

View file

@ -216,9 +216,9 @@ public static string GetCultureName(SupportedLanguage language)
private static void ApplyResourceToControl(Control control, ComponentResourceManager resource, CultureInfo culture)
{
if (control is ToolStrip)
if (control is ToolStrip ts)
{
ApplyResourceToToolStripItemCollection(((ToolStrip)control).Items, resource, culture);
ApplyResourceToToolStripItemCollection(ts.Items, resource, culture);
}
else
{
@ -235,9 +235,9 @@ private static void ApplyResourceToToolStripItemCollection(ToolStripItemCollecti
{
foreach (ToolStripItem item in collection)
{
if (item is ToolStripDropDownItem)
if (item is ToolStripDropDownItem tsddi)
{
ApplyResourceToToolStripItemCollection(((ToolStripDropDownItem)item).DropDownItems, resource, culture);
ApplyResourceToToolStripItemCollection(tsddi.DropDownItems, resource, culture);
}
resource.ApplyResources(item, item.Name, culture);

View file

@ -118,10 +118,7 @@ public void ShowMenu()
protected void OnTaskInfoSelected(QuickTaskInfo taskInfo)
{
if (TaskInfoSelected != null)
{
TaskInfoSelected(taskInfo);
}
TaskInfoSelected?.Invoke(taskInfo);
}
public Image FindSuitableIcon(QuickTaskInfo taskInfo)

View file

@ -284,9 +284,7 @@ private static void StartRecording(ScreenRecordOutput outputType, TaskSettings t
}
}).ContinueInCurrentContext(() =>
{
string customFileName;
if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out customFileName, null, path))
if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out string customFileName, null, path))
{
if (!string.IsNullOrEmpty(customFileName))
{

View file

@ -41,10 +41,8 @@ public StartupState State
{
if (ShortcutHelpers.CheckShortcut(Environment.SpecialFolder.Startup, StartupTargetPath))
{
byte[] status = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder",
"ShareX.lnk", null) as byte[];
if (status != null && status.Length > 0 && status[0] == 3)
if (Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder",
"ShareX.lnk", null) is byte[] status && status.Length > 0 && status[0] == 3)
{
return StartupState.DisabledByUser;
}

View file

@ -106,9 +106,7 @@ public ListViewItem FindItem(WorkerTask task)
{
foreach (ListViewItem lvi in ListViewControl.Items)
{
WorkerTask tag = lvi.Tag as WorkerTask;
if (tag != null && tag == task)
if (lvi.Tag is WorkerTask tag && tag == task)
{
return lvi;
}

View file

@ -137,7 +137,7 @@ public static void UploadFolder(TaskSettings taskSettings = null)
if (folderDialog.ShowDialog() && !string.IsNullOrEmpty(folderDialog.FileName))
{
Program.Settings.FileUploadDefaultDirectory = folderDialog.FileName;
UploadFile(folderDialog.FileName);
UploadFile(folderDialog.FileName, taskSettings);
}
}
}

View file

@ -64,10 +64,7 @@ public virtual void Enable()
protected void OnFileWatcherTrigger(string path)
{
if (FileWatcherTrigger != null)
{
FileWatcherTrigger(path);
}
FileWatcherTrigger?.Invoke(path);
}
private async void fileWatcher_Created(object sender, FileSystemEventArgs e)

View file

@ -1173,10 +1173,7 @@ private void OnTaskCompleted()
Info.Status = Resources.UploadTask_OnUploadCompleted_Done;
}
if (TaskCompleted != null)
{
TaskCompleted(this);
}
TaskCompleted?.Invoke(this);
Dispose();
}