Skip to content

Commit

Permalink
code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
mbnq committed Oct 12, 2024
1 parent e2232d1 commit c5f5e3e
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 45 deletions.
4 changes: 2 additions & 2 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ mbnq00 on gmail

using System.Security.Principal;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace redunDancer
{
Expand All @@ -18,10 +17,11 @@ internal static class Program
static Mutex redunDancerMutex = new Mutex(true, "{readunDancer}");

#region variables and constants
public const string mbVersion = "0.0.1.2";
public const string mbVersion = "0.0.1.4";
#endregion

#region DPI
// not really needed, leftover from template
/*
[DllImport("user32.dll")]
static extern bool SetProcessDPIAware();
Expand Down
4 changes: 1 addition & 3 deletions core/mbGUI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,11 @@ private void StartCheckboxLock()
{
if (int.TryParse(mbTestPingIntervalTextBox.Text, out int interval))
{
int lockDuration = interval * 5 * 1000; // Convert to milliseconds
int lockDuration = interval * 5 * 1000; // to ms
checkboxesLocked = true;
ActiveACheckBox.Enabled = false;
ActiveBCheckBox.Enabled = false;

// Use System.Windows.Forms.Timer
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = lockDuration;
timer.Tick += (s, e) =>
Expand Down Expand Up @@ -172,7 +171,6 @@ private void SwitchSettings()
}));
}

// Lock checkboxes after switching
UpdateNotifyIconText();
StartCheckboxLock();
}
Expand Down
57 changes: 21 additions & 36 deletions core/mbNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ private void DetectCurrentIP()
}
else
{
// Default to Setting A if no match
useSettingA = true;
ActiveACheckBox.Checked = true;
ActiveBCheckBox.Checked = false;
Expand All @@ -85,8 +84,7 @@ private void DetectCurrentIP()
{
string? adapterName = GetSelectedAdapterName(useSettingA);

if (adapterName == null)
return null;
if (adapterName == null) return null;

NetworkInterface? ni = NetworkInterface.GetAllNetworkInterfaces()
.FirstOrDefault(n => n.Name == adapterName);
Expand All @@ -108,42 +106,39 @@ private void DetectCurrentIP()
}
private bool IsSameNetwork(string ip1, string ip2)
{
if (string.IsNullOrWhiteSpace(ip1) || string.IsNullOrWhiteSpace(ip2))
return false;
if (string.IsNullOrWhiteSpace(ip1) || string.IsNullOrWhiteSpace(ip2)) return false;

string network1 = ip1.Substring(0, ip1.LastIndexOf('.'));
string network2 = ip2.Substring(0, ip2.LastIndexOf('.'));
return network1 == network2;
}

private void PingWorker_DoWork(object? sender, DoWorkEventArgs e)
{
int postSwitchDelayMultiplier = 1;

while (pingWorker != null && !pingWorker.CancellationPending)
{
// Get the IP, ping settings, and retry count from textboxes

string ipAddress = useSettingA ? mbDNS1TextBox.Text : mbDNS2TextBox.Text;

// Parse values safely, handle exceptions
int maxPing;
int interval;
int retryCount;

if (!int.TryParse(mbMaxPingTextBox.Text, out maxPing))
{
maxPing = 100; // Default value
maxPing = 100; // def
}

if (!int.TryParse(mbTestPingIntervalTextBox.Text, out interval))
{
interval = 1; // Default value
interval = 1; // def
}
interval *= 1000; // Convert to milliseconds
interval *= 1000; // to ms

if (!int.TryParse(mbTestPingRetryCountTextBox.Text, out retryCount))
{
retryCount = 3; // Default value
retryCount = 3; // def
}

string? currentIP = GetCurrentIPAddress();
Expand Down Expand Up @@ -179,17 +174,13 @@ private void PingWorker_DoWork(object? sender, DoWorkEventArgs e)
SwitchSettings();
PopUpNotification("redunDancer", "Switching network.", 5000);
consecutiveFailures = 0;
postSwitchDelayMultiplier = 2; // Double the delay after switching
postSwitchDelayMultiplier = 2;
}

mbRetryPbar.Value = consecutiveFailures;
SleepWithCancellation(interval * postSwitchDelayMultiplier);

// Reset the multiplier back to 1 after the extended delay
if (postSwitchDelayMultiplier > 1)
{
postSwitchDelayMultiplier = 1;
}
if (postSwitchDelayMultiplier > 1) postSwitchDelayMultiplier = 1;
}
}
private void LogPingResult(string message, bool isImportant = true)
Expand Down Expand Up @@ -237,7 +228,7 @@ private void LogPingResult(string message, bool isImportant = true)
}
private void SleepWithCancellation(int milliseconds)
{
int sleepInterval = 100; // Sleep in 100ms intervals
int sleepInterval = 100;
int elapsed = 0;
while (elapsed < milliseconds)
{
Expand All @@ -255,23 +246,23 @@ private void ApplySettings(string ip, string mask, string gateway)
LogPingResult($"Applying settings: IP={ip}, Mask={mask}, Gateway={gateway}", true);
SetNetworkSettings(ip, mask, gateway);

// Determine if we are using DHCP and update the corresponding checkbox
// determine if we are using DHCP and update the corresponding checkbox
bool isUsingDHCP = string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(mask) || string.IsNullOrWhiteSpace(gateway);

if (useSettingA)
{
Invoke(new Action(() =>
{
checkBoxDhcpA.Checked = isUsingDHCP;
checkBoxDhcpA.Enabled = false; // Disable to show it's an indicator
checkBoxDhcpA.Enabled = false;
}));
}
else
{
Invoke(new Action(() =>
{
checkBoxDhcpB.Checked = isUsingDHCP;
checkBoxDhcpB.Enabled = false; // Disable to show it's an indicator
checkBoxDhcpB.Enabled = false;
}));
}
}
Expand All @@ -290,14 +281,13 @@ private void SetNetworkSettings(string ip, string mask, string gateway)

if (string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(mask) || string.IsNullOrWhiteSpace(gateway))
{
// Set to DHCP
SetDHCP(adapterName);
Task.Delay(2000).Wait();
GetIPSettings(adapterName, useSettingA, false);
}
else
{
// Set static IP settings
// static IP settings
string setIPCmd = $"interface ip set address name=\"{adapterName}\" static {ip} {mask} {gateway} 1";
string setDNSCmd1 = $"interface ip set dnsservers name=\"{adapterName}\" static {mbDNS1TextBox.Text} primary";
string setDNSCmd2 = $"interface ip add dnsservers name=\"{adapterName}\" address={mbDNS2TextBox.Text} index=2";
Expand All @@ -312,6 +302,7 @@ private void SetNetworkSettings(string ip, string mask, string gateway)
catch (Exception ex)
{
LogPingResult($"Error applying network settings: {ex.Message}", true);
PopUpNotification("redunDancer", "Error applying network settings!", 5000);
}
}

Expand Down Expand Up @@ -344,16 +335,15 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex

LogPingResult($"Obtained IP settings: IP={ip}, Mask={mask}, Gateway={gateway}", true);

// Determine if DHCP is being used
// determine if DHCP is being used
bool isUsingDHCP = string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(mask) || string.IsNullOrWhiteSpace(gateway);

// Update the checkboxes for DHCP
if (isSettingA)
{
Invoke(new Action(() =>
{
checkBoxDhcpA.Checked = isUsingDHCP;
checkBoxDhcpA.Enabled = false; // Disable to show it's an indicator
checkBoxDhcpA.Enabled = false;
if (populateTextBoxes)
{
mbIPTextBoxA.Text = ip;
Expand All @@ -367,7 +357,7 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex
Invoke(new Action(() =>
{
checkBoxDhcpB.Checked = isUsingDHCP;
checkBoxDhcpB.Enabled = false; // Disable to show it's an indicator
checkBoxDhcpB.Enabled = false;
if (populateTextBoxes)
{
mbIPTextBoxB.Text = ip;
Expand All @@ -380,10 +370,10 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex
else
{
LogPingResult("Failed to obtain IP settings.", true);
PopUpNotification("redunDancer", "Failed to obtain IP settings.", 5000);
}
}
}

private string? GetDefaultAdapterName()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
Expand All @@ -397,7 +387,6 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex
}
return null;
}

private string? GetSelectedAdapterName(bool isSettingA)
{
string? selectedAdapter = null;
Expand Down Expand Up @@ -440,7 +429,6 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex
return selectedAdapter;
}
}

private string? GetNetshInterfaceName(bool isSettingA)
{
string? adapterName = GetSelectedAdapterName(isSettingA);
Expand All @@ -449,7 +437,6 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex

return GetNetshInterfaceNameByAdapterName(adapterName);
}

private string? GetNetshInterfaceNameByAdapterName(string adapterName)
{
NetworkInterface? ni = NetworkInterface.GetAllNetworkInterfaces()
Expand All @@ -461,7 +448,6 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex
}
return null;
}

private string? GetNetshInterfaceNameById(string adapterId)
{
string query = $"SELECT * FROM Win32_NetworkAdapter WHERE GUID = '{adapterId}'";
Expand All @@ -478,18 +464,17 @@ private void GetIPSettings(string adapterName, bool isSettingA, bool populateTex
}
return null;
}

private void RunNetshCommand(string command)
{
LogPingResult($"Running netsh command: {command}", true);

ProcessStartInfo psi = new ProcessStartInfo("netsh", command)
{
RedirectStandardOutput = true,
RedirectStandardError = true, // Capture errors
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
Verb = "runas" // Run as administrator
Verb = "runas" // run as admin
};

using (Process? process = Process.Start(psi))
Expand Down
6 changes: 2 additions & 4 deletions core/mbNotification.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ mbnq00 on gmail
*/

using redunDancer;

public class mbNotificationForm : Form
{
private Label mbTitleLabel, mbMessageLabel;
Expand All @@ -27,7 +26,7 @@ public mbNotificationForm(string title, string message, int timeout = 3000)
mbTitleLabel.AutoSize = false;
mbTitleLabel.TextAlign = ContentAlignment.MiddleCenter;
mbTitleLabel.Dock = DockStyle.Top;
mbTitleLabel.Font = new Font("Consolas", 12, FontStyle.Regular);
mbTitleLabel.Font = new Font("Consolas", 10, FontStyle.Regular);
mbTitleLabel.Height = 20;
mbTitleLabel.BackColor = Color.Gray;

Expand All @@ -36,7 +35,7 @@ public mbNotificationForm(string title, string message, int timeout = 3000)
mbMessageLabel.AutoSize = false;
mbMessageLabel.TextAlign = ContentAlignment.MiddleCenter;
mbMessageLabel.Dock = DockStyle.Fill;
mbMessageLabel.Font = new Font("Consolas", 12);
mbMessageLabel.Font = new Font("Consolas", 10);

// ---
this.Controls.Add(mbTitleLabel);
Expand All @@ -56,7 +55,6 @@ public mbNotificationForm(string title, string message, int timeout = 3000)
mbKillWithDelay(timeout);
}
}

private async void mbKillWithDelay(int timeout)
{
this.Opacity = 80;
Expand Down

0 comments on commit c5f5e3e

Please sign in to comment.