From 7e396b4ff6f272e57717dd62f5e17ce375d20bd2 Mon Sep 17 00:00:00 2001 From: VahidN Date: Mon, 3 Apr 2017 20:31:12 +0430 Subject: [PATCH] Improved active lists handling --- ProcessProxifier/Core/ProcessesListManager.cs | 125 ++-- ProcessProxifier/Core/ProxyRouter.cs | 182 +++--- ProcessProxifier/Core/SettingsManager.cs | 95 +-- ProcessProxifier/Core/SettingsSerializer.cs | 61 +- ProcessProxifier/MainWindow.xaml | 596 +++++++++--------- ProcessProxifier/Models/Process.cs | 162 ++--- ProcessProxifier/Models/ProxifierSettings.cs | 318 +++++----- ProcessProxifier/Models/ServerInfo.cs | 110 ++-- ProcessProxifier/ProcessProxifier.csproj | 456 +++++++------- ProcessProxifier/Properties/AssemblyInfo.cs | 108 ++-- ProcessProxifier/Utils/ExceptionLogger.cs | 266 ++++---- ProcessProxifier/Utils/ProcessUtils.cs | 17 + ProcessProxifier/Utils/SimpleTaskScheduler.cs | 60 +- .../ViewModels/MainWindowViewModel.cs | 419 ++++++------ ProcessProxifier/packages.config | 4 + 15 files changed, 1493 insertions(+), 1486 deletions(-) create mode 100644 ProcessProxifier/Utils/ProcessUtils.cs create mode 100644 ProcessProxifier/packages.config diff --git a/ProcessProxifier/Core/ProcessesListManager.cs b/ProcessProxifier/Core/ProcessesListManager.cs index a7dd7ca..1f84126 100644 --- a/ProcessProxifier/Core/ProcessesListManager.cs +++ b/ProcessProxifier/Core/ProcessesListManager.cs @@ -1,66 +1,61 @@ -using System; -using System.Linq; -using ProcessProxifier.Models; -using ProcessProxifier.Utils; - -namespace ProcessProxifier.Core -{ - public static class ProcessesListManager - { - public static AsyncObservableCollection UpdateProcesses(ProxifierSettings guiModelData, ProxifierSettings settings) - { - var processesList = System.Diagnostics.Process.GetProcesses().OrderBy(x => x.ProcessName).ToList(); - - var finishedProcesses = guiModelData.ProcessesList - .Where(x => !processesList.Select(p => p.Id).Contains(x.Pid) - && !x.IsEnabled) - .ToList(); - foreach (var process in finishedProcesses) - { - guiModelData.ProcessesList.Remove(process); - } - - var newProcesses = processesList.Where(x => !guiModelData.ProcessesList.Select(p => p.Pid).Contains(x.Id)).ToList(); - - foreach (var process in newProcesses) - { - var path = getPath(process); - var newProcess = new Process - { - Name = process.ProcessName, - Pid = process.Id, - Path = path - }; - - var settingsProcess = settings.ProcessesList - .FirstOrDefault(x => x.Path.Equals(path, StringComparison.InvariantCultureIgnoreCase)); - if (settingsProcess != null) - { - newProcess.IsEnabled = settingsProcess.IsEnabled; - newProcess.ServerInfo = new ServerInfo - { - ServerIP = settingsProcess.ServerInfo.ServerIP, - ServerPort = settingsProcess.ServerInfo.ServerPort, - ServerType = settingsProcess.ServerInfo.ServerType - }; - } - - guiModelData.ProcessesList.Add(newProcess); - } - - return guiModelData.ProcessesList; - } - - private static string getPath(System.Diagnostics.Process process) - { - try - { - return process.MainModule.FileName; - } - catch - { - return string.Empty; - } - } - } +using System; +using System.Linq; +using ProcessProxifier.Models; +using ProcessProxifier.Utils; + +namespace ProcessProxifier.Core +{ + public static class ProcessesListManager + { + public static AsyncObservableCollection UpdateProcesses( + ProxifierSettings guiModelData, + ProxifierSettings settings) + { + var systemProcessList = System.Diagnostics.Process.GetProcesses().OrderBy(x => x.ProcessName).ToList(); + var systemProcessIds = systemProcessList.Select(p => p.Id).ToList(); + var finishedProcesses = guiModelData.ProcessesList + .Where(process => !systemProcessIds.Contains(process.Pid)) + .ToList(); + + if (finishedProcesses.Any()) + { + SettingsManager.SaveSettings(guiModelData, settings); + } + + foreach (var process in finishedProcesses) + { + guiModelData.ProcessesList.Remove(process); + } + + var guiProcessIds = guiModelData.ProcessesList.Select(process => process.Pid).ToList(); + var newSystemProcesses = systemProcessList.Where(process => !guiProcessIds.Contains(process.Id)).ToList(); + foreach (var systemProcess in newSystemProcesses) + { + var path = systemProcess.GetPath(); + var newProcess = new Process + { + Name = systemProcess.ProcessName, + Pid = systemProcess.Id, + Path = path + }; + + var settingsProcess = settings.ActiveProcessesList + .FirstOrDefault(x => x.Path.Equals(path, StringComparison.InvariantCultureIgnoreCase)); + if (settingsProcess != null) + { + newProcess.IsEnabled = settingsProcess.IsEnabled; + newProcess.ServerInfo = new ServerInfo + { + ServerIP = settingsProcess.ServerInfo.ServerIP, + ServerPort = settingsProcess.ServerInfo.ServerPort, + ServerType = settingsProcess.ServerInfo.ServerType + }; + } + + guiModelData.ProcessesList.Add(newProcess); + } + + return guiModelData.ProcessesList; + } + } } \ No newline at end of file diff --git a/ProcessProxifier/Core/ProxyRouter.cs b/ProcessProxifier/Core/ProxyRouter.cs index 06b7d26..69e28a7 100644 --- a/ProcessProxifier/Core/ProxyRouter.cs +++ b/ProcessProxifier/Core/ProxyRouter.cs @@ -1,96 +1,88 @@ -using System.Linq; -using System.Net.Security; -using System.Threading; -using Fiddler; -using ProcessProxifier.Models; -using ProcessProxifier.Utils; - -namespace ProcessProxifier.Core -{ - using System.Globalization; - - public class ProxyRouter - { - #region Properties (4) - - public ServerInfo DefaultServerInfo { set; get; } - - public int FiddlerPort { set; get; } - - public AsyncObservableCollection ProcessesList { set; get; } - - public AsyncObservableCollection RoutedConnectionsList { set; get; } - - #endregion Properties - - #region Methods (5) - - // Public Methods (2)  - - public void Shutdown() - { - FiddlerApplication.BeforeRequest -= beforeRequest; - FiddlerApplication.OnValidateServerCertificate -= onValidateServerCertificate; - - if (FiddlerApplication.oProxy != null) - FiddlerApplication.oProxy.Detach(); - - FiddlerApplication.Shutdown(); - - Thread.Sleep(1000); - } - - public void Start() - { - FiddlerApplication.BeforeRequest += beforeRequest; - FiddlerApplication.OnValidateServerCertificate += onValidateServerCertificate; - - FiddlerApplication.Startup(FiddlerPort, - FiddlerCoreStartupFlags.RegisterAsSystemProxy | - FiddlerCoreStartupFlags.MonitorAllConnections | - FiddlerCoreStartupFlags.CaptureFTP); - } - // Private Methods (3)  - - void beforeRequest(Session oSession) - { - var process = ProcessesList.FirstOrDefault(p => p.Pid == oSession.LocalProcessID && p.IsEnabled); - if (process == null) - return; - - var useDefaultServerInfo = string.IsNullOrWhiteSpace(process.ServerInfo.ServerIP); - if (useDefaultServerInfo) - { - oSession["X-OverrideGateway"] = (DefaultServerInfo.ServerType == ServerType.Socks ? "socks=" : "") + DefaultServerInfo.ServerIP + ":" + DefaultServerInfo.ServerPort; - } - else - { - oSession["X-OverrideGateway"] = (process.ServerInfo.ServerType == ServerType.Socks ? "socks=" : "") + process.ServerInfo.ServerIP + ":" + process.ServerInfo.ServerPort; - } - - RoutedConnectionsList.Add(new RoutedConnection - { - ProcessPid = oSession.LocalProcessID, - Url = oSession.fullUrl, - ProcessName = getProcessName(oSession), - ProcessPath = process.Path - }); - } - - private string getProcessName(Session oSession) - { - var process = ProcessesList.FirstOrDefault(x => x.Pid == oSession.LocalProcessID); - return process == null ? oSession.LocalProcessID.ToString(CultureInfo.InvariantCulture) : process.Name; - } - - static void onValidateServerCertificate(object sender, ValidateServerCertificateEventArgs e) - { - if (SslPolicyErrors.None == e.CertificatePolicyErrors) - return; - - e.ValidityState = CertificateValidity.ForceValid; - } - - #endregion Methods - } +using System.Linq; +using System.Net.Security; +using System.Threading; +using Fiddler; +using ProcessProxifier.Models; +using ProcessProxifier.Utils; + +namespace ProcessProxifier.Core +{ + using System.Globalization; + + public class ProxyRouter + { + public ServerInfo DefaultServerInfo { set; get; } + + public int FiddlerPort { set; get; } + + public AsyncObservableCollection ProcessesList { set; get; } + + public AsyncObservableCollection RoutedConnectionsList { set; get; } + + // Public Methods (2)  + + public void Shutdown() + { + FiddlerApplication.BeforeRequest -= beforeRequest; + FiddlerApplication.OnValidateServerCertificate -= onValidateServerCertificate; + + if (FiddlerApplication.oProxy != null) + FiddlerApplication.oProxy.Detach(); + + FiddlerApplication.Shutdown(); + + Thread.Sleep(1000); + } + + public void Start() + { + FiddlerApplication.BeforeRequest += beforeRequest; + FiddlerApplication.OnValidateServerCertificate += onValidateServerCertificate; + + FiddlerApplication.Startup(FiddlerPort, + FiddlerCoreStartupFlags.RegisterAsSystemProxy | + FiddlerCoreStartupFlags.MonitorAllConnections | + FiddlerCoreStartupFlags.CaptureFTP); + } + // Private Methods (3)  + + void beforeRequest(Session oSession) + { + var process = ProcessesList.FirstOrDefault(p => p.Pid == oSession.LocalProcessID && p.IsEnabled); + if (process == null) + return; + + var useDefaultServerInfo = string.IsNullOrWhiteSpace(process.ServerInfo.ServerIP); + if (useDefaultServerInfo) + { + oSession["X-OverrideGateway"] = (DefaultServerInfo.ServerType == ServerType.Socks ? "socks=" : "") + DefaultServerInfo.ServerIP + ":" + DefaultServerInfo.ServerPort; + } + else + { + oSession["X-OverrideGateway"] = (process.ServerInfo.ServerType == ServerType.Socks ? "socks=" : "") + process.ServerInfo.ServerIP + ":" + process.ServerInfo.ServerPort; + } + + RoutedConnectionsList.Add(new RoutedConnection + { + ProcessPid = oSession.LocalProcessID, + Url = oSession.fullUrl, + ProcessName = getProcessName(oSession), + ProcessPath = process.Path + }); + } + + private string getProcessName(Session oSession) + { + var process = ProcessesList.FirstOrDefault(x => x.Pid == oSession.LocalProcessID); + return process == null ? oSession.LocalProcessID.ToString(CultureInfo.InvariantCulture) : process.Name; + } + + static void onValidateServerCertificate(object sender, ValidateServerCertificateEventArgs e) + { + if (SslPolicyErrors.None == e.CertificatePolicyErrors) + return; + + e.ValidityState = CertificateValidity.ForceValid; + } + } } \ No newline at end of file diff --git a/ProcessProxifier/Core/SettingsManager.cs b/ProcessProxifier/Core/SettingsManager.cs index a161fc8..1f29ac3 100644 --- a/ProcessProxifier/Core/SettingsManager.cs +++ b/ProcessProxifier/Core/SettingsManager.cs @@ -1,37 +1,60 @@ -using System.IO; -using System.Windows.Forms; -using ProcessProxifier.Models; -using ProcessProxifier.Utils; - -namespace ProcessProxifier.Core -{ - public static class SettingsManager - { - public static string SettingsPath - { - get { return Path.Combine(Application.StartupPath, "settings.xml"); } - } - - public static ProxifierSettings LoadSettings(ProxifierSettings guiModelData) - { - var settings = SettingsSerializer.LoadSettings(SettingsPath); - guiModelData.ProxifierPort = settings.ProxifierPort; - guiModelData.DefaultServerInfo.ServerIP = settings.DefaultServerInfo.ServerIP; - guiModelData.DefaultServerInfo.ServerPort = settings.DefaultServerInfo.ServerPort; - guiModelData.DefaultServerInfo.ServerType = settings.DefaultServerInfo.ServerType; - guiModelData.RunOnStartup = settings.RunOnStartup; - guiModelData.AreAllChecked = settings.AreAllChecked; - return settings; - } - - public static void SaveSettings(ProxifierSettings guiModelData) - { - if (guiModelData.RunOnStartup) - RunOnWindowsStartup.Do(); - else - RunOnWindowsStartup.Undo(); - - SettingsSerializer.SaveSettings(guiModelData, SettingsPath); - } - } +using System.IO; +using System.Windows.Forms; +using ProcessProxifier.Models; +using ProcessProxifier.Utils; + +namespace ProcessProxifier.Core +{ + public static class SettingsManager + { + public static string SettingsPath + { + get { return Path.Combine(Application.StartupPath, "settings.json"); } + } + + public static ProxifierSettings LoadSettings(ProxifierSettings guiModelData) + { + var settings = SettingsSerializer.LoadSettings(SettingsPath); + guiModelData.ProxifierPort = settings.ProxifierPort; + guiModelData.DefaultServerInfo.ServerIP = settings.DefaultServerInfo.ServerIP; + guiModelData.DefaultServerInfo.ServerPort = settings.DefaultServerInfo.ServerPort; + guiModelData.DefaultServerInfo.ServerType = settings.DefaultServerInfo.ServerType; + guiModelData.RunOnStartup = settings.RunOnStartup; + guiModelData.AreAllChecked = settings.AreAllChecked; + return settings; + } + + public static void SaveSettings(ProxifierSettings guiModelData, ProxifierSettings settings) + { + if (guiModelData.RunOnStartup) + RunOnWindowsStartup.Do(); + else + RunOnWindowsStartup.Undo(); + + addNewActiveItems(guiModelData, settings); + SettingsSerializer.SaveSettings(guiModelData, SettingsPath); + } + + private static void addNewActiveItems(ProxifierSettings guiModelData, ProxifierSettings settings) + { + foreach (var process in guiModelData.ProcessesList) + { + if (!process.IsEnabled && string.IsNullOrWhiteSpace(process.ServerInfo.ServerIP) && + process.ServerInfo.ServerPort == 0) + { + continue; + } + + if(!settings.ActiveProcessesList.Contains(process)) + { + settings.ActiveProcessesList.Add(process); + } + + if (!guiModelData.ActiveProcessesList.Contains(process)) + { + guiModelData.ActiveProcessesList.Add(process); + } + } + } + } } \ No newline at end of file diff --git a/ProcessProxifier/Core/SettingsSerializer.cs b/ProcessProxifier/Core/SettingsSerializer.cs index 5b9af77..923b042 100644 --- a/ProcessProxifier/Core/SettingsSerializer.cs +++ b/ProcessProxifier/Core/SettingsSerializer.cs @@ -1,39 +1,24 @@ -using System.IO; -using System.Xml.Linq; -using System.Xml.Serialization; -using ProcessProxifier.Models; -using ProcessProxifier.Utils; - -namespace ProcessProxifier.Core -{ - public static class SettingsSerializer - { - public static void SaveSettings(ProxifierSettings data, string configFilePath) - { - using (var fileStream = new FileStream(configFilePath, FileMode.Create)) - { - using (var streamWriter = new StreamWriter(fileStream)) - { - var ns = new XmlSerializerNamespaces(); ns.Add("", ""); - var xmlSerializer = new XmlSerializer(typeof(ProxifierSettings)); - xmlSerializer.Serialize(streamWriter, data, ns); - } - } - } - - public static ProxifierSettings LoadSettings(string configFilePath) - { - if (!File.Exists(configFilePath)) - { - SaveSettings(new ProxifierSettings(), configFilePath); - } - - var xmlSerializer = new XmlSerializer(typeof(ProxifierSettings)); - var ctx = XDocument.Load(configFilePath); - var result = (ProxifierSettings)xmlSerializer.Deserialize(ctx.Root.CreateReader()); - result.ProcessesList = new AsyncObservableCollection(); - result.RoutedConnectionsList = new AsyncObservableCollection(); - return result; - } - } +using System.IO; +using Newtonsoft.Json; +using ProcessProxifier.Models; + +namespace ProcessProxifier.Core +{ + public static class SettingsSerializer + { + public static void SaveSettings(ProxifierSettings data, string configFilePath) + { + File.WriteAllText(configFilePath, JsonConvert.SerializeObject(data, new JsonSerializerSettings { Formatting = Formatting.Indented })); + } + + public static ProxifierSettings LoadSettings(string configFilePath) + { + if (!File.Exists(configFilePath)) + { + SaveSettings(new ProxifierSettings(), configFilePath); + } + + return JsonConvert.DeserializeObject(File.ReadAllText(configFilePath)); + } + } } \ No newline at end of file diff --git a/ProcessProxifier/MainWindow.xaml b/ProcessProxifier/MainWindow.xaml index 24a42d9..a36b683 100644 --- a/ProcessProxifier/MainWindow.xaml +++ b/ProcessProxifier/MainWindow.xaml @@ -1,299 +1,299 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ProcessProxifier/Models/Process.cs b/ProcessProxifier/Models/Process.cs index 392763e..5cf9d64 100644 --- a/ProcessProxifier/Models/Process.cs +++ b/ProcessProxifier/Models/Process.cs @@ -1,77 +1,87 @@ -using System.ComponentModel; -using System.Xml.Serialization; - -namespace ProcessProxifier.Models -{ - public class Process : INotifyPropertyChanged - { - #region Fields (4) - - bool _isEnabled; - string _name; - int _pid; - ServerInfo _serverInfo = new ServerInfo(); - - #endregion Fields - - #region Properties (5) - - public bool IsEnabled - { - get { return _isEnabled; } - set - { - _isEnabled = value; - notifyPropertyChanged("IsEnabled"); - } - } - - public string Name - { - get { return _name; } - set - { - _name = value; - notifyPropertyChanged("Name"); - } - } - - public string Path { set; get; } - - [XmlIgnore] - public int Pid - { - get { return _pid; } - set - { - _pid = value; - notifyPropertyChanged("Pid"); - } - } - - public ServerInfo ServerInfo - { - get { return _serverInfo; } - set - { - _serverInfo = value; - notifyPropertyChanged("ServerInfo"); - } - } - - #endregion Properties - - - - #region INotifyPropertyChanged Members - public event PropertyChangedEventHandler PropertyChanged; - private void notifyPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } - #endregion - } +using System; +using System.ComponentModel; +using Newtonsoft.Json; + +namespace ProcessProxifier.Models +{ + public class Process : INotifyPropertyChanged + { + bool _isEnabled; + string _name; + int _pid; + ServerInfo _serverInfo = new ServerInfo(); + + public bool IsEnabled + { + get { return _isEnabled; } + set + { + _isEnabled = value; + notifyPropertyChanged("IsEnabled"); + } + } + + public string Name + { + get { return _name; } + set + { + _name = value; + notifyPropertyChanged("Name"); + } + } + + public string Path { set; get; } + + [JsonIgnore] + public int Pid + { + get { return _pid; } + set + { + _pid = value; + notifyPropertyChanged("Pid"); + } + } + + public ServerInfo ServerInfo + { + get { return _serverInfo; } + set + { + _serverInfo = value; + notifyPropertyChanged("ServerInfo"); + } + } + + public event PropertyChangedEventHandler PropertyChanged; + private void notifyPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + public override string ToString() + { + return $"{Name}, {Path}"; + } + + public override bool Equals(object obj) + { + var process = obj as Process; + if (process == null) + return false; + + return this.Path.Equals(process.Path, StringComparison.OrdinalIgnoreCase); + } + + public override int GetHashCode() + { + unchecked + { + var hash = 17; + hash = hash * 23 + Path.GetHashCode(); + return hash; + } + } + } } \ No newline at end of file diff --git a/ProcessProxifier/Models/ProxifierSettings.cs b/ProcessProxifier/Models/ProxifierSettings.cs index 2efce66..2c42641 100644 --- a/ProcessProxifier/Models/ProxifierSettings.cs +++ b/ProcessProxifier/Models/ProxifierSettings.cs @@ -1,160 +1,160 @@ -using System.ComponentModel; -using System.Xml.Serialization; -using ProcessProxifier.Utils; - -namespace ProcessProxifier.Models -{ - public class ProxifierSettings : INotifyPropertyChanged - { - #region Fields (11) - bool _areAllChecked; - bool _isEnabled = true; - AsyncObservableCollection _processesList; - ICollectionView _processesListDataView; - int _proxifierPort = 5656; - AsyncObservableCollection _routedConnectionsList; - bool _runOnStartup = true; - string _searchText; - Process _selectedProcess; - RoutedConnection _selectedRoutedConnection; - ServerInfo _serverInfo = new ServerInfo(); - - #endregion Fields - - #region Properties (11) - - public bool AreAllChecked - { - get { return _areAllChecked; } - set - { - _areAllChecked = value; - notifyPropertyChanged("AreAllChecked"); - - foreach (var item in ProcessesList) - item.IsEnabled = value; - } - } - - public ServerInfo DefaultServerInfo - { - get { return _serverInfo; } - set - { - _serverInfo = value; - notifyPropertyChanged("DefaultServerInfo"); - } - } - - [XmlIgnore] - public bool IsEnabled - { - get { return _isEnabled; } - set - { - _isEnabled = value; - notifyPropertyChanged("IsEnabled"); - } - } - - public AsyncObservableCollection ProcessesList - { - get { return _processesList ?? new AsyncObservableCollection(); } - set - { - _processesList = value; - notifyPropertyChanged("ProcessesList"); - } - } - - [XmlIgnore] - public ICollectionView ProcessesListDataView - { - get { return _processesListDataView; } - set - { - _processesListDataView = value; - notifyPropertyChanged("ProcessesListDataView"); - } - } - - public int ProxifierPort - { - get { return _proxifierPort; } - set - { - _proxifierPort = value; - notifyPropertyChanged("ProxifierPort"); - } - } - - [XmlIgnore] - public AsyncObservableCollection RoutedConnectionsList - { - get { return _routedConnectionsList; } - set - { - _routedConnectionsList = value; - notifyPropertyChanged("RoutedConnectionsList"); - } - } - - public bool RunOnStartup - { - get { return _runOnStartup; } - set - { - _runOnStartup = value; - notifyPropertyChanged("RunOnStartup"); - } - } - - [XmlIgnore] - public string SearchText - { - get { return _searchText; } - set - { - _searchText = value; - notifyPropertyChanged("SearchText"); - } - } - - [XmlIgnore] - public Process SelectedProcess - { - get { return _selectedProcess; } - set - { - _selectedProcess = value; - notifyPropertyChanged("SelectedProcess"); - } - } - - [XmlIgnore] - public RoutedConnection SelectedRoutedConnection - { - get { return _selectedRoutedConnection; } - set - { - _selectedRoutedConnection = value; - notifyPropertyChanged("SelectedRoutedConnection"); - } - } - - #endregion Properties - - - - #region INotifyPropertyChanged Members - public event PropertyChangedEventHandler PropertyChanged; - private void notifyPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } - #endregion - } +using System.ComponentModel; +using Newtonsoft.Json; +using ProcessProxifier.Utils; + +namespace ProcessProxifier.Models +{ + public class ProxifierSettings : INotifyPropertyChanged + { + bool _areAllChecked; + bool _isEnabled = true; + AsyncObservableCollection _processesList = new AsyncObservableCollection(); + ICollectionView _processesListDataView; + int _proxifierPort = 5656; + AsyncObservableCollection _routedConnectionsList = new AsyncObservableCollection(); + bool _runOnStartup = true; + string _searchText; + Process _selectedProcess; + RoutedConnection _selectedRoutedConnection; + ServerInfo _serverInfo = new ServerInfo(); + + public ProxifierSettings() + { + ActiveProcessesList = new AsyncObservableCollection(); + } + + public bool AreAllChecked + { + get { return _areAllChecked; } + set + { + _areAllChecked = value; + notifyPropertyChanged("AreAllChecked"); + + foreach (var item in ProcessesList) + item.IsEnabled = value; + } + } + + public ServerInfo DefaultServerInfo + { + get { return _serverInfo; } + set + { + _serverInfo = value; + notifyPropertyChanged("DefaultServerInfo"); + } + } + + [JsonIgnore] + public bool IsEnabled + { + get { return _isEnabled; } + set + { + _isEnabled = value; + notifyPropertyChanged("IsEnabled"); + } + } + + [JsonIgnore] + public AsyncObservableCollection ProcessesList + { + get { return _processesList; } + set + { + _processesList = value; + notifyPropertyChanged("ProcessesList"); + } + } + + public AsyncObservableCollection ActiveProcessesList + { + get; set; + } + + [JsonIgnore] + public ICollectionView ProcessesListDataView + { + get { return _processesListDataView; } + set + { + _processesListDataView = value; + notifyPropertyChanged("ProcessesListDataView"); + } + } + + public int ProxifierPort + { + get { return _proxifierPort; } + set + { + _proxifierPort = value; + notifyPropertyChanged("ProxifierPort"); + } + } + + [JsonIgnore] + public AsyncObservableCollection RoutedConnectionsList + { + get { return _routedConnectionsList; } + set + { + _routedConnectionsList = value; + notifyPropertyChanged("RoutedConnectionsList"); + } + } + + public bool RunOnStartup + { + get { return _runOnStartup; } + set + { + _runOnStartup = value; + notifyPropertyChanged("RunOnStartup"); + } + } + + [JsonIgnore] + public string SearchText + { + get { return _searchText; } + set + { + _searchText = value; + notifyPropertyChanged("SearchText"); + } + } + + [JsonIgnore] + public Process SelectedProcess + { + get { return _selectedProcess; } + set + { + _selectedProcess = value; + notifyPropertyChanged("SelectedProcess"); + } + } + + [JsonIgnore] + public RoutedConnection SelectedRoutedConnection + { + get { return _selectedRoutedConnection; } + set + { + _selectedRoutedConnection = value; + notifyPropertyChanged("SelectedRoutedConnection"); + } + } + + public event PropertyChangedEventHandler PropertyChanged; + private void notifyPropertyChanged(string propertyName) + { + if (PropertyChanged != null) + { + PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + } } \ No newline at end of file diff --git a/ProcessProxifier/Models/ServerInfo.cs b/ProcessProxifier/Models/ServerInfo.cs index c0557b0..f515841 100644 --- a/ProcessProxifier/Models/ServerInfo.cs +++ b/ProcessProxifier/Models/ServerInfo.cs @@ -1,62 +1,50 @@ -using System.ComponentModel; - -namespace ProcessProxifier.Models -{ - public class ServerInfo : INotifyPropertyChanged - { - #region Fields - - ServerType _serverType; - string _serverIP = string.Empty; - int _serverPort; - - #endregion Fields - - #region Properties (4) - - public ServerType ServerType - { - get { return _serverType; } - set - { - _serverType = value; - notifyPropertyChanged("ServerType"); - } - } - - public string ServerIP - { - get { return _serverIP; } - set - { - _serverIP = value; - notifyPropertyChanged("ServerIP"); - } - } - - public int ServerPort - { - get { return _serverPort; } - set - { - _serverPort = value; - notifyPropertyChanged("ServerPort"); - } - } - - #endregion Properties - - - - #region INotifyPropertyChanged Members - public event PropertyChangedEventHandler PropertyChanged; - private void notifyPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } - #endregion - } +using System.ComponentModel; + +namespace ProcessProxifier.Models +{ + public class ServerInfo : INotifyPropertyChanged + { + ServerType _serverType; + string _serverIP = string.Empty; + int _serverPort; + + public ServerType ServerType + { + get { return _serverType; } + set + { + _serverType = value; + notifyPropertyChanged("ServerType"); + } + } + + public string ServerIP + { + get { return _serverIP; } + set + { + _serverIP = value; + notifyPropertyChanged("ServerIP"); + } + } + + public int ServerPort + { + get { return _serverPort; } + set + { + _serverPort = value; + notifyPropertyChanged("ServerPort"); + } + } + + public event PropertyChangedEventHandler PropertyChanged; + private void notifyPropertyChanged(string propertyName) + { + if (PropertyChanged != null) + { + PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + } } \ No newline at end of file diff --git a/ProcessProxifier/ProcessProxifier.csproj b/ProcessProxifier/ProcessProxifier.csproj index aa08c91..994750a 100644 --- a/ProcessProxifier/ProcessProxifier.csproj +++ b/ProcessProxifier/ProcessProxifier.csproj @@ -1,226 +1,232 @@ - - - - Debug - x86 - 8.0.30703 - 2.0 - {0644897E-EB19-44D8-B24F-2CE3C776C623} - WinExe - Properties - ProcessProxifier - ProcessProxifier - v4.0 - - - 512 - {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 4 - - - x86 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - AnyCPU - Bin\ - pdbonly - true - - - network.ico - - - - ..\Libs\DotNet4\FiddlerCore4.dll - - - - - - - - - - - - 4.0 - - - - - - - - MSBuild:Compile - Designer - - - - - - - - - - - - - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - App.xaml - Code - - - - MainWindow.xaml - Code - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - - - Code - - - True - True - Resources.resx - - - True - Settings.settings - True - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Debug + x86 + 8.0.30703 + 2.0 + {0644897E-EB19-44D8-B24F-2CE3C776C623} + WinExe + Properties + ProcessProxifier + ProcessProxifier + v4.0 + + + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + AnyCPU + Bin\ + pdbonly + true + + + network.ico + + + + ..\Libs\DotNet4\FiddlerCore4.dll + + + + ..\packages\Newtonsoft.Json.10.0.2\lib\net40\Newtonsoft.Json.dll + True + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + + + + + + + + + + + + + + + + + + + + + + + + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + + MainWindow.xaml + Code + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ProcessProxifier/Properties/AssemblyInfo.cs b/ProcessProxifier/Properties/AssemblyInfo.cs index 14b03e8..0d51d46 100644 --- a/ProcessProxifier/Properties/AssemblyInfo.cs +++ b/ProcessProxifier/Properties/AssemblyInfo.cs @@ -1,55 +1,53 @@ -using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Windows; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ProcessProxifier")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ProcessProxifier")] -[assembly: AssemblyCopyright("Copyright © vahid_nasiri@yahoo.com 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -//In order to begin building localizable applications, set -//CultureYouAreCodingWith in your .csproj file -//inside a . For example, if you are using US english -//in your source files, set the to en-US. Then uncomment -//the NeutralResourceLanguage attribute below. Update the "en-US" in -//the line below to match the UICulture setting in the project file. - -//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] - - -[assembly: ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) -)] - - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.1.0.0")] -[assembly: AssemblyFileVersion("1.1.0.0")] +using System.Reflection; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ProcessProxifier")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ProcessProxifier")] +[assembly: AssemblyCopyright("Copyright © vahid_nasiri@yahoo.com 2014")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.2.0.0")] +[assembly: AssemblyFileVersion("1.2.0.0")] diff --git a/ProcessProxifier/Utils/ExceptionLogger.cs b/ProcessProxifier/Utils/ExceptionLogger.cs index 63ae50f..0cd0b92 100644 --- a/ProcessProxifier/Utils/ExceptionLogger.cs +++ b/ProcessProxifier/Utils/ExceptionLogger.cs @@ -1,136 +1,132 @@ -using System; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Windows.Forms; - -namespace ProcessProxifier.Utils -{ - public class ExceptionLogger - { - #region Methods (6) - - // Public Methods (2)  - - public static string GetDetailedException(Exception exception) - { - var result = new StringBuilder(); - - var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo(); - - result.AppendLine(string.Format("Application: {0}", Application.ProductName)); - result.AppendLine(string.Format("Path: {0}", Application.ExecutablePath)); - result.AppendLine(string.Format("Version: {0}", Application.ProductVersion)); - result.AppendLine(string.Format("Date: {0}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"))); - result.AppendLine(string.Format("Computer name: {0}", SystemInformation.ComputerName)); - result.AppendLine(string.Format("User name: {0}", SystemInformation.UserName)); - result.AppendLine(string.Format("OSVersion: {0}", computerInfo.OSVersion)); - result.AppendLine(string.Format("OSPlatform: {0}", (Environment.Is64BitOperatingSystem ? "X64" : "X86"))); - result.AppendLine(string.Format("OSFullName: {0}", computerInfo.OSFullName)); - result.AppendLine(string.Format("Culture: {0}", CultureInfo.CurrentCulture.Name)); - result.AppendLine(string.Format("Resolution: {0}", SystemInformation.PrimaryMonitorSize)); - result.AppendLine(string.Format("System up time: {0}", getSystemUpTime())); - result.AppendLine(string.Format("App up time: {0}", (DateTime.Now - Process.GetCurrentProcess().StartTime))); - result.AppendLine(string.Format("Total memory: {0}Mb", computerInfo.TotalPhysicalMemory / (1024 * 1024))); - result.AppendLine(string.Format("Available memory: {0}Mb", computerInfo.AvailablePhysicalMemory / (1024 * 1024))); - //Getting Available Drive Space - var currentDrive = DriveInfo.GetDrives().FirstOrDefault(x => - String.Equals(x.Name, Application.ExecutablePath.Substring(0, 3), StringComparison.CurrentCultureIgnoreCase)); - if (currentDrive != null) - { - result.AppendLine(string.Format("Drive {0}", currentDrive.Name)); - result.AppendLine(string.Format("Volume label: {0}", currentDrive.VolumeLabel)); - result.AppendLine(string.Format("File system: {0}", currentDrive.DriveFormat)); - result.AppendLine(string.Format("Available space to current user: {0} MB", currentDrive.AvailableFreeSpace / (1024 * 1024))); - result.AppendLine(string.Format("Total available space: {0} MB", currentDrive.TotalFreeSpace / (1024 * 1024))); - result.AppendLine(string.Format("Total size of drive: {0} MB ", currentDrive.TotalSize / (1024 * 1024))); - } - - //Get callerInfo - var stackTrace = new StackTrace(); - var stackFrame = stackTrace.GetFrame(2); //caller of LogExceptionToFile - var methodBase = stackFrame.GetMethod(); - var callingType = methodBase.DeclaringType; - result.AppendLine(string.Format("Url: {0} -> {1}", callingType.Assembly.Location, callingType.Assembly.FullName)); - result.AppendLine(string.Format("Caller: {0} -> {1}", callingType.FullName, methodBase.Name)); - - - result.AppendLine("Exception classes: "); - result.AppendLine(getExceptionTypeStack(exception)); - result.AppendLine("Exception messages: "); - result.AppendLine(getExceptionMessageStack(exception)); - result.AppendLine("Stack Traces:"); - result.AppendLine(getExceptionCallStack(exception)); - return result.ToString(); - } - - public static void LogExceptionToFile(object exception, string fileName = "ErrosLog.Log") - { - try - { - string appPath = Path.GetDirectoryName(Application.ExecutablePath); - var errs = GetDetailedException(exception as Exception); - File.AppendAllText( - appPath + "\\" + fileName, - string.Format(@"+-------------------------------------------------------------------+{0}{1}", - Environment.NewLine, errs), Encoding.UTF8); - //todo: send e-mail - } - catch - { - /*کاری نمی‌شود کرد. بدترین حالت ممکن است*/ - } - } - // Private Methods (4)  - - private static string getExceptionCallStack(Exception e) - { - if (e.InnerException != null) - { - var message = new StringBuilder(); - message.AppendLine(getExceptionCallStack(e.InnerException)); - message.AppendLine("--- Next Call Stack:"); - message.AppendLine(e.StackTrace); - return (message.ToString()); - } - return e.StackTrace; - } - - private static string getExceptionMessageStack(Exception e) - { - if (e.InnerException != null) - { - var message = new StringBuilder(); - message.AppendLine(getExceptionMessageStack(e.InnerException)); - message.AppendLine(string.Format(" {0}", e.Message)); - return (message.ToString()); - } - return string.Format(" {0}", e.Message); - } - - private static string getExceptionTypeStack(Exception e) - { - if (e.InnerException != null) - { - var message = new StringBuilder(); - message.AppendLine(getExceptionTypeStack(e.InnerException)); - message.AppendLine(string.Format(" {0}", e.GetType())); - return (message.ToString()); - } - return string.Format(" {0}", e.GetType()); - } - - private static TimeSpan getSystemUpTime() - { - using (var upTime = new PerformanceCounter("System", "System Up Time")) - { - upTime.NextValue(); - return TimeSpan.FromSeconds(upTime.NextValue()); - } - } - - #endregion Methods - } +using System; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace ProcessProxifier.Utils +{ + public class ExceptionLogger + { + // Public Methods (2)  + + public static string GetDetailedException(Exception exception) + { + var result = new StringBuilder(); + + var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo(); + + result.AppendLine(string.Format("Application: {0}", Application.ProductName)); + result.AppendLine(string.Format("Path: {0}", Application.ExecutablePath)); + result.AppendLine(string.Format("Version: {0}", Application.ProductVersion)); + result.AppendLine(string.Format("Date: {0}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"))); + result.AppendLine(string.Format("Computer name: {0}", SystemInformation.ComputerName)); + result.AppendLine(string.Format("User name: {0}", SystemInformation.UserName)); + result.AppendLine(string.Format("OSVersion: {0}", computerInfo.OSVersion)); + result.AppendLine(string.Format("OSPlatform: {0}", (Environment.Is64BitOperatingSystem ? "X64" : "X86"))); + result.AppendLine(string.Format("OSFullName: {0}", computerInfo.OSFullName)); + result.AppendLine(string.Format("Culture: {0}", CultureInfo.CurrentCulture.Name)); + result.AppendLine(string.Format("Resolution: {0}", SystemInformation.PrimaryMonitorSize)); + result.AppendLine(string.Format("System up time: {0}", getSystemUpTime())); + result.AppendLine(string.Format("App up time: {0}", (DateTime.Now - Process.GetCurrentProcess().StartTime))); + result.AppendLine(string.Format("Total memory: {0}Mb", computerInfo.TotalPhysicalMemory / (1024 * 1024))); + result.AppendLine(string.Format("Available memory: {0}Mb", computerInfo.AvailablePhysicalMemory / (1024 * 1024))); + //Getting Available Drive Space + var currentDrive = DriveInfo.GetDrives().FirstOrDefault(x => + String.Equals(x.Name, Application.ExecutablePath.Substring(0, 3), StringComparison.CurrentCultureIgnoreCase)); + if (currentDrive != null) + { + result.AppendLine(string.Format("Drive {0}", currentDrive.Name)); + result.AppendLine(string.Format("Volume label: {0}", currentDrive.VolumeLabel)); + result.AppendLine(string.Format("File system: {0}", currentDrive.DriveFormat)); + result.AppendLine(string.Format("Available space to current user: {0} MB", currentDrive.AvailableFreeSpace / (1024 * 1024))); + result.AppendLine(string.Format("Total available space: {0} MB", currentDrive.TotalFreeSpace / (1024 * 1024))); + result.AppendLine(string.Format("Total size of drive: {0} MB ", currentDrive.TotalSize / (1024 * 1024))); + } + + //Get callerInfo + var stackTrace = new StackTrace(); + var stackFrame = stackTrace.GetFrame(2); //caller of LogExceptionToFile + var methodBase = stackFrame.GetMethod(); + var callingType = methodBase.DeclaringType; + result.AppendLine(string.Format("Url: {0} -> {1}", callingType.Assembly.Location, callingType.Assembly.FullName)); + result.AppendLine(string.Format("Caller: {0} -> {1}", callingType.FullName, methodBase.Name)); + + + result.AppendLine("Exception classes: "); + result.AppendLine(getExceptionTypeStack(exception)); + result.AppendLine("Exception messages: "); + result.AppendLine(getExceptionMessageStack(exception)); + result.AppendLine("Stack Traces:"); + result.AppendLine(getExceptionCallStack(exception)); + return result.ToString(); + } + + public static void LogExceptionToFile(object exception, string fileName = "ErrosLog.Log") + { + try + { + string appPath = Path.GetDirectoryName(Application.ExecutablePath); + var errs = GetDetailedException(exception as Exception); + File.AppendAllText( + appPath + "\\" + fileName, + string.Format(@"+-------------------------------------------------------------------+{0}{1}", + Environment.NewLine, errs), Encoding.UTF8); + //todo: send e-mail + } + catch + { + /*کاری نمی‌شود کرد. بدترین حالت ممکن است*/ + } + } + // Private Methods (4)  + + private static string getExceptionCallStack(Exception e) + { + if (e.InnerException != null) + { + var message = new StringBuilder(); + message.AppendLine(getExceptionCallStack(e.InnerException)); + message.AppendLine("--- Next Call Stack:"); + message.AppendLine(e.StackTrace); + return (message.ToString()); + } + return e.StackTrace; + } + + private static string getExceptionMessageStack(Exception e) + { + if (e.InnerException != null) + { + var message = new StringBuilder(); + message.AppendLine(getExceptionMessageStack(e.InnerException)); + message.AppendLine(string.Format(" {0}", e.Message)); + return (message.ToString()); + } + return string.Format(" {0}", e.Message); + } + + private static string getExceptionTypeStack(Exception e) + { + if (e.InnerException != null) + { + var message = new StringBuilder(); + message.AppendLine(getExceptionTypeStack(e.InnerException)); + message.AppendLine(string.Format(" {0}", e.GetType())); + return (message.ToString()); + } + return string.Format(" {0}", e.GetType()); + } + + private static TimeSpan getSystemUpTime() + { + using (var upTime = new PerformanceCounter("System", "System Up Time")) + { + upTime.NextValue(); + return TimeSpan.FromSeconds(upTime.NextValue()); + } + } + } } \ No newline at end of file diff --git a/ProcessProxifier/Utils/ProcessUtils.cs b/ProcessProxifier/Utils/ProcessUtils.cs new file mode 100644 index 0000000..0c40164 --- /dev/null +++ b/ProcessProxifier/Utils/ProcessUtils.cs @@ -0,0 +1,17 @@ +namespace ProcessProxifier.Utils +{ + public static class ProcessUtils + { + public static string GetPath(this System.Diagnostics.Process process) + { + try + { + return process.MainModule.FileName; + } + catch + { + return string.Empty; + } + } + } +} \ No newline at end of file diff --git a/ProcessProxifier/Utils/SimpleTaskScheduler.cs b/ProcessProxifier/Utils/SimpleTaskScheduler.cs index c32305f..f9f101d 100644 --- a/ProcessProxifier/Utils/SimpleTaskScheduler.cs +++ b/ProcessProxifier/Utils/SimpleTaskScheduler.cs @@ -1,31 +1,31 @@ -using System; -using System.Threading; -using ThreadTimer = System.Threading.Timer; - -namespace ProcessProxifier.Utils -{ - public class SimpleTaskScheduler - { - private ThreadTimer _threadTimer; //keep it alive - - public Action DoWork { set; get; } - - public void Start(long startAfter = 1 * 60 * 1000, long interval = 15*1000) - { - _threadTimer = new ThreadTimer(doWork, null, Timeout.Infinite, 1000); - _threadTimer.Change(startAfter, interval); - } - - public void Stop() - { - if (_threadTimer != null) - _threadTimer.Change(Timeout.Infinite, Timeout.Infinite); - } - - private void doWork(object state) - { - if (DoWork != null) - DoWork(); - } - } +using System; +using System.Threading; +using ThreadTimer = System.Threading.Timer; + +namespace ProcessProxifier.Utils +{ + public class SimpleTaskScheduler + { + private ThreadTimer _threadTimer; //keep it alive + + public Action DoWork { set; get; } + + public void Start(long startAfter = 1 * 60 * 1000, long interval = 15 * 1000) + { + _threadTimer = new ThreadTimer(doWork, null, Timeout.Infinite, 1000); + _threadTimer.Change(startAfter, interval); + } + + public void Stop() + { + if (_threadTimer != null) + _threadTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + private void doWork(object state) + { + if (DoWork != null) + DoWork(); + } + } } \ No newline at end of file diff --git a/ProcessProxifier/ViewModels/MainWindowViewModel.cs b/ProcessProxifier/ViewModels/MainWindowViewModel.cs index 580a258..ead8e1b 100644 --- a/ProcessProxifier/ViewModels/MainWindowViewModel.cs +++ b/ProcessProxifier/ViewModels/MainWindowViewModel.cs @@ -1,214 +1,207 @@ -using System; -using System.ComponentModel; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Data; -using ProcessProxifier.Core; -using ProcessProxifier.Models; -using ProcessProxifier.Utils; - -namespace ProcessProxifier.ViewModels -{ - public class MainWindowViewModel - { - #region Fields (3) - - readonly ProxyRouter _poxyRouter = new ProxyRouter(); - readonly ProxifierSettings _settings; - readonly SimpleTaskScheduler _taskScheduler = new SimpleTaskScheduler(); - - #endregion Fields - - #region Constructors (1) - - public MainWindowViewModel() - { - setupData(); - setupCommands(); - _settings = SettingsManager.LoadSettings(GuiModelData); - manageAppExit(); - Task.Factory.StartNew(() => doStart(string.Empty)); - initTaskScheduler(); - } - - #endregion Constructors - - #region Properties (10) - - public DelegateCommand DoClearLogs { set; get; } - - public DelegateCommand DoClearLogsList { set; get; } - - public DelegateCommand DoCopyAllLines { set; get; } - - public DelegateCommand DoCopySelectedLine { set; get; } - - public DelegateCommand DoRefresh { set; get; } - - public DelegateCommand DoSave { set; get; } - - public DelegateCommand DoStart { set; get; } - - public DelegateCommand DoStop { set; get; } - - public DelegateCommand DoUseDefaultSettings { set; get; } - - public ProxifierSettings GuiModelData { set; get; } - - #endregion Properties - - #region Methods (14) - - // Private Methods (14) - - bool canDoStart(string data) - { - return GuiModelData.IsEnabled; - } - - void currentExit(object sender, ExitEventArgs e) - { - exit(); - } - - void currentSessionEnding(object sender, SessionEndingCancelEventArgs e) - { - exit(); - } - - void doCopyAllLines(string data) - { - var lines = new StringBuilder(); - foreach (var item in GuiModelData.RoutedConnectionsList) - { - lines.AppendLine(string.Format("{0}\t{1}", item.ProcessName, item.Url)); - } - - lines.ToString().ClipboardSetText(); - } - - void doCopySelectedLine(string data) - { - if (GuiModelData.SelectedRoutedConnection == null) return; - (string.Format("{0}\t{1}", GuiModelData.SelectedRoutedConnection.ProcessName, GuiModelData.SelectedRoutedConnection.Url)).ClipboardSetText(); - } - - void doStart(string data) - { - ProcessesListManager.UpdateProcesses(GuiModelData, _settings); - - if (Designer.IsInDesignModeStatic) - return; - - if (string.IsNullOrWhiteSpace(GuiModelData.DefaultServerInfo.ServerIP)) - return; - - _poxyRouter.FiddlerPort = GuiModelData.ProxifierPort; - _poxyRouter.DefaultServerInfo = new ServerInfo - { - ServerIP = GuiModelData.DefaultServerInfo.ServerIP, - ServerPort = GuiModelData.DefaultServerInfo.ServerPort, - ServerType = GuiModelData.DefaultServerInfo.ServerType - }; - _poxyRouter.ProcessesList = GuiModelData.ProcessesList; - _poxyRouter.RoutedConnectionsList = GuiModelData.RoutedConnectionsList; - _poxyRouter.Start(); - GuiModelData.IsEnabled = false; - } - - void doStop(string data) - { - _poxyRouter.Shutdown(); - GuiModelData.RoutedConnectionsList.Clear(); - SettingsManager.SaveSettings(GuiModelData); - GuiModelData.IsEnabled = true; - } - - void doUseDefaultSettings(string data) - { - if (GuiModelData.SelectedProcess == null) - return; - - GuiModelData.SelectedProcess.ServerInfo.ServerType = GuiModelData.DefaultServerInfo.ServerType; - GuiModelData.SelectedProcess.ServerInfo.ServerIP = GuiModelData.DefaultServerInfo.ServerIP; - GuiModelData.SelectedProcess.ServerInfo.ServerPort = GuiModelData.DefaultServerInfo.ServerPort; - } - - private void exit() - { - SettingsManager.SaveSettings(GuiModelData); - _poxyRouter.Shutdown(); - _taskScheduler.Stop(); - } - - void guiModelDataPropertyChanged(object sender, PropertyChangedEventArgs e) - { - switch (e.PropertyName) - { - case "SearchText": - GuiModelData.ProcessesListDataView.Filter = row => - { - if (row == null) return false; - var process = row as Process; - return process != null && - process.Name.StartsWith(GuiModelData.SearchText, StringComparison.InvariantCultureIgnoreCase); - }; - break; - } - } - - private void initTaskScheduler() - { - _taskScheduler.Start(); - _taskScheduler.DoWork = () => - { - try - { - ProcessesListManager.UpdateProcesses(GuiModelData, _settings); - - if (GuiModelData.RoutedConnectionsList.Count > 500) - { - GuiModelData.RoutedConnectionsList.Clear(); - } - } - catch (Exception ex) - { - ExceptionLogger.LogExceptionToFile(ex); - } - }; - } - - private void manageAppExit() - { - Application.Current.Exit += currentExit; - Application.Current.SessionEnding += currentSessionEnding; - } - - private void setupCommands() - { - DoStart = new DelegateCommand(doStart, canDoStart); - DoStop = new DelegateCommand(doStop, data => true); - DoSave = new DelegateCommand(data => SettingsManager.SaveSettings(GuiModelData), data => true); - DoClearLogs = new DelegateCommand(data => GuiModelData.RoutedConnectionsList.Clear(), data => true); - DoClearLogsList = new DelegateCommand(data => GuiModelData.RoutedConnectionsList.Clear(), data => true); - DoUseDefaultSettings = new DelegateCommand(doUseDefaultSettings, data => true); - DoRefresh = new DelegateCommand(data => ProcessesListManager.UpdateProcesses(GuiModelData, _settings), data => true); - DoCopySelectedLine = new DelegateCommand(doCopySelectedLine, data => true); - DoCopyAllLines = new DelegateCommand(doCopyAllLines, data => true); - } - - private void setupData() - { - GuiModelData = new ProxifierSettings - { - RoutedConnectionsList = new AsyncObservableCollection(), - ProcessesList = new AsyncObservableCollection() - }; - GuiModelData.PropertyChanged += guiModelDataPropertyChanged; - GuiModelData.ProcessesListDataView = CollectionViewSource.GetDefaultView(GuiModelData.ProcessesList); - } - - #endregion Methods - } +using System; +using System.ComponentModel; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; +using ProcessProxifier.Core; +using ProcessProxifier.Models; +using ProcessProxifier.Utils; + +namespace ProcessProxifier.ViewModels +{ + public class MainWindowViewModel + { + readonly ProxyRouter _poxyRouter = new ProxyRouter(); + readonly SimpleTaskScheduler _taskScheduler = new SimpleTaskScheduler(); + ProxifierSettings _settings; + + public MainWindowViewModel() + { + setupData(); + setupCommands(); + loadSettings(); + manageAppExit(); + Task.Factory.StartNew(() => doStart(string.Empty)); + initTaskScheduler(); + } + + public DelegateCommand DoClearLogs { set; get; } + + public DelegateCommand DoClearLogsList { set; get; } + + public DelegateCommand DoCopyAllLines { set; get; } + + public DelegateCommand DoCopySelectedLine { set; get; } + + public DelegateCommand DoRefresh { set; get; } + + public DelegateCommand DoSave { set; get; } + + public DelegateCommand DoStart { set; get; } + + public DelegateCommand DoStop { set; get; } + + public DelegateCommand DoUseDefaultSettings { set; get; } + + public ProxifierSettings GuiModelData { set; get; } + + bool canDoStart(string data) + { + return GuiModelData.IsEnabled; + } + + // Private Methods (14) + void currentExit(object sender, ExitEventArgs e) + { + exit(); + } + + void currentSessionEnding(object sender, SessionEndingCancelEventArgs e) + { + exit(); + } + + void doCopyAllLines(string data) + { + var lines = new StringBuilder(); + foreach (var item in GuiModelData.RoutedConnectionsList) + { + lines.AppendLine(string.Format("{0}\t{1}", item.ProcessName, item.Url)); + } + + lines.ToString().ClipboardSetText(); + } + + void doCopySelectedLine(string data) + { + if (GuiModelData.SelectedRoutedConnection == null) return; + string.Format("{0}\t{1}", GuiModelData.SelectedRoutedConnection.ProcessName, GuiModelData.SelectedRoutedConnection.Url).ClipboardSetText(); + } + + void doStart(string data) + { + ProcessesListManager.UpdateProcesses(GuiModelData, _settings); + + if (Designer.IsInDesignModeStatic) + return; + + if (string.IsNullOrWhiteSpace(GuiModelData.DefaultServerInfo.ServerIP)) + return; + + _poxyRouter.FiddlerPort = GuiModelData.ProxifierPort; + _poxyRouter.DefaultServerInfo = new ServerInfo + { + ServerIP = GuiModelData.DefaultServerInfo.ServerIP, + ServerPort = GuiModelData.DefaultServerInfo.ServerPort, + ServerType = GuiModelData.DefaultServerInfo.ServerType + }; + _poxyRouter.ProcessesList = GuiModelData.ProcessesList; + _poxyRouter.RoutedConnectionsList = GuiModelData.RoutedConnectionsList; + _poxyRouter.Start(); + GuiModelData.IsEnabled = false; + } + + void doStop(string data) + { + _poxyRouter.Shutdown(); + GuiModelData.RoutedConnectionsList.Clear(); + saveSettings(); + GuiModelData.IsEnabled = true; + } + + void doUseDefaultSettings(string data) + { + if (GuiModelData.SelectedProcess == null) + return; + + GuiModelData.SelectedProcess.ServerInfo.ServerType = GuiModelData.DefaultServerInfo.ServerType; + GuiModelData.SelectedProcess.ServerInfo.ServerIP = GuiModelData.DefaultServerInfo.ServerIP; + GuiModelData.SelectedProcess.ServerInfo.ServerPort = GuiModelData.DefaultServerInfo.ServerPort; + } + + private void exit() + { + saveSettings(); + _poxyRouter.Shutdown(); + _taskScheduler.Stop(); + } + + void guiModelDataPropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) + { + case "SearchText": + GuiModelData.ProcessesListDataView.Filter = row => + { + if (row == null) return false; + var process = row as Process; + return process != null && + process.Name.StartsWith(GuiModelData.SearchText, StringComparison.InvariantCultureIgnoreCase); + }; + break; + } + } + + private void initTaskScheduler() + { + _taskScheduler.Start(); + _taskScheduler.DoWork = () => + { + try + { + ProcessesListManager.UpdateProcesses(GuiModelData, _settings); + + if (GuiModelData.RoutedConnectionsList.Count > 500) + { + GuiModelData.RoutedConnectionsList.Clear(); + } + } + catch (Exception ex) + { + ExceptionLogger.LogExceptionToFile(ex); + } + }; + } + + private void loadSettings() + { + _settings = SettingsManager.LoadSettings(GuiModelData); + } + + private void manageAppExit() + { + Application.Current.Exit += currentExit; + Application.Current.SessionEnding += currentSessionEnding; + } + + private void saveSettings() + { + SettingsManager.SaveSettings(GuiModelData, _settings); + } + + private void setupCommands() + { + DoStart = new DelegateCommand(doStart, canDoStart); + DoStop = new DelegateCommand(doStop, data => true); + DoSave = new DelegateCommand(data => saveSettings(), data => true); + DoClearLogs = new DelegateCommand(data => GuiModelData.RoutedConnectionsList.Clear(), data => true); + DoClearLogsList = new DelegateCommand(data => GuiModelData.RoutedConnectionsList.Clear(), data => true); + DoUseDefaultSettings = new DelegateCommand(doUseDefaultSettings, data => true); + DoRefresh = new DelegateCommand(data => ProcessesListManager.UpdateProcesses(GuiModelData, _settings), data => true); + DoCopySelectedLine = new DelegateCommand(doCopySelectedLine, data => true); + DoCopyAllLines = new DelegateCommand(doCopyAllLines, data => true); + } + + private void setupData() + { + GuiModelData = new ProxifierSettings + { + RoutedConnectionsList = new AsyncObservableCollection(), + ProcessesList = new AsyncObservableCollection() + }; + GuiModelData.PropertyChanged += guiModelDataPropertyChanged; + GuiModelData.ProcessesListDataView = CollectionViewSource.GetDefaultView(GuiModelData.ProcessesList); + } + } } \ No newline at end of file diff --git a/ProcessProxifier/packages.config b/ProcessProxifier/packages.config new file mode 100644 index 0000000..4415b0d --- /dev/null +++ b/ProcessProxifier/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file