Exemple #1
0
        private static void UpdateAppInfoFile()
        {
            ResetAppInfoFile();
            if (_appInfo?.Count > 430)
            {
                goto Shareware;
            }

            foreach (var mirror in AppSupply.GetMirrors(AppSuppliers.Internal))
            {
                var link = PathEx.AltCombine(mirror, ".free", "AppInfo.ini");
                if (Log.DebugMode > 0)
                {
                    Log.Write($"Cache: Looking for '{link}'.");
                }
                if (NetEx.FileIsAvailable(link, 30000, UserAgents.Internal))
                {
                    WebTransfer.DownloadFile(link, CachePaths.AppInfo, 60000, UserAgents.Internal, false);
                }
                if (!File.Exists(CachePaths.AppInfo))
                {
                    continue;
                }
                break;
            }

            var blacklist = Array.Empty <string>();

            if (File.Exists(CachePaths.AppInfo))
            {
                blacklist = Ini.GetSections(CachePaths.AppInfo).Where(x => Ini.Read(x, "Disabled", false, CachePaths.AppInfo)).ToArray();
                UpdateAppInfoData(CachePaths.AppInfo, blacklist);
            }

            var tmpDir = Path.Combine(CorePaths.TempDir, DirectoryEx.GetUniqueName());

            if (!DirectoryEx.Create(tmpDir))
            {
                return;
            }
            var tmpZip = Path.Combine(tmpDir, "AppInfo.7z");

            foreach (var mirror in AppSupply.GetMirrors(AppSuppliers.Internal))
            {
                var link = PathEx.AltCombine(mirror, ".free", "AppInfo.7z");
                if (Log.DebugMode > 0)
                {
                    Log.Write($"Cache: Looking for '{link}'.");
                }
                if (NetEx.FileIsAvailable(link, 30000, UserAgents.Internal))
                {
                    WebTransfer.DownloadFile(link, tmpZip, 60000, UserAgents.Internal, false);
                }
                if (!File.Exists(tmpZip))
                {
                    continue;
                }
                break;
            }
            if (!File.Exists(tmpZip))
            {
                var link = PathEx.AltCombine(AppSupplierHosts.PortableApps, "updater", "update.7z");
                if (Log.DebugMode > 0)
                {
                    Log.Write($"Cache: Looking for '{link}'.");
                }
                if (NetEx.FileIsAvailable(link, 60000, UserAgents.Empty))
                {
                    WebTransfer.DownloadFile(link, tmpZip, 60000, UserAgents.Empty, false);
                }
            }
            if (File.Exists(tmpZip))
            {
                using (var process = SevenZip.DefaultArchiver.Extract(tmpZip, tmpDir))
                    if (process?.HasExited == false)
                    {
                        process.WaitForExit();
                    }
                FileEx.TryDelete(tmpZip);
            }
            var tmpIni = DirectoryEx.GetFiles(tmpDir, "*.ini").FirstOrDefault();

            if (!File.Exists(tmpIni))
            {
                DirectoryEx.TryDelete(tmpDir);
                return;
            }
            UpdateAppInfoData(tmpIni, blacklist);

            FileEx.Serialize(CachePaths.AppInfo, AppInfo, true);
            DirectoryEx.TryDelete(tmpDir);

Shareware:
            if (!Shareware.Enabled)
            {
                return;
            }

            foreach (var srv in Shareware.GetAddresses())
            {
                var key = Shareware.FindAddressKey(srv);
                var usr = Shareware.GetUser(srv);
                var pwd = Shareware.GetPassword(srv);
                var url = PathEx.AltCombine(srv, "AppInfo.ini");
                if (Log.DebugMode > 0)
                {
                    Log.Write($"Shareware: Looking for '{{{key.Encode()}}}/AppInfo.ini'.");
                }
                if (!NetEx.FileIsAvailable(url, usr, pwd, 60000, UserAgents.Default))
                {
                    continue;
                }
                var appInfo = WebTransfer.DownloadString(url, usr, pwd, 60000, UserAgents.Default);
                if (string.IsNullOrWhiteSpace(appInfo))
                {
                    continue;
                }
                var srvKey = key?.Decode(BinaryToTextEncoding.Base85);
                UpdateAppInfoData(appInfo, null, srvKey?.Any() == true ? new ReadOnlyCollection <byte>(srvKey) : default);
            }
        }
Exemple #2
0
        /// <summary>
        ///     Enables/disables the file redirection.
        /// </summary>
        /// <param name="option">
        ///     The option that determines whether the redirect will be enabled or disabled.
        /// </param>
        /// <param name="fileMap">
        ///     The file map.
        ///     <para>
        ///         The key is used for the source file, and the value is used for the destination
        ///         file.
        ///     </para>
        /// </param>
        /// <param name="simple">
        ///     true to copy &amp; paste the specified files; otherwise, false to create symbolic links.
        /// </param>
        public static void FileRedirection(PortalizerActions option, Dictionary <string, string> fileMap, bool simple = false)
        {
            if (fileMap?.Any() != true)
            {
                return;
            }
            var hash  = nameof(FileRedirection).Encrypt();
            var hPath = PathEx.Combine(Attributes.TempDir, hash);

            switch (option)
            {
            case PortalizerActions.Disable:
                FileEx.TryDelete(hPath);
                break;

            default:
                if (File.Exists(hPath))
                {
                    FileRedirection(PortalizerActions.Disable, fileMap, simple);
                }
                FileEx.Create(hPath);
                break;
            }
            foreach (var data in fileMap)
            {
                if (string.IsNullOrWhiteSpace(data.Key) || string.IsNullOrWhiteSpace(data.Value))
                {
                    continue;
                }
                var    srcPath = data.Key;
                string srcFile;
                try
                {
                    srcFile = Path.GetFileName(srcPath);
                    if (string.IsNullOrEmpty(srcFile))
                    {
                        throw new ArgumentNullException(nameof(srcFile));
                    }
                    if (!srcFile.Contains('*'))
                    {
                        srcPath = PathEx.Combine(srcPath);
                    }
                    else
                    {
                        var srcDir = PathEx.GetDirectoryName(srcPath);
                        if (string.IsNullOrEmpty(srcDir))
                        {
                            throw new ArgumentNullException(nameof(srcDir));
                        }
                        srcDir  = PathEx.Combine(srcDir);
                        srcPath = string.Concat(srcDir, Path.DirectorySeparatorChar, srcFile);
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                    continue;
                }
                if (string.IsNullOrWhiteSpace(srcFile))
                {
                    continue;
                }
                var  destDir  = PathEx.Combine(data.Value);
                var  destPath = PathEx.Combine(destDir, srcFile);
                bool doSimple;
                try
                {
                    if (srcPath.Contains('*'))
                    {
                        doSimple = true;
                    }
                    else
                    {
                        doSimple = simple;
                        if (!File.Exists(destPath))
                        {
                            if (string.IsNullOrEmpty(destDir))
                            {
                                throw new ArgumentNullException(nameof(destDir));
                            }
                            if (!Directory.Exists(destDir))
                            {
                                Directory.CreateDirectory(destDir);
                            }
                            File.Create(destPath).Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                    continue;
                }
                var backupPath = $"{srcPath}-{{{EnvironmentEx.MachineId}}}.backup";
                switch (option)
                {
                case PortalizerActions.Disable:
                    if (doSimple)
                    {
                        try
                        {
                            if (srcPath.Contains('*'))
                            {
                                var dir = PathEx.GetDirectoryName(srcPath);
                                if (string.IsNullOrEmpty(dir))
                                {
                                    continue;
                                }
                                var pattern = Path.GetFileName(srcPath);
                                if (string.IsNullOrEmpty(pattern))
                                {
                                    continue;
                                }
                                dir = PathEx.Combine(dir);
                                foreach (var file in Directory.EnumerateFiles(dir, pattern, SearchOption.TopDirectoryOnly))
                                {
                                    var name = Path.GetFileName(file);
                                    if (string.IsNullOrEmpty(name))
                                    {
                                        continue;
                                    }
                                    var path = PathEx.Combine(destDir, name);
                                    if (File.Exists(path))
                                    {
                                        File.Delete(path);
                                    }
                                    File.Move(file, path);
                                }
                                continue;
                            }
                            srcPath = PathEx.Combine(srcPath);
                            if (File.Exists(srcPath))
                            {
                                File.Copy(srcPath, destPath, true);
                                if (File.Exists(destPath))
                                {
                                    File.Delete(srcPath);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                        }
                        continue;
                    }
                    FileEx.SetAttributes(backupPath, FileAttributes.Normal);
                    if (Elevation.IsAdministrator && FileEx.DestroySymbolicLink(srcPath, true))
                    {
                        continue;
                    }
                    try
                    {
                        srcPath = PathEx.Combine(srcPath);
                        if (File.Exists(srcPath))
                        {
                            FileEx.SetAttributes(srcPath, FileAttributes.Normal);
                            File.Copy(srcPath, destPath, true);
                            File.Delete(srcPath);
                        }
                        if (File.Exists(backupPath))
                        {
                            File.Copy(backupPath, srcPath, true);
                            File.Delete(backupPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    break;

                default:
                    if (doSimple)
                    {
                        try
                        {
                            if (srcPath.Contains('*'))
                            {
                                var pattern = Path.GetFileName(srcPath);
                                if (string.IsNullOrEmpty(pattern))
                                {
                                    continue;
                                }
                                foreach (var file in Directory.EnumerateFiles(destDir, pattern, SearchOption.TopDirectoryOnly))
                                {
                                    var dir = Path.GetDirectoryName(srcPath);
                                    if (string.IsNullOrEmpty(dir))
                                    {
                                        continue;
                                    }
                                    var name = Path.GetFileName(file);
                                    if (string.IsNullOrEmpty(name))
                                    {
                                        continue;
                                    }
                                    var path = PathEx.Combine(dir, name);
                                    File.Copy(file, path, true);
                                }
                                continue;
                            }
                            srcPath = PathEx.Combine(srcPath);
                            if (File.Exists(destPath) && (!File.Exists(srcPath) || File.GetLastWriteTime(destPath) > File.GetLastWriteTime(srcPath)))
                            {
                                File.Copy(destPath, srcPath, true);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                        }
                        continue;
                    }
                    if (Elevation.IsAdministrator && FileEx.CreateSymbolicLink(srcPath, destPath, true))
                    {
                        FileEx.SetAttributes(backupPath, FileAttributes.Hidden);
                        continue;
                    }
                    try
                    {
                        srcPath = PathEx.Combine(srcPath);
                        if (File.Exists(srcPath))
                        {
                            if (!File.Exists(backupPath))
                            {
                                File.Copy(srcPath, backupPath);
                                FileEx.SetAttributes(backupPath, FileAttributes.Hidden);
                            }
                            File.Delete(srcPath);
                        }
                        if (!File.Exists(destPath))
                        {
                            var dir = Path.GetDirectoryName(destPath);
                            if (string.IsNullOrEmpty(dir))
                            {
                                continue;
                            }
                            if (!Directory.Exists(dir))
                            {
                                Directory.CreateDirectory(dir);
                            }
                            File.Create(destPath).Close();
                        }
                        FileEx.SetAttributes(backupPath, FileAttributes.Normal);
                        File.Copy(destPath, srcPath, true);
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    break;
                }
            }
        }
        private async Task CopyDirectoryAsync(IFileOperationsExecuter fileOps, string sourcePath, string targetPath, IOperationExecutionContext context)
        {
            if (!await fileOps.DirectoryExistsAsync(sourcePath).ConfigureAwait(false))
            {
                this.LogWarning($"Source directory {sourcePath} does not exist.");
                return;
            }

            var infos = await fileOps.GetFileSystemInfosAsync(
                sourcePath,
                new MaskingContext(this.Includes, this.Excludes)
                ).ConfigureAwait(false);

            var files = infos.OfType <SlimFileInfo>();

            foreach (var file in files)
            {
                context.CancellationToken.ThrowIfCancellationRequested();

                var targetFileName = PathEx.Combine(targetPath, file.FullName.Substring(sourcePath.Length).TrimStart('/', '\\'));
                if (this.VerboseLogging)
                {
                    this.LogDebug($"Copying {file.FullName} to {targetFileName}...");
                }

                try
                {
                    if (!this.Overwrite && await fileOps.FileExistsAsync(targetFileName).ConfigureAwait(false))
                    {
                        this.LogError($"Target file {targetFileName} already exists and overwrite is set to false.");
                        continue;
                    }

                    await fileOps.CreateDirectoryAsync(file.DirectoryName).ConfigureAwait(false);

                    await fileOps.CopyFileAsync(file.FullName, targetFileName, this.Overwrite).ConfigureAwait(false);

                    this.filesCopied++;
                }
                catch (Exception ex)
                {
                    this.LogError($"Cannot copy {file.FullName}: {ex.Message}");
                }
            }

            var dirs = infos.OfType <SlimDirectoryInfo>();

            foreach (var dir in dirs)
            {
                context.CancellationToken.ThrowIfCancellationRequested();

                var targetDir = PathEx.Combine(targetPath, dir.FullName.Substring(sourcePath.Length).TrimStart('/', '\\'));
                if (this.VerboseLogging)
                {
                    this.LogDebug($"Creating directory {targetDir}...");
                }

                await fileOps.CreateDirectoryAsync(targetDir).ConfigureAwait(false);

                this.directoriesCopied++;
            }
        }
Exemple #4
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                var source = NetEx.Transfer.DownloadString(Resources.RegexFirstUrl);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.RegexSecBtnMatch)).Take(1).Join();
                foreach (Match match in Regex.Matches(source, Resources.RegexSecUrlPattern, RegexOptions.Singleline))
                {
                    var mUrl = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mUrl))
                    {
                        continue;
                    }
                    source = NetEx.Transfer.DownloadString(mUrl);
                    if (string.IsNullOrWhiteSpace(source))
                    {
                        throw new ArgumentNullException(nameof(source));
                    }
                    source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.RegexThirdBtnMatch) || !Resources.RegexThirdExtMatch.SplitNewLine().Any(y => x.ContainsEx(y))).Take(1).Join();
                    foreach (Match match2 in Regex.Matches(source, Resources.RegexThirdUrlPattern, RegexOptions.Singleline))
                    {
                        mUrl = match2.Groups[1].ToString();
                        if (string.IsNullOrWhiteSpace(mUrl))
                        {
                            continue;
                        }
                        if (mUrl.ContainsEx("/show/"))
                        {
                            mUrl = mUrl.Replace("/show/", "/get/");
                        }
                        updUrl = mUrl;
                        break;
                    }
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
        internal static async Task RunKubeCtlAsync(this ILogSink log, IOperationExecutionContext context, IEnumerable <string> args, Action <string> logOutput = null, Action <string> logError = null, Func <int?, bool> handleExit = null, CancellationToken?cancellationToken = null)
        {
            var fileOps = await context.Agent.TryGetServiceAsync <ILinuxFileOperationsExecuter>() ?? await context.Agent.GetServiceAsync <IFileOperationsExecuter>();

            var procExec = await context.Agent.GetServiceAsync <IRemoteProcessExecuter>();

            var escapeArg = fileOps is ILinuxFileOperationsExecuter ? (Func <string, string>)Utils.EscapeLinuxArg : Utils.EscapeWindowsArg;

            var startInfo = new RemoteProcessStartInfo
            {
                FileName         = "kubectl",
                Arguments        = string.Join(" ", (args ?? new string[0]).Where(arg => arg != null).Select(escapeArg)),
                WorkingDirectory = context.WorkingDirectory
            };

            log.LogDebug($"Working directory: {startInfo.WorkingDirectory}");
            await fileOps.CreateDirectoryAsync(startInfo.WorkingDirectory);

            log.LogDebug($"Running command: {escapeArg(startInfo.FileName)} {startInfo.Arguments}");

            int?exitCode;

            using (var process = procExec.CreateProcess(startInfo))
            {
                process.OutputDataReceived += (s, e) => (logOutput ?? log.LogInformation)(e.Data);
                process.ErrorDataReceived  += (s, e) => (logError ?? log.LogError)(e.Data);
                process.Start();
                await process.WaitAsync(cancellationToken ?? context.CancellationToken);

                exitCode = process.ExitCode;
            }

            if (handleExit?.Invoke(exitCode) == true)
            {
                return;
            }

            if (exitCode == 0)
            {
                log.LogInformation("Process exit code indicates success.");
                return;
            }

            log.LogError($"Process exit code indicates failure. ({AH.CoalesceString(exitCode, "(unknown)")})");

            // Command failed. Try to give a better error message if kubectl isn't even installed.
            var verifyInstalledStartInfo = new RemoteProcessStartInfo
            {
                FileName         = fileOps is ILinuxFileOperationsExecuter ? "/usr/bin/which" : "System32\\where.exe",
                Arguments        = escapeArg(startInfo.FileName),
                WorkingDirectory = context.WorkingDirectory
            };

            if (fileOps is ILinuxFileOperationsExecuter)
            {
                verifyInstalledStartInfo.Arguments = "-- " + verifyInstalledStartInfo.Arguments;
            }
            else
            {
                verifyInstalledStartInfo.FileName = PathEx.Combine(await procExec.GetEnvironmentVariableValueAsync("SystemRoot"), verifyInstalledStartInfo.FileName);
            }

            using (var process = procExec.CreateProcess(verifyInstalledStartInfo))
            {
                // Don't care about output.
                process.Start();
                await process.WaitAsync(cancellationToken ?? context.CancellationToken);

                // 0 = file exists, anything other than 0 or 1 = error trying to run which/where.exe
                if (process.ExitCode == 1)
                {
                    log.LogWarning("Is kubectl installed and in the PATH?");
                }
            }
        }
        public void ConfigureServices(IServiceCollection services)
        {
            #pragma warning disable ASP0000
            var serverSettings = services
                                 .UseAttributeScanner(s => s.AddService <ServerSettings>())
                                 .BuildServiceProvider()
                                 .GetRequiredService <ServerSettings>();
            #pragma warning restore ASP0000

            services.AddResponseCompression(opts => {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });
            // Logging
            services.AddLogging(logging => {
                logging.ClearProviders();
                logging.AddConsole();
                logging.SetMinimumLevel(LogLevel.Information);
                if (Env.IsDevelopment())
                {
                    logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Information);
                    logging.AddFilter("Stl.Fusion.Operations", LogLevel.Information);
                }
            });

            // DbContext & related services
            var appTempDir = PathEx.GetApplicationTempDirectory("", true);
            var dbPath     = appTempDir & "App.db";
            services.AddDbContextFactory <AppDbContext>(builder => {
                builder.UseSqlite($"Data Source={dbPath}", sqlite => { });
                if (Env.IsDevelopment())
                {
                    builder.EnableSensitiveDataLogging();
                }
            });
            services.AddDbContextServices <AppDbContext>(b => {
                // This is the best way to add DbContext-related services from Stl.Fusion.EntityFramework
                b.AddDbOperations((_, o) => {
                    // We use FileBasedDbOperationLogChangeMonitor, so unconditional wake up period
                    // can be arbitrary long - all depends on the reliability of Notifier-Monitor chain.
                    o.UnconditionalWakeUpPeriod = TimeSpan.FromSeconds(Env.IsDevelopment() ? 60 : 5);
                });
                b.AddFileBasedDbOperationLogChangeTracking(dbPath + "_changed");
                if (!serverSettings.UseInMemoryAuthService)
                {
                    b.AddDbAuthentication();
                }
                b.AddKeyValueStore();
            });

            // Fusion services
            services.AddSingleton(new Publisher.Options()
            {
                Id = serverSettings.PublisherId
            });
            var fusion       = services.AddFusion();
            var fusionServer = fusion.AddWebServer();
            var fusionClient = fusion.AddRestEaseClient();
            var fusionAuth   = fusion.AddAuthentication().AddServer(
                signInControllerOptionsBuilder: (_, options) => {
                options.DefaultScheme = MicrosoftAccountDefaults.AuthenticationScheme;
            });

            // This method registers services marked with any of ServiceAttributeBase descendants, including:
            // [Service], [ComputeService], [RestEaseReplicaService], [LiveStateUpdater]
            services.UseAttributeScanner()
            .AddServicesFrom(typeof(TodoService).Assembly)
            .AddServicesFrom(Assembly.GetExecutingAssembly());
            // Registering shared services from the client
            UI.Program.ConfigureSharedServices(services);

            services.AddAuthentication(options => {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(options => {
                options.LoginPath  = "/signIn";
                options.LogoutPath = "/signOut";
                if (Env.IsDevelopment())
                {
                    options.Cookie.SecurePolicy = CookieSecurePolicy.None;
                }
            }).AddMicrosoftAccount(options => {
                options.ClientId     = serverSettings.MicrosoftAccountClientId;
                options.ClientSecret = serverSettings.MicrosoftAccountClientSecret;
                // That's for personal account authentication flow
                options.AuthorizationEndpoint      = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
                options.TokenEndpoint              = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
                options.CorrelationCookie.SameSite = SameSiteMode.Lax;
            }).AddGitHub(options => {
                options.ClientId     = serverSettings.GitHubClientId;
                options.ClientSecret = serverSettings.GitHubClientSecret;
                options.Scope.Add("read:user");
                options.Scope.Add("user:email");
                options.CorrelationCookie.SameSite = SameSiteMode.Lax;
            });

            // Web
            services.AddRouting();
            services.AddMvc().AddApplicationPart(Assembly.GetExecutingAssembly());
            services.AddServerSideBlazor(o => o.DetailedErrors = true);
            fusionAuth.AddBlazor(o => { }); // Must follow services.AddServerSideBlazor()!

            // Swagger & debug tools
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Templates.Blazor1 API", Version = "v1"
                });
            });
        }
Exemple #7
0
        private static void executeDocker(string[] args)
        {
            var nArgs = CLIHelper.GetNamedArguments(args);

            switch (args[1]?.ToLower())
            {
            case "gen":
            {
                var tmpOutp = nArgs.GetValueOrDefault("output");
                if (tmpOutp.IsNullOrWhitespace() || tmpOutp == "./" || tmpOutp == "\\" || tmpOutp == "/")
                {
                    tmpOutp = Environment.CurrentDirectory;
                    Console.WriteLine($"Output is set to be the current console directory: {tmpOutp}");
                }

                var output = tmpOutp.ToDirectoryInfo();
                Console.WriteLine($"Directory output is set to: {output.FullName}");

                var configInfo = nArgs["config"].ToFileInfo();

                if (!configInfo.Exists)
                {
                    throw new Exception($"Can't find config file: '{configInfo.FullName}'.");
                }
                else
                {
                    Console.WriteLine($"Config file set to: {configInfo.FullName}");
                }

                var config = configInfo.ReadAllText().JsonDeserialize <DockergenConfig>();
                config.workingDirectory = config.workingDirectory.CoalesceNullOrWhitespace($"/{Guid.NewGuid()}");
                config.relativePath     = config.relativePath.CoalesceNullOrWhitespace("/");

                if (config.version != 1)
                {
                    throw new Exception($"Incompatible config version, was: {config.version}, but expected 1");
                }

                var imageName   = nArgs["image-name"];
                var force       = nArgs.GetValueOrDefault("force", "false").ToBoolOrDefault() || config.force;
                var exposedPort = nArgs.GetValueOrDefault("exposed-port", "80").ToIntOrDefault(80);

                if (force)
                {
                    output.Create();
                }

                if (!output.Exists)
                {
                    throw new Exception($"Directory not found: '{output.FullName}'.");
                }
                else
                {
                    Console.WriteLine($"Output directory: {output.FullName}");
                }

                var nginxConfigInfo = PathEx.RuntimeCombine(
                    output.FullName,
                    config.relativePath,
                    "nginx.conf").ToFileInfo();

                if (force)
                {
                    nginxConfigInfo.TryDelete();
                }
                else
                {
                    Console.WriteLine($"Nginx config directory: {nginxConfigInfo.FullName}");
                }

                var useEnginx = config.port != exposedPort && !nginxConfigInfo.Exists;
                if (useEnginx)
                {
                    Console.WriteLine($"Generating nginx configuration in: '{nginxConfigInfo.FullName}'");

                    var nginxConfig = NginxConfigGenerator.GetSinglePortProxy(
                        sourcePort: exposedPort, destinationPort: config.port);

                    nginxConfigInfo.WriteAllText(nginxConfig);
                    Console.WriteLine($"Nginx Config: \n'{nginxConfig}'");
                }
                else
                {
                    Console.WriteLine($"Nginx configuration will not be set because defined application port ({config.port}) is the same as exposed port ({exposedPort}) and request proxy is not needed or nginx config is already defined ({nginxConfigInfo.Exists}).");
                }

                var dockerComposeInfo = PathEx.RuntimeCombine(
                    output.FullName,
                    config.relativePath,
                    "docker-compose.app.yml").ToFileInfo();

                if (force)
                {
                    dockerComposeInfo.TryDelete();
                }

                if (!dockerComposeInfo.Exists)
                {
                    Console.WriteLine($"Generating docker compose file in: '{dockerComposeInfo.FullName}'");

                    var dockerCompose = DockerfileConfigGenerator.GetDockerCompose(
                        imageName: imageName,
                        port: exposedPort,
                        exposedPorts: config.exposedPorts,
                        portsMap: config.portsMap);

                    dockerComposeInfo.WriteAllText(dockerCompose);
                    Console.WriteLine($"Docker Compose: \n'{dockerCompose}'");
                }
                else
                {
                    Console.WriteLine($"Docker Compose file was not creaed because it already existed.");
                }


                var envFileInfo = PathEx.RuntimeCombine(
                    output.FullName,
                    config.relativePath,
                    ".env").ToFileInfo();

                if (force)
                {
                    envFileInfo.TryDelete();
                }

                if (!envFileInfo.Exists)
                {
                    Console.WriteLine($"Generating Env file: '{envFileInfo.FullName}'");

                    if (!envFileInfo.Exists)
                    {
                        envFileInfo.Create().Close();
                    }

                    if (!config.env.IsNullOrEmpty())
                    {
                        var text = envFileInfo.ReadAllText() + "\r\n";

                        foreach (var line in config.env)
                        {
                            text += line.Trim() + "\r\n";
                        }

                        text = text.Trim("\r\n");

                        envFileInfo.WriteAllText(text, System.IO.Compression.CompressionLevel.NoCompression, mode: FileMode.Create);
                    }

                    Console.WriteLine($"Env file: \n'{envFileInfo.ReadAllText()}'");
                }
                else
                {
                    Console.WriteLine($"Env file was not creaed because it already existed.");
                }


                var dockerfileInfo = PathEx.RuntimeCombine(
                    output.FullName,
                    config.relativePath,
                    "Dockerfile").ToFileInfo();

                if (force)
                {
                    dockerfileInfo.TryDelete();
                }

                if (!dockerfileInfo.Exists)
                {
                    Console.WriteLine($"Generating dockerfile in: '{dockerfileInfo.FullName}'");

                    var dockerfile = DockerfileConfigGenerator.GetDockerfile(
                        baseImage: config.baseImage,
                        port: config.port,
                        exposedPorts: config.exposedPorts,
                        workingDirectory: config.workingDirectory,
                        buildpackId: config.buildpackId,
                        customBuildCommand: config.customBuildCommand,
                        customStartCommand: config.customStartCommand,
                        enginx: useEnginx,
                        env: config.env);

                    dockerfileInfo.WriteAllText(dockerfile);
                    Console.WriteLine($"Dockerfile: \n'{dockerfile}'");
                }
                else
                {
                    Console.WriteLine($"Docker Compose file was not creaed because it already existed.");
                }

                Console.WriteLine("SUCCESS, dockergen finished running.");
            }
                ; break;

            case "help":
            case "--help":
            case "-help":
            case "-h":
            case "h":
                HelpPrinter($"{args[0]}", "Docker Helper",
                            ("gen", "Accepts params: config, output, image-name, force (optional/false), exposed-port (optional/80)"));
                break;

            default:
            {
                Console.WriteLine($"Try '{args[0]} help' to find out list of available commands.");
                throw new Exception($"Unknown docker command: '{args[0]} {args[1]}'");
            }
            }
        }
Exemple #8
0
        internal static void RepairAppsSuiteDirs()
        {
            if (!Elevation.WritableLocation())
            {
                Elevation.RestartAsAdministrator(ActionGuid.RepairDirs);
            }

            foreach (var dirs in new[]
            {
                CorePaths.AppDirs,
                CorePaths.UserDirs
            })
            {
                foreach (var dir in dirs)
                {
                    if (!DirectoryEx.Create(dir))
                    {
                        Elevation.RestartAsAdministrator(ActionGuid.RepairDirs);
                    }
                }
            }

            var iniMap = new[]
            {
                new[]
                {
                    CorePaths.AppDirs.First(),
                    "IconResource=..\\Assets\\FolderIcons.dll,3"
                },
                new[]
                {
                    CorePaths.AppDirs.Second(),
                    "LocalizedResourceName=\"Port-Able\" - Freeware",
                    "IconResource=..\\..\\Assets\\FolderIcons.dll,4"
                },
                new[]
                {
                    CorePaths.AppDirs.Third(),
                    "LocalizedResourceName=\"PortableApps\" - Repacks",
                    "IconResource=..\\..\\Assets\\FolderIcons.dll,2"
                },
                new[]
                {
                    CorePaths.AppDirs.Last(),
                    "LocalizedResourceName=\"Custom\" - Shareware",
                    "IconResource=..\\..\\Assets\\FolderIcons.dll,1"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Assets"),
                    "IconResource=FolderIcons.dll,5"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Binaries"),
                    "IconResource=..\\Assets\\FolderIcons.dll,5"
                },
                new[]
                {
                    CorePaths.UserDirs.First(),
                    "LocalizedResourceName=Profile",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,117",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-235"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Documents", ".cache"),
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,112"
                },
                new[]
                {
                    CorePaths.UserDirs.Second(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21770",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-112",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-235"
                },
                new[]
                {
                    CorePaths.UserDirs.Third(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21790",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-108",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-237",
                    "InfoTip=@%SystemRoot%\\system32\\shell32.dll,-12689"
                },
                new[]
                {
                    CorePaths.UserDirs.Fourth(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21779",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-113",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-236",
                    "InfoTip=@%SystemRoot%\\system32\\shell32.dll,-12688"
                },
                new[]
                {
                    CorePaths.UserDirs.Last(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21791",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-189",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-238",
                    "InfoTip=@%SystemRoot%\\system32\\shell32.dll,-12690"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Help"),
                    "IconResource=..\\Assets\\FolderIcons.dll,4"
                }
            };

            for (var i = 0; i < iniMap.Length; i++)
            {
                var array = iniMap[i];
                var dir   = array.FirstOrDefault();
                if (!PathEx.IsValidPath(dir) || i >= iniMap.Length - 2 && !Directory.Exists(dir))
                {
                    continue;
                }
                if (!Elevation.WritableLocation(dir))
                {
                    Elevation.RestartAsAdministrator(ActionGuid.RepairDirs);
                }
                var path = PathEx.Combine(dir, "desktop.ini");
                foreach (var str in array.Skip(1))
                {
                    var ent = str?.Split('=');
                    if (ent?.Length != 2)
                    {
                        continue;
                    }
                    var key = ent.FirstOrDefault();
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    var val = ent.LastOrDefault();
                    if (string.IsNullOrEmpty(val))
                    {
                        continue;
                    }
                    Ini.WriteDirect(".ShellClassInfo", key, val, path);
                }
                FileEx.SetAttributes(path, FileAttributes.System | FileAttributes.Hidden);
                DirectoryEx.SetAttributes(dir, FileAttributes.ReadOnly);
            }
        }
Exemple #9
0
        public override void BindToForm(ActionBase action)
        {
            var zipAct = (UnZipFileAction)action;

            this.txtFileName.Text = PathEx.Combine(zipAct.OverriddenSourceDirectory, zipAct.FileName);
        }
Exemple #10
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                var appDir  = PathEx.Combine(PathEx.LocalDir, "App\\winamp");
                var appPath = PathEx.Combine(appDir, "winamp.exe");
                if (!File.Exists(appPath))
                {
                    return;
                }

                var iniPath  = Path.ChangeExtension(PathEx.LocalPath, ".ini");
                var sortArgs = Ini.ReadDirect("Settings", "SortArgs", iniPath).EqualsEx("True");

                if (!newInstance)
                {
                    ProcessEx.Start(appPath, EnvironmentEx.CommandLine(sortArgs));
                    return;
                }

                if (!File.Exists(iniPath))
                {
                    Ini.WriteDirect("Associations", "FileTypes", "mp3,mp2,mp1,aac,vlb,avi,cda,mkv,webm,nsv,nsa,swf,ogg,oga,m4a,mp4,mpg,mpeg,m2v,flac,flv,wma,wmv,asf,aiff,aif,au,avr,caf,htk,iff,mat,paf,pvf,raw,rf64,sd2,sds,sf,voc,w64,wav,wve,xi,mid,midi,rmi,kar,miz,mod,mdz,nst,stm,stz,s3m,s3z,it,itz,xm,xmz,mtm,ult,669,far,amf,okt,ptm,m3u,m3u8,pls,b4s,xspf,wpl,asx", iniPath);
                    Ini.WriteDirect("Settings", "SortArgs", false, iniPath);
                }

                iniPath = PathEx.Combine(PathEx.LocalDir, "Data\\winamp.ini");
                if (!File.Exists(iniPath))
                {
                    var langDir = Path.Combine(appDir, "Lang");
                    if (Directory.Exists(langDir))
                    {
                        var langs = Directory.EnumerateFiles(langDir, "*.wlz").Select(Path.GetFileNameWithoutExtension).ToArray();
                        if (langs.Length > 0)
                        {
                            Application.EnableVisualStyles();
                            Application.SetCompatibleTextRenderingDefault(false);
                            Form langSelection = new LangSelectionForm(langs, iniPath);
                            if (langSelection.ShowDialog() != DialogResult.OK)
                            {
                                Application.Exit();
                                return;
                            }
                        }
                    }
                }
                Ini.WriteDirect("Winamp", "no_registry", 0, iniPath);
                Ini.WriteDirect("WinampReg", "NeedReg", 0, iniPath);
                Ini.WriteDirect("Winamp", "skin", "Big Bento", iniPath, false, true);
                Ini.WriteDirect("WinampReg", "skin", "Big Bento", iniPath, false, true);
                Ini.WriteDirect("Winamp", "eq_data", "24,19,40,46,42,31,19,16,26,32", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "nbkeys", 15, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "version", 2, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "enabled", 0, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "appcommand", 0, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action0", "ghkdc play", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey0", 3629, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action1", "ghkdc pause", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey1", 3620, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action2", "ghkdc stop", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey2", 3619, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action3", "ghkdc prev", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey3", 3617, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action4", "ghkdc next", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey4", 3618, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action5", "ghkdc vup", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey5", 3622, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action6", "ghkdc vdown", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey6", 3624, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action7", "ghkdc forward", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey7", 3623, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action8", "ghkdc rewind", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey8", 3621, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action9", "ghkdc jump", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey9", 3658, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action10", "ghkdc file", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey10", 3660, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action11", "ghkdc stop", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey11", 2226, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action12", "ghkdc play/pause", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey12", 2227, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action13", "ghkdc prev", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey13", 2225, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "action14", "ghkdc next", iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "hotkey14", 2224, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "col1", 212, iniPath, false, true);
                Ini.WriteDirect("gen_hotkeys", "col2", 177, iniPath, false, true);

                var dirMap = new Dictionary <string, string>
                {
                    {
                        "%CurDir%\\App\\winamp\\Plugins\\ml",
                        "%CurDir%\\Data\\Plugins\\ml"
                    }
                };

                var fileMap = new Dictionary <string, string>
                {
                    {
                        "%CurDir%\\App\\winamp\\gen_jumpex.m3u8",
                        "%CurDir%\\Data\\gen_jumpex.m3u8"
                    },
                    {
                        "%CurDir%\\App\\winamp\\winamp.bm",
                        "%CurDir%\\Data\\winamp.bm"
                    },
                    {
                        "%CurDir%\\App\\winamp\\winamp.bm3",
                        "%CurDir%\\Data\\winamp.bm3"
                    },
                    {
                        "%CurDir%\\App\\winamp\\winamp.bm8",
                        "%CurDir%\\Data\\winamp.bm8"
                    },
                    {
                        "%CurDir%\\App\\winamp\\winamp.ini",
                        "%CurDir%\\Data\\winamp.ini"
                    },
                    {
                        "%CurDir%\\App\\winamp\\winamp.m3u",
                        "%CurDir%\\Data\\winamp.m3u"
                    },
                    {
                        "%CurDir%\\App\\winamp\\winamp.m3u8",
                        "%CurDir%\\Data\\winamp.m3u8"
                    },
                    {
                        "%CurDir%\\App\\winamp\\winamp.q1",
                        "%CurDir%\\Data\\winamp.q1"
                    },
                    {
                        "%CurDir%\\App\\winamp\\links.xml",
                        "%CurDir%\\Data\\links.xml"
                    },
                    {
                        "%CurDir%\\App\\winamp\\studio.xnf",
                        "%CurDir%\\Data\\studio.xnf"
                    },
                    {
                        "%CurDir%\\App\\winamp\\Plugins\\feedback.ini",
                        "%CurDir%\\Data\\Plugins\\feedback.ini"
                    },
                    {
                        "%CurDir%\\App\\winamp\\Plugins\\gen_ml.ini",
                        "%CurDir%\\Data\\Plugins\\gen_ml.ini"
                    },
                    {
                        "%CurDir%\\App\\winamp\\Plugins\\Milkdrop2\\milk2.ini",
                        "%CurDir%\\Data\\Plugins\\Milkdrop2\\milk2.ini"
                    },
                    {
                        "%CurDir%\\App\\winamp\\Plugins\\Milkdrop2\\milk2_img.ini",
                        "%CurDir%\\Data\\Plugins\\Milkdrop2\\milk2_img.ini"
                    },
                    {
                        "%CurDir%\\App\\winamp\\Plugins\\Milkdrop2\\milk2_msg.ini",
                        "%CurDir%\\Data\\Plugins\\Milkdrop2\\milk2_msg.ini"
                    }
                };

                Helper.DirectoryForwarding(Helper.Options.Start, dirMap);

                Helper.FileForwarding(Helper.Options.Start, fileMap, true);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(sortArgs));

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);

                Helper.FileForwarding(Helper.Options.Exit, fileMap, true);
            }
        }
Exemple #11
0
 public static bool IsWiffFile(string filePath)
 {
     return(PathEx.HasExtension(filePath, EXT_WIFF));
 }
Exemple #12
0
        private static void Main()
        {
            Log.AllowLogging();
            try
            {
                using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
                {
                    if (!newInstance)
                    {
                        return;
                    }

                    var appDir   = PathEx.Combine(PathEx.LocalDir, "App\\ZedAttackProxy");
                    var appPaths = Directory.GetFiles(appDir, "zap-*.jar", SearchOption.TopDirectoryOnly).ToList();
                    appPaths.Sort();
                    var appPath = appPaths.Last();

                    if (!File.Exists(appPath) || IsRunning())
                    {
                        return;
                    }

                    var iniPath = Path.ChangeExtension(PathEx.LocalPath, ".ini");
                    Helper.FindJava(out string javaPath, iniPath);

                    var dirMap = new Dictionary <string, string>
                    {
                        {
                            "%UserProfile%\\OWASP ZAP",
                            "%CurDir%\\Data"
                        }
                    };
                    Helper.DirectoryForwarding(Helper.Options.Start, dirMap);

                    var args = $"-Xmx512m -XX:PermSize=256M -jar \"{appPath}\" {EnvironmentEx.CommandLine(false)}".Trim();
                    using (var p = ProcessEx.Start(javaPath, Path.GetDirectoryName(appPath), args, false, false))
                        if (p?.HasExited == false)
                        {
                            p.WaitForExit();
                        }

Recheck:
                    var appName = Path.GetFileNameWithoutExtension(javaPath);
                    foreach (var p in ProcessEx.GetInstances(appName))
                    {
                        var  wasRunning = false;
                        bool isRunning;
                        do
                        {
                            isRunning = p?.GetCommandLine()?.ContainsEx(appDir) == true;
                            if (p?.HasExited == false)
                            {
                                p.WaitForExit();
                            }
                            if (!wasRunning && isRunning)
                            {
                                wasRunning = true;
                            }
                            Thread.Sleep(200);
                        }while (isRunning);
                        if (!wasRunning)
                        {
                            continue;
                        }
                        Thread.Sleep(250);
                        goto Recheck;
                    }

                    Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
Exemple #13
0
        public static WsdProject CreateAndSave(
            WsdProjectCreateInfo info, string destinationPath, IProgressHandle progress)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            if (string.IsNullOrEmpty(destinationPath))
            {
                throw new ArgumentNullException(nameof(destinationPath));
            }

            if (PathEx.Identify(destinationPath) != PathIdentity.Directory ||
                Directory.GetFiles(destinationPath, "*", SearchOption.AllDirectories).Length > 0)
            {
                throw new ArgumentException(ExceptionMessage.DestinationPathMustBeEmptyAndExisting);
            }

            if (progress == null)
            {
                throw new ArgumentNullException(nameof(progress));
            }

            info.AssertIsValid();

            progress.SetMessageFormat(MessageFormat.LoadingDictionary_Bytes);

            var dictionary = InputDictionaryReader.ReadAll(info.DictionaryPath, progress);

            progress.SetMessageFormat(MessageFormat.ComputingDictionaryStatistics);

            var dictionaryStatistics = new DictionaryStatistics().Compute(dictionary, progress);

            TextData[] trainData;
            TextData[] testData;

            if (info.DataType == InputDataType.PlainText)
            {
                progress.SetMessageFormat(MessageFormat.LoadingTrainData_Files);

                trainData = InputPlainTextDataReader.ReadAllFiles(info.TrainDataPath, progress);

                progress.SetMessageFormat(MessageFormat.LoadingTestData_Files);

                testData = InputPlainTextDataReader.ReadAllFiles(info.TestDataPath, progress);
            }
            else
            {
                progress.SetMessageFormat(MessageFormat.LoadingSynsetMappings_Bytes);

                var synsetMappings = InputSynsetMappingReader.ReadAll(info.SynsetMappingsPath, progress);

                progress.SetMessageFormat(MessageFormat.LoadingTrainData_Files);

                trainData = InputXmlDataReader.Read(
                    info.TrainDataPath, info.TrainGoldKeyPath, synsetMappings, dictionary,
                    out var trainXmlParseErrors, progress);

                if (trainXmlParseErrors != null && trainXmlParseErrors.Any())
                {
                    XmlParseErrorWriter.WriteAll(
                        Path.Combine(destinationPath, FileName.TrainXmlParseErrors + FileExtension.Text),
                        trainXmlParseErrors);
                }

                progress.SetMessageFormat(MessageFormat.LoadingTestData_Files);

                testData = InputXmlDataReader.Read(
                    info.TestDataPath, info.TestGoldKeyPath, synsetMappings, dictionary,
                    out var testXmlParseErrors, progress);

                if (testXmlParseErrors != null && testXmlParseErrors.Any())
                {
                    XmlParseErrorWriter.WriteAll(
                        Path.Combine(destinationPath, FileName.TestXmlParseErrors + FileExtension.Text),
                        testXmlParseErrors);
                }
            }

            progress.SetMessageFormat(MessageFormat.AnalyzingData_Files);

            var dataAnalysis = new WordAnalysisDictionary()
                               .Analyze(dictionary, trainData, testData, progress);

            progress.SetMessageFormat(MessageFormat.ComputingDataStatistics);

            var dataStatistics = new DataStatistics()
                                 .Compute(dictionary, dataAnalysis, progress);

            progress.SetMessageFormat(MessageFormat.LoadingWordEmbeddings_Bytes);

            var wordEmbeddings = InputEmbeddingReader.ReadAll(
                info.WordEmbeddingsPath, dataAnalysis.GetAllWordOccurrences(), progress);

            var wordEmbeddingStatistics = new EmbeddingStatistics().Compute(wordEmbeddings);

            EmbeddingDictionary meaningEmbeddings = null;

            var meaningEmbeddingStatistics = new EmbeddingStatistics();

            if (!string.IsNullOrWhiteSpace(info.MeaningEmbeddingsPath))
            {
                progress.SetMessageFormat(MessageFormat.LoadingMeaningEmbeddings_Bytes);

                meaningEmbeddings = InputEmbeddingReader.ReadAll(
                    info.MeaningEmbeddingsPath, dataAnalysis.GetAllMeaningOccurrences(), progress);

                meaningEmbeddingStatistics.Compute(meaningEmbeddings);
            }

            var projectInfo = new WsdProjectInfo
            {
                ProjectName        = Path.GetFileName(destinationPath),
                ProjectVersion     = CurrentProjectVersion,
                ApplicationVersion = typeof(WsdProject).Assembly.GetName().Version.ToString(),
                Dictionary         = FileName.Dictionary + FileExtension.WsdData,
                TrainData          = trainData.Select(x => new WsdProjectTextDataInfo
                {
                    Name = x.TextName,
                    Path = Path.Combine(FolderName.Train, x.TextName + FileExtension.WsdData)
                }).ToArray(),
                TestData = testData.Select(x => new WsdProjectTextDataInfo
                {
                    Name = x.TextName,
                    Path = Path.Combine(FolderName.Test, x.TextName + FileExtension.WsdData)
                }).ToArray(),
                WordEmbeddings    = FileName.WordEmbeddings + FileExtension.WsdData,
                MeaningEmbeddings = meaningEmbeddings != null
                    ? FileName.MeaningEmbeddings + FileExtension.WsdData
                    : string.Empty,
                DataAnalysis                = FileName.DataAnalysis + FileExtension.WsdData,
                DictionaryStatistics        = FileName.DictionaryStatistics + FileExtension.WsdData,
                DataStatistics              = FileName.DataStatistics + FileExtension.WsdData,
                WordEmbeddingsStatistics    = FileName.WordEmbeddingsStatistics + FileExtension.WsdData,
                MeaningEmbeddingsStatistics = FileName.MeaningEmbeddingsStatistics + FileExtension.WsdData
            };

            progress.SetMessageFormat(MessageFormat.SavingDictionary_Words);

            SystemDictionaryWriter.WriteAll(
                Path.Combine(destinationPath, projectInfo.Dictionary), dictionary, progress);

            progress.SetMessageFormat(MessageFormat.SavingTrainData_Files);

            SystemDataWriter.WriteAllFiles(
                destinationPath,
                projectInfo.TrainData
                .Select(x => (x.Path, trainData.Single(y => y.TextName == x.Name).Data))
                .ToArray(),
                progress);

            progress.SetMessageFormat(MessageFormat.SavingTestData_Files);

            SystemDataWriter.WriteAllFiles(
                destinationPath,
                projectInfo.TestData
                .Select(x => (x.Path, testData.Single(y => y.TextName == x.Name).Data))
                .ToArray(),
                progress);

            progress.SetMessageFormat(MessageFormat.SavingWordEmbeddings_Embeddings);

            SystemEmbeddingWriter.WriteAll(
                Path.Combine(destinationPath, projectInfo.WordEmbeddings), wordEmbeddings, progress);

            if (meaningEmbeddings != null)
            {
                progress.SetMessageFormat(MessageFormat.SavingMeaningEmbeddings_Embeddings);

                SystemEmbeddingWriter.WriteAll(
                    Path.Combine(destinationPath, projectInfo.MeaningEmbeddings), meaningEmbeddings, progress);
            }

            progress.SetMessageFormat(MessageFormat.SavingDataAnalysis_Words);

            SystemDataAnalysisWriter.WriteAll(
                Path.Combine(destinationPath, projectInfo.DataAnalysis), dataAnalysis, progress);

            SystemJsonWriter.Write(
                Path.Combine(destinationPath, projectInfo.DictionaryStatistics), dictionaryStatistics);

            SystemJsonWriter.Write(
                Path.Combine(destinationPath, projectInfo.DataStatistics), dataStatistics);

            SystemJsonWriter.Write(
                Path.Combine(destinationPath, projectInfo.WordEmbeddingsStatistics), wordEmbeddingStatistics);

            SystemJsonWriter.Write(
                Path.Combine(destinationPath, projectInfo.MeaningEmbeddingsStatistics),
                meaningEmbeddingStatistics);

            SystemJsonWriter.Write(
                Path.Combine(destinationPath, projectInfo.ProjectName + FileExtension.WsdProj),
                projectInfo);

            return(new WsdProject(
                       projectInfo, dictionary, trainData, testData, wordEmbeddings, meaningEmbeddings,
                       dataAnalysis, dictionaryStatistics, dataStatistics, wordEmbeddingStatistics,
                       meaningEmbeddingStatistics));
        }
Exemple #14
0
        public static WsdProject Load(string path, IProgressHandle progress)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (PathEx.Identify(path) != PathIdentity.File ||
                Path.GetExtension(path) != FileExtension.WsdProj)
            {
                throw new ArgumentException(ExceptionMessage.PathMustBeExistingWsdProj);
            }

            var projectInfo      = SystemJsonReader.Read <WsdProjectInfo>(path);
            var projectDirectory = Path.GetDirectoryName(path);

            if (projectInfo.ProjectVersion != CurrentProjectVersion)
            {
                throw new Exception(ExceptionMessage.ProjectVersionNotSupported(
                                        projectInfo.ProjectVersion, CurrentProjectVersion));
            }

            progress.SetMessageFormat(MessageFormat.LoadingDictionary_Bytes);

            var dictionary = SystemDictionaryReader.ReadAll(
                Path.Combine(projectDirectory, projectInfo.Dictionary), progress);

            progress.SetMessageFormat(MessageFormat.LoadingTrainData_Files);

            var trainData = SystemDataReader.ReadAllFiles(
                projectDirectory, projectInfo.TrainData.Select(x => (x.Path, x.Name)).ToArray(),
                progress);

            progress.SetMessageFormat(MessageFormat.LoadingTestData_Files);

            var testData = SystemDataReader.ReadAllFiles(
                projectDirectory, projectInfo.TestData.Select(x => (x.Path, x.Name)).ToArray(),
                progress);

            progress.SetMessageFormat(MessageFormat.LoadingWordEmbeddings_Bytes);

            var wordEmbeddings = SystemEmbeddingReader.ReadAll(
                Path.Combine(projectDirectory, projectInfo.WordEmbeddings), progress);

            EmbeddingDictionary meaningEmbeddings = null;

            if (!string.IsNullOrWhiteSpace(projectInfo.MeaningEmbeddings))
            {
                progress.SetMessageFormat(MessageFormat.LoadingMeaningEmbeddings_Bytes);

                meaningEmbeddings = SystemEmbeddingReader.ReadAll(
                    Path.Combine(projectDirectory, projectInfo.MeaningEmbeddings), progress);
            }

            progress.SetMessageFormat(MessageFormat.LoadingDataAnalysis_Bytes);

            var dataAnalysis = SystemDataAnalysisReader.ReadAll(
                Path.Combine(projectDirectory, projectInfo.DataAnalysis), progress);

            var dictionaryStatistics = SystemJsonReader.Read <DictionaryStatistics>(
                Path.Combine(projectDirectory, projectInfo.DictionaryStatistics));

            var dataStatistics = SystemJsonReader.Read <DataStatistics>(
                Path.Combine(projectDirectory, projectInfo.DataStatistics));

            var wordEmbeddingsStatistics = SystemJsonReader.Read <EmbeddingStatistics>(
                Path.Combine(projectDirectory, projectInfo.WordEmbeddingsStatistics));

            var meaningEmbeddingsStatistics = SystemJsonReader.Read <EmbeddingStatistics>(
                Path.Combine(projectDirectory, projectInfo.MeaningEmbeddingsStatistics));

            return(new WsdProject(
                       projectInfo, dictionary, trainData, testData, wordEmbeddings, meaningEmbeddings,
                       dataAnalysis, dictionaryStatistics, dataStatistics, wordEmbeddingsStatistics,
                       meaningEmbeddingsStatistics));
        }
Exemple #15
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            var    source = NetEx.Transfer.DownloadString(Resources.RegexUrl);
            string updUrl = null;

            try
            {
                foreach (Match match in Regex.Matches(source, Resources.RegexFileNamePattern, RegexOptions.Singleline))
                {
                    var mName = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mName) || !mName.ContainsEx(Resources.AppName))
                    {
                        continue;
                    }
                    updUrl = string.Format(Resources.UpdateUrl, mName);
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var appPath    = PathEx.Combine(Resources.AppPath);
            var localDate  = File.GetLastWriteTime(appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
        /// <summary>
        /// Loads curve and event information from the provided clip, and creates a new instance of this object containing
        /// the required data for editing the source clip in the animation editor.
        /// </summary>
        /// <param name="clip">Clip to load.</param>
        /// <returns>Editor specific editable information about an animation clip.</returns>
        public static EditorAnimClipInfo Create(AnimationClip clip)
        {
            EditorAnimClipInfo clipInfo = new EditorAnimClipInfo();

            clipInfo.clip       = clip;
            clipInfo.isImported = IsClipImported(clip);
            clipInfo.sampleRate = (int)clip.SampleRate;

            AnimationCurves        clipCurves      = clip.Curves;
            EditorAnimClipTangents editorCurveData = null;

            string resourcePath = ProjectLibrary.GetPath(clip);

            if (!string.IsNullOrEmpty(resourcePath))
            {
                LibraryEntry entry    = ProjectLibrary.GetEntry(resourcePath);
                string       clipName = PathEx.GetTail(resourcePath);

                if (entry != null && entry.Type == LibraryEntryType.File)
                {
                    FileEntry      fileEntry = (FileEntry)entry;
                    ResourceMeta[] metas     = fileEntry.ResourceMetas;

                    if (clipInfo.isImported)
                    {
                        for (int i = 0; i < metas.Length; i++)
                        {
                            if (clipName == metas[i].SubresourceName)
                            {
                                editorCurveData = metas[i].EditorData as EditorAnimClipTangents;
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (metas.Length > 0)
                        {
                            editorCurveData = metas[0].EditorData as EditorAnimClipTangents;
                        }
                    }
                }
            }

            if (editorCurveData == null)
            {
                editorCurveData = new EditorAnimClipTangents();
            }

            int globalCurveIdx = 0;
            Action <NamedVector3Curve[], EditorVector3CurveTangents[], string> loadVector3Curve =
                (curves, tangents, subPath) =>
            {
                foreach (var curveEntry in curves)
                {
                    TangentMode[] tangentsX = null;
                    TangentMode[] tangentsY = null;
                    TangentMode[] tangentsZ = null;

                    if (tangents != null)
                    {
                        foreach (var tangentEntry in tangents)
                        {
                            if (tangentEntry.name == curveEntry.name)
                            {
                                tangentsX = tangentEntry.tangentsX;
                                tangentsY = tangentEntry.tangentsY;
                                tangentsZ = tangentEntry.tangentsZ;
                                break;
                            }
                        }
                    }

                    // Convert compound curve to three per-component curves
                    AnimationCurve[] componentCurves = AnimationUtility.SplitCurve(curveEntry.curve);

                    FieldAnimCurves fieldCurves = new FieldAnimCurves();
                    fieldCurves.type            = SerializableProperty.FieldType.Vector3;
                    fieldCurves.curveInfos      = new EdCurveDrawInfo[3];
                    fieldCurves.isPropertyCurve = !clipInfo.isImported;

                    fieldCurves.curveInfos[0]       = new EdCurveDrawInfo();
                    fieldCurves.curveInfos[0].curve = new EdAnimationCurve(componentCurves[0], tangentsX);
                    fieldCurves.curveInfos[0].color = GetUniqueColor(globalCurveIdx++);

                    fieldCurves.curveInfos[1]       = new EdCurveDrawInfo();
                    fieldCurves.curveInfos[1].curve = new EdAnimationCurve(componentCurves[1], tangentsY);
                    fieldCurves.curveInfos[1].color = GetUniqueColor(globalCurveIdx++);

                    fieldCurves.curveInfos[2]       = new EdCurveDrawInfo();
                    fieldCurves.curveInfos[2].curve = new EdAnimationCurve(componentCurves[2], tangentsZ);
                    fieldCurves.curveInfos[2].color = GetUniqueColor(globalCurveIdx++);

                    string curvePath = curveEntry.name.TrimEnd('/') + subPath;
                    clipInfo.curves[curvePath] = fieldCurves;
                }
            };

            // Convert rotation from quaternion to euler
            NamedQuaternionCurve[] rotationCurves      = clipCurves.Rotation;
            NamedVector3Curve[]    eulerRotationCurves = new NamedVector3Curve[rotationCurves.Length];
            for (int i = 0; i < rotationCurves.Length; i++)
            {
                eulerRotationCurves[i]       = new NamedVector3Curve();
                eulerRotationCurves[i].name  = rotationCurves[i].name;
                eulerRotationCurves[i].flags = rotationCurves[i].flags;
                eulerRotationCurves[i].curve = AnimationUtility.QuaternionToEulerCurve(rotationCurves[i].curve);
            }

            loadVector3Curve(clipCurves.Position, editorCurveData.positionCurves, "/Position");
            loadVector3Curve(eulerRotationCurves, editorCurveData.rotationCurves, "/Rotation");
            loadVector3Curve(clipCurves.Scale, editorCurveData.scaleCurves, "/Scale");

            // Find which individual float curves belong to the same field
            Dictionary <string, Tuple <int, int, bool>[]> floatCurveMapping = new Dictionary <string, Tuple <int, int, bool>[]>();

            {
                int curveIdx = 0;
                foreach (var curveEntry in clipCurves.Generic)
                {
                    string path         = curveEntry.name;
                    string pathNoSuffix = null;

                    string pathSuffix;
                    if (path.Length >= 2)
                    {
                        pathSuffix   = path.Substring(path.Length - 2, 2);
                        pathNoSuffix = path.Substring(0, path.Length - 2);
                    }
                    else
                    {
                        pathSuffix = "";
                    }

                    int tangentIdx        = -1;
                    int currentTangentIdx = 0;
                    foreach (var tangentEntry in editorCurveData.floatCurves)
                    {
                        if (tangentEntry.name == curveEntry.name)
                        {
                            tangentIdx = currentTangentIdx;
                            break;
                        }

                        currentTangentIdx++;
                    }

                    Animation.PropertySuffixInfo suffixInfo;
                    if (Animation.PropertySuffixInfos.TryGetValue(pathSuffix, out suffixInfo))
                    {
                        Tuple <int, int, bool>[] curveInfo;
                        if (!floatCurveMapping.TryGetValue(pathNoSuffix, out curveInfo))
                        {
                            curveInfo = new Tuple <int, int, bool> [4];
                        }

                        curveInfo[suffixInfo.elementIdx] = Tuple.Create(curveIdx, tangentIdx, suffixInfo.isVector);
                        floatCurveMapping[pathNoSuffix]  = curveInfo;
                    }
                    else
                    {
                        Tuple <int, int, bool>[] curveInfo = new Tuple <int, int, bool> [4];
                        curveInfo[0] = Tuple.Create(curveIdx, tangentIdx, suffixInfo.isVector);

                        floatCurveMapping[path] = curveInfo;
                    }

                    curveIdx++;
                }
            }

            foreach (var KVP in floatCurveMapping)
            {
                int numCurves = 0;
                for (int i = 0; i < 4; i++)
                {
                    if (KVP.Value[i] == null)
                    {
                        continue;
                    }

                    numCurves++;
                }

                if (numCurves == 0)
                {
                    continue; // Invalid curve
                }
                FieldAnimCurves fieldCurves = new FieldAnimCurves();

                // Deduce type (note that all single value types are assumed to be float even if their source type is int or bool)
                if (numCurves == 1)
                {
                    fieldCurves.type = SerializableProperty.FieldType.Float;
                }
                else if (numCurves == 2)
                {
                    fieldCurves.type = SerializableProperty.FieldType.Vector2;
                }
                else if (numCurves == 3)
                {
                    fieldCurves.type = SerializableProperty.FieldType.Vector3;
                }
                else // 4 curves
                {
                    bool isVector = KVP.Value[0].Item3;
                    if (isVector)
                    {
                        fieldCurves.type = SerializableProperty.FieldType.Vector4;
                    }
                    else
                    {
                        fieldCurves.type = SerializableProperty.FieldType.Color;
                    }
                }

                bool   isMorphCurve = false;
                string curvePath    = KVP.Key;

                fieldCurves.curveInfos = new EdCurveDrawInfo[numCurves];
                for (int i = 0; i < numCurves; i++)
                {
                    int curveIdx   = KVP.Value[i].Item1;
                    int tangentIdx = KVP.Value[i].Item2;

                    TangentMode[] tangents = null;
                    if (tangentIdx != -1)
                    {
                        tangents = editorCurveData.floatCurves[tangentIdx].tangents;
                    }

                    fieldCurves.curveInfos[i]       = new EdCurveDrawInfo();
                    fieldCurves.curveInfos[i].curve = new EdAnimationCurve(clipCurves.Generic[curveIdx].curve, tangents);
                    fieldCurves.curveInfos[i].color = GetUniqueColor(globalCurveIdx++);

                    if (clipCurves.Generic[curveIdx].flags.HasFlag(AnimationCurveFlags.MorphFrame))
                    {
                        curvePath    = "MorphShapes/Frames/" + KVP.Key;
                        isMorphCurve = true;
                    }
                    else if (clipCurves.Generic[curveIdx].flags.HasFlag(AnimationCurveFlags.MorphWeight))
                    {
                        curvePath    = "MorphShapes/Weight/" + KVP.Key;
                        isMorphCurve = true;
                    }
                }

                fieldCurves.isPropertyCurve = !clipInfo.isImported && !isMorphCurve;

                clipInfo.curves[curvePath] = fieldCurves;
            }

            // Add events
            clipInfo.events = clip.Events;
            return(clipInfo);
        }
Exemple #17
0
        public static readonly string[] EXTENSIONS = { ".exe", ".com", ".pif", ".cmd", ".bat", ".py", ".pl" }; // Not L10N

        public static bool CheckExtension(string path)
        {
            // Avoid Path.GetExtension() because it throws an exception for an invalid path
            return(EXTENSIONS.Any(extension => PathEx.HasExtension(path, extension)));
        }
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            var appData = CacheData.FindAppData(appsBox.SelectedItem.ToString());

            if (appData != default(LocalAppData))
            {
                if (string.IsNullOrWhiteSpace(fileTypes.Text))
                {
                    appData.Settings.FileTypes = default(string[]);
                }
                else
                {
                    if (e == EventArgs.Empty || !FileTypesConflict())
                    {
                        var typesList = new List <string>();
                        foreach (var item in $"{fileTypes.Text},".Split(','))
                        {
                            if (string.IsNullOrWhiteSpace(item))
                            {
                                continue;
                            }
                            var type = new string(item.ToCharArray().Where(c => !Path.GetInvalidFileNameChars().Contains(c) && !char.IsWhiteSpace(c)).ToArray());
                            if (string.IsNullOrWhiteSpace(type) || type.Length < 1)
                            {
                                continue;
                            }
                            if (type.StartsWith("."))
                            {
                                while (type.Contains(".."))
                                {
                                    type = type.Replace("..", ".");
                                }
                                if (typesList.ContainsEx(type) || typesList.ContainsEx(type.Substring(1)))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (typesList.ContainsEx(type) || typesList.ContainsEx($".{type}"))
                                {
                                    continue;
                                }
                            }
                            if (type.Length == 1 && type.StartsWith("."))
                            {
                                continue;
                            }
                            typesList.Add(type);
                        }
                        if (typesList.Any())
                        {
                            var comparer = new Comparison.AlphanumericComparer();
                            typesList                  = typesList.OrderBy(x => x, comparer).ToList();
                            fileTypes.Text             = typesList.Join(",");
                            appData.Settings.FileTypes = typesList.ToArray();
                        }
                    }
                    else
                    {
                        fileTypes.Text = appData.Settings.FileTypes.Join(',');
                    }
                }

                appData.Settings.StartArgsFirst = startArgsFirst.Text;
                appData.Settings.StartArgsLast  = startArgsLast.Text;

                appData.Settings.SortArgPaths = sortArgPathsCheck.Checked;
                appData.Settings.NoConfirm    = noConfirmCheck.Checked;
                appData.Settings.RunAsAdmin   = runAsAdminCheck.Checked;
                appData.Settings.NoUpdates    = noUpdatesCheck.Checked;
            }

            if (defBgCheck.Checked)
            {
                if (CacheData.CurrentImageBg != default(Image))
                {
                    CacheData.CurrentImageBg = default(Image);
                    if (Result != DialogResult.Yes)
                    {
                        Result = DialogResult.Yes;
                    }
                }
                bgLayout.SelectedIndex = 1;
            }

            Settings.Window.FadeInEffect   = (Settings.Window.FadeInEffectOptions)fadeInCombo.SelectedIndex;
            Settings.Window.FadeInDuration = (int)fadeInNum.Value;
            Settings.Window.Opacity        = (double)opacityNum.Value;

            Settings.Window.BackgroundImageLayout = (ImageLayout)bgLayout.SelectedIndex;

            Settings.Window.Colors.Base        = mainColorPanel.BackColor;
            Settings.Window.Colors.Control     = controlColorPanel.BackColor;
            Settings.Window.Colors.ControlText = controlTextColorPanel.BackColor;
            Settings.Window.Colors.Button      = btnColorPanel.BackColor;
            Settings.Window.Colors.ButtonHover = btnHoverColorPanel.BackColor;
            Settings.Window.Colors.ButtonText  = btnTextColorPanel.BackColor;

            Settings.Window.HideHScrollBar = hScrollBarCheck.Checked;
            Settings.Window.LargeImages    = showLargeImagesCheck.Checked;

            var dirList = new List <string>();

            if (!string.IsNullOrWhiteSpace(appDirs.Text))
            {
                var tmpDir = appDirs.Text + Environment.NewLine;
                foreach (var item in tmpDir.SplitNewLine())
                {
                    if (string.IsNullOrWhiteSpace(item))
                    {
                        continue;
                    }
                    var dir = PathEx.Combine(item);
                    try
                    {
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        dir = EnvironmentEx.GetVariablePathFull(dir);
                        if (!dirList.ContainsEx(dir))
                        {
                            dirList.Add(dir);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                }
                if (dirList.Count > 0)
                {
                    dirList.Sort();
                    appDirs.Text = dirList.Join(Environment.NewLine);
                }
            }
            Settings.AppDirs = dirList.ToArray();

            Settings.StartMenuIntegration = startMenuIntegration.SelectedIndex > 0;
            if (!Settings.StartMenuIntegration)
            {
                try
                {
                    var shortcutDirs = new[]
                    {
                        Environment.GetFolderPath(Environment.SpecialFolder.SendTo),
                        PathEx.Combine(Environment.SpecialFolder.StartMenu, "Programs")
                    };
                    foreach (var dir in shortcutDirs)
                    {
                        var shortcuts = Directory.GetFiles(dir, "Apps Launcher*.lnk", SearchOption.TopDirectoryOnly);
                        foreach (var shortcut in shortcuts)
                        {
                            if (File.Exists(shortcut))
                            {
                                File.Delete(shortcut);
                            }
                        }
                    }
                    var startMenuDir = Path.Combine(shortcutDirs.Last(), "Portable Apps");
                    if (Directory.Exists(startMenuDir))
                    {
                        Directory.Delete(startMenuDir, true);
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }
            }

            Settings.Window.DefaultPosition = defaultPos.SelectedIndex;

            Settings.UpdateCheck   = (Settings.UpdateCheckOptions)updateCheck.SelectedIndex;
            Settings.UpdateChannel = (Settings.UpdateChannelOptions)updateChannel.SelectedIndex;

            var lang = setLang.SelectedItem.ToString();

            if (!Settings.Language.EqualsEx(lang))
            {
                if (Result != DialogResult.Yes)
                {
                    Result = DialogResult.Yes;
                }
                Settings.Language = lang;
                LoadSettings();
            }

            Settings.WriteToFile();

            MessageBoxEx.Show(this, Language.GetText(nameof(en_US.SavedSettings)), MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
Exemple #19
0
        public AppTransferor(AppData appData)
        {
            AppData  = appData ?? throw new ArgumentNullException(nameof(appData));
            DestPath = default;
            SrcData  = new List <Tuple <string, string, string, bool> >();
            UserData = Tuple.Create(default(string), default(string));

            var downloadCollection = AppData.DownloadCollection;
            var packageVersion     = default(string);

            if (ActionGuid.IsUpdateInstance && AppData?.UpdateCollection?.SelectMany(x => x.Value).All(x => x?.Item1?.StartsWithEx("http") == true) == true)
            {
                var appIniDir  = Path.Combine(appData.InstallDir, "App", "AppInfo");
                var appIniPath = Path.Combine(appIniDir, "appinfo.ini");
                if (!File.Exists(appIniPath))
                {
                    appIniPath = Path.Combine(appIniDir, "plugininstaller.ini");
                }
                packageVersion = Ini.Read("Version", nameof(appData.PackageVersion), default(string), appIniPath);
                if (!string.IsNullOrEmpty(packageVersion) && AppData?.UpdateCollection?.ContainsKey(packageVersion) == true)
                {
                    downloadCollection = AppData.UpdateCollection;
                }
            }

            foreach (var pair in downloadCollection)
            {
                if (!pair.Key.EqualsEx(AppData.Settings.ArchiveLang) && (string.IsNullOrEmpty(packageVersion) || !pair.Key.EqualsEx(packageVersion)))
                {
                    continue;
                }

                foreach (var(item1, item2) in pair.Value)
                {
                    var srcUrl = item1;
                    if (srcUrl.StartsWith("{", StringComparison.InvariantCulture) && srcUrl.EndsWith("}", StringComparison.InvariantCulture))
                    {
                        srcUrl = FindArchivePath(srcUrl).Item2;
                    }

                    if (DestPath == default)
                    {
                        if (!DirectoryEx.Create(Settings.TransferDir))
                        {
                            continue;
                        }
                        var fileName = Path.GetFileName(srcUrl);
                        if (string.IsNullOrEmpty(fileName))
                        {
                            continue;
                        }
                        DestPath = PathEx.Combine(Settings.TransferDir, fileName);
                    }

                    var           shortHost = NetEx.GetShortHost(srcUrl);
                    var           redirect  = Settings.ForceTransferRedirection || !NetEx.IPv4IsAvalaible && !string.IsNullOrWhiteSpace(shortHost) && !shortHost.EqualsEx(AppSupplierHosts.Internal);
                    string        userAgent;
                    List <string> mirrors;
                    switch (shortHost)
                    {
                    case AppSupplierHosts.Internal:
                        userAgent = UserAgents.Internal;
                        mirrors   = AppSupply.GetMirrors(AppSuppliers.Internal);
                        break;

                    case AppSupplierHosts.PortableApps:
                        userAgent = UserAgents.Empty;
                        mirrors   = AppSupply.GetMirrors(AppSuppliers.PortableApps);
                        break;

                    case AppSupplierHosts.SourceForge:
                        userAgent = UserAgents.Default;
                        mirrors   = AppSupply.GetMirrors(AppSuppliers.SourceForge);
                        break;

                    default:
                        userAgent = UserAgents.Default;
                        if (AppData.ServerKey != default)
                        {
                            var srv = Shareware.GetAddresses().FirstOrDefault(x => Shareware.FindAddressKey(x) == AppData.ServerKey.ToArray().Encode(BinaryToTextEncoding.Base85));
                            if (srv != default)
                            {
                                if (!srcUrl.StartsWithEx("http://", "https://"))
                                {
                                    srcUrl = PathEx.AltCombine(srv, srcUrl);
                                }
                                UserData = Tuple.Create(Shareware.GetUser(srv), Shareware.GetPassword(srv));
                            }
                        }
                        SrcData.Add(Tuple.Create(srcUrl, item2, userAgent, false));
                        continue;
                    }

                    var sHost = NetEx.GetShortHost(srcUrl);
                    var fhost = srcUrl.Substring(0, srcUrl.IndexOf(sHost, StringComparison.OrdinalIgnoreCase) + sHost.Length);
                    foreach (var mirror in mirrors)
                    {
                        if (!fhost.EqualsEx(mirror))
                        {
                            srcUrl = srcUrl.Replace(fhost, mirror);
                        }
                        if (SrcData.Any(x => x.Item1.EqualsEx(srcUrl)))
                        {
                            continue;
                        }
                        if (redirect)
                        {
                            userAgent = UserAgents.Internal;
                            srcUrl    = CorePaths.RedirectUrl + srcUrl.Encode();
                        }
                        SrcData.Add(Tuple.Create(srcUrl, item2, userAgent, false));
                        if (Log.DebugMode > 1)
                        {
                            Log.Write($"Transfer: '{srcUrl}' has been added.");
                        }
                    }
                }
                break;
            }
            Transfer = new WebTransferAsync();
        }
Exemple #20
0
        protected virtual void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(Out);

            // Logging
            services.AddLogging(logging => {
                var debugCategories = new List <string> {
                    "Stl.Fusion",
                    "Stl.Tests.Fusion",
                    // DbLoggerCategory.Database.Transaction.Name,
                    // DbLoggerCategory.Database.Connection.Name,
                    // DbLoggerCategory.Database.Command.Name,
                    // DbLoggerCategory.Query.Name,
                    // DbLoggerCategory.Update.Name,
                };

                bool LogFilter(string category, LogLevel level)
                => IsLoggingEnabled &&
                debugCategories.Any(category.StartsWith) &&
                level >= LogLevel.Debug;

                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Debug);
                logging.AddFilter(LogFilter);
                logging.AddDebug();
                // XUnit logging requires weird setup b/c otherwise it filters out
                // everything below LogLevel.Information
                logging.AddProvider(new XunitTestOutputLoggerProvider(
                                        new TestOutputHelperAccessor(Out),
                                        LogFilter));
            });

            // DbContext & related services
            var testType   = GetType();
            var appTempDir = PathEx.GetApplicationTempDirectory("", true);

            DbPath = appTempDir & PathEx.GetHashedName($"{testType.Name}_{testType.Namespace}.db");
            services.AddDbContextPool <TestDbContext>(builder => {
                if (Options.UseInMemoryDatabase)
                {
                    builder.UseInMemoryDatabase(DbPath);
                }
                else
                {
                    builder.UseSqlite($"Data Source={DbPath}", sqlite => { });
                }
            }, 256);

            services.AddSingleton(c => new TestWebHost(c));

            // Core fusion services
            var fusion       = services.AddFusion();
            var fusionServer = fusion.AddWebSocketServer();
            var fusionClient = fusion.AddRestEaseClient(
                (c, options) => {
                options.BaseUri         = c.GetRequiredService <TestWebHost>().ServerUri;
                options.MessageLogLevel = LogLevel.Information;
            }).ConfigureHttpClientFactory(
                (c, name, options) => {
                var baseUri         = c.GetRequiredService <TestWebHost>().ServerUri;
                var apiUri          = new Uri($"{baseUri}api/");
                var isFusionService = !(name ?? "").Contains("Tests");
                var clientBaseUri   = isFusionService ? baseUri : apiUri;
                options.HttpClientActions.Add(c => c.BaseAddress = clientBaseUri);
            });
            var fusionAuth = fusion.AddAuthentication().AddClient();

            // Auto-discovered services
            services.AttributeBased()
            .SetTypeFilter(testType.Namespace !)
            .AddServicesFrom(testType.Assembly);

            // Custom live state
            fusion.AddState(c => c.GetStateFactory().NewLive <ServerTimeModel2>(
                                async(state, cancellationToken) => {
                var client = c.GetRequiredService <IClientTimeService>();
                var time   = await client.GetTimeAsync(cancellationToken).ConfigureAwait(false);
                return(new ServerTimeModel2(time));
            }));
        }
Exemple #21
0
        private void ExtractDownload_DoWork(object sender, DoWorkEventArgs e)
        {
            var updDir = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempDirName()}");

            try
            {
                if (_transfer?.FilePath == null || !File.Exists(_transfer.FilePath))
                {
                    return;
                }
                var helperPath = PathEx.Combine(_tmpDir, "iu.exe");
                if (!File.Exists(helperPath))
                {
                    throw new FileNotFoundException();
                }
                if (!Directory.Exists(updDir))
                {
                    Directory.CreateDirectory(updDir);
                }
                using (var p = ProcessEx.Start(helperPath, string.Format(Resources.Extract, _transfer.FilePath, updDir), Elevation.IsAdministrator, ProcessWindowStyle.Minimized, false))
                    if (p?.HasExited == false)
                    {
                        p.WaitForExit();
                    }
                Thread.Sleep(1500);
                var innerDir = Path.Combine(updDir, "{app}");
                var updFiles = Directory.GetFiles(innerDir, "*", SearchOption.AllDirectories);
                if (updFiles.Length == 0)
                {
                    throw new ArgumentNullException(nameof(updFiles));
                }
                var appPath = Directory.EnumerateFiles(updDir, $"*{Resources.AppName}.exe", SearchOption.AllDirectories).FirstOrDefault();
                if (string.IsNullOrEmpty(appPath))
                {
                    throw new ArgumentNullException(nameof(appPath));
                }
                var curFiles = Directory.EnumerateFiles(PathEx.LocalDir, "*", SearchOption.AllDirectories).Where(s => !s.ContainsEx(updDir) && !Resources.WhiteList.ContainsEx(Path.GetFileName(s)));
                foreach (var file in curFiles)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch
                    {
                        try
                        {
                            File.Move(file, $"{file}.{{{Path.GetDirectoryName(updDir)}}}");
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                        }
                    }
                }
                Data.DirCopy(innerDir, PathEx.LocalDir, true, true);
                if (Directory.Exists(updDir))
                {
                    Directory.Delete(updDir, true);
                }
                if (File.Exists(_appPath))
                {
                    File.SetLastWriteTime(_appPath, DateTime.Now);
                }
                e.Result = true;
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                e.Result = false;
                Data.ForceDelete(updDir);
            }
        }
Exemple #22
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl;

            try
            {
                updUrl = string.Format(Resources.UpdateUrl,
#if x86
                                       "x86"
#else
                                       "x64"
#endif
                                       );
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var appPath    = PathEx.Combine(Resources.AppPath);
            var localDate  = File.GetLastWriteTime(appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);
            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemple #23
0
        /// <summary>
        /// Constructs a new resource tile entry.
        /// </summary>
        /// <param name="owner">Content area this entry is part of.</param>
        /// <param name="parent">Parent layout to add this entry's GUI elements to.</param>
        /// <param name="path">Path to the project library entry to display data for.</param>
        /// <param name="index">Sequential index of the entry in the conent area.</param>
        /// <param name="width">Width of the GUI entry.</param>
        /// <param name="height">Maximum allowed height for the label.</param>"
        /// <param name="type">Type of the entry, which controls its style and/or behaviour.</param>
        public LibraryGUIEntry(LibraryGUIContent owner, GUILayout parent, string path, int index, int width, int height,
                               LibraryGUIEntryType type)
        {
            GUILayout entryLayout;

            if (owner.GridLayout)
            {
                entryLayout = parent.AddLayoutY();
            }
            else
            {
                entryLayout = parent.AddLayoutX();
            }

            SpriteTexture iconTexture = GetIcon(path, owner.TileSize);

            icon = new GUITexture(iconTexture, GUITextureScaleMode.ScaleToFit,
                                  true, GUIOption.FixedHeight(owner.TileSize), GUIOption.FixedWidth(owner.TileSize));

            label = null;

            string name = PathEx.GetTail(path);

            if (owner.GridLayout)
            {
                int labelHeight = height - owner.TileSize;

                label = new GUILabel(name, EditorStyles.MultiLineLabelCentered,
                                     GUIOption.FixedWidth(width), GUIOption.FixedHeight(labelHeight));

                switch (type)
                {
                case LibraryGUIEntryType.Single:
                    break;

                case LibraryGUIEntryType.MultiFirst:
                    groupUnderlay = new GUITexture(null, LibraryEntryFirstBg);
                    break;

                case LibraryGUIEntryType.MultiElement:
                    groupUnderlay = new GUITexture(null, LibraryEntryBg);
                    break;

                case LibraryGUIEntryType.MultiLast:
                    groupUnderlay = new GUITexture(null, LibraryEntryLastBg);
                    break;
                }
            }
            else
            {
                label = new GUILabel(name, GUIOption.FixedWidth(width - owner.TileSize), GUIOption.FixedHeight(height));

                switch (type)
                {
                case LibraryGUIEntryType.Single:
                    break;

                case LibraryGUIEntryType.MultiFirst:
                    groupUnderlay = new GUITexture(null, LibraryEntryVertFirstBg);
                    break;

                case LibraryGUIEntryType.MultiElement:
                    groupUnderlay = new GUITexture(null, LibraryEntryVertBg);
                    break;

                case LibraryGUIEntryType.MultiLast:
                    groupUnderlay = new GUITexture(null, LibraryEntryVertLastBg);
                    break;
                }
            }

            entryLayout.AddElement(icon);
            entryLayout.AddElement(label);

            if (groupUnderlay != null)
            {
                owner.DeepUnderlay.AddElement(groupUnderlay);
            }

            this.owner    = owner;
            this.index    = index;
            this.path     = path;
            this.bounds   = new Rect2I();
            this.underlay = null;
            this.type     = type;
            this.width    = width;
        }
Exemple #24
0
        /// <summary>
        /// Single action transform
        /// </summary>
        /// <param name="template">path for XSLT style-sheet</param>
        /// <param name="inputSource"></param>
        /// <param name="input">source XML file</param>
        /// <param name="output">resulting text content</param>
        public void Transform(string template, string inputSource, IXPathNavigable input, string output)
        {
            template = PathEx.FixUpPath(template);
            inputSource = PathEx.FixUpPath(inputSource);
            output = PathEx.FixUpPath(output);
            var sandbox = PathEx.FixUpPath(_sandbox);

            var xsltArgumentList = new XsltArgumentList().AddExtensions(_extensions);

            xsltArgumentList.XsltMessageEncountered += (sender, eventArgs) => Console.WriteLine($"\t\t[{Thread.CurrentThread.ManagedThreadId}]{eventArgs.Message}");

            XNamespace ns = this.GetXmlNamespace();
            xsltArgumentList.AddParam("files", "", new XElement(ns + "file",
                new XAttribute(nameof(template), Path.GetFullPath(template)),
                new XAttribute(nameof(input), Path.GetFullPath(inputSource)),
                new XAttribute(nameof(input) + "Type", input.GetType().AssemblyQualifiedName),
                new XAttribute(nameof(output), Path.GetFullPath(output)),
                new XAttribute(nameof(output) + "Path", Path.GetDirectoryName(Path.GetFullPath(output))),
                new XAttribute("sandbox", Path.GetFullPath(sandbox))
                ).ToXPathNavigable().CreateNavigator());

            var xslt = new XslCompiledTransform(false);
            using var xmlreader = XmlReader.Create(template, new XmlReaderSettings
            {
                DtdProcessing = DtdProcessing.Parse,
                ConformanceLevel = ConformanceLevel.Document,
                NameTable = new NameTable(),
            });
            var xsltSettings = new XsltSettings(false, false);

            xslt.Load(xmlreader, xsltSettings, null);

            var outputDir = Path.GetDirectoryName(output);
            if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir);
            using var resultStream = File.Create(output);

            var currentDirectory = Environment.CurrentDirectory;
            try
            {
                var localOutfolder = Path.GetDirectoryName(output);
                if (!Directory.Exists(localOutfolder))
                {
                    Directory.CreateDirectory(localOutfolder);
                }
                Environment.CurrentDirectory = localOutfolder;

                var inputNavigator = input.CreateNavigator();
                inputNavigator.MoveToRoot();

                //var x = xslt.GetType();
                //var pf = x.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
                //var pfc = pf.First(i => i.Name == "_command");
                //var pfv = pfc.GetValue(xslt);

                xslt.Transform(inputNavigator, xsltArgumentList, resultStream);
            }
            finally
            {
                Environment.CurrentDirectory = currentDirectory;
            }
        }
Exemple #25
0
        private static void Main()
        {
            Log.AllowLogging();

#if x86
            var curPath64 = PathEx.Combine(PathEx.LocalDir, "YoloMouse64Portable.exe");
            if (Environment.Is64BitOperatingSystem && File.Exists(curPath64))
            {
                ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                return;
            }
            var appDir      = PathEx.Combine(PathEx.LocalDir, "App\\YoloMouse");
            var updaterPath = PathEx.Combine(appDir, "YoloMouseUpdater.exe");
#else
            var appDir      = PathEx.Combine(PathEx.LocalDir, "App\\YoloMouse64");
            var updaterPath = PathEx.Combine(appDir, "YoloMouseUpdater64.exe");
#endif

            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var appPath = PathEx.Combine(appDir, "YoloMouse.exe");
                if (ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)) || !File.Exists(updaterPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(updaterPath)))
                {
                    return;
                }

                var dataDir = PathEx.Combine(PathEx.LocalDir, "Data");

                var defCursorDir = PathEx.Combine(appDir, "Cursors");
                var cursorDir    = PathEx.Combine(dataDir, "Cursors");
                var dirMap       = new Dictionary <string, string>
                {
                    {
                        "%LocalAppData%\\YoloMouse",
                        dataDir
                    },
                    {
                        defCursorDir,
                        cursorDir
                    }
                };

                Helper.ApplicationStart(updaterPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updaterPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }

                var cfgPath = Path.Combine(dataDir, "Settings.ini");
                if (!File.Exists(cfgPath))
                {
                    if (!Directory.Exists(dataDir))
                    {
                        Directory.CreateDirectory(dataDir);
                    }
                    File.WriteAllText(cfgPath, Resources.DefaultSettings);
                }

                if (Directory.Exists(defCursorDir))
                {
                    Data.DirCopy(defCursorDir, cursorDir, true, true);
                    try
                    {
                        Directory.Delete(defCursorDir);
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                        ProcessEx.SendHelper.WaitForExitThenDelete(defCursorDir, ProcessEx.CurrentName, Elevation.IsAdministrator);
                    }
                }

                Helper.DirectoryForwarding(Helper.Options.Start, dirMap);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);
            }
        }
        protected virtual void ConfigureServices(IServiceCollection services, bool isClient = false)
        {
            if (Options.UseTestClock)
            {
                services.AddSingleton <IMomentClock, TestClock>();
            }
            services.AddSingleton(Out);

            // Logging
            if (Options.UseLogging)
            {
                services.AddLogging(logging => {
                    var debugCategories = new List <string> {
                        "Stl.Fusion",
                        "Stl.CommandR",
                        "Stl.Tests.Fusion",
                        // DbLoggerCategory.Database.Transaction.Name,
                        // DbLoggerCategory.Database.Connection.Name,
                        // DbLoggerCategory.Database.Command.Name,
                        // DbLoggerCategory.Query.Name,
                        // DbLoggerCategory.Update.Name,
                    };

                    bool LogFilter(string category, LogLevel level)
                    => IsLoggingEnabled &&
                    debugCategories.Any(category.StartsWith) &&
                    level >= LogLevel.Debug;

                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Debug);
                    logging.AddFilter(LogFilter);
                    logging.AddDebug();
                    // XUnit logging requires weird setup b/c otherwise it filters out
                    // everything below LogLevel.Information
                    logging.AddProvider(new XunitTestOutputLoggerProvider(
                                            new TestOutputHelperAccessor(Out),
                                            LogFilter));
                });
            }

            // Core Fusion services
            var fusion = services.AddFusion();

            fusion.AddLiveClock();

            // Auto-discovered services
            var testType = GetType();

            services.UseAttributeScanner()
            .WithTypeFilter(testType.Namespace !)
            .AddServicesFrom(testType.Assembly);

            if (!isClient)
            {
                // Configuring Services and ServerServices
                services.UseAttributeScanner(ServiceScope.Services)
                .WithTypeFilter(testType.Namespace !)
                .AddServicesFrom(testType.Assembly);

                // DbContext & related services
                var appTempDir = PathEx.GetApplicationTempDirectory("", true);
                SqliteDbPath = appTempDir & PathEx.GetHashedName($"{testType.Name}_{testType.Namespace}.db");
                services.AddPooledDbContextFactory <TestDbContext>(builder => {
                    switch (Options.DbType)
                    {
                    case FusionTestDbType.Sqlite:
                        builder.UseSqlite($"Data Source={SqliteDbPath}");
                        break;

                    case FusionTestDbType.InMemory:
                        builder.UseInMemoryDatabase(SqliteDbPath)
                        .ConfigureWarnings(w => {
                            w.Ignore(InMemoryEventId.TransactionIgnoredWarning);
                        });
                        break;

                    case FusionTestDbType.PostgreSql:
                        builder.UseNpgsql(PostgreSqlConnectionString);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    builder.EnableSensitiveDataLogging();
                }, 256);
                services.AddDbContextServices <TestDbContext>(b => {
                    b.AddDbEntityResolver <long, User>();
                    b.AddDbOperations((_, o) => {
                        o.UnconditionalWakeUpPeriod = TimeSpan.FromSeconds(5);
                        // Enable this if you debug multi-host invalidation
                        // o.MaxCommitDuration = TimeSpan.FromMinutes(5);
                    });
                    b.AddKeyValueStore();
                    if (Options.DbType == FusionTestDbType.PostgreSql)
                    {
                        b.AddNpgsqlDbOperationLogChangeTracking();
                    }
                    else
                    {
                        b.AddFileBasedDbOperationLogChangeTracking();
                    }
                    if (!Options.UseInMemoryAuthService)
                    {
                        b.AddDbAuthentication();
                    }
                });
                if (Options.UseInMemoryAuthService)
                {
                    fusion.AddAuthentication().AddServerSideAuthService();
                }

                // WebHost
                var webHost = (FusionTestWebHost?)WebHost;
                services.AddSingleton(c => webHost ?? new FusionTestWebHost(services));
            }
            else
            {
                // Configuring ClientServices
                services.UseAttributeScanner(ServiceScope.ClientServices)
                .WithTypeFilter(testType.Namespace !)
                .AddServicesFrom(testType.Assembly);

                // Fusion client
                var fusionClient = fusion.AddRestEaseClient(
                    (c, options) => {
                    options.BaseUri         = WebHost.ServerUri;
                    options.MessageLogLevel = LogLevel.Information;
                }).ConfigureHttpClientFactory(
                    (c, name, options) => {
                    var baseUri         = WebHost.ServerUri;
                    var apiUri          = new Uri($"{baseUri}api/");
                    var isFusionService = !(name ?? "").Contains("Tests");
                    var clientBaseUri   = isFusionService ? baseUri : apiUri;
                    options.HttpClientActions.Add(c => c.BaseAddress = clientBaseUri);
                });
                fusion.AddAuthentication(fusionAuth => fusionAuth.AddRestEaseClient());

                // Custom live state
                fusion.AddState(c => c.StateFactory().NewLive <ServerTimeModel2>(
                                    async(state, cancellationToken) => {
                    var client = c.GetRequiredService <IClientTimeService>();
                    var time   = await client.GetTime(cancellationToken).ConfigureAwait(false);
                    return(new ServerTimeModel2(time));
                }));
            }
        }
Exemple #27
0
        /// <summary>
        ///     Enables/disables the directory redirection.
        /// </summary>
        /// <param name="option">
        ///     The option that determines whether the redirect will be enabled or disabled.
        /// </param>
        /// <param name="dirMap">
        ///     The diretory map.
        ///     <para>
        ///         The key is used for the source directory, and the value is used for the
        ///         destination directory.
        ///     </para>
        /// </param>
        public static void DirRedirection(PortalizerActions option, Dictionary <string, string> dirMap)
        {
            if (dirMap?.Any() != true)
            {
                return;
            }
            var hash  = nameof(DirRedirection).Encrypt();
            var hPath = PathEx.Combine(Attributes.TempDir, hash);

            switch (option)
            {
            case PortalizerActions.Disable:
                FileEx.TryDelete(hPath);
                break;

            default:
                if (File.Exists(hPath))
                {
                    DirRedirection(PortalizerActions.Disable, dirMap);
                }
                FileEx.Create(hPath);
                break;
            }
            foreach (var data in dirMap)
            {
                if (string.IsNullOrWhiteSpace(data.Key) || string.IsNullOrWhiteSpace(data.Value))
                {
                    continue;
                }
                var srcPath  = PathEx.Combine(data.Key);
                var destPath = PathEx.Combine(data.Value);
                DirectoryEx.SetAttributes(srcPath, FileAttributes.Normal);
                var backupPath = $"{srcPath}-{{{EnvironmentEx.MachineId}}}.backup";
                switch (option)
                {
                case PortalizerActions.Disable:
                    DirectoryEx.SetAttributes(backupPath, FileAttributes.Normal);
                    if (DirectoryEx.DestroySymbolicLink(srcPath, true))
                    {
                        continue;
                    }
                    try
                    {
                        if (Directory.Exists(srcPath))
                        {
                            DirectoryEx.SetAttributes(srcPath, FileAttributes.Normal);
                            DirectoryEx.Copy(srcPath, destPath, true, true);
                            Directory.Delete(srcPath, true);
                        }
                        if (Directory.Exists(backupPath))
                        {
                            DirectoryEx.Copy(backupPath, srcPath, true, true);
                            Directory.Delete(backupPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    break;

                default:
                    if (DirectoryEx.CreateSymbolicLink(srcPath, destPath, true))
                    {
                        DirectoryEx.SetAttributes(backupPath, FileAttributes.Normal);
                        continue;
                    }
                    try
                    {
                        if (Directory.Exists(srcPath))
                        {
                            if (!Directory.Exists(backupPath))
                            {
                                DirectoryEx.Move(srcPath, backupPath);
                                DirectoryEx.SetAttributes(backupPath, FileAttributes.Hidden);
                            }
                            if (Directory.Exists(srcPath))
                            {
                                Directory.Delete(srcPath, true);
                            }
                        }
                        if (Directory.Exists(destPath))
                        {
                            DirectoryEx.SetAttributes(destPath, FileAttributes.Normal);
                            DirectoryEx.Copy(destPath, srcPath);
                        }
                        if (!Directory.Exists(srcPath))
                        {
                            Directory.CreateDirectory(srcPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    break;
                }
            }
        }
Exemple #28
0
        private void ExtractDownload_DoWork(object sender, DoWorkEventArgs e)
        {
            var updDir = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempDirName()}");
            var entry  = string.Empty;

            try
            {
                if (_transfer?.FilePath == null || !File.Exists(_transfer.FilePath))
                {
                    return;
                }
                if (!Directory.Exists(updDir))
                {
                    Directory.CreateDirectory(updDir);
                }
                using (var archive = ZipFile.OpenRead(_transfer.FilePath))
                    foreach (var ent in archive.Entries)
                    {
                        try
                        {
                            if (!Path.HasExtension(ent.FullName))
                            {
                                continue;
                            }
                            var entPath = ent.FullName;
                            entPath = PathEx.Combine(updDir, entPath);
                            if (File.Exists(entPath))
                            {
                                File.Delete(entPath);
                            }
                            var entDir = Path.GetDirectoryName(entPath);
                            if (string.IsNullOrEmpty(entDir))
                            {
                                continue;
                            }
                            if (!Directory.Exists(entDir))
                            {
                                if (File.Exists(entDir))
                                {
                                    File.Delete(entDir);
                                }
                                Directory.CreateDirectory(entDir);
                            }
                            ent.ExtractToFile(entPath, true);
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                            entry = ent.FullName.Split('/').Join('\\');
                            throw;
                        }
                    }
                var appPath = Directory.EnumerateFiles(updDir, $"*{Resources.AppName}.exe", SearchOption.AllDirectories).FirstOrDefault();
                if (string.IsNullOrEmpty(appPath))
                {
                    throw new ArgumentNullException(nameof(appPath));
                }
                var appDir = Path.GetDirectoryName(appPath);
                if (string.IsNullOrEmpty(appDir))
                {
                    throw new ArgumentNullException(nameof(appDir));
                }
                var curFiles = Directory.EnumerateFiles(PathEx.LocalDir, "*", SearchOption.AllDirectories).Where(x => !Resources.WhiteList.ContainsEx(Path.GetFileName(x)));
                foreach (var file in curFiles)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch
                    {
                        try
                        {
                            File.Move(file, $"{file}.{{{Path.GetFileName(updDir)}}}");
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                            Data.ForceDelete(file, true);
                        }
                    }
                }
                Data.DirCopy(appDir, PathEx.LocalDir, true, true);
                if (Directory.Exists(updDir))
                {
                    Directory.Delete(updDir, true);
                }
                appPath = PathEx.Combine(Resources.AppPath);
                if (File.Exists(appPath))
                {
                    File.SetLastWriteTime(appPath, DateTime.Now);
                }
                e.Result = true;
            }
            catch (PathTooLongException ex)
            {
                Log.Write(ex);
                e.Result = false;
                Data.ForceDelete(updDir);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(string.Format("{0}{3}{3}('{1}\\{2}')", ex.Message, PathEx.LocalDir, entry, Environment.NewLine), Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                e.Result = false;
                Data.ForceDelete(updDir);
            }
        }
Exemple #29
0
        protected override void Execute()
        {
            var addresses = this.GetToAddresses().ToList();

            if (!addresses.Any())
            {
                this.LogWarning("The \"To address(es)\" field is empty, therefore no emails will be sent.");
                return;
            }

            this.LogInformation("Preparing to send email message to {0}...", addresses.Count > 1 ? addresses.Count + " addresses" : addresses.First());

            using (var smtp = new BuildMasterSmtpClient())
                using (var message = BuildMasterSmtpClient.CreateMailMessage(addresses))
                {
                    message.IsBodyHtml = this.IsBodyHtml;
                    message.Subject    = this.Subject;
                    message.Body       = this.Message;

                    if (this.Timeout > 0)
                    {
                        smtp.Timeout = this.Timeout;
                    }

                    if (!string.IsNullOrEmpty(this.Attachment))
                    {
                        using (var agent = BuildMasterAgent.Create(this.ServerId.Value))
                        {
                            var fileOps        = agent.GetService <IFileOperationsExecuter>();
                            var sourceDir      = fileOps.GetLegacyWorkingDirectory((IGenericBuildMasterContext)this.Context, PathEx.GetDirectoryName(this.Attachment));
                            var attachmentPath = fileOps.CombinePath(sourceDir, PathEx.GetFileName(this.Attachment));
                            this.LogDebug("Adding attachment at file path \"{0}\"...", attachmentPath);

                            if (!fileOps.FileExists(attachmentPath))
                            {
                                this.LogWarning("Could not attach \"{0}\" to the email message because the file was not found on the selected server.", this.Attachment);
                                smtp.Send(message);
                            }
                            else
                            {
                                using (var fileStream = fileOps.OpenFile(attachmentPath, FileMode.Open, FileAccess.Read))
                                {
                                    message.Attachments.Add(new Attachment(fileStream, PathEx.GetFileName(attachmentPath)));
                                    smtp.Send(message);
                                }
                            }
                        }
                    }
                    else
                    {
                        smtp.Send(message);
                    }
                }

            this.LogInformation("Email message{0} sent.", addresses.Count > 1 ? "s" : "");
        }
Exemple #30
0
        //生成数据代码
        public void GenModelScript(BaseUI ui)
        {
            rootGo = ui.gameObject;
            uiType = ui.GetType();
            string modelClassName = uiType.Name + "Model";

            if (File.Exists(PathEx.Combine(Application.dataPath, UIModel.uiModelScriptPath, modelClassName + ".cs")))
            {
                if (!EditorUtility.DisplayDialog("提示", "已存在" + modelClassName + ",是否要覆盖?", "继续", "取消"))
                {
                    return;
                }
            }

            CodeGener gener = new CodeGener(UIModel.uiModelNameSpace, modelClassName);

            gener.AddBaseType(typeof(UIModel).Name)
            .AddImport("ResetCore.UGUI")
            .AddImport("ResetCore.Event");

            List <string> hasAddedProperty = new List <string>();

            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;

            rootGo.transform.DoToSelfAndAllChildren((tran) =>
            {
                GameObject go = tran.gameObject;
                if (!go.name.StartsWith(UIModel.genableSign))
                {
                    return;
                }

                string goName = go.name.Replace(UIModel.genableSign, string.Empty);
                string propertyName;
                string typeName;

                if (!goName.Contains(splitGoNameAndProperty[0]))
                {
                    return;
                }

                string[] tempstrs = goName.Split(splitGoNameAndProperty, StringSplitOptions.RemoveEmptyEntries);
                goName            = tempstrs[0];

                if (!tempstrs[1].Contains(splitComponentAndProperty[0]))
                {
                    EditorUtility.WarnPrefab(go, "命名错误", go.name + "的格式不正确,标准格式为“g-View变量名@组件名->Model属性名:变量类型”", "好的");
                    return;
                }

                propertyName = tempstrs[1].Split(splitComponentAndProperty, StringSplitOptions.RemoveEmptyEntries)[1];

                if (!propertyName.Contains(splitPropertyAndType.ToString()))
                {
                    typeName = "EventProperty<string>";
                }

                tempstrs     = propertyName.Split(splitPropertyAndType, StringSplitOptions.RemoveEmptyEntries);
                propertyName = tempstrs[0];
                typeName     = "EventProperty<" + tempstrs[1] + ">";

                if (!hasAddedProperty.Contains(propertyName))
                {
                    gener.AddMemberProperty(typeName, propertyName);
                    hasAddedProperty.Add(propertyName);

                    constructor.Statements.AddRange(new CodeStatement[]
                    {
                        new CodeCommentStatement("From " + go.name),
                        new CodeSnippetStatement(propertyName + " = new " + typeName + "();")
                    });
                }
            });
            gener.newClass.Members.Add(constructor);
            gener.GenCSharp(PathEx.Combine(Application.dataPath, UIModel.uiModelScriptPath));
        }