public static string InitLogDir(string?alias = null)
        {
            var logDirPath = Path.Combine(AppContext.BaseDirectory, "Logs");

            IOPath.DirCreateByNotExists(logDirPath);
#if StartupTrace
            StartupTrace.Restart("InitLogDir.IO");
#endif
            var logDirPath_ = logDirPath + Path.DirectorySeparatorChar;

            InternalLogger.LogFile  = logDirPath_ + "internal-nlog" + alias + ".txt";
            InternalLogger.LogLevel = NLogLevel.Error;
            var objConfig = new LoggingConfiguration();
            var logfile   = new FileTarget("logfile")
            {
                FileName = logDirPath_ + "nlog-all-${shortdate}" + alias + ".log",
                Layout   = "${longdate}|${level}|${logger}|${message} |${all-event-properties} ${exception:format=tostring}",
            };
            objConfig.AddTarget(logfile);
            objConfig.AddRule(NLogLevel.Error, NLogLevel.Fatal, logfile, "Microsoft.*");
            objConfig.AddRule(NLogLevel.Error, NLogLevel.Fatal, logfile, "System.Net.Http.*");
            objConfig.AddRule(AppHelper.DefaultNLoggerMinLevel, NLogLevel.Fatal, logfile, "*");
#if StartupTrace
            StartupTrace.Restart("InitLogDir.CreateLoggingConfiguration");
#endif
            LogManager.Configuration = objConfig;

            return(logDirPath);
        }
Beispiel #2
0
        public MainWindow() : base()
        {
            InitializeComponent();

#if WINDOWS
            //var wp = this.FindControl<WallpaperControl>("DesktopBackground");
            var panel = this.FindControl <Panel>("Panel");
            var wp    = new WallpaperControl();
            wp.Bind(WallpaperControl.IsVisibleProperty, new Binding
            {
                Source = UISettings.EnableDesktopBackground,
                Mode   = BindingMode.OneWay,
                Path   = nameof(UISettings.EnableDesktopBackground.Value)
            });
            panel.Children.Insert(0, wp);
            _backHandle = wp.Handle;
#endif

#if DEBUG
            this.AttachDevTools();
#endif
#if StartupTrace
            StartupTrace.Restart("MainWindow.ctor");
#endif
        }
Beispiel #3
0
        public MainWindow() : base()
        {
            InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif
#if StartupTrace
            StartupTrace.Restart("MainWindow.ctor");
#endif
        }
Beispiel #4
0
    public override void DidFinishLaunching(NSNotification notification)
#endif
    {
        var args = new string[0];

        StartupTrace.WriteLine("Startup: Reached AppDelegate.DidFinishLaunching / AppDelegate.FinishedLaunching");

        ErrorProtection.RunEarly(() => ProtectedStartup(args));
        ErrorProtection.RunMain(_kernel.TryGet <IErrorReport>(), ProtectedRun);
    }
Beispiel #5
0
        static void ConfigureServices(IServiceCollection services, StartupOptions options)
        {
            ConfigureRequiredServices(services, options);
#if StartupTrace
            StartupTrace.Restart("DI.ConfigureRequiredServices");
#endif
            ConfigureDemandServices(services, options);
#if StartupTrace
            StartupTrace.Restart("DI.ConfigureDemandServices");
#endif
        }
Beispiel #6
0
                    static void ConfigureServices(IServiceCollection services, DILevel level)
                    {
                        ConfigureRequiredServices(services);
#if StartupTrace
                        StartupTrace.Restart("DI.ConfigureRequiredServices");
#endif
                        ConfigureDemandServices(services, level);
#if StartupTrace
                        StartupTrace.Restart("DI.ConfigureDemandServices");
#endif
                    }
Beispiel #7
0
        static int Main(string[] args)
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
            }
            catch (NotSupportedException)
            {
            }

#if WINDOWS_DESKTOP_BRIDGE
            if (!DesktopBridgeHelper.Init())
            {
                return(0);
            }
            DesktopBridgeHelper.OnActivated(ref args);
#elif !__MOBILE__
#if MAC
            AppDelegate.Init(/*args*/);
            FileSystemDesktopMac.InitFileSystem();
#elif LINUX
            FileSystemDesktopXDG.InitFileSystem();
#elif WINDOWS
            FileSystemDesktopWindows.InitFileSystem();
#else
            FileSystem2.InitFileSystem();
#endif
#endif
#if StartupTrace
            StartupTrace.Restart();
#endif
            // 目前桌面端默认使用 SystemTextJson 如果出现兼容性问题可取消下面这行代码
            // Serializable.DefaultJsonImplType = Serializable.JsonImplType.NewtonsoftJson;
            IsMainProcess = args.Length == 0;
            IsCLTProcess  = !IsMainProcess && args.FirstOrDefault() == "-clt";

            IApplication.InitLogDir();
#if StartupTrace
            StartupTrace.Restart("InitLogDir");
#endif

            //void InitCefNetApp() => CefNetApp.Init(AppHelper.LogDirPath, args);
            Startup.InitGlobalExceptionHandler();
            try
            {
                string[] args_clt;
                if (IsCLTProcess) // 命令行模式
                {
                    args_clt = args.Skip(1).ToArray();
                    if (args_clt.Length == 1 && args_clt[0].Equals(command_main, StringComparison.OrdinalIgnoreCase))
                    {
                        return(default);
Beispiel #8
0
        /// <summary>
        /// 初始化启动
        /// </summary>
        public static void Init(DILevel level)
        {
            if (!isInitialized)
            {
                isInitialized = true;
#if !__MOBILE__
                FileSystemDesktop.InitFileSystem();
#if StartupTrace
                StartupTrace.Restart("Startup.InitFileSystem");
#endif
#endif
                if (level.HasFlag(DILevel.ServerApiClient))
                {
                    ModelValidatorProvider.Init();
#if StartupTrace
                    StartupTrace.Restart("ModelValidatorProvider.Init");
#endif
                }
                InitDI(level);
#if StartupTrace
                StartupTrace.Restart($"InitDI: {level}");
Beispiel #9
0
    public static void Main(string[] args)
    {
        if (args.Contains("--debug-startup"))
        {
            StartupTrace.EmitStartupTrace = true;
        }

        NSApplication.Init();

        StartupTrace.WriteLine("Startup: Finished NSApplication.Init in static Main");

        using (var p = new NSAutoreleasePool())
        {
            NSApplication.SharedApplication.Delegate = new AppDelegate();

            // TODO: Offer a way of setting the application icon.
            //NSImage appIcon = NSImage.ImageNamed("monogameicon.png");
            //NSApplication.SharedApplication.ApplicationIconImage = appIcon;

            NSApplication.Main(args);
        }
    }
Beispiel #10
0
        /// <summary>
        /// 初始化启动
        /// </summary>
        public static void Init(DILevel level)
        {
            if (!isInitialized)
            {
                isInitialized = true;
#if StartupTrace
                StartupTrace.Restart("Startup.InitFileSystem");
#endif
                var options = new StartupOptions(level);
                if (options.HasServerApiClient)
                {
                    ModelValidatorProvider.Init();
#if StartupTrace
                    StartupTrace.Restart("ModelValidatorProvider.Init");
#endif
                }
                InitDI(options);
#if StartupTrace
                StartupTrace.Restart($"InitDI: {level}");
#endif
                if (!Essentials.IsSupported)
                {
                    // 在 Xamarin.Essentials 支持的平台上由平台 Application 初始化时调用
                    // 通常在 DI 之前,例如 Android 上的 MainApplication.OnCreate
                    VersionTracking2.Track();
#if StartupTrace
                    StartupTrace.Restart($"VersionTracking2.Track");
#endif
                }

                Migrations.Up();
#if StartupTrace
                StartupTrace.Restart($"Migrations.Up");
#endif
            }
        }
Beispiel #11
0
        /// <summary>
        /// 配置按需使用的依赖注入服务
        /// </summary>
        /// <param name="services"></param>
        static void ConfigureDemandServices(IServiceCollection services, StartupOptions options)
        {
#if !UI_DEMO
            // 平台服务 此项放在其他通用业务实现服务之前
            services.AddPlatformService(options);
#endif
#if StartupTrace
            StartupTrace.Restart("DI.ConfigureDemandServices.Calc");
#endif
            services.AddDnsAnalysisService();
#if !CONSOLEAPP
            if (options.HasGUI)
            {
                services.AddPinyin();
#if __MOBILE__
                services.TryAddFontManager();
#else
                services.TryAddAvaloniaFontManager(useGdiPlusFirst: true);
#endif
                // 添加 Toast 提示服务
#if !DEBUG
                services.AddStartupToastIntercept();
#endif
                services.TryAddToast();

                services.AddSingleton <IApplication>(_ => PlatformApplication.Instance);
#if __ANDROID__
                services.AddSingleton <IAndroidApplication>(_ => PlatformApplication.Instance);
#endif
#if __MOBILE__
                // 添加电话服务
                services.AddTelephonyService();

                //services.AddMSALPublicClientApp(AppSettings.MASLClientId);
#else
                services.AddSingleton <IAvaloniaApplication>(_ => PlatformApplication.Instance);
                services.TryAddSingleton <IClipboardPlatformService>(_ => PlatformApplication.Instance);

                // 添加主线程助手(MainThreadDesktop)
                services.AddMainThreadPlatformService();

                services.TryAddFilePickerPlatformService();
#endif
                #region MessageBox

                /* System.Windows.MessageBox 在 WPF 库中,仅支持 Win 平台
                 * 改为 System.Windows.MessageBoxCompat 可跨平台兼容
                 * 在其他平台上使用 MessageBox.Avalonia 库实现
                 * API变更说明:
                 * - 如果需要获取返回值,即点击那个按钮,则使用异步版本 ShowAsync
                 * - 如果不需要获取返回值,则可直接使用 同步版本 Show
                 * 注意事项:
                 * - 图标(Icon)与按钮(Button)不要使用标记为 Obsolete 的
                 * - WPF 中 显示窗口(Show)会锁死父窗口等,类似 ShowDialog
                 * - MessageBox.Avalonia 中则不会锁死窗口
                 * 已知问题:
                 * - 在 MessageBox.Avalonia 中
                 *  - 如果内容文本(messageBoxText)过短 UI 上的文字显示不全
                 *  - 点击窗口按 Ctrl+C 无法复制弹窗中的文本内容
                 *  - 按钮文本(ButtonText)缺少本地化翻译(Translate)
                 *  - 某些图标图片与枚举值不太匹配,例如 Information
                 */
                services.TryAddWindowManager();

#if WINDOWS
                // 可选项,在 Win 平台使用 WPF 实现的 MessageBox
                //services.AddSingleton<IMessageBoxCompatService, WPFMessageBoxCompatService>();
#endif

                #endregion

                // 添加管理主窗口服务
                services.AddViewModelManager();

                services.TryAddBiometricService();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.GUI");
#endif
            }
#endif
            if (options.HasHttpClientFactory
#if !CONSOLEAPP
                || options.HasServerApiClient
#endif
                )
            {
                // 添加 Http 平台助手桌面端或移动端实现
                services.TryAddClientHttpPlatformHelperService();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.ClientHttpPlatformHelperService");
#endif
            }

            if (options.HasHttpClientFactory)
            {
#if __MOBILE__
                // 添加 HttpClientFactory 平台原生实现
                services.AddNativeHttpClient();
#endif
                // 通用 Http 服务
                services.AddHttpService();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.HttpClientFactory");
#endif
            }
            services.TryAddScriptManager();
#if StartupTrace
            StartupTrace.Restart("DI.ConfigureDemandServices.ScriptManager");
#endif

#if !CONSOLEAPP
            if (options.HasHttpProxy)
            {
                // 通用 Http 代理服务
                services.AddHttpProxyService();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.HttpProxy");
#endif
            }
#endif
#if !CONSOLEAPP
            if (options.HasServerApiClient)
            {
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.AppSettings");
#endif
                // 添加模型验证框架
                services.TryAddModelValidator();

                // 添加服务端API调用
                services.TryAddCloudServiceClient <CloudServiceClient>(c =>
                {
#if NETCOREAPP3_0_OR_GREATER
                    c.DefaultRequestVersion = HttpVersion.Version30;
#endif
                }, configureHandler:
#if NETCOREAPP2_1_OR_GREATER
                                                                       () => new SocketsHttpHandler
                {
                    UseCookies             = false,
                    AutomaticDecompression = DecompressionMethods.Brotli | DecompressionMethods.GZip,
                }
#elif __ANDROID__
                                                                       () =>
                {
                    var handler                    = PlatformHttpMessageHandlerBuilder.CreateAndroidClientHandler();
                    handler.UseCookies             = false;
                    handler.AutomaticDecompression = DecompressionMethods.GZip;
                    return(handler);
                }
#else
                                                                       null
#endif
                                                                       );

                services.AddAutoMapper();

                // 添加仓储服务
                services.AddRepositories();

                // 业务平台用户管理
                services.TryAddUserManager();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.ServerApiClient");
#endif
            }
#endif
#if !CONSOLEAPP
            // 添加通知服务
            AddNotificationService();
#if StartupTrace
            StartupTrace.Restart("DI.ConfigureDemandServices.AddNotificationService");
#endif
            void AddNotificationService()
            {
#if !__MOBILE__
                if (!Program.IsMainProcess)
                {
                    return;
                }
#endif
                services.TryAddNotificationService();
            }
#endif
#if !CONSOLEAPP
            if (options.HasHosts)
            {
                // hosts 文件助手服务
                services.AddHostsFileService();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.HostsFileService");
#endif
            }
#endif
            if (options.HasSteam)
            {
#if !__ANDROID__
                // Steam 相关助手、工具类服务
                services.AddSteamService();
#endif

                // Steamworks LocalApi Service
                services.TryAddSteamworksLocalApiService();

                // SteamDb WebApi Service
                services.AddSteamDbWebApiService();

                // Steamworks WebApi Service
                services.AddSteamworksWebApiService();

                // ASF Service
                services.AddArchiSteamFarmService();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.Steam");
#endif
            }
#if !CONSOLEAPP
            if (options.HasMainProcessRequired)
            {
                // 应用程序更新服务
                services.AddApplicationUpdateService();
#if StartupTrace
                StartupTrace.Restart("DI.ConfigureDemandServices.AppUpdateService");
#endif
            }
#endif
        }
Beispiel #12
0
            public static int Run(string[] args)
            {
                if (args.Length == 0)
                {
                    args = new[] { "-h" }
                }
                ;

                // https://docs.microsoft.com/zh-cn/archive/msdn-magazine/2019/march/net-parse-the-command-line-with-system-commandline
                var rootCommand = new RootCommand("命令行工具(Command Line Tools/CLT)");

                void MainHandler() => MainHandler_(null);

                void MainHandler_(Action?onInitStartuped)
                {
#if StartupTrace
                    StartupTrace.Restart("ProcessCheck");
#endif
                    Startup.Init(IsMainProcess ? DILevel.MainProcess : DILevel.Min);
#if StartupTrace
                    StartupTrace.Restart("Startup.Init");
#endif
                    onInitStartuped?.Invoke();
                    if (IsMainProcess)
                    {
                        var isInitAppInstanceReset = false;
                        initAppInstance : appInstance = new();
                        if (!appInstance.IsFirst)
                        {
                            //Console.WriteLine("ApplicationInstance.SendMessage(string.Empty);");
                            if (IApplication.SingletonInstance.SendMessage(string.Empty))
                            {
                                return;
                            }
                            else
                            {
                                if (!isInitAppInstanceReset &&
                                    IApplication.SingletonInstance.TryKillCurrentAllProcess())
                                {
                                    isInitAppInstanceReset = true;
                                    appInstance.Dispose();
                                    goto initAppInstance;
                                }
                                else
                                {
                                    return;
                                }
                            }
                        }
                        appInstance.MessageReceived += value =>
                        {
                            if (string.IsNullOrEmpty(value))
                            {
                                var app = App.Instance;
                                if (app != null)
                                {
                                    MainThread2.BeginInvokeOnMainThread(app.RestoreMainWindow);
                                }
                            }
                        };
                    }
                    //#if StartupTrace
                    //                    StartupTrace.Restart("ApplicationInstance");
                    //#endif
                    //                    initCef();
                    //#if StartupTrace
                    //                    StartupTrace.Restart("InitCefNetApp");
                    //#endif
                    if (IsMainProcess)
                    {
                        BuildAvaloniaAppAndStartWithClassicDesktopLifetime(args);
                    }
#if StartupTrace
                    StartupTrace.Restart("InitAvaloniaApp");
#endif
                }

                void MainHandlerByCLT() => MainHandlerByCLT_(null);

                void MainHandlerByCLT_(Action?onInitStartuped)
                {
                    IsMainProcess = true;
                    IsCLTProcess  = false;
                    MainHandler_(onInitStartuped);
                }

#if DEBUG
                // -clt debug -args 730
                var debug = new Command("debug", "调试");
                debug.AddOption(new Option <string>("-args", () => "", "测试参数"));
                debug.Handler = CommandHandler.Create((string args) => // 参数名与类型要与 Option 中一致!
                {
                    //Console.WriteLine("-clt debug -args " + args);
                    // OutputType WinExe 导致控制台输入不会显示,只能附加一个新的控制台窗口显示内容,不合适
                    // 如果能取消 管理员权限要求,改为运行时管理员权限,
                    // 则可尝试通过 Windows Terminal 或直接 Host 进行命令行模式
                    MainHandlerByCLT();
                });
                rootCommand.AddCommand(debug);
#endif

                var main = new Command(command_main)
                {
                    Handler = CommandHandler.Create(MainHandler)
                };
                rootCommand.AddCommand(main);

                // -clt devtools
                // -clt devtools -disable_gpu
                // -clt devtools -use_wgl
                var devtools = new Command("devtools");
                devtools.AddOption(new Option <bool>("-disable_gpu", () => false, "禁用 GPU 硬件加速"));
                devtools.AddOption(new Option <bool>("-use_wgl", () => false, "使用 Native OpenGL(仅 Windows)"));
                devtools.Handler = CommandHandler.Create((bool disable_gpu, bool use_wgl) =>
                {
                    IApplication.EnableDevtools = true;
                    IApplication.DisableGPU     = disable_gpu;
                    IApplication.UseWgl         = use_wgl;
                    MainHandlerByCLT_(onInitStartuped: () =>
                    {
                        IApplication.LoggerMinLevel = LogLevel.Debug;
                    });
                });
                rootCommand.AddCommand(devtools);

                // -clt c -silence
                var common = new Command("c", "common");
                common.AddOption(new Option <bool>("-silence", "静默启动(不弹窗口)"));
                common.Handler = CommandHandler.Create((bool silence) =>
                {
                    IsMinimize = silence;
                    MainHandlerByCLT();
                });
                rootCommand.AddCommand(common);

                // -clt steam -account
                var steamuser = new Command("steam", "Steam相关操作");
                steamuser.AddOption(new Option <string>("-account", "指定对应steam用户名"));
                steamuser.Handler = CommandHandler.Create((string account) =>
                {
                    if (!string.IsNullOrEmpty(account))
                    {
                        Startup.Init(DILevel.Steam);
                        ISteamService.Instance.TryKillSteamProcess();
                        ISteamService.Instance.SetCurrentUser(account);
                        ISteamService.Instance.StartSteam();
                    }
                });
                rootCommand.AddCommand(steamuser);

                // -clt app -id 632360
                var unlock_achievement = new Command("app", "打开成就解锁窗口");
                unlock_achievement.AddOption(new Option <int>("-id", "指定一个Steam游戏Id"));
                unlock_achievement.AddOption(new Option <bool>("-silence", "挂运行服务,不加载窗口,内存占用更小"));
                unlock_achievement.Handler = CommandHandler.Create(async(int id, bool silence) =>
                {
                    try
                    {
                        if (id <= 0)
                        {
                            return;
                        }
                        if (!silence)
                        {
                            Startup.Init(DILevel.GUI | DILevel.Steam | DILevel.HttpClientFactory);
                            IViewModelManager.Instance.InitUnlockAchievement(id);
                            BuildAvaloniaAppAndStartWithClassicDesktopLifetime(args);
                        }
                        else
                        {
                            Startup.Init(DILevel.Steam);
                            SteamConnectService.Current.Initialize(id);
                            TaskCompletionSource tcs = new();
                            await tcs.Task;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(nameof(unlock_achievement), ex, "Start");
                    }
                });
                rootCommand.AddCommand(unlock_achievement);

                var r = rootCommand.InvokeAsync(args).Result;
                return(r);
            }
        }