string.Replace(char, char)

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

3159 Examples 7

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

public void ProcessCommand(IExecutionContext context, string inputLine, ActionCommand command, ContainerInfo container)
        {
            command.Properties.TryGetValue(IssueCommandProperties.File, out string file);
            command.Properties.TryGetValue(IssueCommandProperties.Line, out string line);
            command.Properties.TryGetValue(IssueCommandProperties.Column, out string column);

            if (!ActionCommandManager.EnhancedAnnotationsEnabled(context))
            {
                context.Debug("Enhanced Annotations not enabled on the server. The 'replacedle', 'end_line', and 'end_column' fields are unsupported.");
            }

            Issue issue = new Issue()
            {
                Category = "General",
                Type = this.Type,
                Message = command.Data
            };

            if (!string.IsNullOrEmpty(file))
            {
                issue.Category = "Code";

                if (container != null)
                {
                    // Translate file path back from container path
                    file = container.TranslateToHostPath(file);
                    command.Properties[IssueCommandProperties.File] = file;
                }

                // Get the values that represent the server path given a local path
                string repoName = context.GetGitHubContext("repository");
                var repoPath = context.GetGitHubContext("workspace");

                string relativeSourcePath = IOUtil.MakeRelative(file, repoPath);
                if (!string.Equals(relativeSourcePath, file, IOUtil.FilePathStringComparison))
                {
                    // add repo info
                    if (!string.IsNullOrEmpty(repoName))
                    {
                        command.Properties["repo"] = repoName;
                    }

                    if (!string.IsNullOrEmpty(relativeSourcePath))
                    {
                        // replace sourcePath with the new relative path
                        // prefer `/` on all platforms
                        command.Properties[IssueCommandProperties.File] = relativeSourcePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    }
                }
            }

            foreach (var property in command.Properties)
            {
                if (!string.Equals(property.Key, Constants.Runner.InternalTelemetryIssueDataKey, StringComparison.OrdinalIgnoreCase))
                {
                    issue.Data[property.Key] = property.Value;
                }
            }

            context.AddIssue(issue);
        }

19 View Source File : TestCase.cs
License : MIT License
Project Creator : adamant

public override string ToString()
        {
            var pathWithoutExtension = Path.ChangeExtension(RelativeCodePath, null);
            return pathWithoutExtension
                .Replace(Path.DirectorySeparatorChar, '.')
                .Replace(Path.AltDirectorySeparatorChar, '.');
        }

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

public static string LoadSourceFile(string name)
        {
            replacedembly replacedembly = typeof(ExampleLoader).replacedembly;

            var names = replacedembly.GetManifestResourceNames();

            var allExampleSourceFiles = names.Where(x => x.Contains("SciChart.Examples.Examples"));

            var find = name.Replace('/', '.').Replace(".txt", string.Empty).Replace("Resources.ExampleSourceFiles.", string.Empty);
            var file = allExampleSourceFiles.FirstOrDefault(x => x.EndsWith(find));

            if (file == null)
                throw new Exception(string.Format("Unable to find the source code resource {0}", find));

            using (var s = replacedembly.GetManifestResourceStream(file))
            using (var sr = new StreamReader(s))
            {
                return sr.ReadToEnd();
            }
        }

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

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;

                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string problemMatcher = @"    
{
    ""problemMatcher"": [
        {
            ""owner"": ""checkout-git"",
            ""pattern"": [
                {
                    ""regexp"": ""^fatal: (.*)$"",
                    ""message"": 1
                }
            ]
        }
    ]
}";
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, problemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static List<string> ReadScript(string filename)
        {
            var replacedembly = replacedembly.GetExecutingreplacedembly();
            var resourceName = prefix + filename.Replace('/', '.');

            using (var stream = replacedembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null) return null;

                var lines = new List<string>();

                using (var reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                        lines.Add(reader.ReadLine());
                }
                return lines;
            }
        }

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

private static void AddLeapEditorAsmDefs()
        {
            if (FileUtilities.FindFilesInreplacedets("LeapMotion.Core.Editor.asmdef").Length == 0)
            {
                foreach (KeyValuePair<string, string[]> leapAsmDef in leapEditorDirectories)
                {
                    // Convert asmdef name to a path
                    string leapAsmDefPath = leapAsmDef.Key.Replace('.', '/');

                    string leapAsmDefFilename = string.Concat(leapAsmDef.Key, ".asmdef");

                    // Path for the asmdef including the filename
                    string fullLeapAsmDefFilePath = Path.Combine(Application.dataPath, pathDifference, leapAsmDefPath, leapAsmDefFilename);

                    // Path for the asmdef NOT including the filename
                    string fullLeapAsmDefDirectoryPath = Path.Combine(Application.dataPath, pathDifference, leapAsmDefPath);

                    // Make sure the directory exists within the leap core replacedets before we add the asmdef
                    // The leap core replacedets version 4.5.0 contains the LeapMotion/Core/Tests/Editor directory while 4.4.0 does not.
                    if (!File.Exists(fullLeapAsmDefFilePath) && Directory.Exists(fullLeapAsmDefDirectoryPath))
                    {
                        // Create and save the new asmdef
                        replacedemblyDefinition leapEditorAsmDef = new replacedemblyDefinition
                        {
                            Name = leapAsmDef.Key,
                            References = leapAsmDef.Value,
                            IncludePlatforms = new string[] { "Editor" }
                        };

#if !UNITY_2019_3_OR_NEWER
                        // In Unity 2018.4, directories that contain tests need to have a test replacedembly.
                        // An asmdef is added to a leap directory that contains tests for the leap core replacedets 4.5.0.
                        if (leapEditorAsmDef.Name.Contains("Tests"))
                        {
                            leapEditorAsmDef.OptionalUnityReferences = new string[] { "Testreplacedemblies" };
                        }
#endif

                        leapEditorAsmDef.Save(fullLeapAsmDefFilePath);
                    }
                }
            }
        }

19 View Source File : SmokeTextAdornmentManager.cs
License : MIT License
Project Creator : Actipro

private void PuffSmoke(Point location) {
			Random rand = new Random();

			List<Ellipse> smokeClouds = new List<Ellipse>();
			int smokeCloudCount = 4 + rand.Next(2);

			for (int index = 0; index < smokeCloudCount; index++) {
				Ellipse smokeCloud = new Ellipse();
				smokeCloud.Fill = Brushes.Silver;
				smokeCloud.Stroke = Brushes.Gray;
				smokeCloud.StrokeThickness = 1.0;
				smokeCloud.Opacity = 0.3;

				smokeCloud.Width = 10 + rand.Next(10);
				smokeCloud.Height = 10 + rand.Next(10);

				Point smokeCloudLocation = new Point(location.X - (smokeCloud.Width / 2), location.Y - (smokeCloud.Height / 2));

				TransformGroup group = new TransformGroup();
				smokeCloud.RenderTransform = group;

				Storyboard sb = new Storyboard();
				sb.Duration = new Duration(TimeSpan.FromSeconds(2.7));
				sb.Completed += new EventHandler(OnStoryboardCompleted);
				sb.Name = String.Format("SC{0}", Guid.NewGuid().ToString().Replace('-', '_'));
				DoubleAnimation anim;

				this.AdornmentLayer.AddAdornment(AdornmentChangeReason.Other, smokeCloud, smokeCloudLocation, sb.Name, null);

				ScaleTransform scale = new ScaleTransform();
				scale.CenterX = smokeCloud.Width / 2;
				scale.CenterY = smokeCloud.Height / 2;
				group.Children.Add(scale);
				double targetScaleFactor = 2 + rand.NextDouble();

				anim = new DoubleAnimation();
				anim.To = targetScaleFactor;
				Storyboard.SetTargetProperty(anim, new PropertyPath("(0).(1)[0].(2)", UIElement.RenderTransformProperty, TransformGroup.ChildrenProperty, ScaleTransform.ScaleXProperty));
				sb.Children.Add(anim);
				
				anim = new DoubleAnimation();
				anim.To = targetScaleFactor;
				Storyboard.SetTargetProperty(anim, new PropertyPath("(0).(1)[0].(2)", UIElement.RenderTransformProperty, TransformGroup.ChildrenProperty, ScaleTransform.ScaleYProperty));
				sb.Children.Add(anim);
				
				TranslateTransform translate = new TranslateTransform();
				group.Children.Add(translate);
				
				anim = new DoubleAnimation();
				anim.To = 20 - 40 * rand.NextDouble();
				Storyboard.SetTargetProperty(anim, new PropertyPath("(0).(1)[1].(2)", UIElement.RenderTransformProperty, TransformGroup.ChildrenProperty, TranslateTransform.XProperty));
				sb.Children.Add(anim);
				
				anim = new DoubleAnimation();
				anim.To = 20 - 40 * rand.NextDouble();
				Storyboard.SetTargetProperty(anim, new PropertyPath("(0).(1)[1].(2)", UIElement.RenderTransformProperty, TransformGroup.ChildrenProperty, TranslateTransform.YProperty));
				sb.Children.Add(anim);
				
				anim = new DoubleAnimation();
				anim.To = 0.0;
				Storyboard.SetTargetProperty(anim, new PropertyPath(UIElement.OpacityProperty));
				sb.Children.Add(anim);

				sb.Begin(smokeCloud);
			}			
		}

19 View Source File : DynamicDNAConverterBehaviourEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

private void RecursiveScanFoldersForreplacedets(string path, Delegate callback, int addMethod)
		{
			var replacedetFiles = System.IO.Directory.GetFiles(path, "*.prefab");
			foreach (var replacedetFile in replacedetFiles)
			{
				var tempDnaGO = replacedetDatabase.LoadreplacedetAtPath(replacedetFile, typeof(GameObject)) as GameObject;
				DynamicDNAConverterBehaviour tempDnareplacedet = tempDnaGO.GetComponent<DynamicDNAConverterBehaviour>();
				if (tempDnareplacedet)
				{
					callback.DynamicInvoke(tempDnareplacedet, addMethod);
				}
			}
			foreach (var subFolder in System.IO.Directory.GetDirectories(path))
			{
				RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'), callback,  addMethod);
			}
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

private static byte[] Decode(string text)
		{
			var padded = text.PadRight(text.Length + (4 - text.Length % 4) % 4, '=').Replace('-', '+').Replace('_', '/');
			var decoded = Convert.FromBase64String(padded);

			return decoded;
		}

19 View Source File : OverlayLibraryEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

private void RecursiveScanFoldersForreplacedets(string path)
		{
			var replacedetFiles = System.IO.Directory.GetFiles(path, "*.replacedet");
			foreach (var replacedetFile in replacedetFiles)
			{
				var tempOverlayData = replacedetDatabase.LoadreplacedetAtPath(replacedetFile, typeof(OverlayDatareplacedet)) as OverlayDatareplacedet;
				if (tempOverlayData)
				{
					AddOverlayData(tempOverlayData);
				}
			}
			foreach (var subFolder in System.IO.Directory.GetDirectories(path))
			{
				RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'));
			}
		}

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

public static string MakeRelative(string path, string folder)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            ArgUtil.NotNull(folder, nameof(folder));

            // Replace all Path.AltDirectorySeparatorChar with Path.DirectorySeparatorChar from both inputs
            path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            folder = folder.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

            // Check if the dir is a prefix of the path (if not, it isn't relative at all).
            if (!path.StartsWith(folder, IOUtil.FilePathStringComparison))
            {
                return path;
            }

            // Dir is a prefix of the path, if they are the same length then the relative path is empty.
            if (path.Length == folder.Length)
            {
                return string.Empty;
            }

            // If the dir ended in a '\\' (like d:\) or '/' (like user/bin/)  then we have a relative path.
            if (folder.Length > 0 && folder[folder.Length - 1] == Path.DirectorySeparatorChar)
            {
                return path.Substring(folder.Length);
            }
            // The next character needs to be a '\\' or they aren't really relative.
            else if (path[folder.Length] == Path.DirectorySeparatorChar)
            {
                return path.Substring(folder.Length + 1);
            }
            else
            {
                return path;
            }
        }

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

public void WritePerfCounter(string counter)
        {
            if (!string.IsNullOrEmpty(_perfFile))
            {
                string normalizedCounter = counter.Replace(':', '_');
                lock (_perfLock)
                {
                    try
                    {
                        File.AppendAllLines(_perfFile, new[] { $"{normalizedCounter}:{DateTime.UtcNow.ToString("O")}" });
                    }
                    catch (Exception ex)
                    {
                        _trace.Error(ex);
                    }
                }
            }
        }

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

public static string NormalizeSeparators(this string path)
            => path?.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);

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

public static byte[] FromBase64StringNoPadding(this String base64String)
        {
            ArgumentUtility.CheckStringForNullOrEmpty(base64String, "base64String");

            string s = base64String;
            s = s.Replace('-', '+'); // 62nd char of encoding
            s = s.Replace('_', '/'); // 63rd char of encoding
            switch (s.Length % 4) // Pad with trailing '='s
            {
                case 0: break; // No pad chars in this case
                case 2: s += "=="; break; // Two pad chars
                case 3: s += "="; break; // One pad char
                default:
                    throw new ArgumentException(CommonResources.IllegalBase64String(), "base64String");
            }
            return Convert.FromBase64String(s); // Standard base64 decoder
        }

19 View Source File : LyricsFetcher.cs
License : MIT License
Project Creator : 71

private static void PopulateFromSrt(TextReader reader, List<Subreplacedle> subreplacedles)
        {
            // Parse using a simple state machine:
            //   0: Parsing number
            //   1: Parsing start / end time
            //   2: Parsing text
            byte state = 0;

            float startTime = 0f,
                  endTime = 0f;

            StringBuilder text = new StringBuilder();
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                switch (state)
                {
                    case 0:
                        if (string.IsNullOrEmpty(line))
                            // No number found; continue in same state.
                            continue;

                        if (!int.TryParse(line, out int _))
                            goto Invalid;

                        // Number found; continue to next state.
                        state = 1;
                        break;

                    case 1:
                        Match m = Regex.Match(line, @"(\d+):(\d+):(\d+,\d+) *--> *(\d+):(\d+):(\d+,\d+)");

                        if (!m.Success)
                            goto Invalid;

                        startTime = int.Parse(m.Groups[1].Value) * 3600
                                  + int.Parse(m.Groups[2].Value) * 60
                                  + float.Parse(m.Groups[3].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);

                        endTime = int.Parse(m.Groups[4].Value) * 3600
                                + int.Parse(m.Groups[5].Value) * 60
                                + float.Parse(m.Groups[6].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);

                        // Subreplacedle start / end found; continue to next state.
                        state = 2;
                        break;

                    case 2:
                        if (string.IsNullOrEmpty(line))
                        {
                            // End of text; continue to next state.
                            subreplacedles.Add(new Subreplacedle(text.ToString(), startTime, endTime));

                            text.Length = 0;
                            state = 0;
                        }
                        else
                        {
                            // Continuation of text; continue in same state.
                            text.AppendLine(line);
                        }

                        break;

                    default:
                        // Shouldn't happen.
                        throw new Exception();
                }
            }

            Invalid:

            Debug.Log("[Beat Singer] Invalid subtiles file found, cancelling load...");
            subreplacedles.Clear();
        }

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, "[email protected]: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 : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static string FormatSeparatorsForUnity(string path) => path?.Replace('\\', '/');

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

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static string TransformFileNameToreplacedemblyResourceID(string fileName) =>
			fileName?.Replace(Path.DirectorySeparatorChar, '.')
					 .Replace(' ', '_');

19 View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private static VmessItem ResolveSip002(string result)
        {
            Uri parsedUrl;
            try
            {
                parsedUrl = new Uri(result);
            }
            catch (UriFormatException)
            {
                return null;
            }
            VmessItem server = new VmessItem
            {
                remarks = parsedUrl.GetComponents(UriComponents.Fragment, UriFormat.Unescaped),
                address = parsedUrl.IdnHost,
                port = parsedUrl.Port,
            };

            // parse base64 UserInfo
            string rawUserInfo = parsedUrl.GetComponents(UriComponents.UserInfo, UriFormat.Unescaped);
            string base64 = rawUserInfo.Replace('-', '+').Replace('_', '/');    // Web-safe base64 to normal base64
            string userInfo;
            try
            {
                userInfo = Encoding.UTF8.GetString(Convert.FromBase64String(
                base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=')));
            }
            catch (FormatException)
            {
                return null;
            }
            string[] userInfoParts = userInfo.Split(new char[] { ':' }, 2);
            if (userInfoParts.Length != 2)
            {
                return null;
            }
            server.security = userInfoParts[0];
            server.id = userInfoParts[1];

            NameValueCollection queryParameters = HttpUtility.ParseQueryString(parsedUrl.Query);
            if (queryParameters["plugin"] != null)
            {
                return null;
            }

            return server;
        }

19 View Source File : Resources.cs
License : MIT License
Project Creator : adams85

public static string GetEmbeddedResourcereplacedtring(string resourcePath)
        {
            using (Stream stream = s_replacedembly.GetManifestResourceStream($"{s_replacedembly.GetName().Name}.{resourcePath.Replace('/', '.')}"))
            using (var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true))
                return reader.ReadToEnd();
        }

19 View Source File : NameUtility.cs
License : Apache License 2.0
Project Creator : acblog

public static string Encode(string str)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(str)).Replace('+', '-').Replace('/', '_');
        }

19 View Source File : NameUtility.cs
License : Apache License 2.0
Project Creator : acblog

public static string Decode(string str)
        {
            return Encoding.UTF8.GetString(Convert.FromBase64String(str.Replace('-', '+').Replace('_', '/')));
        }

19 View Source File : StringExtension.cs
License : MIT License
Project Creator : 3F

public static string MakeRelativePath(this string root, string path)
        {
            if(String.IsNullOrWhiteSpace(root) || String.IsNullOrWhiteSpace(path)) {
                return null;
            }

            if(!Uri.TryCreate(root.DirectoryPathFormat(), UriKind.Absolute, out Uri uriRoot)) {
                return null;
            }

            if(!Uri.TryCreate(path, UriKind.Absolute, out Uri uriPath)) {
                uriPath = new Uri(uriRoot, new Uri(path, UriKind.Relative));
            }

            Uri urirel  = uriRoot.MakeRelativeUri(uriPath);
            string ret  = Uri.UnescapeDataString(urirel.IsAbsoluteUri ? urirel.LocalPath : urirel.ToString());

            return ret.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
        }

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

public static string GetSafeFileName(string fileName)
        {
            if (fileName == null)
            {
                return null;
            }
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(c, '_');
            }
            return fileName;
        }

19 View Source File : Loger.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string Bytes(byte[] bs)
        {
            return BitConverter.ToString(bs).Replace('-', ' ');
        }

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

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;
                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, GitHubSourceProvider.ProblemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

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

private async Task<UploadResult> UploadAsync(RunnerActionPluginExecutionContext context, int uploaderId, CancellationToken token)
        {
            List<string> failedFiles = new List<string>();
            long uploadedSize = 0;
            string fileToUpload;
            Stopwatch uploadTimer = new Stopwatch();
            while (_fileUploadQueue.TryDequeue(out fileToUpload))
            {
                token.ThrowIfCancellationRequested();
                try
                {
                    using (FileStream fs = File.Open(fileToUpload, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        string itemPath = (_containerPath.TrimEnd('/') + "/" + fileToUpload.Remove(0, _sourceParentDirectory.Length + 1)).Replace('\\', '/');
                        bool failAndExit = false;
                        try
                        {
                            uploadTimer.Restart();
                            using (HttpResponseMessage response = await _fileContainerHttpClient.UploadFileAsync(_containerId, itemPath, fs, _projectId, cancellationToken: token, chunkSize: 4 * 1024 * 1024))
                            {
                                if (response == null || response.StatusCode != HttpStatusCode.Created)
                                {
                                    context.Output($"Unable to copy file to server StatusCode={response?.StatusCode}: {response?.ReasonPhrase}. Source file path: {fileToUpload}. Target server path: {itemPath}");

                                    if (response?.StatusCode == HttpStatusCode.Conflict)
                                    {
                                        // fail upload task but continue with any other files
                                        context.Error($"Error '{fileToUpload}' has already been uploaded.");
                                    }
                                    else if (_fileContainerHttpClient.IsFastFailResponse(response))
                                    {
                                        // Fast fail: we received an http status code where we should abandon our efforts
                                        context.Output($"Cannot continue uploading files, so draining upload queue of {_fileUploadQueue.Count} items.");
                                        DrainUploadQueue(context);
                                        failedFiles.Clear();
                                        failAndExit = true;
                                        throw new UploadFailedException($"Critical failure uploading '{fileToUpload}'");
                                    }
                                    else
                                    {
                                        context.Debug($"Adding '{fileToUpload}' to retry list.");
                                        failedFiles.Add(fileToUpload);
                                    }
                                    throw new UploadFailedException($"Http failure response '{response?.StatusCode}': '{response?.ReasonPhrase}' while uploading '{fileToUpload}'");
                                }

                                uploadTimer.Stop();
                                context.Debug($"File: '{fileToUpload}' took {uploadTimer.ElapsedMilliseconds} milliseconds to finish upload");
                                uploadedSize += fs.Length;
                                OutputLogForFile(context, fileToUpload, $"Detail upload trace for file: {itemPath}", context.Debug);
                            }
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            context.Output($"File upload has been cancelled during upload file: '{fileToUpload}'.");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            context.Output($"Fail to upload '{fileToUpload}' due to '{ex.Message}'.");
                            context.Output(ex.ToString());

                            OutputLogForFile(context, fileToUpload, $"Detail upload trace for file that fail to upload: {itemPath}", context.Output);

                            if (failAndExit)
                            {
                                context.Debug("Exiting upload.");
                                throw;
                            }
                        }
                    }

                    Interlocked.Increment(ref _uploadFilesProcessed);
                }
                catch (Exception ex)
                {
                    context.Output($"File error '{ex.Message}' when uploading file '{fileToUpload}'.");
                    throw ex;
                }
            }

            return new UploadResult(failedFiles, uploadedSize);
        }

19 View Source File : Repository.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string NormalizeLogin(string login)
        {
            char[] invalidFileChars = Path.GetInvalidFileNameChars();
            foreach (var c in invalidFileChars) if (login.Contains(c)) login = login.Replace(c, '_');
            return login.ToLowerInvariant();
        }

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

public static string ResolvePath(String rootPath, String relativePath)
        {
            ArgUtil.NotNullOrEmpty(rootPath, nameof(rootPath));
            ArgUtil.NotNullOrEmpty(relativePath, nameof(relativePath));

            if (!Path.IsPathRooted(rootPath))
            {
                throw new ArgumentException($"{rootPath} should be a rooted path.");
            }

            if (relativePath.IndexOfAny(Path.GetInvalidPathChars()) > -1)
            {
                throw new InvalidOperationException($"{relativePath} contains invalid path characters.");
            }
            else if (Path.GetFileName(relativePath).IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
            {
                throw new InvalidOperationException($"{relativePath} contains invalid folder name characters.");
            }
            else if (Path.IsPathRooted(relativePath))
            {
                throw new InvalidOperationException($"{relativePath} can not be a rooted path.");
            }
            else
            {
                rootPath = rootPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

                // Root the path
                relativePath = String.Concat(rootPath, Path.AltDirectorySeparatorChar, relativePath);

                // Collapse ".." directories with their parent, and skip "." directories.
                String[] split = relativePath.Split(new[] { Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
                var segments = new Stack<String>(split.Length);
                Int32 skip = 0;
                for (Int32 i = split.Length - 1; i >= 0; i--)
                {
                    String segment = split[i];
                    if (String.Equals(segment, ".", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    else if (String.Equals(segment, "..", StringComparison.Ordinal))
                    {
                        skip++;
                    }
                    else if (skip > 0)
                    {
                        skip--;
                    }
                    else
                    {
                        segments.Push(segment);
                    }
                }

                if (skip > 0)
                {
                    throw new InvalidOperationException($"The file path {relativePath} is invalid");
                }

#if OS_WINDOWS
                if (segments.Count > 1)
                {
                    return String.Join(Path.DirectorySeparatorChar, segments);
                }
                else
                {
                    return segments.Pop() + Path.DirectorySeparatorChar;
                }
#else
                return Path.DirectorySeparatorChar + String.Join(Path.DirectorySeparatorChar, segments);
#endif
            }
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

internal static string Filter(this string str) => str.Replace('\r', ' ').Replace('\n', ' ');

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

public static String ToBase64StringNoPadding(this byte[] bytes)
        {
            ArgumentUtility.CheckEnumerableForNullOrEmpty(bytes, "bytes");

            string s = Convert.ToBase64String(bytes); // Regular base64 encoder
            s = s.Split('=')[0]; // Remove any trailing '='s
            s = s.Replace('+', '-'); // 62nd char of encoding
            s = s.Replace('/', '_'); // 63rd char of encoding
            return s;
        }

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

private static string FormatGroupedTypeName(Type type, TypeGrouping grouping)
        {
            string name = type.FullName;

            switch (grouping)
            {
                case TypeGrouping.None:
                    return name;
                case TypeGrouping.ByNamespace:
                    return string.IsNullOrEmpty(name) ? string.Empty : name.Replace('.', '/');
                case TypeGrouping.ByNamespaceFlat:
                    int lastPeriodIndex = string.IsNullOrEmpty(name) ? -1 : name.LastIndexOf('.');
                    if (lastPeriodIndex != -1)
                    {
                        name = string.IsNullOrEmpty(name)
                            ? string.Empty
                            : $"{name.Substring(0, lastPeriodIndex)}/{name.Substring(lastPeriodIndex + 1)}";
                    }

                    return name;
                case TypeGrouping.ByAddComponentMenu:
                    var addComponentMenuAttributes = type.GetCustomAttributes(typeof(AddComponentMenu), false);
                    if (addComponentMenuAttributes.Length == 1)
                    {
                        return ((AddComponentMenu)addComponentMenuAttributes[0]).componentMenu;
                    }

                    Debug.replacedert(type.FullName != null);
                    return $"Scripts/{type.FullName.Replace('.', '/')}";
                default:
                    throw new ArgumentOutOfRangeException(nameof(grouping), grouping, null);
            }
        }

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

protected void AddInputsToEnvironment()
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(Inputs, nameof(Inputs));

            // Add the inputs to the environment variable dictionary.
            foreach (KeyValuePair<string, string> pair in Inputs)
            {
                AddEnvironmentVariable(
                    key: $"INPUT_{pair.Key?.Replace(' ', '_').ToUpperInvariant()}",
                    value: pair.Value);
            }
        }

19 View Source File : ExtensionMethod.cs
License : MIT License
Project Creator : 1iveowl

public static string ToBase64UrlDecoded(this string str)
        {
            str = str.Replace('-', '+').Replace('_', '/');

            str = str.PadRight(str.Length + (4 - str.Length % 4) % 4, '=');

            var byteArray = Convert.FromBase64String(str);
            var decoded = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length );
            
            return decoded;
        }

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

protected MutexScope GetNewMutexScope()
            {
                return new MutexScope(m_filePath.Replace(Path.DirectorySeparatorChar, '_'));
            }

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

private static string NormalizeSeparators(string path) =>
            path?.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);

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

private static List<ProductInfoHeaderValue> ConstructDefaultRestUserAgent()
        {
            // Pick up the replacedembly version from this dll
            String fileVersion = "unavailable";
            try
            {
                replacedemblyFileVersionAttribute attr = typeof(UserAgentUtility).GetTypeInfo().replacedembly.GetCustomAttribute<replacedemblyFileVersionAttribute>();
                if (attr != null)
                {
                    fileVersion = attr.Version;
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("DefaultUserAgent: Unable to get fileVersion: " + e.ToString());
            }

            String commentValue = string.Format("(NetStandard; {0})", RuntimeInformation.OSDescription.Replace('(', '[').Replace(')', ']').Trim());

            return new List<ProductInfoHeaderValue> {
                new ProductInfoHeaderValue("VSServices", fileVersion),
                new ProductInfoHeaderValue(commentValue) };
        }

19 View Source File : UMAAssetIndexerEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

private void RecursiveScanFoldersForreplacedets(string path)
		{
			var replacedetFiles = System.IO.Directory.GetFiles(path);

			foreach (var replacedetFile in replacedetFiles)
			{
				string Extension = System.IO.Path.GetExtension(replacedetFile).ToLower();
				if (Extension == ".replacedet" || Extension == ".controller" || Extension == ".txt")
				{
					Object o = replacedetDatabase.LoadMainreplacedetAtPath(replacedetFile);

					if (o)
					{
						AddedDuringGui.Add(o);
					}
				}
			}
			foreach (var subFolder in System.IO.Directory.GetDirectories(path))
			{
				RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'));
			}
		}

private static string FormatData(c.Flip flip, int nRows, int nColumns,
            string csvMessage, List<string> rowList)
        {

            for (int column = 0; column < nColumns; column++)
                System.Console.Write((column > 0 ? "," : "") + flip.x[column]);

            for (int row = 0; row < nRows; row++)
            { // Define a Delimiter
                for (int column = 0; column < nColumns; column++)
                {
                    csvMessage += "," + c.at(flip.y[column], row);
                    Console.WriteLine("Formatted:" + row.ToString());
                }
            }

            var length = csvMessage.Length;
            var result = csvMessage.Substring(1, length - 1).Replace(',', '\t');
            return result;
        }

19 View Source File : PathHelper.cs
License : MIT License
Project Creator : absurd-joy

public static string MakeRelativePath(string fromPath, string toPath)
	{
		var fromUri = new Uri(Path.GetFullPath(fromPath));
		var toUri = new Uri(Path.GetFullPath(toPath));

		if (fromUri.Scheme != toUri.Scheme)
		{
			return toPath;
		}

		var relativeUri = fromUri.MakeRelativeUri(toUri);
		var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

		if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
		{
			relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
		}

		return relativePath;
	}

19 View Source File : NameMangler.cs
License : MIT License
Project Creator : adamant

internal static void ManglePart(string name, StringBuilder builder)
        {
            // Fast path no need to escape anything
            if (StandardIdentifierPattern.IsMatch(name))
            {
                builder.Append(name);
                return;
            }

            builder.Append(name.Replace(' ', '_'));
        }

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

public async Task DumpAsync(string output)
        {
            // check and create output folder
            var dumpPath = output;
            while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
            {
                var parent = Path.GetDirectoryName(dumpPath);
                if (parent == null || parent == dumpPath)
                    dumpPath = null;
                else
                    dumpPath = parent;
            }
            if (filesystemStructure is null)
                (filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
            var validators = GetValidationInfo();
            if (!string.IsNullOrEmpty(dumpPath))
            {
                var root = Path.GetPathRoot(Path.GetFullPath(output));
                var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
                if (drive != null)
                {
                    var spaceAvailable = drive.AvailableFreeSpace;
                    TotalFileSize = filesystemStructure.Sum(f => f.Length);
                    var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
                    if (diff > 0)
                        Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
                }
            }

            foreach (var dir in emptyDirStructure)
                Log.Trace($"Empty dir: {dir}");
            foreach (var file in filesystemStructure)
                Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
            var outputPathBase = Path.Combine(output, OutputDir);
            if (!Directory.Exists(outputPathBase))
                Directory.CreateDirectory(outputPathBase);

            TotalFileCount = filesystemStructure.Count;
            TotalSectors = discReader.TotalClusters;
            Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
            var decryptionKey = allMatchingKeys.First().DecryptedKey;
            var sectorSize = (int)discReader.ClusterSize;
            var unprotectedRegions = driveStream.GetUnprotectedRegions();
            ValidationStatus = true;

            foreach (var dir in emptyDirStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
                    var outputName = Path.Combine(outputPathBase, convertedName);
                    if (!Directory.Exists(outputName))
                    {
                        Log.Debug("Creating empty directory " + outputName);
                        Directory.CreateDirectory(outputName);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
                }
            }
            
            foreach (var file in filesystemStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
                    CurrentFileNumber++;
                    var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
                    var inputFilename = Path.Combine(input, convertedFilename);

                    if (!File.Exists(inputFilename))
                    {
                        Log.Error($"Missing {file.Filename}");
                        BrokenFiles.Add((file.Filename, "missing"));
                        continue;
                    }

                    var outputFilename = Path.Combine(outputPathBase, convertedFilename);
                    var fileDir = Path.GetDirectoryName(outputFilename);
                    if (!Directory.Exists(fileDir))
                    {
                        Log.Debug("Creating directory " + fileDir);
                        Directory.CreateDirectory(fileDir);
                    }

                    var error = false;
                    var expectedHashes = (
                        from v in validators
                        where v.Files.ContainsKey(file.Filename)
                        select v.Files[file.Filename].Hashes
                    ).ToList();
                    var lastHash = "";
                    var tries = 2;
                    do
                    {
                        try
                        {
                            tries--;
                            using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
                            using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                            using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
                            Decrypter = decrypter;
                            await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
                            outputStream.Flush();
                            var resultHashes = decrypter.GetHashes();
                            var resultMd5 = resultHashes["MD5"];
                            if (decrypter.WasEncrypted && decrypter.WasUnprotected)
                                Log.Debug("Partially decrypted " + file.Filename);
                            else if (decrypter.WasEncrypted)
                                Log.Debug("Decrypted " + file.Filename);

                            if (!expectedHashes.Any())
                            {
                                if (ValidationStatus == true)
                                    ValidationStatus = null;
                            }
                            else if (!IsMatch(resultHashes, expectedHashes))
                            {
                                error = true;
                                var msg = "Unexpected hash: " + resultMd5;
                                if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
                                {
                                    Log.Error(msg);
                                    BrokenFiles.Add((file.Filename, "corrupted"));
                                    break;
                                }
                                Log.Warn(msg + ", retrying");
                            }

                            lastHash = resultMd5;
                        }
                        catch (Exception e)
                        {
                            Log.Error(e, e.Message);
                            error = true;
                        }
                    } while (error && tries > 0 && !Cts.IsCancellationRequested);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
                }
            }
            Log.Info("Completed");
        }

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

protected static string NormalizeVariableName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw Logger.Fatal<ArgumentException>($"{nameof(name)} is null or empty");

            var retVal = name.Trim().Replace(' ', '_');
            return retVal;
        }

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

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (MainWindowViewModel.SearchText.IsNullOrEmpty())
            {
                return string.Empty;
            }

            var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
            var codeFiles = (Dictionary<string, string>) value;

            var uiCodeFiles = codeFiles.Where(x => x.Key.EndsWith(".xaml"));

            var lines = new List<string>();
            foreach (var file in uiCodeFiles)
            {
                lines.AddRange(file.Value.Split(new[] {"\r\n"}, StringSplitOptions.None));
            }

            var toHighlight = new HashSet<string>();
            foreach (var term in terms)
            {
                var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
                containsTerm.Take(2).Select(x => x.Trim()).ForEachDo(x => toHighlight.Add(x));
            }

            string result;

            if (toHighlight.Any())
            {
                lines = toHighlight.Take(2).Select(x => x.Trim().Replace('<', ' ').Replace('>', ' ') + '.').ToList();
                result = HighlightText(lines, terms);
            }
            else
            {
                var sentences = lines.Take(2).Select(x => string.Format("... {0} ...", x.Trim().Replace('<', ' ').Replace('>', ' ').ToList()));
                result = string.Join("\n", sentences);
            }

            return result;
        }

19 View Source File : SlotLibraryEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

private void RecursiveScanFoldersForreplacedets(string path)
		{
			var replacedetFiles = System.IO.Directory.GetFiles(path, "*.replacedet");
			foreach (var replacedetFile in replacedetFiles)
			{
				var tempSlotDatareplacedet = replacedetDatabase.LoadreplacedetAtPath(replacedetFile, typeof(SlotDatareplacedet)) as SlotDatareplacedet;
				if (tempSlotDatareplacedet)
				{
					AddSlotDatareplacedet(tempSlotDatareplacedet);
				}
			}
			foreach (var subFolder in System.IO.Directory.GetDirectories(path))
			{
				RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'));
			}
		}

19 View Source File : FileSystemHelper.cs
License : zlib License
Project Creator : 0x0ade

public static string ChangePath(string path, char separator) {
            // Can't trust File.Exists if MONO_IOMAP_ALL is set.
            if (!MONO_IOMAP_ALL) {
                string pathMaybe = path;
                // Check if target exists in the first place.
                if (Directory.Exists(path) || File.Exists(path))
                    return pathMaybe;

                // Try a simpler fix first: Maybe the casing is already correct...
                pathMaybe = path.Replace('/', separator).Replace('\\', separator);
                if (Directory.Exists(pathMaybe) || File.Exists(pathMaybe))
                    return pathMaybe;

                // Fall back to the slow rebuild.
            }

            // Check if the path has been rebuilt before.
            Dictionary<string, string> cachedPaths;
            if (!_CachedChanges.TryGetValue(separator, out cachedPaths))
                _CachedChanges[separator] = cachedPaths = new Dictionary<string, string>();
            string cachedPath;
            if (cachedPaths.TryGetValue(path, out cachedPath))
                return cachedPath;

            // Split and rebuild path.

            string[] pathSplit = path.Split(DirectorySeparatorChars);

            StringBuilder builder = new StringBuilder();

            bool unixRooted = false;

            if (Path.IsPathRooted(path)) {
                // The first element in a rooted path will always be correct.
                // On Windows, this will be the drive letter.
                // On Unix and Unix-like systems, this will be empty.
                if (unixRooted = (builder.Length == 0))
                    // Path is rooted, but the path separator is the root.
                    builder.Append(separator);
                else
                    builder.Append(pathSplit[0]);
            }

            for (int i = 1; i < pathSplit.Length; i++) {
                string next;
                if (i < pathSplit.Length - 1)
                    next = GetDirectory(builder.ToString(), pathSplit[i]);
                else
                    next = GetTarget(builder.ToString(), pathSplit[i]);
                next = next ?? pathSplit[i];

                if (i != 1 || !unixRooted)
                    builder.Append(separator);

                builder.Append(next);
            }

            return cachedPaths[path] = builder.ToString();
        }

19 View Source File : GraphyManagerEditor.cs
License : MIT License
Project Creator : 1ZouLTReX1

private string GetMonoScriptFilePath(ScriptableObject scriptableObject) //TODO: Perhaps add a null check.
        {
            MonoScript ms = MonoScript.FromScriptableObject(scriptableObject);
            string filePath = replacedetDatabase.GetreplacedetPath(ms);

            FileInfo fi = new FileInfo(filePath);

            if (fi.Directory != null)
            {
                filePath = fi.Directory.ToString();
                return filePath.Replace
                (
                    oldChar: '\\',
                    newChar: '/'
                );
            }
            return null;
        }

19 View Source File : PersonFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private string TransformIntoValidEmailFormat(string eMail)
        {
            var validFormat = eMail.Replace(' ', '-');
            validFormat = validFormat.RemoveDiacritics();

            return validFormat;
        }

19 View Source File : ChatController.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string ServerCharTranslate(string textChat)
        {
            int pos = 0;
            var clonSpace = textChat.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ').Replace(',', ' ').Replace('.', ' ') + " ";
            while ((pos = textChat.IndexOf("OC_", pos)) >= 0)
            {
                var ep = clonSpace.IndexOf(" ", pos);
                var sub = textChat.Substring(pos, ep - pos);
                var tr = sub.Translate().ToString();
                if (!tr.StartsWith("OC_"))
                {
                    clonSpace = clonSpace.Replace(sub, tr);
                    textChat = textChat.Replace(sub, tr);
                    pos += tr.Length;
                }
                else
                    pos++;
            }

            return textChat;
        }

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

public static string ConvertToValidModelName(string name)
        { 
            const string
                forbiddenCharacters =
                    @". , ; ' ` : / \ * | ? "" & % $ ! + = ( ) [ ] { } < >"; // grabbed these from an AMO exception message
            var modelName = forbiddenCharacters // TODO Could also use TOM.Server.Databases.CreateNewName()
                .Replace(" ", "")
                .ToCharArray()
                .Aggregate(
                    name,
                    (n, c) => n.Replace(c, '_')
                );
            return modelName;
        }

See More Examples