예제 #1
0
        static void Main(string[] args)
        {
#if !_CONSOLE
            using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif
                Directory.SetCurrentDirectory(Application.StartupPath);
                //#if !DEBUG
                Logging.OpenLogFile();
                //#endif
#if !_CONSOLE
                int try_times = 0;
                while (Configuration.Load() == null)
                {
                    if (try_times >= 5)
                        return;
                    InputPassword dlg = new InputPassword();
                    dlg.ShowDialog();
                    Configuration.SetPassword(dlg.password);
                    try_times += 1;
                }
#endif
                _controller = new ShadowsocksController();

#if !_CONSOLE
                _viewController = new MenuViewController(_controller);
#endif

                _controller.Start();

#if !_CONSOLE
                //Util.Utils.ReleaseMemory();

                Application.Run();
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }
예제 #2
0
        static void Main(string[] args)
        {
#if !_CONSOLE
            foreach (string arg in args)
            {
                if (arg == "--setautorun")
                {
                    if (!Controller.AutoStartup.Switch())
                    {
                        Environment.ExitCode = 1;
                    }
                    return;
                }
            }
            using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + Environment.NewLine +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif
                Directory.SetCurrentDirectory(Application.StartupPath);

#if !_CONSOLE
                int try_times = 0;
                while (Configuration.Load() == null)
                {
                    if (try_times >= 5)
                        return;
                    using (InputPassword dlg = new InputPassword())
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                            Configuration.SetPassword(dlg.password);
                        else
                            return;
                    }
                    try_times += 1;
                }
#endif

                _controller = new ShadowsocksController();
                HostMap.Instance().LoadHostFile();

                // Logging
                Configuration cfg = _controller.GetConfiguration();
                Logging.save_to_file = cfg.logEnable;

                //#if !DEBUG
                if (try_times > 0)
                    Logging.save_to_file = false;
                Logging.OpenLogFile();
                //#endif

#if _DOTNET_4_0
                // Enable Modern TLS when .NET 4.5+ installed.
                if (Util.EnvCheck.CheckDotNet45())
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#endif
#if !_CONSOLE
                _viewController = new MenuViewController(_controller);
#endif

                _controller.Start();

#if !_CONSOLE
                //Util.Utils.ReleaseMemory();

                Application.Run();
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }
예제 #3
0
파일: Program.cs 프로젝트: wiriya4777/boy
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Utils.GetExecutablePath()));
#if !_CONSOLE
            foreach (var arg in args)
            {
                if (arg == "--setautorun")
                {
                    if (!AutoStartup.Switch())
                    {
                        Environment.ExitCode = 1;
                    }
                    return;
                }
            }
            using (var mutex = new Mutex(false, "Global\\ShadowsocksR_" + Directory.GetCurrentDirectory().GetDeterministicHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + Environment.NewLine +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif

#if !_CONSOLE
                var tryTimes = 0;
                while (Configuration.Load() == null)
                {
                    if (tryTimes >= 5)
                        return;
                    using (var dlg = new InputPassword())
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                            Configuration.SetPassword(dlg.password);
                        else
                            return;
                    }
                    tryTimes += 1;
                }
#endif

                _controller = new ShadowsocksController();
                HostMap.Instance().LoadHostFile();

                // Logging
                Logging.DefaultOut = Console.Out;
                Logging.DefaultError = Console.Error;

#if _DOTNET_4_0
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

#endif
#if !_CONSOLE
                _viewController = new MenuViewController(_controller);
                SystemEvents.SessionEnding += _viewController.Quit_Click;
#endif

                _controller.Start();

#if !_CONSOLE

                Application.Run();
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }
        private void ButBalance_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                _saleOrder.HowBalance = RadBanlanceModeCash.IsChecked.HasValue && RadBanlanceModeCash.IsChecked.Value
                    ? (SByte)DataType.SaleOrderBalancedMode.Cash
                    : RadBanlanceModeCard.IsChecked.HasValue && RadBanlanceModeCard.IsChecked.Value
                        ? (SByte)DataType.SaleOrderBalancedMode.MemberCard
                        : (SByte)DataType.SaleOrderBalancedMode.UnitUnionPay;

                foreach (var soProduceDomainModel in _soProduceDomainModels)
                {
                    if (soProduceDomainModel.SOProduce.Quantity < 0 &&
                        string.IsNullOrEmpty(soProduceDomainModel.SOProduce.Description))
                    {
                        MessageBox.Show(string.Format("商品'{0}'数量小于零,确认数量或填写备注说明。", soProduceDomainModel.SOProduce.Produce.Name),
                                        Properties.Resources.SystemName,
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    else if (ResourcesHelper.CurrentUserRolePermission.SaleOrderFavorableLimitCost &&
                             soProduceDomainModel.SOProduce.DiscountRate <
                             soProduceDomainModel.SOProduce.Produce.LowestDiscountRate)
                    {
                        MessageBox.Show(string.Format("商品'{0}'折扣过低, 要赔钱了!", soProduceDomainModel.SOProduce.Produce.Name),
                                        Properties.Resources.SystemName,
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }

                if (_balanceDomainModel.DiscountPrice > 0)
                {
                    if (!ResourcesHelper.CurrentUserRolePermission.SaleOrderFavorableCost &&
                        _balanceDomainModel.DiscountPrice > float.Parse(ResourcesHelper.SystemSettings[(short)DataType.SystemSettingCode.SOProduceGeneralMangerMaxDiscountPrice]))
                    {
                        MessageBox.Show("结算失败, 优惠金额超过上限, 要赔钱卖了!", Properties.Resources.SystemName,
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (_balanceDomainModel.DiscountPrice > _balanceDomainModel.TotalPrice)
                    {
                        MessageBox.Show("结算失败, 优惠金额大于应收金额, 要赔钱卖了!", Properties.Resources.SystemName,
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }

                if (RadBanlanceModeCash.IsChecked != null && (bool)RadBanlanceModeCash.IsChecked)
                {
                    if ((_balanceDomainModel.ReturnedPrice < 0))
                    {
                        MessageBox.Show("结算失败, 实收金额小于应收金额, 要多找钱了!", Properties.Resources.SystemName,
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (_user.UserId > 0)
                    {
                        _user.Userlogs.Add(new Userlog
                        {
                            ChangedBy   = ResourcesHelper.CurrentUser.Name,
                            LogType     = (sbyte)DataType.MemberCardLogType.Consumption,
                            DateChanged = DateTime.Now,
                            NewValue    = string.Format(
                                ResourcesHelper.UserLogSaleOrderFormat,
                                _saleOrder.SaleOrderNo,
                                CommonHelper.Enumerate <DataType.SaleOrderBalancedMode>().First(x => x.Key == _saleOrder.HowBalance).Value,
                                _balanceDomainModel.ReceivedPrice.ToString("F2"),
                                _balanceDomainModel.CurrentMemberPoints.ToString("F2"),
                                (_balanceDomainModel.SurplusPrice > 0 ? _balanceDomainModel.SurplusPrice : 0).ToString("F2"),
                                (_balanceDomainModel.CurrentMemberPoints + _balanceDomainModel.MemberPoints).ToString("F2"))
                        });

                        _saleOrder.PurchaseOrderUserId = _user.UserId == 0 ? (int?)null : _user.UserId;
                        _user.MemberPoints            += _balanceDomainModel.ReceivedPrice * float.Parse(ResourcesHelper.SystemSettings[(short)DataType.SystemSettingCode.MemberPointsRate]);

                        _userRepository.Update(_user);
                    }
                }
                else if (RadBanlanceModeCard.IsChecked != null && (bool)RadBanlanceModeCard.IsChecked)
                {
                    if (_memberCard.MemberCardId > 0)
                    {
                        if (_balanceDomainModel.SurplusPrice < 0 ||
                            _memberCard.TotalSurplusMoney - _balanceDomainModel.ReceivedPrice < 0)
                        {
                            MessageBox.Show("结算失败, 购物卡余额不足, 请用充值或现金结算!", Properties.Resources.SystemName,
                                            MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }

                        InputPassword inputPassword = new InputPassword(_memberCard.MemberCardId);
                        inputPassword.ShowDialog();
                        if (!inputPassword.IsCheckOK)
                        {
                            return;
                        }

                        float saveMoney = _balanceDomainModel.ReceivedPrice *
                                          (_memberCard.PrincipalSurplusMoney / _memberCard.TotalSurplusMoney);

                        if (_memberCard.FavorableSurplusMoney >= (_balanceDomainModel.ReceivedPrice - saveMoney))
                        {
                            _memberCard.FavorableSurplusMoney -= (_balanceDomainModel.ReceivedPrice - saveMoney);
                            _memberCard.PrincipalSurplusMoney -= saveMoney;
                        }
                        else
                        {
                            _memberCard.PrincipalSurplusMoney -= _balanceDomainModel.ReceivedPrice -
                                                                 _memberCard.FavorableSurplusMoney;
                            _memberCard.FavorableSurplusMoney -= _memberCard.FavorableSurplusMoney;
                        }
                        _memberCard.TotalSurplusMoney -= _balanceDomainModel.ReceivedPrice;

                        _memberCard.MemberCardlogs.Add(new DataModel.Model.MemberCardLog
                        {
                            FavorableMoney = (_balanceDomainModel.ReceivedPrice - saveMoney),
                            PrincipalMoney = saveMoney,
                            LogType        = (sbyte)DataType.MemberCardLogType.Consumption,
                            ChangedBy      = ResourcesHelper.CurrentUser.Name,
                            DateChanged    = DateTime.Now,
                            NewValue       = string.Format(ResourcesHelper.MemberCardLogSaleOrderFormat,
                                                           _saleOrder.SaleOrderNo,
                                                           CommonHelper.Enumerate <DataType.SaleOrderBalancedMode>()
                                                           .First(x => x.Key == _saleOrder.HowBalance)
                                                           .Value,
                                                           _balanceDomainModel.ReceivedPrice.ToString("F2"),
                                                           _balanceDomainModel.CurrentMemberPoints.ToString("F2"),
                                                           (_balanceDomainModel.SurplusPrice > 0 ? _balanceDomainModel.SurplusPrice : 0)
                                                           .ToString("F2"),
                                                           (_balanceDomainModel.CurrentMemberPoints + _balanceDomainModel.MemberPoints)
                                                           .ToString("F2"))
                        });
                        _memberCardRepository.Update(_memberCard);
                    }

                    if (_user.UserId > 0)
                    {
                        float saveMoney = _balanceDomainModel.ReceivedPrice *
                                          (_user.CashBalance / _user.CashTotal);

                        if (_user.CashFee >= (_balanceDomainModel.ReceivedPrice - saveMoney))
                        {
                            _user.CashFee     -= (_balanceDomainModel.ReceivedPrice - saveMoney);
                            _user.CashBalance -= saveMoney;
                        }
                        else
                        {
                            _user.CashBalance -= _balanceDomainModel.ReceivedPrice - _user.CashFee;
                            _user.CashFee     -= _user.CashFee;
                        }
                        _user.CashTotal -= _balanceDomainModel.ReceivedPrice;

                        _user.Userlogs.Add(new Userlog
                        {
                            ChangedBy   = ResourcesHelper.CurrentUser.Name,
                            DateChanged = DateTime.Now,
                            LogType     = (sbyte)DataType.MemberCardLogType.Consumption,
                            NewValue    = string.Format(
                                ResourcesHelper.UserLogSaleOrderFormat,
                                _saleOrder.SaleOrderNo,
                                CommonHelper.Enumerate <DataType.SaleOrderBalancedMode>()
                                .First(x => x.Key == _saleOrder.HowBalance)
                                .Value,
                                _balanceDomainModel.ReceivedPrice.ToString("F2"),
                                _balanceDomainModel.CurrentMemberPoints.ToString("F2"),
                                (_balanceDomainModel.SurplusPrice > 0 ? _balanceDomainModel.SurplusPrice : 0).ToString(
                                    "F2"),
                                (_balanceDomainModel.CurrentMemberPoints + _balanceDomainModel.MemberPoints).ToString(
                                    "F2"))
                        });

                        _saleOrder.PurchaseOrderUserId = _user.UserId == 0 ? (int?)null : _user.UserId;
                        _user.MemberPoints            += _balanceDomainModel.ReceivedPrice *
                                                         float.Parse(
                            ResourcesHelper.SystemSettings[
                                (short)DataType.SystemSettingCode.MemberPointsRate]);

                        _userRepository.Update(_user);
                    }
                }
                else
                {
                    _balanceDomainModel.RealPrice = _balanceDomainModel.ReceivedPrice;
                    if (_user.UserId > 0)
                    {
                        _user.Userlogs.Add(new Userlog
                        {
                            ChangedBy   = ResourcesHelper.CurrentUser.Name,
                            DateChanged = DateTime.Now,
                            LogType     = (sbyte)DataType.MemberCardLogType.Consumption,
                            NewValue    = string.Format(
                                ResourcesHelper.UserLogSaleOrderFormat,
                                _saleOrder.SaleOrderNo,
                                CommonHelper.Enumerate <DataType.SaleOrderBalancedMode>().First(x => x.Key == _saleOrder.HowBalance).Value,
                                _balanceDomainModel.ReceivedPrice.ToString("F2"),
                                _balanceDomainModel.CurrentMemberPoints.ToString("F2"),
                                (_balanceDomainModel.SurplusPrice > 0 ? _balanceDomainModel.SurplusPrice : 0).ToString("F2"),
                                (_balanceDomainModel.CurrentMemberPoints + _balanceDomainModel.MemberPoints).ToString("F2"))
                        });

                        _saleOrder.PurchaseOrderUserId = _user.UserId == 0 ? (int?)null : _user.UserId;
                        _user.MemberPoints            += _balanceDomainModel.ReceivedPrice * float.Parse(ResourcesHelper.SystemSettings[(short)DataType.SystemSettingCode.MemberPointsRate]);

                        _userRepository.Update(_user);
                    }
                }

                SaveSaleOrder(DataType.SaleOrderStatus.Balanced);

                _saleOrder.FavorableCost = _balanceDomainModel.DiscountPrice;
                _saleOrder.TotalCost     = _balanceDomainModel.ReceivedPrice;
                _saleOrder.SOProduces.ForEach(x =>
                {
                    x.Produce.Quantity -= (x.Quantity ?? 0);
                    x.Produce.Producelogs.Add(new Producelog
                    {
                        ChangedBy   = ResourcesHelper.CurrentUser.Name,
                        DateChanged = DateTime.Now,
                        NewValue    = string.Format(ResourcesHelper.ProduceLogSaleOrderFormat,
                                                    _saleOrder.SaleOrderNo,
                                                    (x.Quantity ?? 0).ToString("F2"),
                                                    (x.CostPerUnit ?? 0).ToString("F2"),
                                                    x.Produce.Quantity.ToString("F2"))
                    });
                });
                _saleOrder.SaleOrderStatus = (sbyte)DataType.SaleOrderStatus.Balanced;
                _unitOfWork.Commit();

                if (ResourcesHelper.CurrentUser.UserType != (byte)DataType.UserType.Admin)
                {
                    try
                    {
                        SaleOrderReportPrint.Print(_saleOrder);

                        MessageBox.Show("结算成功!", Properties.Resources.SystemName,
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    catch (Exception ex)
                    {
                        Log4NetHelper.WriteLog(ex.ToString());

                        MessageBox.Show("结算成功, 打印小票失败!", Properties.Resources.SystemName,
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }

                SaleOrderWindow.ExecuteSearchText();
                Close();
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteLog(ex.ToString());
                MessageBox.Show("结算失败, 请重新新建零售记录!", SmallHoneybee.Wpf.Properties.Resources.SystemName,
                                MessageBoxButton.OK, MessageBoxImage.Error);

                SaleOrderWindow.ExecuteSearchText();
                Close();
            }
        }
        static void Main(string[] args)
        {
#if !_CONSOLE
            foreach (string arg in args)
            {
                if (arg == "--setautorun")
                {
                    if (!Controller.AutoStartup.Switch())
                    {
                        Environment.ExitCode = 1;
                    }
                    return;
                }
            }
            using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif
                Directory.SetCurrentDirectory(Application.StartupPath);
                //#if !DEBUG
                Logging.OpenLogFile();
                //#endif
#if !_CONSOLE
                int try_times = 0;
                while (Configuration.Load() == null)
                {
                    if (try_times >= 5)
                        return;
                    using (InputPassword dlg = new InputPassword())
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                            Configuration.SetPassword(dlg.password);
                        else
                            return;
                    }
                    try_times += 1;
                }
#endif
                //  _controller = new ShadowsocksController();
                // HostMap.Instance().LoadHostFile();
#if !_CONSOLE
                //   _viewController = new MenuViewController(_controller);
#endif

                // _controller.Start();

#if !_CONSOLE
                //  Util.Utils.ReleaseMemory();

                // Application.Run(new UserLoginForm());
                Application.Run(new ConfigForm(new ShadowsocksController(), new UpdateChecker(), 1));
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }
예제 #6
0
        static void Main(string[] args)
        {

            if (Utils.IsVirusExist())
            {
                return;
            }
#if !_CONSOLE
                foreach (string arg in args)
            {
                if (arg == "--setautorun")
                {
                    if (!AutoStartup.Switch())
                    {
                        Environment.ExitCode = 1;
                    }
                    return;
                }
            }

            using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);
                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif
                Directory.SetCurrentDirectory(Application.StartupPath);

#if !_CONSOLE
                int try_times = 0;
                while (Configuration.Load() == null)
                {
                    if (try_times >= 5)
                        return;
                    using (InputPassword dlg = new InputPassword())
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                            Configuration.SetPassword(dlg.password);
                        else
                            return;
                    }
                    try_times += 1;
                }
                //if (try_times > 0)
                //    Logging.save_to_file = false;
#endif

                Logging.OpenLogFile();

                ServicePointManager.DefaultConnectionLimit = 512;
#if _DOTNET_4_0
                // Enable Modern TLS when .NET 4.5+ installed.
                if (EnvCheck.CheckDotNet45())
                    ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12;//(SecurityProtocolType)3072;
                if (EnvCheck.CheckDotNet471())
                    ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls13;
#endif
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;


                _controller = new ShadowsocksController();
                HostMap.Instance().LoadHostFile();

#if !_CONSOLE
                _viewController = new MenuViewController(_controller);
#endif
                _controller.Start();
                SystemEvents.SessionEnding += _viewController.Quit_Click;

#if !_CONSOLE

                foreach (string arg in args)
                {
                    if (arg == "-Direct")
                    {
                        _viewController.DirectItem_Click();
                        break;
                    }
                    else if(arg == "-Pac")
                    {
                        _viewController.PACModeItem_Click();
                        break;
                    }
                    else if(arg == "-Global")
                    {
                        _viewController.GlobalModeItem_Click();
                        break;
                    }
                }

                Application.Run();
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }
예제 #7
0
        private static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Utils.GetExecutablePath()));
            if (args.Any(arg => arg == @"--setautorun"))
            {
                if (!AutoStartup.Switch())
                {
                    Environment.ExitCode = 1;
                }
                return;
            }

            using var mutex = new Mutex(false, $@"Global\ShadowsocksR_{Directory.GetCurrentDirectory().GetDeterministicHashCode()}");
            if (!mutex.WaitOne(0, false))
            {
                MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + Environment.NewLine +
                                I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                I18N.GetString("ShadowsocksR is already running."));
                return;
            }

            var app = new Application
            {
                ShutdownMode = ShutdownMode.OnExplicitShutdown
            };

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            System.Windows.Forms.Application.EnableVisualStyles();
            System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
            app.Exit += App_Exit;

            var tryTimes = 0;

            while (Configuration.Load() == null)
            {
                if (tryTimes >= 5)
                {
                    return;
                }
                using (var dlg = new InputPassword())
                {
                    if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Configuration.SetPassword(dlg.password);
                    }
                    else
                    {
                        return;
                    }
                }
                tryTimes += 1;
            }

            _controller = new ShadowsocksController();
            HostMap.Instance().LoadHostFile();

            // Logging
            Logging.DefaultOut   = Console.Out;
            Logging.DefaultError = Console.Error;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            _viewController             = new MenuViewController(_controller);
            SystemEvents.SessionEnding += _viewController.Quit_Click;

            _controller.Start();
            app.Run();
        }