System.IO.Path.Combine(string, string, string)

Here are the examples of the csharp api System.IO.Path.Combine(string, string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2801 Examples 7

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public string GetUserDataFilePath(string uid, Type type)
            => Path.Combine(UserRoot, uid, GetDataFileName(type));

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public string GetUserDataFilePath(string uid, string name)
            => Path.Combine(UserRoot, uid, name + ".yaml");

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public override void CopyTo(UserData other) {
            using UserDataBatchContext batch = other.OpenBatch();
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);

                Dictionary<string, Type?> types = new();
                replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();

                foreach (string uid in GetAll()) {
                    PrivateUserInfo info = Load<PrivateUserInfo>(uid);
                    other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());

                    foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
                        string name = Path.GetFileNameWithoutExtension(path);
                        if (name == typeof(PrivateUserInfo).FullName)
                            continue;

                        if (!types.TryGetValue(name, out Type? type)) {
                            foreach (replacedembly asm in asms)
                                if ((type = asm.GetType(name)) != null)
                                    break;
                            types[name] = type;
                        }

                        using Stream stream = File.OpenRead(path);
                        other.InsertData(uid, name, type, stream);
                    }

                    string dir = Path.Combine(UserRoot, uid, "data");
                    if (Directory.Exists(dir)) {
                        foreach (string path in Directory.GetFiles(dir)) {
                            string name = Path.GetFileName(path);
                            using Stream stream = File.OpenRead(path);
                            other.InsertFile(uid, name, stream);
                        }
                    }
                }
            }
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

public void DetectDisc(string inDir = "", Func<Dumper, string> outputDirFormatter = null)
        {
            outputDirFormatter ??= d => $"[{d.ProductCode}] {d.replacedle}";
            string discSfbPath = null;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom && d.IsReady);
                if (string.IsNullOrEmpty(inDir))
                {
                    foreach (var drive in drives)
                    {
                        discSfbPath = Path.Combine(drive.Name, "PS3_DISC.SFB");
                        if (!File.Exists(discSfbPath))
                            continue;

                        input = drive.Name;
                        Drive = drive.Name[0];
                        break;
                    }
                }
                else
                {
                    discSfbPath = Path.Combine(inDir, "PS3_DISC.SFB");
                    if (File.Exists(discSfbPath))
                    {
                        input = Path.GetPathRoot(discSfbPath);
                        Drive = discSfbPath[0];
                    }
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                if (string.IsNullOrEmpty(inDir))
                    inDir = "/media";
                discSfbPath = IOEx.GetFilepaths(inDir, "PS3_DISC.SFB", 2).FirstOrDefault();
                if (!string.IsNullOrEmpty(discSfbPath))
                    input = Path.GetDirectoryName(discSfbPath);
            }
            else
                throw new NotImplementedException("Current OS is not supported");

            if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(discSfbPath))
                throw new DriveNotFoundException("No valid PS3 disc was detected. Disc must be detected and mounted.");

            Log.Info("Selected disc: " + input);
            discSfbData = File.ReadAllBytes(discSfbPath);
            var replacedleId = CheckDiscSfb(discSfbData);
            var paramSfoPath = Path.Combine(input, "PS3_GAME", "PARAM.SFO");
            if (!File.Exists(paramSfoPath))
                throw new InvalidOperationException($"Specified folder is not a valid PS3 disc root (param.sfo is missing): {input}");

            using (var stream = File.Open(paramSfoPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                ParamSfo = ParamSfo.ReadFrom(stream);
            CheckParamSfo(ParamSfo);
            if (replacedleId != ProductCode)
                Log.Warn($"Product codes in ps3_disc.sfb ({replacedleId}) and in param.sfo ({ProductCode}) do not match");

            // todo: maybe use discutils instead to read TOC as one block
            var files = IOEx.GetFilepaths(input, "*", SearchOption.AllDirectories);
            DiscFilenames = new List<string>();
            var totalFilesize = 0L;
            var rootLength = input.Length;
            foreach (var f in files)
            {
                try { totalFilesize += new FileInfo(f).Length; } catch { }
                DiscFilenames.Add(f.Substring(rootLength));
            }
            TotalFileSize = totalFilesize;
            TotalFileCount = DiscFilenames.Count;

            OutputDir = new string(outputDirFormatter(this).ToCharArray().Where(c => !InvalidChars.Contains(c)).ToArray());
            Log.Debug($"Output: {OutputDir}");
        }

19 View Source File : WebContentFolderHelper.cs
License : MIT License
Project Creator : 52ABP

public static string CalculateContentRootFolder()
        {
            var corereplacedemblyDirectoryPath = Path.GetDirectoryName(typeof(BookListCoreModule).Getreplacedembly().Location);
            if (corereplacedemblyDirectoryPath == null)
            {
                throw new Exception("Could not find location of Cloud.BookList.Core replacedembly!");
            }

            var directoryInfo = new DirectoryInfo(corereplacedemblyDirectoryPath);
            while (!DirectoryContains(directoryInfo.FullName, "Cloud.BookList.sln"))
            {
                if (directoryInfo.Parent == null)
                {
                    throw new Exception("Could not find content root folder!");
                }

                directoryInfo = directoryInfo.Parent;
            }

            var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "Cloud.BookList.Web.Mvc");
            if (Directory.Exists(webMvcFolder))
            {
                return webMvcFolder;
            }

            var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "Cloud.BookList.Web.Host");
            if (Directory.Exists(webHostFolder))
            {
                return webHostFolder;
            }

            throw new Exception("Could not find root folder of the web project!");
        }

19 View Source File : WebContentFolderHelper.cs
License : MIT License
Project Creator : 52ABP

public static string CalculateContentRootFolder()
        {
            var corereplacedemblyDirectoryPath = Path.GetDirectoryName(typeof(PhoneBookCoreModule).Getreplacedembly().Location);
            if (corereplacedemblyDirectoryPath == null)
            {
                throw new Exception("Could not find location of SPACore.PhoneBook.Core replacedembly!");
            }

            var directoryInfo = new DirectoryInfo(corereplacedemblyDirectoryPath);
            while (!DirectoryContains(directoryInfo.FullName, "SPACore.PhoneBook.sln"))
            {
                if (directoryInfo.Parent == null)
                {
                    throw new Exception("Could not find content root folder!");
                }

                directoryInfo = directoryInfo.Parent;
            }

            var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "SPACore.PhoneBook.Web.Mvc");
            if (Directory.Exists(webMvcFolder))
            {
                return webMvcFolder;
            }

            var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "SPACore.PhoneBook.Web.Host");
            if (Directory.Exists(webHostFolder))
            {
                return webHostFolder;
            }

            throw new Exception("Could not find root folder of the web project!");
        }

19 View Source File : SimRuntime.cs
License : MIT License
Project Creator : abdullin

public string GetSimulationFolder() {
            if (_folder != null) {
                return _folder;
            }

            // HINT: create a memory disk here
            var root = "/Volumes/SimDisk";
            if (!Directory.Exists(root)) {
                root = Path.GetTempPath();
            }

            var folder = Path.Combine(root, "sim", DateTime.UtcNow.ToString("yy-MM-dd-HH-mm-ss"));
            _folder = folder;
            return folder;
        }

19 View Source File : UwpAppxBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static bool UpdateVSProj(IBuildInfo buildInfo)
        {
            // For ARM64 builds we need to add ResolvereplacedemblyWarnOrErrorOnTargetArchitectureMismatch
            // to vcxproj file in order to ensure that the build preplacedes

            string projectName = PlayerSettings.productName;
            string projectFilePath = Path.Combine(Path.GetFullPath(buildInfo.OutputDirectory), projectName, $"{projectName}.vcsproj");

            if (!File.Exists(projectFilePath))
            {
                Debug.LogError($"Cannot find project file: {projectFilePath}");
                return false;
            }

            var rootNode = XElement.Load(projectFilePath);
            var defaultNamespace = rootNode.GetDefaultNamespace();
            var propertyGroupNode = rootNode.Element(defaultNamespace + "PropertyGroup");
            
            if (propertyGroupNode == null)
            {
                propertyGroupNode = new XElement(defaultNamespace + "PropertyGroup", new XAttribute("Label", "Globals"));
                rootNode.Add(propertyGroupNode);
            }

            var newNode = propertyGroupNode.Element(defaultNamespace + "ResolvereplacedemblyWarnOrErrorOnTargetArchitectureMismatch");
            if (newNode != null)
            {
                // If this setting already exists in the project, ensure it's value is "None"
                newNode.Value = "None";
            }
            else
            {
                propertyGroupNode.Add(new XElement(defaultNamespace + "ResolvereplacedemblyWarnOrErrorOnTargetArchitectureMismatch", "None"));
            }

            rootNode.Save(projectFilePath);

            return true;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnLoaded(object sender, RoutedEventArgs e)
        {
            // Read image pixels
            var path = Path.Combine(Environment.CurrentDirectory, @"Resources", "TestImage.jpg");
            BitmapSource bitmap = new BitmapImage(new Uri(path));
            _pixels = new int[bitmap.PixelWidth * bitmap.PixelHeight];
            bitmap.CopyPixels(_pixels, bitmap.PixelWidth * 4, 0);

            // Create a Texture
            using (var rc = RenderSurface.GetRenderContext())
            {
                // Texture creation is very consuming, so recreate it as seldom as possible
                if (_texture == null)
                {
                    _texture.SafeDispose();
                    _texture = rc.CreateTexture(bitmap.PixelWidth, bitmap.PixelHeight);
                }
            }

            // Draw a Texture
            RenderTexture();
        }

19 View Source File : FileCache.cs
License : Apache License 2.0
Project Creator : acarteas

public override long GetCount(string regionName = null)
        {
            if (regionName == null)
            {
                regionName = "";
            }
            string path = Path.Combine(CacheDir, _cacheSubFolder, regionName);
            if (Directory.Exists(path))
                return Directory.GetFiles(path).Count();
            else
                return 0;
        }

19 View Source File : RunScriptViewModel.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public void LoadScratch()
        {
            var s = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var p = Path.Combine(s, "SCaddins", "Script.cs");
            if (!File.Exists(p)) {
                return;
            }
            Script = File.ReadAllText(p);
        }

19 View Source File : TabularModelSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit

internal static JObject SerializeColumns(JObject table, IProjectFolder modelFolder, string pathPrefix)
        {
            var columns = table["columns"]?.Value<JArray>();
            if (columns == null) return table;

            foreach (JObject column in columns)
            {
                var name = column["name"]?.Value<string>();
                if (name == null) continue;

                if (column["type"]?.Value<string>() == "calculated" && column.ContainsKey("expression"))
                {
                    var expression = column.SelectToken("expression");
                    modelFolder.Write(
                        ConvertExpression(expression),
                        Path.Combine(pathPrefix, "columns", $"{name.SanitizeFilename()}.dax")
                    );
                    expression.Parent.Remove();
                }

                modelFolder.Write(column, 
                    Path.Combine(pathPrefix, "columns", $"{name.SanitizeFilename()}.json")
                );
            }

            table = new JObject(table);
            table.Remove("columns");
            return table;
        }

19 View Source File : TabularModelSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit

internal static JObject SerializeMeasures(JObject table, IProjectFolder modelFolder, string pathPrefix)
        {
            var measures = table["measures"]?.Value<JArray>();
            if (measures == null) return table;

            foreach (var measure in measures)
            {
                var name = measure["name"]?.Value<string>();
                if (name == null) continue;

                modelFolder.WriteText(
                    Path.Combine(pathPrefix, "measures", $"{name.SanitizeFilename()}.xml"), 
                    WriteMeasureXml(measure)
                );

                var expression = measure.SelectToken("expression");
                if (expression != null)
                { 
                    modelFolder.Write(
                        ConvertExpression(expression),
                        Path.Combine(pathPrefix, "measures", $"{name.SanitizeFilename()}.dax")
                    );
                }
            }

            table = new JObject(table);
            table.Remove("measures");
            return table;
        }

19 View Source File : TabularModelSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit

internal static JObject SerializeHierarchies(JObject table, IProjectFolder modelFolder, string pathPrefix)
        {
            var hierarchies = table["hierarchies"]?.Value<JArray>();
            if (hierarchies == null) return table;

            foreach (var hierarchy in hierarchies)
            {
                var name = hierarchy["name"]?.Value<string>();
                if (name == null) continue;

                modelFolder.Write(hierarchy, 
                    Path.Combine(pathPrefix, "hierarchies", $"{name.SanitizeFilename()}.json")
                );
            }

            table = new JObject(table);
            table.Remove("hierarchies");
            return table;
        }

19 View Source File : CmdLineActions.cs
License : MIT License
Project Creator : action-bi-toolkit

[ArgActionMethod, ArgShortcut("export-bim"), ArgDescription("Converts the Model artifacts to a TMSL/BIM file.")]
        public void ExportBim(
            [ArgRequired, ArgExistingDirectory, ArgDescription("The PbixProj folder to export the BIM file from.")] string folder,
            [ArgDescription("Generate model data sources. Only required for deployment to Azure replacedysis Services, but not for Power BI Premium via the XMLA endpoint.")] bool generateDataSources,
            [ArgDescription("List transformations to be applied to TMSL doreplacedent.")] ExportTransforms transforms
        )
        {
            using (var rootFolder = new FileSystem.ProjectRootFolder(folder))
            {
                var serializer = new Serialization.TabularModelSerializer(rootFolder, ProjectSystem.PbixProject.FromFolder(rootFolder).Settings.Model);
                if (serializer.TryDeserialize(out var db))  // throws for V1 models
                {
                    if (generateDataSources)
                    {
#if NETFRAMEWORK
                        var dataSources = TabularModel.TabularModelConversions.GenerateDataSources(db);
                        db["model"]["dataSources"] = dataSources;
#elif NET
                        throw new PlatformNotSupportedException("Generating DataSources is not supported by the pbi-tools Core version.");
#endif
                    }

                    if (transforms.HasFlag(ExportTransforms.RemovePBIDataSourceVersion))
                    {
                        db["model"]["defaultPowerBIDataSourceVersion"]?.Parent.Remove();
                    }

                    var path = Path.GetFullPath(Path.Combine(folder, "..", $"{Path.GetFileName(folder)}.bim"));
                    using (var writer = new JsonTextWriter(File.CreateText(path)))
                    {
                        writer.Formatting = Formatting.Indented;
                        db.WriteTo(writer);
                    }

                    Console.WriteLine($"BIM file written to: {path}");
                }
                else
                {
                    throw new PbiToolsCliException(ExitCode.UnspecifiedError, "A BIM file could not be exported.");
                }
            }
        }

19 View Source File : SelfUpdater.cs
License : MIT License
Project Creator : actions

private string GenerateUpdateScript(bool restartInteractiveRunner)
        {
            int processId = Process.GetCurrentProcess().Id;
            string updateLog = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Diag), $"SelfUpdate-{DateTime.UtcNow.ToString("yyyyMMdd-HHmmss")}.log");
            string runnerRoot = HostContext.GetDirectory(WellKnownDirectory.Root);

#if OS_WINDOWS
            string templateName = "update.cmd.template";
#else
            string templateName = "update.sh.template";
#endif

            string templatePath = Path.Combine(runnerRoot, $"bin.{_targetPackage.Version}", templateName);
            string template = File.ReadAllText(templatePath);

            template = template.Replace("_PROCESS_ID_", processId.ToString());
            template = template.Replace("_RUNNER_PROCESS_NAME_", $"Runner.Listener{IOUtil.ExeExtension}");
            template = template.Replace("_ROOT_FOLDER_", runnerRoot);
            template = template.Replace("_EXIST_RUNNER_VERSION_", BuildConstants.RunnerPackage.Version);
            template = template.Replace("_DOWNLOAD_RUNNER_VERSION_", _targetPackage.Version);
            template = template.Replace("_UPDATE_LOG_", updateLog);
            template = template.Replace("_RESTART_INTERACTIVE_RUNNER_", restartInteractiveRunner ? "1" : "0");

#if OS_WINDOWS
            string scriptName = "_update.cmd";
#else
            string scriptName = "_update.sh";
#endif

            string updateScript = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), scriptName);
            if (File.Exists(updateScript))
            {
                IOUtil.DeleteFile(updateScript);
            }

            File.WriteAllText(updateScript, template);
            return updateScript;
        }

19 View Source File : GitCliManager.cs
License : MIT License
Project Creator : actions

public async Task<int> GitFetch(RunnerActionPluginExecutionContext context, string repositoryPath, string remoteName, int fetchDepth, List<string> refSpec, string additionalCommandLine, CancellationToken cancellationToken)
        {
            context.Debug($"Fetch git repository at: {repositoryPath} remote: {remoteName}.");
            if (refSpec != null && refSpec.Count > 0)
            {
                refSpec = refSpec.Where(r => !string.IsNullOrEmpty(r)).ToList();
            }

            // default options for git fetch.
            string options = StringUtil.Format($"--tags --prune --progress --no-recurse-submodules {remoteName} {string.Join(" ", refSpec)}");

            // If shallow fetch add --depth arg
            // If the local repository is shallowed but there is no fetch depth provide for this build,
            // add --unshallow to convert the shallow repository to a complete repository
            if (fetchDepth > 0)
            {
                options = StringUtil.Format($"--tags --prune --progress --no-recurse-submodules --depth={fetchDepth} {remoteName} {string.Join(" ", refSpec)}");
            }
            else
            {
                if (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")))
                {
                    options = StringUtil.Format($"--tags --prune --progress --no-recurse-submodules --unshallow {remoteName} {string.Join(" ", refSpec)}");
                }
            }

            int retryCount = 0;
            int fetchExitCode = 0;
            while (retryCount < 3)
            {
                fetchExitCode = await ExecuteGitCommandAsync(context, repositoryPath, "fetch", options, additionalCommandLine, cancellationToken);
                if (fetchExitCode == 0)
                {
                    break;
                }
                else
                {
                    if (++retryCount < 3)
                    {
                        var backOff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10));
                        context.Warning($"Git fetch failed with exit code {fetchExitCode}, back off {backOff.TotalSeconds} seconds before retry.");
                        await Task.Delay(backOff);
                    }
                }
            }

            return fetchExitCode;
        }

19 View Source File : GitSourceProvider.cs
License : MIT License
Project Creator : actions

private async Task RemoveGitConfig(RunnerActionPluginExecutionContext executionContext, GitCliManager gitCommandManager, string targetPath, string configKey, string configValue)
        {
            int exitCode_configUnset = await gitCommandManager.GitConfigUnset(executionContext, targetPath, configKey);
            if (exitCode_configUnset != 0)
            {
                // if unable to use git.exe unset http.extraheader or core.askpreplaced, modify git config file on disk. make sure we don't left credential.
                if (!string.IsNullOrEmpty(configValue))
                {
                    executionContext.Warning("An unsuccessful attempt was made using git command line to remove \"http.extraheader\" from the git config. Attempting to modify the git config file directly to remove the credential.");
                    string gitConfig = Path.Combine(targetPath, ".git/config");
                    if (File.Exists(gitConfig))
                    {
                        string gitConfigContent = File.ReadAllText(Path.Combine(targetPath, ".git", "config"));
                        if (gitConfigContent.Contains(configKey))
                        {
                            string setting = $"extraheader = {configValue}";
                            gitConfigContent = Regex.Replace(gitConfigContent, setting, string.Empty, RegexOptions.IgnoreCase);

                            setting = $"askpreplaced = {configValue}";
                            gitConfigContent = Regex.Replace(gitConfigContent, setting, string.Empty, RegexOptions.IgnoreCase);

                            File.WriteAllText(gitConfig, gitConfigContent);
                        }
                    }
                }
                else
                {
                    executionContext.Warning($"Unable to remove \"{configKey}\" from the git config. To remove the credential, execute \"git config --unset - all {configKey}\" from the repository root \"{targetPath}\".");
                }
            }
        }

19 View Source File : OutputManager.cs
License : MIT License
Project Creator : actions

private string GetRepositoryPath(string filePath, int recursion = 0)
        {
            // Prevent the cache from growing too much
            if (_directoryMap.Count > 100)
            {
                _directoryMap.Clear();
            }

            // Empty directory means we hit the root of the drive
            var directoryPath = Path.GetDirectoryName(filePath);
            if (string.IsNullOrEmpty(directoryPath) || recursion > _failsafe)
            {
                return null;
            }

            // Check the cache
            if (_directoryMap.TryGetValue(directoryPath, out string repositoryPath))
            {
                return repositoryPath;
            }

            try
            {
                // Check if .git/config exists
                var gitConfigPath = Path.Combine(directoryPath, ".git", "config");
                if (File.Exists(gitConfigPath))
                {
                    // Check if the config contains the workflow repository url
                    var serverUrl = _executionContext.GetGitHubContext("server_url");
                    serverUrl = !string.IsNullOrEmpty(serverUrl) ? serverUrl : "https://github.com";
                    var host = new Uri(serverUrl, UriKind.Absolute).Host;
                    var nameWithOwner = _executionContext.GetGitHubContext("repository");
                    var patterns = new[] {
                        $"url = {serverUrl}/{nameWithOwner}",
                        $"url = git@{host}:{nameWithOwner}.git",
                    };
                    var content = File.ReadAllText(gitConfigPath);
                    foreach (var line in content.Split("\n").Select(x => x.Trim()))
                    {
                        foreach (var pattern in patterns)
                        {
                            if (String.Equals(line, pattern, StringComparison.OrdinalIgnoreCase))
                            {
                                repositoryPath = directoryPath;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    // Recursive call
                    repositoryPath = GetRepositoryPath(directoryPath, recursion + 1);
                }
            }
            catch (Exception ex)
            {
                _executionContext.Debug($"Error when attempting to determine whether the path '{filePath}' is under the workflow repository: {ex.Message}");
            }

            _directoryMap[directoryPath] = repositoryPath;
            return repositoryPath;
        }

19 View Source File : GitCliManager.cs
License : MIT License
Project Creator : actions

public async Task<int> GitFetchNoTags(RunnerActionPluginExecutionContext context, string repositoryPath, string remoteName, int fetchDepth, List<string> refSpec, string additionalCommandLine, CancellationToken cancellationToken)
        {
            context.Debug($"Fetch git repository at: {repositoryPath} remote: {remoteName}.");
            if (refSpec != null && refSpec.Count > 0)
            {
                refSpec = refSpec.Where(r => !string.IsNullOrEmpty(r)).ToList();
            }

            string options;

            // If shallow fetch add --depth arg
            // If the local repository is shallowed but there is no fetch depth provide for this build,
            // add --unshallow to convert the shallow repository to a complete repository
            if (fetchDepth > 0)
            {
                options = StringUtil.Format($"--no-tags --prune --progress --no-recurse-submodules --depth={fetchDepth} {remoteName} {string.Join(" ", refSpec)}");
            }
            else if (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")))
            {
                options = StringUtil.Format($"--no-tags --prune --progress --no-recurse-submodules --unshallow {remoteName} {string.Join(" ", refSpec)}");
            }
            else
            {
                // default options for git fetch.
                options = StringUtil.Format($"--no-tags --prune --progress --no-recurse-submodules {remoteName} {string.Join(" ", refSpec)}");
            }

            int retryCount = 0;
            int fetchExitCode = 0;
            while (retryCount < 3)
            {
                fetchExitCode = await ExecuteGitCommandAsync(context, repositoryPath, "fetch", options, additionalCommandLine, cancellationToken);
                if (fetchExitCode == 0)
                {
                    break;
                }
                else
                {
                    if (++retryCount < 3)
                    {
                        var backOff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10));
                        context.Warning($"Git fetch failed with exit code {fetchExitCode}, back off {backOff.TotalSeconds} seconds before retry.");
                        await Task.Delay(backOff);
                    }
                }
            }

            return fetchExitCode;
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesDirectoriesRecursively()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a grandchild directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    Directory.CreateDirectory(Path.Combine(directory, "some child directory", "some grandchild directory"));

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : OutputManagerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public async void MatcherFile()
        {
            Environment.SetEnvironmentVariable("RUNNER_TEST_GET_REPOSITORY_PATH_FAILSAFE", "2");
            var matchers = new IssueMatchersConfig
            {
                Matchers =
                {
                    new IssueMatcherConfig
                    {
                        Owner = "my-matcher-1",
                        Patterns = new[]
                        {
                            new IssuePatternConfig
                            {
                                Pattern = @"(.+): (.+)",
                                File = 1,
                                Message = 2,
                            },
                        },
                    },
                },
            };
            using (var hostContext = Setup(matchers: matchers))
            using (_outputManager)
            {
                // Setup github.workspace, github.repository
                var workDirectory = hostContext.GetDirectory(WellKnownDirectory.Work);
                ArgUtil.NotNullOrEmpty(workDirectory, nameof(workDirectory));
                Directory.CreateDirectory(workDirectory);
                var workspaceDirectory = Path.Combine(workDirectory, "workspace");
                Directory.CreateDirectory(workspaceDirectory);
                _executionContext.Setup(x => x.GetGitHubContext("workspace")).Returns(workspaceDirectory);
                _executionContext.Setup(x => x.GetGitHubContext("repository")).Returns("my-org/workflow-repo");

                // Setup some git repositories
                // <WORKSPACE>/workflow-repo
                // <WORKSPACE>/workflow-repo/nested-other-repo
                // <WORKSPACE>/other-repo
                // <WORKSPACE>/other-repo/nested-workflow-repo
                // <WORKSPACE>/workflow-repo-using-ssh
                var workflowRepository = Path.Combine(workspaceDirectory, "workflow-repo");
                var nestedOtherRepository = Path.Combine(workspaceDirectory, "workflow-repo", "nested-other-repo");
                var otherRepository = Path.Combine(workspaceDirectory, workflowRepository, "nested-other-repo");
                var nestedWorkflowRepository = Path.Combine(workspaceDirectory, "other-repo", "nested-workflow-repo");
                var workflowRepositoryUsingSsh = Path.Combine(workspaceDirectory, "workflow-repo-using-ssh");
                await CreateRepository(hostContext, workflowRepository, "https://github.com/my-org/workflow-repo");
                await CreateRepository(hostContext, nestedOtherRepository, "https://github.com/my-org/other-repo");
                await CreateRepository(hostContext, otherRepository, "https://github.com/my-org/other-repo");
                await CreateRepository(hostContext, nestedWorkflowRepository, "https://github.com/my-org/workflow-repo");
                await CreateRepository(hostContext, workflowRepositoryUsingSsh, "git@github.com:my-org/workflow-repo.git");

                // Create test files
                var file_noRepository = Path.Combine(workspaceDirectory, "no-repo.txt");
                var file_workflowRepository = Path.Combine(workflowRepository, "workflow-repo.txt");
                var file_workflowRepository_nestedDirectory = Path.Combine(workflowRepository, "subdir", "subdir2", "workflow-repo-nested-dir.txt");
                var file_workflowRepository_failsafe = Path.Combine(workflowRepository, "failsafe-subdir", "failsafe-subdir2", "failsafe-subdir3", "workflow-repo-failsafe.txt");
                var file_nestedOtherRepository = Path.Combine(nestedOtherRepository, "nested-other-repo");
                var file_otherRepository = Path.Combine(otherRepository, "other-repo.txt");
                var file_nestedWorkflowRepository = Path.Combine(nestedWorkflowRepository, "nested-workflow-repo.txt");
                var file_workflowRepositoryUsingSsh = Path.Combine(workflowRepositoryUsingSsh, "workflow-repo-using-ssh.txt");
                foreach (var file in new[] { file_noRepository, file_workflowRepository, file_workflowRepository_nestedDirectory, file_workflowRepository_failsafe, file_nestedOtherRepository, file_otherRepository, file_nestedWorkflowRepository, file_workflowRepositoryUsingSsh })
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(file));
                    File.WriteAllText(file, "");
                }

                // Process
                Process($"{file_noRepository}: some error 1");
                Process($"{file_workflowRepository}: some error 2");
                Process($"{file_workflowRepository.Substring(workspaceDirectory.Length + 1)}: some error 3"); // Relative path from workspace dir
                Process($"{file_workflowRepository_nestedDirectory}: some error 4");
                Process($"{file_workflowRepository_failsafe}: some error 5");
                Process($"{file_nestedOtherRepository}: some error 6");
                Process($"{file_otherRepository}: some error 7");
                Process($"{file_nestedWorkflowRepository}: some error 8");
                Process($"{file_workflowRepositoryUsingSsh}: some error 9");

                replacedert.Equal(9, _issues.Count);

                replacedert.Equal("some error 1", _issues[0].Item1.Message);
                replacedert.False(_issues[0].Item1.Data.ContainsKey("file"));

                replacedert.Equal("some error 2", _issues[1].Item1.Message);
                replacedert.Equal(file_workflowRepository.Substring(workflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[1].Item1.Data["file"]);

                replacedert.Equal("some error 3", _issues[2].Item1.Message);
                replacedert.Equal(file_workflowRepository.Substring(workflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[2].Item1.Data["file"]);

                replacedert.Equal("some error 4", _issues[3].Item1.Message);
                replacedert.Equal(file_workflowRepository_nestedDirectory.Substring(workflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[3].Item1.Data["file"]);

                replacedert.Equal("some error 5", _issues[4].Item1.Message);
                replacedert.False(_issues[4].Item1.Data.ContainsKey("file"));

                replacedert.Equal("some error 6", _issues[5].Item1.Message);
                replacedert.False(_issues[5].Item1.Data.ContainsKey("file"));

                replacedert.Equal("some error 7", _issues[6].Item1.Message);
                replacedert.False(_issues[6].Item1.Data.ContainsKey("file"));

                replacedert.Equal("some error 8", _issues[7].Item1.Message);
                replacedert.Equal(file_nestedWorkflowRepository.Substring(nestedWorkflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[7].Item1.Data["file"]);

                replacedert.Equal("some error 9", _issues[8].Item1.Message);
                replacedert.Equal(file_workflowRepositoryUsingSsh.Substring(workflowRepositoryUsingSsh.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[8].Item1.Data["file"]);
            }

            Environment.SetEnvironmentVariable("RUNNER_TEST_GET_REPOSITORY_PATH_FAILSAFE", "");
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesFilesRecursively()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a grandchild file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string file = Path.Combine(directory, "some subdirectory", "some file");
                    Directory.CreateDirectory(Path.GetDirectoryName(file));
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : SetEnvFileCommandL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public void SetEnvFileCommand_DirectoryNotFound()
        {
            using (var hostContext = Setup())
            {
                var envFile = Path.Combine(_rootDirectory, "directory-not-found", "env");
                _setEnvFileCommand.ProcessCommand(_executionContext.Object, envFile, null);
                replacedert.Equal(0, _issues.Count);
                replacedert.Equal(0, _executionContext.Object.Global.EnvironmentVariables.Count);
            }
        }

19 View Source File : PipelineDirectoryManagerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public void DeletesNonResourceDirectoryWhenCleanIsOutputs()
        {
            // Arrange.
            using (TestHostContext hc = Setup())
            {
                _existingConfig = new TrackingConfig(_ec.Object);
                _trackingManager.Setup(x => x.LoadIfExists(_ec.Object, _trackingFile)).Returns(_existingConfig);

                _workspaceOptions.Clean = Pipelines.PipelineConstants.WorkspaceCleanOptions.Outputs;
                string nonResourceDirectory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Work), _existingConfig.PipelineDirectory, "somedir");
                string sourceFile = Path.Combine(nonResourceDirectory, "some subdirectory", "some source file");
                Directory.CreateDirectory(Path.GetDirectoryName(sourceFile));
                File.WriteAllText(path: sourceFile, contents: "some source contents");

                // Act.
                _pipelineDirectoryManager.PrepareDirectory(_ec.Object, _workspaceOptions);

                // replacedert.
                replacedert.False(Directory.Exists(nonResourceDirectory));
            }
        }

19 View Source File : PipelineDirectoryManagerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public void DeletesResourceDirectoryWhenCleanIsResources()
        {
            // Arrange.
            using (TestHostContext hc = Setup())
            {
                _existingConfig = new TrackingConfig(_ec.Object);
                _trackingManager.Setup(x => x.LoadIfExists(_ec.Object, _trackingFile)).Returns(_existingConfig);

                _workspaceOptions.Clean = Pipelines.PipelineConstants.WorkspaceCleanOptions.Resources;
                string workspaceDirectory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Work), _existingConfig.WorkspaceDirectory);
                string sourceFile = Path.Combine(workspaceDirectory, "some subdirectory", "some source file");
                Directory.CreateDirectory(Path.GetDirectoryName(sourceFile));
                File.WriteAllText(path: sourceFile, contents: "some source contents");

                // Act.
                _pipelineDirectoryManager.PrepareDirectory(_ec.Object, _workspaceOptions);

                // replacedert.
                replacedert.True(Directory.Exists(workspaceDirectory));
                replacedert.Equal(0, Directory.GetFileSystemEntries(workspaceDirectory, "*", SearchOption.AllDirectories).Length);
            }
        }

19 View Source File : PipelineDirectoryManagerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public void RecreatesPipelinesDirectoryWhenCleanIsAll()
        {
            // Arrange.
            using (TestHostContext hc = Setup())
            {
                _existingConfig = new TrackingConfig(_ec.Object);
                _trackingManager.Setup(x => x.LoadIfExists(_ec.Object, _trackingFile)).Returns(_existingConfig);

                _workspaceOptions.Clean = Pipelines.PipelineConstants.WorkspaceCleanOptions.All;

                string pipelinesDirectory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Work), _existingConfig.PipelineDirectory);
                string looseFile = Path.Combine(pipelinesDirectory, "some loose directory", "some loose file");
                Directory.CreateDirectory(Path.GetDirectoryName(looseFile));
                File.WriteAllText(path: looseFile, contents: "some loose file contents");

                // Act.
                _pipelineDirectoryManager.PrepareDirectory(_ec.Object, _workspaceOptions);

                // replacedert.
                replacedert.Equal(1, Directory.GetFileSystemEntries(pipelinesDirectory, "*", SearchOption.AllDirectories).Length);
                replacedert.True(Directory.Exists(Path.Combine(hc.GetDirectory(WellKnownDirectory.Work), _existingConfig.WorkspaceDirectory)));
            }
        }

19 View Source File : SuppressionFileIOTests.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private string GetFileFullPath(string shortFileName)
		{
			DirectoryInfo debugOrReleaseDir = new DirectoryInfo(Environment.CurrentDirectory);
			string solutionDir = debugOrReleaseDir.Parent.Parent.FullName;
			return Path.Combine(solutionDir, RelativeTestPath, shortFileName);
		}

19 View Source File : GenerateNuSpecFileTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            var replacedle = !string.IsNullOrEmpty(replacedle) ? replacedle : PackageId;

            var sb = new System.Text.StringBuilder(); //TODO refactor to LINQ XML
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine($"<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">");
            sb.AppendLine($" <metadata>");
            sb.AppendLine($"  <id>{PackageId}</id>");
            sb.AppendLine($"  <version>{PackageVersionFull}</version>");
            sb.AppendLine($"  <authors>{Authors}</authors>");
            sb.AppendLine($"  <replacedle>{replacedle}</replacedle>");
            sb.AppendLine($"  <owners>{Authors}</owners>");
            sb.AppendLine($"  <requireLicenseAcceptance>{PackageRequireLicenseAcceptance}</requireLicenseAcceptance>");
            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
            if (!string.IsNullOrEmpty(PackageLicense))
            {
                sb.AppendLine($"  <license type=\"expression\">{PackageLicense}</license>");
            }
            else
            {
                sb.AppendLine($"  <licenseUrl>{PackageLicenseUrl}</licenseUrl>");
            }
            sb.AppendLine($"  <projectUrl>{PackageProjectUrl}</projectUrl>");
            sb.AppendLine($"  <iconUrl>{PackageIconUrl}</iconUrl>");
            sb.AppendLine($"  <description>{Description}</description>");
            sb.AppendLine($"  <releaseNotes>{PackageReleaseNotes}</releaseNotes>");
            sb.AppendLine($"  <copyright>{Copyright}</copyright>");
            sb.AppendLine($"  <tags>{PackageTags}</tags>");
            sb.AppendLine(
                $"  <repository url=\"{RepositoryUrl}\" type=\"git\" branch=\"{GitBranch}\" commit=\"{GitCommit}\" />");
            sb.AppendLine($"  <dependencies>");
            sb.AppendLine($"   <group targetFramework=\"{TargetFramework}\">");

            if (PackageReferences != null)
            {
                foreach (var r in PackageReferences)
                {
                    var item = r.ItemSpec;
                    if (item != "NETStandard.Library")
                        sb.AppendLine(
                            $"    <dependency id=\"{r.ItemSpec}\" version=\"{r.GetMetadata("Version")}\" exclude=\"Build,replacedyzers\" />");
                }
            }

            var resolvedProjectReferences =
                new List<string>(); //project references that has been resolved as NuGet packages
            if (ProjectReferences != null)
            {
                foreach (var src in ProjectReferences)
                {
                    var refPackageDependencyFile = Path.Combine(src.GetMetadata("RelativeDir"), IntermediateOutputPath,
                        Configuration, "package_dependency.txt");
                    if (!File.Exists(refPackageDependencyFile)) continue;

                    var refPackageDependency = File.ReadAllText(refPackageDependencyFile);

                    resolvedProjectReferences.Add(refPackageDependency);
                    sb.AppendLine(refPackageDependency);
                }
            }

            sb.AppendLine($"   </group>");
            sb.AppendLine($"  </dependencies>");
            sb.AppendLine($" </metadata>");

            sb.AppendLine($"  <files>");
            var dllFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.dll");
            sb.AppendLine($@"    <file src=""{dllFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.dll"" />");

            var pdbFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.pdb");
            if (File.Exists(pdbFile))
            {
                sb.AppendLine($@"    <file src=""{pdbFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.pdb"" />");
            }

            var xmlDocFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.xml");
            if (File.Exists(xmlDocFile))
            {
                sb.AppendLine(
                    $@"    <file src=""{xmlDocFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.xml"" />");
            }

            if (SourceFiles != null && Configuration.ToLower() != "release")
            {
                sb.AppendLine("");

                foreach (var src in SourceFiles)
                {
                    var srcFileOriginal = src.GetMetadata("OriginalItemSpec");
                    var srcFileRel = srcFileOriginal.Replace($@"{ProjectDirectory}\", "");
                    if (Path.IsPathRooted(srcFileRel)) continue; //not a project file (probably source-only package) - project files have the relative path in srcFileRel, non project files have full path in srcFileRel 

                    var targetFile = Path.Combine("src", ProjectName, srcFileRel);
                    sb.AppendLine($@"    <file src=""{src}"" target=""{targetFile}"" />");
                }
            }

            //include project references that has NOT been resolved as NuGet packages
            if (ProjectReferences != null && ReferenceCopyLocalPaths != null)
            {
                foreach (var rf in ReferenceCopyLocalPaths)
                {
                    if (rf.GetMetadata("ReferenceSourceTarget") == "ProjectReference")
                    {
                        var fileName = rf.GetMetadata("FileName");
                        if (!resolvedProjectReferences.Exists(s => s.Contains($"id=\"{fileName}\"")))
                        {
                            sb.AppendLine(
                                $@"    <file src=""{rf.GetMetadata("FullPath")}"" target=""lib\{TargetFramework}\{rf.GetMetadata("FileName")}{rf.GetMetadata("Extension")}"" />");
                        }
                    }
                }
            }

            sb.AppendLine($"  </files>");

            sb.AppendLine($"</package>  ");

            //Write NuSpec file to /obj directory
            NuSpecFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
                PackageVersionShort + ".nuspec");
            File.WriteAllText(NuSpecFile, sb.ToString());

            Log.LogMessage(sb.ToString());

            //Create dependency file for package in /obj directory
            var dep =
                $@"<dependency id=""{PackageId}"" version=""{PackageVersionFull}"" exclude=""Build,replacedyzers"" />";
            var dependencyFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
                "package_dependency.txt");
            File.WriteAllText(dependencyFile, dep);

            return true;
        }

19 View Source File : Solution.cs
License : Apache License 2.0
Project Creator : adamralph

public static string GetFullPath(string path) =>
            Path.GetFullPath(Path.Combine(typeof(Solution).replacedembly.Location, $"../../../../../", path));

19 View Source File : ResourceTestBase.cs
License : MIT License
Project Creator : adrianoc

protected void replacedertResourceTestBinary(string resourceBasePath, TestKind kind)
        {
            var expectedreplacedemblyPath = resourceBasePath.GetPathOfBinaryResource("Expected.dll", kind);

            var tbc = ReadResource(resourceBasePath, "cs", kind);
            var actualreplacedemblyPath = Path.Combine(Path.GetTempPath(), "CecilifierTests/", resourceBasePath + ".dll");
            replacedertResourceTest(actualreplacedemblyPath, expectedreplacedemblyPath, tbc);
        }

19 View Source File : ResourceTestBase.cs
License : MIT License
Project Creator : adrianoc

protected void replacedertResourceTestWithExplicitExpectation(string resourceName, string methodSignature)
        {
            using (var tbc = ReadResource(resourceName, "cs", TestKind.Integration))
            using (var expectedILStream = ReadResource(resourceName, "cs.il", TestKind.Integration))
            {
                var expectedIL = ReadToEnd(expectedILStream);

                var actualreplacedemblyPath = Path.Combine(Path.GetTempPath(), "CecilifierTests/", resourceName + ".dll");

                replacedertResourceTestWithExplicitExpectedIL(actualreplacedemblyPath, expectedIL, methodSignature, tbc);

                Console.WriteLine();
                Console.WriteLine("Expected IL: {0}", expectedIL);
                Console.WriteLine("Actual replacedembly path : {0}", actualreplacedemblyPath);
            }
        }

19 View Source File : SimpleAudioRecorderImplementation.cs
License : MIT License
Project Creator : adrianstevens

string GetTempFileName()
        {
            var docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var libFolder = Path.Combine(docFolder, "..", "Library");
            var tempFileName = Path.Combine(libFolder, Path.GetTempFileName());

            return tempFileName;
        }

19 View Source File : VideoPlayer.cs
License : GNU General Public License v3.0
Project Creator : aduskin

public override void OnApplyTemplate()
      {
         this.UnRegisterEvent();

         base.OnApplyTemplate();

         this.PART_VlcControl = this.GetTemplateChild("PART_VlcControl") as VlcControl;
         if (this.PART_VlcControl != null)
         {
            var vlcLibDirectory = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));

            var options = new string[]
            {
               // VLC options can be given here. Please refer to the VLC command line doreplacedentation.
            };

            Task.Run(() =>
            {
               Application.Current.Dispatcher.Invoke(() =>
               {
                   this.IsVlcControlLoading = true;
                });
               this.PART_VlcControl.SourceProvider.CreatePlayer(vlcLibDirectory, options);
            }).ContinueWith((t) =>
            {
               Application.Current.Dispatcher.Invoke(() =>
                   {
                   this.IsVlcControlLoading = false;
                   this.RegisterEvent();
                   if (this.PART_Volume_Slider != null)
                   {
                      this.PART_Volume_Slider.Maximum = InitVolume;
                      this.PART_Volume_Slider.Minimum = 0;
                      this.PART_Volume_Slider.Value = this.Volume;
                   }
                });
            });
         }

         this.PART_Btn_Play = this.GetTemplateChild("PART_Btn_Play") as Button;
         this.PART_Btn_Pause = this.GetTemplateChild("PART_Btn_Pause") as Button;
         this.PART_Btn_Stop = this.GetTemplateChild("PART_Btn_Stop") as Button;
         this.PART_Btn_Next = this.GetTemplateChild("PART_Btn_Next") as Button;
         this.PART_Btn_Previous = this.GetTemplateChild("PART_Btn_Previous") as Button;
         this.PART_Time_Current = this.GetTemplateChild("PART_Time_Current") as Run;
         this.PART_Time_Total = this.GetTemplateChild("PART_Time_Total") as Run;
         this.PART_Video_Time = this.GetTemplateChild("PART_Video_Time") as TextBlock;
         this.PART_Bottom_Tool = this.GetTemplateChild("PART_Bottom_Tool") as Border;
         this.PART_Slider = this.GetTemplateChild("PART_Slider") as AduFlatSilder;
         this.PART_Btn_Slower = this.GetTemplateChild("PART_Btn_Slower") as Button;
         this.PART_Btn_Faster = this.GetTemplateChild("PART_Btn_Faster") as Button;
         this.PART_MouseOver_Area = this.GetTemplateChild("PART_MouseOver_Area") as Border;
         this.PART_Volume_Slider = this.GetTemplateChild("PART_Volume_Slider") as Slider;
         this.PART_Loading = this.GetTemplateChild("PART_Loading") as AduLoading;
         //播放地址
         this.PART_PlayInfo = this.GetTemplateChild("PART_PlayInfo") as Border;
         this.PART_Txt_VideoSource = this.GetTemplateChild("PART_Txt_VideoSource") as MetroTextBox;
         this.PART_Btn_PlayLocalFile = this.GetTemplateChild("PART_Btn_PlayLocalFile") as AduFlatButton;
         this.PART_Btn_PlayUri = this.GetTemplateChild("PART_Btn_PlayUri") as AduFlatButton;
         this.PART_Btn_Screenshot = this.GetTemplateChild("PART_Btn_Screenshot") as Button;
         this.PART_Btn_OpenFile = this.GetTemplateChild("PART_Btn_OpenFile") as Button;
         this.VideoStoped();
      }

19 View Source File : MobilePhoneCall.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void ShowMainCallDialogue(NPC npc)
        {
            Monitor.Log($"Showing Main Call Dialogue");

            ModEntry.buildingInCall = false;

            if (!ModEntry.inCall)
            {
                Monitor.Log($"Not in call, exiting");
                return;
            }

            List<Response> answers = new List<Response>();
            if (npc.CurrentDialogue != null && npc.CurrentDialogue.Count > 0)
                answers.Add(new Response("PhoneApp_InCall_Chat", Helper.Translation.Get("chat")));

            if (inCallReminiscence == null)
            {
                Reminiscence r;
                if (contentPackReminiscences.ContainsKey(npc.Name))
                {
                    r = contentPackReminiscences[npc.Name];
                }
                else
                {
                    r = Helper.Data.ReadJsonFile<Reminiscence>(Path.Combine("replacedets", "events", $"{npc.Name}.json")) ?? new Reminiscence();
                }
                Monitor.Log($"Total Reminisces: {r.events.Count}");
                r.WeedOutUnseen();
                Monitor.Log($"Seen Reminisces: {r.events.Count}");
                inCallReminiscence = new List<Reminisce>(r.events);
            }
            if (inCallReminiscence != null && inCallReminiscence.Count > 0)
            {
                answers.Add(new Response("PhoneApp_InCall_Reminisce", Helper.Translation.Get("reminisce")));
            }
            if (eventInvites.Count > 0)
            {
                foreach (EventInvite ei in eventInvites)
                {
                    if (ei.CanInvite(npc))
                    {
                        answers.Add(new Response("PhoneApp_InCall_Invite", Helper.Translation.Get("invite")));
                        break;
                    }
                }
            }
            if (ModEntry.npcAdventureModApi != null && ModEntry.npcAdventureModApi.IsPossibleCompanion(npc) && ModEntry.npcAdventureModApi.CanAskToFollow(npc) && !npc.isSleeping.Value)
            {
                answers.Add(new Response("PhoneApp_InCall_Recruit", Helper.Translation.Get("recruit")));
            }
            if (npc.Name == "Robin" && Game1.player.daysUntilHouseUpgrade.Value < 0 && !Game1.getFarm().isThereABuildingUnderConstruction())
            {
                if (Game1.player.HouseUpgradeLevel < 3)
                    answers.Add(new Response("PhoneApp_InCall_Upgrade", Helper.Translation.Get("upgrade-house")));
                answers.Add(new Response("PhoneApp_InCall_Build", Helper.Translation.Get("build-buildings")));
            }
            answers.Add(new Response("PhoneApp_InCall_GoodBye", Helper.Translation.Get("goodbye")));

            Game1.player.currentLocation.createQuestionDialogue(GetCallGreeting(npc), answers.ToArray(), CallDialogueAnswer);
            Game1.objectDialoguePortraitPerson = npc;
        }

19 View Source File : PhoneGameLoop.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
        {
            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
            {
                Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}");
                try
                {
                    MobilePhonePackJSON json = contentPack.ReadJsonFile<MobilePhonePackJSON>("content.json") ?? null;
                    
                    if(json != null)
                    {
                        if (json.apps != null && json.apps.Any())
                        {
                            foreach (AppJSON app in json.apps)
                            {
                                Texture2D tex = contentPack.Loadreplacedet<Texture2D>(app.iconPath);
                                if (tex == null)
                                {
                                    continue;
                                }
                                ModEntry.apps.Add(app.id, new MobileApp(app.name, app.keyPress, app.closePhone, tex));
                                Monitor.Log($"Added app {app.name} from {contentPack.DirectoryPath}");
                            }
                        }
                        else if (json.iconPath != null)
                        {
                            Texture2D icon = contentPack.Loadreplacedet<Texture2D>(json.iconPath);
                            if (icon == null)
                            {
                                continue;
                            }
                            ModEntry.apps.Add(json.id, new MobileApp(json.name, json.keyPress, json.closePhone, icon));
                            Monitor.Log($"Added app {json.name} from {contentPack.DirectoryPath}");
                        }
                        if (json.invites != null && json.invites.Any())
                        {
                            foreach (EventInvite invite in json.invites)
                            {
                                MobilePhoneCall.eventInvites.Add(invite);
                                Monitor.Log($"Added event invite {invite.name} from {contentPack.DirectoryPath}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log($"error reading content.json file in content pack {contentPack.Manifest.Name}.\r\n{ex}", LogLevel.Error);
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "events")))
                {
                    Monitor.Log($"Adding events");
                    string[] events = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "events"), "*.json");
                    Monitor.Log($"CP has {events.Length} events");
                    foreach (string eventFile in events)
                    {
                        try
                        {
                            string eventPath = Path.Combine("replacedets", "events", Path.GetFileName(eventFile));
                            Monitor.Log($"Adding events {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
                            Reminiscence r = contentPack.ReadJsonFile<Reminiscence>(eventPath);
                            MobilePhoneCall.contentPackReminiscences.Add(Path.GetFileName(eventFile).Replace(".json", ""), r);
                            Monitor.Log($"Added event {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
                        }
                        catch { }
                    }
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins")))
                {
                    Monitor.Log($"Adding skins");
                    string[] skins = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins"), "*_landscape.png");
                    Monitor.Log($"CP has {skins.Length} skins");
                    foreach (string skinFile in skins)
                    {
                        try
                        {
                            string skinPath = Path.Combine("replacedets", "skins", Path.GetFileName(skinFile));
                            Monitor.Log($"Adding skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                            Texture2D skin = contentPack.Loadreplacedet<Texture2D>(skinPath.Replace("_landscape.png", ".png"));
                            Texture2D skinl = contentPack.Loadreplacedet<Texture2D>(skinPath);
                            ThemeApp.skinList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""));
                            ThemeApp.skinDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""), new Texture2D[] { skin, skinl});
                            Monitor.Log($"Added skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                        }
                        catch { }
                    }
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds")))
                {
                    Monitor.Log($"Adding backgrounds");
                    string[] backgrounds = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds"), "*_landscape.png");
                    Monitor.Log($"CP has {backgrounds.Length} backgrounds");
                    foreach (string backFile in backgrounds)
                    {
                        try
                        {
                            string backPath = Path.Combine("replacedets", "backgrounds", Path.GetFileName(backFile));
                            Monitor.Log($"Adding background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                            Texture2D back = contentPack.Loadreplacedet<Texture2D>(backPath.Replace("_landscape.png", ".png"));
                            Texture2D backl = contentPack.Loadreplacedet<Texture2D>(backPath);
                            ThemeApp.backgroundDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""), new Texture2D[] { back, backl });
                            ThemeApp.backgroundList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""));
                            Monitor.Log($"Added background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                        }
                        catch { }
                    }
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones")))
                {
                    Monitor.Log($"Adding ringtones");
                    string[] rings = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones"), "*.wav");
                    Monitor.Log($"CP has {rings.Length} ringtones");
                    foreach (string path in rings)
                    {
                        try
                        {
                            object ring;
                            try
                            {
                                var type = Type.GetType("System.Media.SoundPlayer, System");
                                ring = Activator.CreateInstance(type, new object[] { path });
                            }
                            catch
                            {
                                ring = SoundEffect.FromStream(new FileStream(path, FileMode.Open));
                            }
                            if (ring != null)
                            {
                                ThemeApp.ringDict.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")), ring);
                                ThemeApp.ringList.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")));
                                Monitor.Log($"loaded ring {path}");
                            }
                            else
                                Monitor.Log($"Couldn't load ring {path}");
                        }
                        catch (Exception ex)
                        {
                            Monitor.Log($"Couldn't load ring {path}:\r\n{ex}", LogLevel.Error);
                        }
                    }
                }
            }

            ModEntry.listHeight = Config.IconMarginY + (int)Math.Ceiling(ModEntry.apps.Count / (float)ModEntry.gridWidth) * (Config.IconHeight + Config.IconMarginY);
            PhoneVisuals.CreatePhoneTextures();
            PhoneUtils.RefreshPhoneLayout();

            if (Helper.ModRegistry.IsLoaded("purrplingcat.npcadventure"))
            {
                INpcAdventureModApi api = Helper.ModRegistry.GetApi<INpcAdventureModApi>("purrplingcat.npcadventure");
                if (api != null)
                {
                    Monitor.Log("Loaded NpcAdventureModApi successfully");
                    ModEntry.npcAdventureModApi = api;
                }
            }
        }

19 View Source File : PhoneVisuals.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void CreatePhoneTextures()
        {
            if (ThemeApp.skinDict.ContainsKey(Config.PhoneSkinPath))
            {
                ModEntry.phoneTexture = ThemeApp.skinDict[Config.PhoneSkinPath][0];
                ModEntry.phoneRotatedTexture = ThemeApp.skinDict[Config.PhoneSkinPath][1];
            }
            else
            {
                ModEntry.phoneTexture = ThemeApp.skinDict[Path.Combine("replacedets", "skins", "black.png")][0];
                ModEntry.phoneRotatedTexture = ThemeApp.skinDict[Path.Combine("replacedets", "skins", "black.png")][1];
            }
            if (ThemeApp.backgroundDict.ContainsKey(Config.BackgroundPath))
            {
                ModEntry.backgroundTexture = ThemeApp.backgroundDict[Config.BackgroundPath][0];
                ModEntry.backgroundRotatedTexture = ThemeApp.backgroundDict[Config.BackgroundPath][1];
            }
            else
            {
                ModEntry.backgroundTexture = ThemeApp.backgroundDict[Path.Combine("replacedets", "backgrounds", "clouds.png")][0];
                ModEntry.backgroundRotatedTexture = ThemeApp.backgroundDict[Path.Combine("replacedets", "backgrounds", "clouds.png")][1];
            }
            ModEntry.upArrowTexture = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", Config.UpArrowTexturePath));
            ModEntry.downArrowTexture = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", Config.DownArrowTexturePath));
            if (Config.ShowPhoneIcon)
            {
                ModEntry.iconTexture = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", Config.iconTexturePath));
            }
        }

19 View Source File : ThemeApp.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static void CreateThemeLists()
        {

            if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "skins")))
            {
                string[] skins = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "skins"), "*_landscape.png");

                foreach (string path in skins)
                {
                    try
                    {
                        Texture2D skin = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "skins", Path.GetFileName(path).Replace("_landscape", "")));
                        Texture2D skinl = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "skins", Path.GetFileName(path)));
                        if (skin != null && skinl != null)
                        {
                            skinDict.Add(Path.Combine("replacedets", "skins", Path.GetFileName(path).Replace("_landscape", "")), new Texture2D[] { skin, skinl });
                            Monitor.Log($"loaded skin {path.Replace("_landscape", "")}");
                        }
                        else
                            Monitor.Log($"Couldn't load skin {path.Replace("_landscape", "")}: texture was null", LogLevel.Error);
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log($"Couldn't load skin {path.Replace("_landscape", "")}: {ex}", LogLevel.Error);
                    }
                }
            }

            if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "backgrounds")))
            {
                string[] papers = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "backgrounds"), "*_landscape.png");
                foreach (string path in papers)
                {
                    try
                    {
                        Texture2D back = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path).Replace("_landscape", "")));
                        Texture2D backl = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path)));
                        if (back != null && backl != null)
                        {
                            backgroundDict.Add(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path).Replace("_landscape", "")), new Texture2D[] { back, backl });
                            Monitor.Log($"loaded background {path.Replace("_landscape", "")}");
                        }
                        else
                            Monitor.Log($"Couldn't load background {path.Replace("_landscape", "")}: texture was null", LogLevel.Error);
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log($"Couldn't load background {path.Replace("_landscape", "")}: {ex}", LogLevel.Error);
                    }
                }
            }


            if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "ringtones")))
            {
                string[] rings = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "ringtones"), "*.wav");
                foreach (string path in rings)
                {
                    try
                    {
                        object ring;
                        try
                        {
                            var type = Type.GetType("System.Media.SoundPlayer, System");
                            ring = Activator.CreateInstance(type, new object[] { path });
                        }
                        catch 
                        {
                            ring = SoundEffect.FromStream(new FileStream(path, FileMode.Open));
                        }
                        if (ring != null)
                        {
                            ringDict.Add(Path.GetFileName(path).Replace(".wav", ""), ring);
                            Monitor.Log($"loaded ring {path}");
                        }
                        else
                            Monitor.Log($"Couldn't load ring {path}", LogLevel.Error);
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log($"Couldn't load ring {path}:\r\n{ex}", LogLevel.Error);
                    }
                }
                rings = Config.BuiltInRingTones.Split(',');
                foreach (string ring in rings)
                {
                    ringDict.Add(ring, null);
                }
            }
            ringList = ringDict.Keys.ToList();
            skinList = skinDict.Keys.ToList();
            backgroundList = backgroundDict.Keys.ToList();
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public override void Entry(IModHelper helper)
        {
            context = this;
            Config = Helper.ReadConfig<ModConfig>();
            if (!Config.EnableMod)
                return;
            helper.Events.GameLoop.GameLaunched += GameLoop_GameLaunched;
            helper.Events.GameLoop.DayStarted += GameLoop_DayStarted;
            helper.Events.Player.Warped += Player_Warped;

            var harmony = HarmonyInstance.Create(ModManifest.UniqueID);

            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.placementAction)),
               postfix: new HarmonyMethod(typeof(ModEntry), nameof(placementAction_Postfix))
            );

            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.performRemoveAction)),
               postfix: new HarmonyMethod(typeof(ModEntry), nameof(performRemoveAction_Postfix))
            );
            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.checkForAction)),
               prefix: new HarmonyMethod(typeof(ModEntry), nameof(checkForAction_Prefix))
            );
            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.isPreplacedable)),
               prefix: new HarmonyMethod(typeof(ModEntry), nameof(Object_isPreplacedable_Prefix))
            );

            if (Config.LoadCustomTerrarium)
            {
                try
                {
                    string path = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[CP] Lively Frog Sanctuary")).FirstOrDefault()?.FullName;
                    if (path != null)
                    {
                        Texture2D tex = new Texture2D(Game1.graphics.GraphicsDevice, 48, 48);
                        Color[] data = new Color[tex.Width * tex.Height];
                        tex.GetData(data);

                        FileStream setStream = File.Open(Path.Combine(path, "replacedets", "frog-vivarium.png"), FileMode.Open);
                        Texture2D source = Texture2D.FromStream(Game1.graphics.GraphicsDevice, setStream);
                        setStream.Dispose();
                        Color[] srcData = new Color[source.Width * source.Height];
                        source.GetData(srcData);

                        for (int i = 0; i < srcData.Length; i++)
                        {
                            if (data.Length <= i + 48 * 12)
                                break;
                            data[i + 48 * 12] = srcData[i];
                        }
                        tex.SetData(data);
                        string outDir = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[BC] Terrarium")).FirstOrDefault()?.FullName;
                        Stream stream = File.Create(Path.Combine(outDir, "replacedets", "terrarium.png"));
                        tex.SaveAsPng(stream, tex.Width, tex.Height);
                        stream.Dispose();
                        Monitor.Log("Terrarium overwritten with lively frog sanctuary", LogLevel.Debug);
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log($"Can't load lively frog sanctuary for Terrarium\n{ex}", LogLevel.Error);
                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AElfProject

private static replacedembly OnreplacedemblyResolve(object sender, ResolveEventArgs args)
        {
            var folderPath = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var replacedemblyPath = Path.Combine(folderPath, new replacedemblyName(args.Name).Name + ".dll");
            if (!File.Exists(replacedemblyPath))
            {
                if (replacedemblyPath.Contains("Contract"))
                {
                    replacedemblyPath = replacedemblyPath.Substring(0,
                        replacedemblyPath.IndexOf("bin", StringComparison.Ordinal) - 1);
                    replacedemblyPath = Path.Combine(replacedemblyPath, "contracts", new replacedemblyName(args.Name).Name + ".dll");
                }
                else
                    return null;
            }

            var replacedembly = replacedembly.LoadFrom(replacedemblyPath);
            return replacedembly;
        }

19 View Source File : PublicizeInternals.cs
License : MIT License
Project Creator : aelij

public override bool Execute()
        {
            if (SourceReferences == null) throw new ArgumentNullException(nameof(SourceReferences));

            var replacedemblyNames = new HashSet<string>(
                (replacedemblyNames ?? string.Empty).Split(Semicolon, StringSplitOptions.RemoveEmptyEntries),
                StringComparer.OrdinalIgnoreCase);

            if (replacedemblyNames.Count == 0)
            {
                return true;
            }

            var targetPath = Path.Combine(_sourceDir, "obj", "GeneratedPublicizedreplacedemblies");
            Directory.CreateDirectory(targetPath);

            GenerateAttributes(targetPath, replacedemblyNames);

            foreach (var replacedemblyPath in SourceReferences
                .Select(a => Path.GetDirectoryName(GetFullFilePath(a.ItemSpec))))
            {
                _resolver.AddSearchDirectory(replacedemblyPath);
            }

            var targetReferences = new List<ITaskItem>();
            var removedReferences = new List<ITaskItem>();

            foreach (var replacedembly in SourceReferences)
            {
                var replacedemblyPath = GetFullFilePath(replacedembly.ItemSpec);
                var replacedemblyName = Path.GetFileNameWithoutExtension(replacedemblyPath);
                if (replacedemblyNames.Contains(replacedemblyName))
                {
                    // ReSharper disable once replacedignNullToNotNullAttribute
                    var targetreplacedemblyPath = Path.Combine(targetPath, Path.GetFileName(replacedemblyPath));

                    var targetAsemblyFileInfo = new FileInfo(targetreplacedemblyPath);
                    if (!targetAsemblyFileInfo.Exists || targetAsemblyFileInfo.Length == 0)
                    {
                        CreatePublicreplacedembly(replacedemblyPath, targetreplacedemblyPath);
                        Log.LogMessageFromText("Created publicized replacedembly at " + targetreplacedemblyPath, MessageImportance.Normal);
                    }
                    else
                    {
                        Log.LogMessageFromText("Publicized replacedembly already exists at " + targetreplacedemblyPath, MessageImportance.Low);
                    }

                    targetReferences.Add(new TaskItem(targetreplacedemblyPath));
                    removedReferences.Add(replacedembly);
                }
            }

            TargetReferences = targetReferences.ToArray();
            RemovedReferences = removedReferences.ToArray();

            return true;
        }

19 View Source File : TxtRecorder.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private void ResetFile(string sub, FileInfo info)
        {

            info.Size = 0;
            info.Index = 0;
            do
            {
                info.Index++;
                var fileName = DayFolder
                    ? Path.Combine(LogPath,
                        $"{pointTime.Year}{pointTime.Month:D2}{pointTime.Day:D2}",
                        $"{sub}.{info.Index:D3}.log")
                     : Path.Combine(LogPath,
                        $"{pointTime.Year}{pointTime.Month:D2}{pointTime.Day:D2}.{sub}.{info.Index:D3}.log");
                if (File.Exists(fileName))
                {
                    var stream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    info.Size = stream.Length;
                    if (stream.Length >= SplitNumber)
                    {
                        stream.Close();
                        stream.Dispose();
                        continue;
                    }
                    info.Stream = new StreamWriter(stream)
                    {
                        AutoFlush = true
                    };
                    return;
                }
                IOHelper.CheckPath(Path.GetDirectoryName(fileName));
                info.Stream = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    AutoFlush = true
                };
                info.Size = 0;
                return;
            }
            while (true);
        }

19 View Source File : ZeroAppConfig.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void CheckConfig()
        {
            var curPath = ConfigurationManager.Root.GetValue("contentRoot", Environment.CurrentDirectory);
            string rootPath;
            if (ConfigurationManager.Root["ASPNETCORE_ENVIRONMENT_"] == "Development")
            {
                ZeroTrace.SystemLog("Option", "Development");
                AppName = ConfigurationManager.Root["AppName"];
                rootPath = curPath;
            }
            else
            {
                ZeroTrace.SystemLog("Option", RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" : "Windows");
                rootPath = Path.GetDirectoryName(curPath);
                AppName= Path.GetFileName(curPath);
                // ReSharper disable once replacedignNullToNotNullAttribute
                var file = Path.Combine(rootPath, "config", "zero.json");
                if (File.Exists(file))
                    ConfigurationManager.Load(file);
                file = Path.Combine(rootPath, "config", $"{AppName}.json");
                if (File.Exists(file))
                    ConfigurationManager.Load(file);
                var name = ConfigurationManager.Root["AppName"];
                if (name == null)
                    ConfigurationManager.Root["AppName"] = AppName;
                else
                    AppName = name;
            }

            ConfigurationManager.Root["rootPath"] = rootPath;

            var sec = ConfigurationManager.Get("Zero");
            if (sec == null)
                throw new Exception("无法找到主配置节点,路径为Zero,在appsettings.json中设置");
            var global = sec.Child<ZeroAppConfig>("Global");
            if (global == null)
                throw new Exception("无法找到主配置节点,路径为Zero.Global,在appsettings.json中设置");
            Config = string.IsNullOrWhiteSpace(AppName)
                ? sec.Child<ZeroAppConfig>("Station")
                : sec.Child<ZeroAppConfig>(AppName) ?? sec.Child<ZeroAppConfig>("Station");
            

            if (Config == null)
                throw new Exception($"无法找到主配置节点,路径为Zero.{AppName}或Zero.Station,在appsettings.json中设置");
            Config.BinPath = curPath;
            Config.RootPath = rootPath;

            var socketOption = sec.Child<SocketOption>("socketOption");
            if (socketOption != null)
                ZSocket.Option = socketOption;

            if (string.IsNullOrWhiteSpace(AppName))
                ConfigurationManager.Root["AppName"] = AppName = Config.StationName;

            Config.IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
            
            global.LogFolder = string.IsNullOrWhiteSpace(global.LogFolder) ? IOHelper.CheckPath(rootPath, "logs") : global.LogFolder.Trim();
            global.DataFolder = string.IsNullOrWhiteSpace(global.DataFolder) ? IOHelper.CheckPath(rootPath, "datas") : global.DataFolder.Trim();
            global.ServiceName = string.IsNullOrWhiteSpace(global.ServiceName) ? Dns.GetHostName() : global.ServiceName.Trim();
            global.ServiceKey = string.IsNullOrWhiteSpace(global.ServiceKey) ? RandomOperate.Generate(8) : global.ServiceKey.Trim();
            global.ConfigFolder = string.IsNullOrWhiteSpace(global.ConfigFolder) ? IOHelper.CheckPath(rootPath, "config") : global.ConfigFolder.Trim();

            global.ZeroAddress = string.IsNullOrWhiteSpace(global.ZeroAddress) ? "127.0.0.1" : global.ZeroAddress.Trim();
            if (global.ZeroManagePort <= 1024 || Config.ZeroManagePort >= 65000)
                global.ZeroManagePort = 8000;
            if (global.ZeroMonitorPort <= 1024 || Config.ZeroMonitorPort >= 65000)
                global.ZeroMonitorPort = 8001;


            if (global.StationIsolate || Config.StationIsolate)
            {
                Config.ServiceName = string.IsNullOrWhiteSpace(Config.ServiceName) ? global.ServiceName : Config.ServiceName.Trim();
                Config.ServiceKey = string.IsNullOrWhiteSpace(Config.ServiceKey) ? global.ServiceKey : Config.ServiceKey.Trim();
                Config.ZeroAddress = string.IsNullOrWhiteSpace(Config.ZeroAddress) ? global.ZeroAddress : Config.ZeroAddress.Trim();
                if (Config.ZeroManagePort <= 1024 || Config.ZeroManagePort >= 65000)
                    Config.ZeroManagePort = global.ZeroManagePort;
                if (Config.ZeroMonitorPort <= 1024 || Config.ZeroMonitorPort >= 65000)
                    Config.ZeroMonitorPort = global.ZeroMonitorPort;

                Config.DataFolder = string.IsNullOrWhiteSpace(Config.DataFolder) ? global.DataFolder : IOHelper.CheckPath(global.DataFolder, AppName, "datas");
                Config.LogFolder = string.IsNullOrWhiteSpace(Config.LogFolder) ? global.LogFolder : IOHelper.CheckPath(global.LogFolder, AppName, "logs");
                Config.ConfigFolder = string.IsNullOrWhiteSpace(Config.ConfigFolder) ? global.ConfigFolder : IOHelper.CheckPath(rootPath, AppName, "config");
            }
            else
            {
                Config.ServiceName = global.ServiceName;
                Config.ServiceKey = global.ServiceKey;
                Config.ZeroAddress = global.ZeroAddress;
                Config.ZeroManagePort = global.ZeroManagePort;
                Config.ZeroMonitorPort = global.ZeroMonitorPort;

                Config.DataFolder = global.DataFolder;
                Config.LogFolder = global.LogFolder;
                Config.ConfigFolder = global.ConfigFolder;
            }
            TxtRecorder.LogPath = Config.LogFolder;
            ConfigurationManager.Get("LogRecorder")["txtPath"] = Config.LogFolder;

            Config.ZeroManageAddress = ZeroIdenreplacedyHelper.GetRequestAddress("SystemManage", Config.ZeroManagePort);
            Config.ZeroMonitorAddress = ZeroIdenreplacedyHelper.GetWorkerAddress("SystemMonitor", Config.ZeroMonitorPort);
            Config.LocalIpAddress = GetHostIps();
            Config.ShortName = string.IsNullOrWhiteSpace(Config.ShortName) ? Config.StationName : Config.ShortName.Trim();
            Config.RealName = ZeroIdenreplacedyHelper.CreateRealName(false);
            Config.Idenreplacedy = Config.RealName.ToAsciiBytes();
            //模式选择

            if (Config.SpeedLimitModel < SpeedLimitType.Single || Config.SpeedLimitModel > SpeedLimitType.WaitCount)
                Config.SpeedLimitModel = SpeedLimitType.ThreadCount;

            if (Config.TaskCpuMultiple <= 0)
                Config.TaskCpuMultiple = 1;
            else if (Config.TaskCpuMultiple > 128)
                Config.TaskCpuMultiple = 128;

            if (Config.MaxWait < 0xFF)
                Config.MaxWait = 0xFF;
            else if (Config.MaxWait > 0xFFFFF)
                Config.MaxWait = 0xFFFFF;

            ShowOptionInfo(rootPath);
        }

19 View Source File : GeneratorTests.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : agocke

internal static Task VerifyGeneratedCode(
            string src,
            (string fileName, string expected)[] generated,
            params DiagnosticResult[] diagnostics)
        {
            var verifier = CreateVerifier(src);
            verifier.ExpectedDiagnostics.AddRange(diagnostics);
            foreach (var (fileName, expected) in generated)
            {
                verifier.TestState.GeneratedSources.Add((
                    Path.Combine("SerdeGenerator", $"Serde.{nameof(Generator)}", $"{fileName}.cs"),
                    SourceText.From(expected, Encoding.UTF8))
                );
            }
            return verifier.RunAsync();
        }

19 View Source File : FilePackageStorageService.cs
License : MIT License
Project Creator : ai-traders

private void EnsurePathExists(string lowercasedId, string lowercasedNormalizedVersion)
        {
            var path = Path.Combine(_storePath, lowercasedId, lowercasedNormalizedVersion);

            Directory.CreateDirectory(path);
        }

19 View Source File : Startup.cs
License : MIT License
Project Creator : ai-traders

public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureLiGet(Configuration, httpServices: true);

            services.AddSpaStaticFiles(configuration =>
            {
                var sourceDist = Path.Combine(Environment.CurrentDirectory, "src", "LiGet.UI" , "dist");
                if(Directory.Exists(sourceDist))
                {
                    // we are running tests from root of project
                    configuration.RootPath = sourceDist;
                    return;
                }
                sourceDist = Path.Combine("src", "LiGet.UI" , "dist");
                for(int depth=0; depth < 5; depth++) {
                    sourceDist = Path.Combine("..", sourceDist);
                    if(Directory.Exists(sourceDist))
                    {
                        // we are running tests from debugger/editor
                        configuration.RootPath = sourceDist;
                        return;
                    }
                }
                // In production, the UI files will be served from wwwroot directory next to LiGet.dll file
                string codeBase = Path.GetDirectoryName(typeof(Startup).replacedembly.CodeBase);
                configuration.RootPath = Path.Combine(codeBase, "wwwroot");
            });
        }

19 View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6

private void enablePAK(PAK pak)
        {
            if (Directory.Exists(Path.Combine(pakDir,"~" + pak.modDir)) && !Directory.Exists(Path.Combine(pakDir, pak.modDir)))
            {
                if (checkHash(Path.Combine(pakDir, "~" + pak.modDir, pak.modFile), pak))
                {
                    Directory.Move(Path.Combine(pakDir, "~" + pak.modDir), Path.Combine(pakDir, pak.modDir));
                }
                else
                {
                    DeleteDirectory(Path.Combine(pakDir, "~" + pak.modDir));
                    using (progressForm PAKDownload = new progressForm("Incorrect " + pak.modName + " Hash", "Downloading new copy of " + pak.modFile + "...", pak))
                    {
                        if (PAKDownload.ShowDialog() == DialogResult.OK)
                        {
                            PAKDownload.Dispose();
                        }
                    }
                }
            }
            else if (Directory.Exists(Path.Combine(pakDir, pak.modDir)) && (!checkHash(Path.Combine(pakDir, pak.modDir, pak.modFile), pak)))
            {
                using (progressForm PAKDownload = new progressForm("Incorrect " + pak.modName + " Hash", "Downloading new copy of " + pak.modFile + "...", pak))
                {
                    if (PAKDownload.ShowDialog() == DialogResult.OK)
                    {
                        PAKDownload.Dispose();
                    }
                }
            }
            else if (!Directory.Exists(Path.Combine(pakDir, pak.modDir)) && !Directory.Exists(Path.Combine(pakDir, "~" + pak.modDir)))
            {
                using (progressForm PAKDownload = new progressForm(pak.modName + " PAK Download", "Downloading " + pak.modFile + "...", pak))
                {
                    DeleteDirectory(Path.Combine(pakDir, pak.modDir));
                    if (PAKDownload.ShowDialog() == DialogResult.OK)
                    {
                        PAKDownload.Dispose();
                    }
                }
            }
            gridSelections.Add(pak.modDir);
        }

19 View Source File : updateForm.cs
License : MIT License
Project Creator : ajohns6

private void checkUpdate(object sender, EventArgs e)
        {
            if (!progressForm.IsConnectedToInternet())
            {
                this.Dispose();
                return;
            }

            string url = "https://api.github.com/repos/ajohns6/SM64-NX-Launcher/releases";
            string releaseString = "";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Accept = "application/json";
            request.Method = "GET";
            request.UserAgent = "Foo";
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    releaseString = reader.ReadToEnd();
                }
            }
            catch
            {
                this.Dispose();
                return;
            }

            Application.DoEvents();

            var releaseList = JsonConvert.DeserializeObject<List<release>>(releaseString);

            if (releaseList[0].tag_name != ("v" + version))
            {
                this.statusLabel.Text = "Downloading " + releaseList[0].tag_name + "...";
                this.progBar.Visible = true;
                string tempPath = Path.Combine(Path.GetTempPath(),
                             "sm64nxlauncherinstaller",
                             version);
                string zipPath = Path.Combine(tempPath, "installer.zip");
                mainForm.DeleteDirectory(tempPath);

                Task.Run(() =>
                {
                    using (var client = new WebClient())
                    {
                        if (!Directory.Exists(tempPath))
                        {
                            Directory.CreateDirectory(tempPath);
                        }

                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgress);
                        client.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadComplete);
                        Uri installerLink = new Uri(releaseList[0].replacedets[0].browser_download_url);
                        client.DownloadFileAsync(installerLink, zipPath);
                    }
                });

                progBar.Maximum = 100;

                Application.DoEvents();

                do
                {
                    progBar.Value = progress;
                } while (progress < 100);

                do
                {
                    Application.DoEvents();
                } while (!complete);

                this.statusLabel.Text = "Extracting installer...";

                Task.Run(() =>
                {
                    bool unzipped = false;
                    do
                    {
                        try
                        {
                            ZipFile.ExtractToDirectory(zipPath, tempPath);
                            unzipped = true;
                        }
                        catch { }
                    } while (!unzipped);
                }).Wait();

                ProcessStartInfo installStart = new ProcessStartInfo();
                installStart.FileName = Path.Combine(tempPath, "setup.exe");

                Process installer = new Process();
                installer.StartInfo = installStart;

                installer.Start();

                Application.Exit();
            }

            this.Close();
        }

19 View Source File : Injector.cs
License : MIT License
Project Creator : Akaion

private static string CreateTemporaryDll(byte[] dllBytes)
        {
            // Ensure a directory exists on disk to store the temporary DLL

            var temporaryDirectoryInfo = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "Bleak", "DLL"));

            // Clear the directory

            foreach (var file in temporaryDirectoryInfo.EnumerateFiles())
            {
                try
                {
                    file.Delete();
                }

                catch (Exception)
                {
                    // The file is currently open and cannot be safely deleted
                }
            }

            // Create a temporary DLL with a randomised name

            var temporaryDllPath = Path.Combine(temporaryDirectoryInfo.FullName, Path.GetRandomFileName() + ".dll");

            try
            {
                File.WriteAllBytes(temporaryDllPath, dllBytes);
            }

            catch (IOException)
            {
                // A DLL already exists with the specified name, is loaded in a process and cannot be safely overwritten
            }

            return temporaryDllPath;
        }

19 View Source File : SqlServerScriptsPathProvider.cs
License : MIT License
Project Creator : akasarto

public string GetPath(string scriptName)
		{
			var baseFolder = Path.GetDirectoryName(_executingreplacedembly.Location);

			return Path.Combine(baseFolder, "SqlServerScripts", scriptName);
		}

See More Examples