Skip to content
This repository was archived by the owner on Aug 19, 2020. It is now read-only.

Commit c962bc8

Browse files
committed
Merge branch 'try-via-registry'
2 parents eea7083 + eec3aeb commit c962bc8

9 files changed

Lines changed: 182 additions & 166 deletions

File tree

Source/ShecanDesktop/App.xaml.cs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,16 @@ public partial class App
1212
{
1313
protected override void OnStartup(StartupEventArgs e)
1414
{
15-
var launcher = new Launcher();
16-
launcher.PrepareApplication();
17-
launcher.StartApplication();
15+
Global.Initialize();
1816

19-
// Must call after the launcher.PrepareApplication() method
17+
// Must call after the Global.Initialize() method
2018
EnableUnhandledExceptionManager();
2119

20+
var launcher = new Launcher(Global.AppInfo);
21+
// Must call after the Global.Initialize() method
22+
launcher.Prepare();
23+
launcher.Start();
24+
2225
base.OnStartup(e);
2326
}
2427

@@ -55,13 +58,13 @@ private static void LogException(Exception exception, string type)
5558
var assemblyName = Assembly.GetExecutingAssembly().GetName();
5659

5760
// Log exception details
58-
using (var crashWriter = new StreamWriter(Launcher.LauncherInfo.AppCrashFile))
61+
using (var crashWriter = new StreamWriter(Global.AppInfo.AppCrashFile))
5962
{
6063
crashWriter.BaseStream.Seek(0L, SeekOrigin.End);
6164
crashWriter.Flush();
6265

6366
crashWriter.WriteLine($"Unhandled exception occurred in {assemblyName.Name} v{assemblyName.Version}");
64-
crashWriter.WriteLine($"At : {Launcher.DateTimeStamp}");
67+
crashWriter.WriteLine($"At : {Global.DateTimeStamp}");
6568
crashWriter.WriteLine($"Type : {type}");
6669
crashWriter.WriteLine($"File name : {Path.GetFileName(frame.GetFileName())}");
6770
crashWriter.WriteLine($"Method name : {frame.GetMethod().Name}");
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
namespace ShecanDesktop.Core
88
{
9-
public class LauncherInfo
9+
public class AppInfo
1010
{
1111
/// <summary>
12-
/// Setting up the <see cref="LauncherInfo" /> properties value
12+
/// Setting up the <see cref="AppInfo" /> properties value
1313
/// </summary>
1414
public void Initialize()
1515
{
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
using System;
2+
using Microsoft.Win32;
3+
using ShecanDesktop.Common.Log;
4+
5+
namespace ShecanDesktop.Core
6+
{
7+
public class Global
8+
{
9+
public static string DateTimeStamp;
10+
public static AppInfo AppInfo;
11+
public static ILogger Logger;
12+
13+
14+
public static void Initialize()
15+
{
16+
DateTimeStamp = $"{DateTime.Now:yyyy-MM-dd hh-mm-ss}";
17+
18+
PrepareAppInfo();
19+
StartLogger();
20+
}
21+
22+
public static string GetOsName()
23+
{
24+
const string systemInfoPathInRegistry = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\";
25+
return Registry.GetValue(systemInfoPathInRegistry, "ProductName", null).ToString();
26+
}
27+
28+
private static void PrepareAppInfo()
29+
{
30+
AppInfo = new AppInfo();
31+
AppInfo.Initialize();
32+
}
33+
34+
private static void StartLogger()
35+
{
36+
var logFileName = $"{AppInfo.AppLogFolder}" +
37+
$"{DateTimeStamp}.log";
38+
39+
Logger = new Logger();
40+
Logger.Start(logFileName, DateTimeStamp);
41+
}
42+
}
43+
}

Source/ShecanDesktop/Core/Launcher.cs

Lines changed: 28 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -3,58 +3,39 @@
33
using System.IO;
44
using System.Linq;
55
using System.Windows;
6-
using ShecanDesktop.Common.Log;
76

87
namespace ShecanDesktop.Core
98
{
109
public class Launcher
1110
{
12-
#region Private Members
11+
#region Constructors
1312

14-
private bool _isAppReadyToLaunch;
13+
public Launcher(AppInfo appInfo)
14+
{
15+
_appInfo = appInfo;
16+
}
1517

1618
#endregion
1719

18-
#region Static Public Members
20+
#region Private Members
1921

20-
public static string DateTimeStamp => $"{DateTime.Now:yyyy-MM-dd hh-mm-ss}";
21-
public static ILogger Logger;
22-
public static LauncherInfo LauncherInfo;
22+
private readonly AppInfo _appInfo;
23+
private bool _isAppReadyToLaunch;
2324

2425
#endregion
2526

26-
#region Non-Static Public Members
27-
28-
public virtual void PrepareApplication()
27+
#region Public Members
28+
29+
public void Prepare()
2930
{
30-
// Create a instance of LauncherInfo and puts it in LauncherInfo field.
31-
// We can access to LauncherInfo field from anywhere of the application.
32-
InitializeLauncher();
33-
34-
// NOTE: Should be call after LauncherInfo initializing.
35-
// Because we need to log directory path that will specify in LauncherInfo.
36-
// Create a logger instance and puts it in Logger field.
37-
// We can access to Logger field from anywhere of the application.
38-
StartLogger();
39-
40-
// NOTE: Should be call after launcher initializing.
41-
// Because we need to primary directories collection that will specify in LauncherInfo.
4231
CheckPrimaryDirectories();
43-
44-
// Manage app crash details
4532
ManageAppCrash();
46-
47-
// Make application single instance
4833
CheckInstances();
49-
50-
// Set application info such as name, version, etc
5134
SetAppInfo();
52-
53-
// Set app status
5435
_isAppReadyToLaunch = true;
5536
}
5637

57-
public virtual void StartApplication()
38+
public void Start()
5839
{
5940
if (!_isAppReadyToLaunch)
6041
throw new InvalidOperationException("App is not ready to launch. You must calling the Prepare method first.");
@@ -66,30 +47,22 @@ public virtual void StartApplication()
6647
// manager in App.xaml.cs (EnableUnhandledExceptionManager method) after
6748
// the application launched, we cannot show the main window using ShowDialog method.
6849
Application.Current.MainWindow.Show();
69-
}
7050

71-
#endregion
72-
73-
#region Protected Methods
51+
if (!Global.AppInfo.AppCommandLine.Contains("-debug")) return;
7452

75-
protected void InitializeLauncher()
76-
{
77-
LauncherInfo = new LauncherInfo();
78-
LauncherInfo.Initialize();
53+
Global.Logger.LogInfo($"Executable Path: {Global.AppInfo.AppFullPath}");
54+
Global.Logger.LogInfo($"App Version: {Global.AppInfo.AppVersion}");
55+
Global.Logger.LogInfo($"Command Line: {Global.AppInfo.AppCommandLine}");
56+
Global.Logger.LogInfo($"Current Os: {Global.GetOsName()}");
7957
}
8058

81-
protected void StartLogger()
82-
{
83-
var logFileName = $"{LauncherInfo.AppLogFolder}" +
84-
$"{DateTimeStamp}.log";
59+
#endregion
8560

86-
Logger = new Logger();
87-
Logger.Start(logFileName, DateTimeStamp);
88-
}
61+
#region Protected Methods
8962

9063
protected void CheckPrimaryDirectories()
9164
{
92-
var primaryDirectories = LauncherInfo.AppPrimaryDirectories;
65+
var primaryDirectories = _appInfo.AppPrimaryDirectories;
9366

9467
foreach (var primaryDirectory in primaryDirectories)
9568
{
@@ -100,23 +73,23 @@ protected void CheckPrimaryDirectories()
10073
}
10174
}
10275

103-
protected static void ManageAppCrash()
76+
protected void ManageAppCrash()
10477
{
105-
if (!File.Exists(LauncherInfo.AppCrashFile))
78+
if (!File.Exists(_appInfo.AppCrashFile))
10679
return;
10780

108-
var crashDetails = File.ReadAllLines(LauncherInfo.AppCrashFile);
81+
var crashDetails = File.ReadAllLines(_appInfo.AppCrashFile);
10982
if (crashDetails.Length < 0) return;
11083

11184
// Crash file new location
112-
var crashFileNewLocation = $"{LauncherInfo.AppCrashFolder}{DateTime.Now:yyyy-MM-dd hh-mm-ss}.txt";
85+
var crashFileNewLocation = $"{_appInfo.AppCrashFolder}{DateTime.Now:yyyy-MM-dd hh-mm-ss}.txt";
11386

11487
// Prepare crash folder
115-
if (!Directory.Exists(LauncherInfo.AppCrashFolder))
116-
Directory.CreateDirectory(LauncherInfo.AppCrashFolder);
88+
if (!Directory.Exists(_appInfo.AppCrashFolder))
89+
Directory.CreateDirectory(_appInfo.AppCrashFolder);
11790

11891
// Move crash file to crash folder
119-
File.Move(LauncherInfo.AppCrashFile,
92+
File.Move(_appInfo.AppCrashFile,
12093
crashFileNewLocation);
12194

12295
// Display app last crash details using Notepad
@@ -134,7 +107,7 @@ protected void CheckInstances()
134107

135108
protected void SetAppInfo()
136109
{
137-
Application.Current.Resources["AppVersion"] = LauncherInfo.AppVersion;
110+
Application.Current.Resources["AppVersion"] = _appInfo.AppVersion;
138111
}
139112

140113
#endregion

Source/ShecanDesktop/Core/Network/BaseDnsService.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,17 @@
22
using System.Diagnostics;
33
using System.Linq;
44
using System.Net.NetworkInformation;
5+
using Microsoft.Win32;
56

67
namespace ShecanDesktop.Core.Network
78
{
89
public abstract class BaseDnsService
910
{
10-
protected readonly string NetworkConfigurationPath;
11+
protected readonly string NetworkConfigurationRegistryPath;
1112

1213
protected BaseDnsService()
1314
{
14-
NetworkConfigurationPath = "Win32_NetworkAdapterConfiguration";
15+
NetworkConfigurationRegistryPath = @"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{0}";
1516
}
1617

1718
protected virtual NetworkInterface GetCurrentInterface()
@@ -26,6 +27,15 @@ protected virtual NetworkInterface GetCurrentInterface()
2627
return networkInterface;
2728
}
2829

30+
protected virtual void ChangeNameServerValue(string ipAddresses)
31+
{
32+
var currentAdapterId = GetCurrentInterface().Id;
33+
var registryPath = string.Format(NetworkConfigurationRegistryPath, currentAdapterId);
34+
35+
using (var registryKey = Registry.LocalMachine.OpenSubKey(registryPath, true))
36+
registryKey?.SetValue("NameServer", ipAddresses);
37+
}
38+
2939
protected virtual void FlushDns()
3040
{
3141
var processInfo = new ProcessStartInfo

Source/ShecanDesktop/Core/Network/DnsService.cs

Lines changed: 24 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -2,72 +2,31 @@
22
using System.Linq;
33
using System.Net.NetworkInformation;
44
using ShecanDesktop.Models;
5-
using System.Management;
65

76
namespace ShecanDesktop.Core.Network
87
{
98
public class DnsService : BaseDnsService, IDnsService
109
{
1110
public event EventHandler DnsChanged;
1211

13-
public virtual void Set(Dns dns)
12+
protected virtual void OnDnsChanged()
1413
{
15-
var ipAddresses = new[] { dns.PreferredServer, dns.AlternateServer };
16-
var currentInterface = GetCurrentInterface();
17-
if (currentInterface == null) return;
18-
19-
var managementClass = new ManagementClass(NetworkConfigurationPath);
20-
var managementObjectCollection = managementClass.GetInstances();
21-
22-
foreach (var o in managementObjectCollection)
23-
{
24-
var managementObject = (ManagementObject)o;
25-
26-
if (!(bool)managementObject["IPEnabled"])
27-
continue;
28-
29-
if (!managementObject["Caption"].ToString().Contains(currentInterface.Description))
30-
continue;
31-
32-
var managementBaseObject = managementObject.GetMethodParameters("SetDNSServerSearchOrder");
33-
34-
if (managementBaseObject == null) continue;
14+
FlushDns();
15+
DnsChanged?.Invoke(this, EventArgs.Empty);
16+
}
3517

36-
managementBaseObject["DNSServerSearchOrder"] = ipAddresses;
37-
managementObject.InvokeMethod("SetDNSServerSearchOrder", managementBaseObject, null);
38-
break;
39-
}
4018

19+
public virtual void Set(Dns dns)
20+
{
21+
var ipAddresses = $"{dns.PreferredServer},{dns.AlternateServer}";
22+
ChangeNameServerValue(ipAddresses);
4123
OnDnsChanged();
4224
}
4325

4426
public virtual void Unset()
4527
{
46-
var currentInterface = GetCurrentInterface();
47-
if (currentInterface == null) return;
48-
49-
var managementClass = new ManagementClass(NetworkConfigurationPath);
50-
var managementObjectCollection = managementClass.GetInstances();
51-
52-
foreach (var o in managementObjectCollection)
53-
{
54-
var managementObject = (ManagementObject)o;
55-
56-
if (!(bool)managementObject["IPEnabled"])
57-
continue;
58-
59-
if (!managementObject["Caption"].ToString().Contains(currentInterface.Description))
60-
continue;
61-
62-
var managementBaseObject = managementObject.GetMethodParameters("SetDNSServerSearchOrder");
63-
64-
if (managementBaseObject == null) continue;
65-
66-
managementBaseObject["DNSServerSearchOrder"] = null;
67-
managementObject.InvokeMethod("SetDNSServerSearchOrder", managementBaseObject, null);
68-
break;
69-
}
70-
28+
var ipAddresses = string.Empty;
29+
ChangeNameServerValue(ipAddresses);
7130
OnDnsChanged();
7231
}
7332

@@ -106,16 +65,22 @@ public virtual string GetCurrentInterfaceAlias()
10665

10766
public Dns GetDnsFromUrl(string url)
10867
{
109-
var addresses = System.Net.Dns.GetHostAddresses(url);
68+
try
69+
{
70+
var addresses = System.Net.Dns.GetHostAddresses(url);
11071

111-
return new Dns(addresses[1].ToString(),
112-
addresses[0].ToString());
113-
}
72+
var preferredIp = addresses[0].ToString().StartsWith("178") ?
73+
addresses[0].ToString() : addresses[1].ToString();
11474

115-
protected virtual void OnDnsChanged()
116-
{
117-
FlushDns();
118-
DnsChanged?.Invoke(this, EventArgs.Empty);
75+
var alternateIp = addresses[0].ToString().StartsWith("185") ?
76+
addresses[0].ToString() : addresses[1].ToString();
77+
78+
return new Dns(preferredIp, alternateIp);
79+
}
80+
catch
81+
{
82+
return null;
83+
}
11984
}
12085
}
12186
}

0 commit comments

Comments
 (0)