string.Equals(string, string, System.StringComparison)

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

3230 Examples 7

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

public static string GetNext(string[] possible, string next) {
            if (possible == null)
                return null;
            for (int pi = 0; pi < possible.Length; pi++) {
                string possibleName = Path.GetFileName(possible[pi]);
                if (string.Equals(next, possibleName, StringComparison.InvariantCultureIgnoreCase))
                    return possibleName;
            }
            return null;
        }

19 View Source File : BoxString.cs
License : MIT License
Project Creator : 0xC0000054

public bool Equals(BoxString other)
        {
            if (other is null)
            {
                return false;
            }

            return string.Equals(this.Value, other.Value, StringComparison.Ordinal);
        }

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

private void UpdateMethodDescriptors()
        {
            _methodDescriptors.Clear();

            _cachedMethodDescriptor = null;

            if (string.IsNullOrWhiteSpace(MethodName) || _targetObjectType is null)
            {
                return;
            }

            foreach (var method in _targetObjectType.GetRuntimeMethods())
            {
                if (string.Equals(method.Name, MethodName, StringComparison.Ordinal) 
                    && method.ReturnType == typeof(void)
                    && method.IsPublic)
                {
                    var parameters = method.GetParameters();

                    if (parameters.Length == 0)
                    {
                        _cachedMethodDescriptor = new MethodDescriptor(method, parameters);
                    }
                        
                    else if (parameters.Length == 2 && parameters[0].ParameterType == typeof(object))
                    {
                        _methodDescriptors.Add(new MethodDescriptor(method, parameters));
                    }
                }
            }

        }

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

public static object Convert(string value, string destinationTypeFullName)
        {
            if (string.IsNullOrWhiteSpace(destinationTypeFullName))
            {
                throw new ArgumentNullException(destinationTypeFullName);
            }

            var scope = GetScope(destinationTypeFullName);

            if (string.Equals(scope, "System", StringComparison.Ordinal))
            {
                if (string.Equals(destinationTypeFullName, typeof(string).FullName, StringComparison.Ordinal))
                {
                    return value;
                }
                else if (string.Equals(destinationTypeFullName, typeof(bool).FullName, StringComparison.Ordinal))
                {
                    return bool.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(int).FullName, StringComparison.Ordinal))
                {
                    return int.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(double).FullName, StringComparison.Ordinal))
                {
                    return double.Parse(value);
                }
            }

            return null;
        }

19 View Source File : AttributeMap.cs
License : MIT License
Project Creator : 404Lcc

public override bool TryGet(string key, bool publicOnly, out object value)
            {
                MemberInfo[] members = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly);
                foreach (MemberInfo member in members)
                {
#if FX11
                    if (member.Name.ToUpper() == key.ToUpper())
#else
                    if (string.Equals(member.Name, key, StringComparison.OrdinalIgnoreCase))
#endif
                    {
                        PropertyInfo prop = member as PropertyInfo;
                        if (prop != null) {
                            //value = prop.GetValue(attribute, null);
                            value = prop.GetGetMethod(true).Invoke(attribute, null);
                            return true;
                        }
                        FieldInfo field = member as FieldInfo;
                        if (field != null) {
                            value = field.GetValue(attribute);
                            return true;
                        }

                        throw new NotSupportedException(member.GetType().Name);
                    }
                }
                value = null;
                return false;
            }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

private PropertyInfo FindProperty(Type type, ParameterInfo parameter, PropertyInfo[] properties)
        {
            if (ActivationConfiguration.Settings.TryGetValue(type, out var setting))
            {
                if (setting.Parameters.TryGetValue(parameter, out var property))
                {
                    return property;
                }
            }

            properties = properties.Where(x => string.Equals(x.Name, parameter.Name, StringComparison.OrdinalIgnoreCase)).ToArray();

            if (properties.Count() != 1)
            {
                throw new Exception($"Unable to find appropriate property to use as a constructor parameter '{parameter.Name}'. Type '{type.Name}'. Consider to use {nameof(ActivationConfiguration)} parameter.");
            }

            return properties.Single();
        }

19 View Source File : JsonConfigurator.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static ILogManager ConfigureAndWatch(string configFilePath)
        {
            var configFileFullPath = Path.GetFullPath(configFilePath);

            var resolver = new HierarchicalResolver();

            var config = ConfigureResolver(configFileFullPath, resolver);

            var watcher = new FileSystemWatcher
            {
                Path = Path.GetDirectoryName(configFileFullPath)!,
                NotifyFilter = NotifyFilters.LastWrite,
                EnableRaisingEvents = true
            };

            watcher.Changed += (sender, args) =>
            {
                try
                {
                    if (!string.Equals(args.FullPath, configFileFullPath, StringComparison.InvariantCultureIgnoreCase))
                        return;

                    var newConfig = ReadConfiguration(configFileFullPath);
                    resolver.Build(newConfig);
                    ConfigureGlobal(newConfig);
                }
                catch (Exception e)
                {
                    LogManager.GetLogger(typeof(JsonConfigurator))
                              .FatalFormat("Updating config failed with: {0}", e.Message);
                }
            };

            var logManager = LogManager.Initialize(resolver, config.GetInitializationConfig());
            ConfigureGlobal(config);
            return logManager;
        }

19 View Source File : CompletionList.cs
License : MIT License
Project Creator : Abdesol

int GetMatchQuality(string itemText, string query)
		{
			if (itemText == null)
				throw new ArgumentNullException("itemText", "ICompletionData.Text returned null");

			// Qualities:
			//  	8 = full match case sensitive
			// 		7 = full match
			// 		6 = match start case sensitive
			//		5 = match start
			//		4 = match CamelCase when length of query is 1 or 2 characters
			// 		3 = match substring case sensitive
			//		2 = match substring
			//		1 = match CamelCase
			//		-1 = no match
			if (query == itemText)
				return 8;
			if (string.Equals(itemText, query, StringComparison.InvariantCultureIgnoreCase))
				return 7;

			if (itemText.StartsWith(query, StringComparison.InvariantCulture))
				return 6;
			if (itemText.StartsWith(query, StringComparison.InvariantCultureIgnoreCase))
				return 5;

			bool? camelCaseMatch = null;
			if (query.Length <= 2) {
				camelCaseMatch = CamelCaseMatch(itemText, query);
				if (camelCaseMatch == true) return 4;
			}

			// search by substring, if filtering (i.e. new behavior) turned on
			if (IsFiltering) {
				if (itemText.IndexOf(query, StringComparison.InvariantCulture) >= 0)
					return 3;
				if (itemText.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) >= 0)
					return 2;
			}

			if (!camelCaseMatch.HasValue)
				camelCaseMatch = CamelCaseMatch(itemText, query);
			if (camelCaseMatch == true)
				return 1;

			return -1;
		}

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

static bool CreatereplacedetPath( string newFolderPath )
	{
		const  int maxFoldersCount = 32;
		string currentPath;
		string[] pathFolders;

		pathFolders = newFolderPath.Split (new char[]{ '/' }, maxFoldersCount);

		if (!string.Equals ("replacedets", pathFolders [0], System.StringComparison.OrdinalIgnoreCase))
		{
			Debug.LogError( "Folder path has to be started with \" replacedets \" " );
			return false;
		}

		currentPath = "replacedets";
		for (int i = 1; i < pathFolders.Length; i++)
		{
			if (!string.IsNullOrEmpty(pathFolders[i]))
			{
				string newPath = currentPath + "/" + pathFolders[i];
				if (!replacedetDatabase.IsValidFolder(newPath))
					replacedetDatabase.CreateFolder(currentPath, pathFolders[i]);
				currentPath = newPath;
			}
		}

		Debug.Log( "Created path: " + currentPath );
		return true;
	}

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

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var stringParam = parameter as string;
            var inverse = string.Equals(stringParam, InvertionFlag, StringComparison.InvariantCultureIgnoreCase);

            var onTrue= inverse ? Visibility.Visible : Visibility.Collapsed;
            var onFalse = inverse ? Visibility.Collapsed : Visibility.Visible;

            return string.IsNullOrEmpty(value as string) ? onTrue : onFalse;
        }

19 View Source File : ViaCepWebservice.cs
License : MIT License
Project Creator : ACBrNet

public override ACBrEndereco[] BuscarPorLogradouro(ConsultaUF uf, string municipio, string logradouro, string tipoLogradouro = "", string bairro = "")
		{
			var url = $"{VIACEP_URL}/{uf}/{municipio.ToLower().ToreplacedleCase()}/{logradouro.ToLower().ToreplacedleCase()}/xml";
			var ret = ConsultaCEP(url);

			if (!tipoLogradouro.IsEmpty())
			{
				ret.RemoveAll(x => !string.Equals(x.TipoLogradouro.RemoveAccent(), tipoLogradouro.RemoveAccent(), StringComparison.CurrentCultureIgnoreCase));
			}

			if (!bairro.IsEmpty())
			{
				ret.RemoveAll(x => !string.Equals(x.Bairro.RemoveAccent(), bairro.RemoveAccent(), StringComparison.CurrentCultureIgnoreCase));
			}

			return ret.ToArray();
		}

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

public bool IsCommand(string name)
        {
            bool result = false;
            if (Commands.Count > 0)
            {
                result = String.Equals(name, Commands[0], StringComparison.CurrentCultureIgnoreCase);
            }

            return result;
        }

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

public void Parse(string[] args)
        {
            _trace.Info(nameof(Parse));
            ArgUtil.NotNull(args, nameof(args));
            _trace.Info("Parsing {0} args", args.Length);

            string argScope = null;
            foreach (string arg in args)
            {
                _trace.Info("parsing argument");

                HasArgs = HasArgs || arg.StartsWith("--");
                _trace.Info("HasArgs: {0}", HasArgs);

                if (string.Equals(arg, "/?", StringComparison.Ordinal))
                {
                    Flags.Add("help");
                }
                else if (!HasArgs)
                {
                    _trace.Info("Adding Command: {0}", arg);
                    Commands.Add(arg.Trim());
                }
                else
                {
                    // it's either an arg, an arg value or a flag
                    if (arg.StartsWith("--") && arg.Length > 2)
                    {
                        string argVal = arg.Substring(2);
                        _trace.Info("arg: {0}", argVal);

                        // this means two --args in a row which means previous was a flag
                        if (argScope != null)
                        {
                            _trace.Info("Adding flag: {0}", argScope);
                            Flags.Add(argScope.Trim());
                        }

                        argScope = argVal;
                    }
                    else if (!arg.StartsWith("-"))
                    {
                        // we found a value - check if we're in scope of an arg
                        if (argScope != null && !Args.ContainsKey(argScope = argScope.Trim()))
                        {
                            if (SecretArgNames.Contains(argScope))
                            {
                                _secretMasker.AddValue(arg);
                            }

                            _trace.Info("Adding option '{0}': '{1}'", argScope, arg);
                            // ignore duplicates - first wins - below will be val1
                            // --arg1 val1 --arg1 val1
                            Args.Add(argScope, arg);
                            argScope = null;
                        }
                    }
                    else
                    {
                        //
                        // ignoring the second value for an arg (val2 below) 
                        // --arg val1 val2

                        // ignoring invalid things like empty - and --
                        // --arg val1 -- --flag
                        _trace.Info("Ignoring arg");
                    }
                }
            }

            _trace.Verbose("done parsing arguments");

            // handle last arg being a flag
            if (argScope != null)
            {
                Flags.Add(argScope);
            }

            _trace.Verbose("Exiting parse");
        }

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

public async Task ConfigureAsync(CommandSettings command)
        {
            _term.WriteLine();
            _term.WriteLine("--------------------------------------------------------------------------------");
            _term.WriteLine("|        ____ _ _   _   _       _          _        _   _                      |");
            _term.WriteLine("|       / ___(_) |_| | | |_   _| |__      / \\   ___| |_(_) ___  _ __  ___      |");
            _term.WriteLine("|      | |  _| | __| |_| | | | | '_ \\    / _ \\ / __| __| |/ _ \\| '_ \\/ __|     |");
            _term.WriteLine("|      | |_| | | |_|  _  | |_| | |_) |  / ___ \\ (__| |_| | (_) | | | \\__ \\     |");
            _term.WriteLine("|       \\____|_|\\__|_| |_|\\__,_|_.__/  /_/   \\_\\___|\\__|_|\\___/|_| |_|___/     |");
            _term.WriteLine("|                                                                              |");
            _term.Write("|                       ");
            _term.Write("Self-hosted runner registration", ConsoleColor.Cyan);
            _term.WriteLine("                        |");
            _term.WriteLine("|                                                                              |");
            _term.WriteLine("--------------------------------------------------------------------------------");

            Trace.Info(nameof(ConfigureAsync));
            if (IsConfigured())
            {
                throw new InvalidOperationException("Cannot configure the runner because it is already configured. To reconfigure the runner, run 'config.cmd remove' or './config.sh remove' first.");
            }

            RunnerSettings runnerSettings = new RunnerSettings();

            // Loop getting url and creds until you can connect
            ICredentialProvider credProvider = null;
            VssCredentials creds = null;
            _term.WriteSection("Authentication");
            while (true)
            {
                // When testing against a dev deployment of Actions Service, set this environment variable
                var useDevActionsServiceUrl = Environment.GetEnvironmentVariable("USE_DEV_ACTIONS_SERVICE_URL");
                var inputUrl = command.GetUrl();
                if (inputUrl.Contains("codedev.ms", StringComparison.OrdinalIgnoreCase)
                    || useDevActionsServiceUrl != null)
                {
                    runnerSettings.ServerUrl = inputUrl;
                    // Get the credentials
                    credProvider = GetCredentialProvider(command, runnerSettings.ServerUrl);
                    creds = credProvider.GetVssCredentials(HostContext);
                    Trace.Info("legacy vss cred retrieved");
                }
                else
                {
                    runnerSettings.GitHubUrl = inputUrl;
                    var registerToken = await GetRunnerTokenAsync(command, inputUrl, "registration");
                    GitHubAuthResult authResult = await GetTenantCredential(inputUrl, registerToken, Constants.RunnerEvent.Register);
                    runnerSettings.ServerUrl = authResult.TenantUrl;
                    creds = authResult.ToVssCredentials();
                    Trace.Info("cred retrieved via GitHub auth");
                }

                try
                {
                    // Determine the service deployment type based on connection data. (Hosted/OnPremises)
                    // Hosted usually means github.com or localhost, while OnPremises means GHES or GHAE
                    runnerSettings.IsHostedServer = runnerSettings.GitHubUrl == null || UrlUtil.IsHostedServer(new UriBuilder(runnerSettings.GitHubUrl));

                    // Warn if the Actions server url and GHES server url has different Host
                    if (!runnerSettings.IsHostedServer)
                    {
                        // Example actionsServerUrl is https://my-ghes/_services/pipelines/[...]
                        // Example githubServerUrl is https://my-ghes
                        var actionsServerUrl = new Uri(runnerSettings.ServerUrl);
                        var githubServerUrl = new Uri(runnerSettings.GitHubUrl);
                        if (!string.Equals(actionsServerUrl.Authority, githubServerUrl.Authority, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new InvalidOperationException($"GitHub Actions is not properly configured in GHES. GHES url: {runnerSettings.GitHubUrl}, Actions url: {runnerSettings.ServerUrl}.");
                        }
                    }

                    // Validate can connect.
                    await _runnerServer.ConnectAsync(new Uri(runnerSettings.ServerUrl), creds);

                    _term.WriteLine();
                    _term.WriteSuccessMessage("Connected to GitHub");

                    Trace.Info("Test Connection complete.");
                    break;
                }
                catch (Exception e) when (!command.Unattended)
                {
                    _term.WriteError(e);
                    _term.WriteError("Failed to connect.  Try again or ctrl-c to quit");
                    _term.WriteLine();
                }
            }

            // We want to use the native CSP of the platform for storage, so we use the RSACSP directly
            RSAParameters publicKey;
            var keyManager = HostContext.GetService<IRSAKeyManager>();
            using (var rsa = keyManager.CreateKey())
            {
                publicKey = rsa.ExportParameters(false);
            }

            _term.WriteSection("Runner Registration");

            // If we have more than one runner group available, allow the user to specify which one to be added into
            string poolName = null;
            TaskAgentPool agentPool = null;
            List<TaskAgentPool> agentPools = await _runnerServer.GetAgentPoolsAsync();
            TaskAgentPool defaultPool = agentPools?.Where(x => x.IsInternal).FirstOrDefault();

            if (agentPools?.Where(x => !x.IsHosted).Count() > 0)
            {
                poolName = command.GetRunnerGroupName(defaultPool?.Name);
                _term.WriteLine();
                agentPool = agentPools.Where(x => string.Equals(poolName, x.Name, StringComparison.OrdinalIgnoreCase) && !x.IsHosted).FirstOrDefault();
            }
            else
            {
                agentPool = defaultPool;
            }

            if (agentPool == null && poolName == null)
            {
                throw new TaskAgentPoolNotFoundException($"Could not find any self-hosted runner groups. Contact support.");
            }
            else if (agentPool == null && poolName != null)
            {
                throw new TaskAgentPoolNotFoundException($"Could not find any self-hosted runner group named \"{poolName}\".");
            }
            else
            {
                Trace.Info($"Found a self-hosted runner group with id {agentPool.Id} and name {agentPool.Name}");
                runnerSettings.PoolId = agentPool.Id;
                runnerSettings.PoolName = agentPool.Name;
            }

            TaskAgent agent;
            while (true)
            {
                runnerSettings.Ephemeral = command.Ephemeral;
                runnerSettings.AgentName = command.GetRunnerName();

                _term.WriteLine();

                var userLabels = command.GetLabels();
                _term.WriteLine();

                var agents = await _runnerServer.GetAgentsAsync(runnerSettings.PoolId, runnerSettings.AgentName);
                Trace.Verbose("Returns {0} agents", agents.Count);
                agent = agents.FirstOrDefault();
                if (agent != null)
                {
                    _term.WriteLine("A runner exists with the same name", ConsoleColor.Yellow);
                    if (command.GetReplace())
                    {
                        // Update existing agent with new PublicKey, agent version.
                        agent = UpdateExistingAgent(agent, publicKey, userLabels, runnerSettings.Ephemeral);

                        try
                        {
                            agent = await _runnerServer.ReplaceAgentAsync(runnerSettings.PoolId, agent);
                            _term.WriteSuccessMessage("Successfully replaced the runner");
                            break;
                        }
                        catch (Exception e) when (!command.Unattended)
                        {
                            _term.WriteError(e);
                            _term.WriteError("Failed to replace the runner.  Try again or ctrl-c to quit");
                        }
                    }
                    else if (command.Unattended)
                    {
                        // if not replace and it is unattended config.
                        throw new TaskAgentExistsException($"A runner exists with the same name {runnerSettings.AgentName}.");
                    }
                }
                else
                {
                    // Create a new agent.
                    agent = CreateNewAgent(runnerSettings.AgentName, publicKey, userLabels, runnerSettings.Ephemeral);

                    try
                    {
                        agent = await _runnerServer.AddAgentAsync(runnerSettings.PoolId, agent);
                        _term.WriteSuccessMessage("Runner successfully added");
                        break;
                    }
                    catch (Exception e) when (!command.Unattended)
                    {
                        _term.WriteError(e);
                        _term.WriteError("Failed to add the runner. Try again or ctrl-c to quit");
                    }
                }
            }
            // Add Agent Id to settings
            runnerSettings.AgentId = agent.Id;

            // See if the server supports our OAuth key exchange for credentials
            if (agent.Authorization != null &&
                agent.Authorization.ClientId != Guid.Empty &&
                agent.Authorization.AuthorizationUrl != null)
            {
                var credentialData = new CredentialData
                {
                    Scheme = Constants.Configuration.OAuth,
                    Data =
                    {
                        { "clientId", agent.Authorization.ClientId.ToString("D") },
                        { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri },
                        { "requireFipsCryptography", agent.Properties.GetValue("RequireFipsCryptography", false).ToString() }
                    },
                };

                // Save the negotiated OAuth credential data
                _store.SaveCredential(credentialData);
            }
            else
            {

                throw new NotSupportedException("Message queue listen OAuth token.");
            }

            // Testing agent connection, detect any potential connection issue, like local clock skew that cause OAuth token expired.
            var credMgr = HostContext.GetService<ICredentialManager>();
            VssCredentials credential = credMgr.LoadCredentials();
            try
            {
                await _runnerServer.ConnectAsync(new Uri(runnerSettings.ServerUrl), credential);
                // ConnectAsync() hits _apis/connectionData which is an anonymous endpoint
                // Need to hit an authenticate endpoint to trigger OAuth token exchange.
                await _runnerServer.GetAgentPoolsAsync();
                _term.WriteSuccessMessage("Runner connection is good");
            }
            catch (VssOAuthTokenRequestException ex) when (ex.Message.Contains("Current server time is"))
            {
                // there are two exception messages server send that indicate clock skew.
                // 1. The bearer token expired on {jwt.ValidTo}. Current server time is {DateTime.UtcNow}.
                // 2. The bearer token is not valid until {jwt.ValidFrom}. Current server time is {DateTime.UtcNow}.
                Trace.Error("Catch exception during test agent connection.");
                Trace.Error(ex);
                throw new Exception("The local machine's clock may be out of sync with the server time by more than five minutes. Please sync your clock with your domain or internet time and try again.");
            }

            _term.WriteSection("Runner settings");

            // We will Combine() what's stored with root.  Defaults to string a relative path
            runnerSettings.WorkFolder = command.GetWork();

            runnerSettings.MonitorSocketAddress = command.GetMonitorSocketAddress();

            _store.SaveSettings(runnerSettings);

            _term.WriteLine();
            _term.WriteSuccessMessage("Settings Saved.");
            _term.WriteLine();

#if OS_WINDOWS
            // config windows service
            bool runreplacedervice = command.GetRunreplacedervice();
            if (runreplacedervice)
            {
                Trace.Info("Configuring to run the agent as service");
                var serviceControlManager = HostContext.GetService<IWindowsServiceControlManager>();
                serviceControlManager.ConfigureService(runnerSettings, command);
            }

#elif OS_LINUX || OS_OSX
            // generate service config script for OSX and Linux, GenerateScripts() will no-opt on windows.
            var serviceControlManager = HostContext.GetService<ILinuxServiceControlManager>();
            serviceControlManager.GenerateScripts(runnerSettings);
#endif
        }

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

public static int Main(string[] args)
        {
            Console.CancelKeyPress += Console_CancelKeyPress;

            // Set encoding to UTF8, process invoker will use UTF8 write to STDIN
            Console.InputEncoding = Encoding.UTF8;
            Console.OutputEncoding = Encoding.UTF8;
            try
            {
                ArgUtil.NotNull(args, nameof(args));
                ArgUtil.Equal(2, args.Length, nameof(args.Length));

                string pluginType = args[0];
                if (string.Equals("action", pluginType, StringComparison.OrdinalIgnoreCase))
                {
                    string replacedemblyQualifiedName = args[1];
                    ArgUtil.NotNullOrEmpty(replacedemblyQualifiedName, nameof(replacedemblyQualifiedName));

                    string serializedContext = Console.ReadLine();
                    ArgUtil.NotNullOrEmpty(serializedContext, nameof(serializedContext));

                    RunnerActionPluginExecutionContext executionContext = StringUtil.ConvertFromJson<RunnerActionPluginExecutionContext>(serializedContext);
                    ArgUtil.NotNull(executionContext, nameof(executionContext));

                    VariableValue culture;
                    ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
                    if (executionContext.Variables.TryGetValue("system.culture", out culture) &&
                        !string.IsNullOrEmpty(culture?.Value))
                    {
                        CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(culture.Value);
                        CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(culture.Value);
                    }

                    replacedemblyLoadContext.Default.Resolving += Resolvereplacedembly;
                    try
                    {
                        Type type = Type.GetType(replacedemblyQualifiedName, throwOnError: true);
                        var taskPlugin = Activator.CreateInstance(type) as IRunnerActionPlugin;
                        ArgUtil.NotNull(taskPlugin, nameof(taskPlugin));
                        taskPlugin.RunAsync(executionContext, tokenSource.Token).GetAwaiter().GetResult();
                    }
                    catch (Exception ex)
                    {
                        // any exception throw from plugin will fail the task.
                        executionContext.Error(ex.Message);
                        executionContext.Debug(ex.StackTrace);
                        return 1;
                    }
                    finally
                    {
                        replacedemblyLoadContext.Default.Resolving -= Resolvereplacedembly;
                    }

                    return 0;
                }
                else
                {
                    throw new ArgumentOutOfRangeException(pluginType);
                }
            }
            catch (Exception ex)
            {
                // infrastructure failure.
                Console.Error.WriteLine(ex.ToString());
                return 1;
            }
            finally
            {
                Console.CancelKeyPress -= Console_CancelKeyPress;
            }
        }

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

private void DeletePreviousVersionRunnerBackup(CancellationToken token)
        {
            // delete previous backup runner (back compat, can be remove after serval sprints)
            // bin.bak.2.99.0
            // externals.bak.2.99.0
            foreach (string existBackUp in Directory.GetDirectories(HostContext.GetDirectory(WellKnownDirectory.Root), "*.bak.*"))
            {
                Trace.Info($"Delete existing runner backup at {existBackUp}.");
                try
                {
                    IOUtil.DeleteDirectory(existBackUp, token);
                }
                catch (Exception ex) when (!(ex is OperationCanceledException))
                {
                    Trace.Error(ex);
                    Trace.Info($"Catch exception during delete backup folder {existBackUp}, ignore this error try delete the backup folder on next auto-update.");
                }
            }

            // delete old bin.2.99.0 folder, only leave the current version and the latest download version
            var allBinDirs = Directory.GetDirectories(HostContext.GetDirectory(WellKnownDirectory.Root), "bin.*");
            if (allBinDirs.Length > 2)
            {
                // there are more than 2 bin.version folder.
                // delete older bin.version folders.
                foreach (var oldBinDir in allBinDirs)
                {
                    if (string.Equals(oldBinDir, Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"bin"), StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(oldBinDir, Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"bin.{BuildConstants.RunnerPackage.Version}"), StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(oldBinDir, Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"bin.{_targetPackage.Version}"), StringComparison.OrdinalIgnoreCase))
                    {
                        // skip for current runner version
                        continue;
                    }

                    Trace.Info($"Delete runner bin folder's backup at {oldBinDir}.");
                    try
                    {
                        IOUtil.DeleteDirectory(oldBinDir, token);
                    }
                    catch (Exception ex) when (!(ex is OperationCanceledException))
                    {
                        Trace.Error(ex);
                        Trace.Info($"Catch exception during delete backup folder {oldBinDir}, ignore this error try delete the backup folder on next auto-update.");
                    }
                }
            }

            // delete old externals.2.99.0 folder, only leave the current version and the latest download version
            var allExternalsDirs = Directory.GetDirectories(HostContext.GetDirectory(WellKnownDirectory.Root), "externals.*");
            if (allExternalsDirs.Length > 2)
            {
                // there are more than 2 externals.version folder.
                // delete older externals.version folders.
                foreach (var oldExternalDir in allExternalsDirs)
                {
                    if (string.Equals(oldExternalDir, Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"externals"), StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(oldExternalDir, Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"externals.{BuildConstants.RunnerPackage.Version}"), StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(oldExternalDir, Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"externals.{_targetPackage.Version}"), StringComparison.OrdinalIgnoreCase))
                    {
                        // skip for current runner version
                        continue;
                    }

                    Trace.Info($"Delete runner externals folder's backup at {oldExternalDir}.");
                    try
                    {
                        IOUtil.DeleteDirectory(oldExternalDir, token);
                    }
                    catch (Exception ex) when (!(ex is OperationCanceledException))
                    {
                        Trace.Error(ex);
                        Trace.Info($"Catch exception during delete backup folder {oldExternalDir}, ignore this error try delete the backup folder on next auto-update.");
                    }
                }
            }
        }

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 : ConfigurationManager.cs
License : MIT License
Project Creator : actions

private async Task<string> GetRunnerTokenAsync(CommandSettings command, string githubUrl, string tokenType)
        {
            var githubPAT = command.GetGitHubPersonalAccessToken();
            var runnerToken = string.Empty;
            if (!string.IsNullOrEmpty(githubPAT))
            {
                Trace.Info($"Retriving runner {tokenType} token using GitHub PAT.");
                var jitToken = await GetJITRunnerTokenAsync(githubUrl, githubPAT, tokenType);
                Trace.Info($"Retrived runner {tokenType} token is good to {jitToken.ExpiresAt}.");
                HostContext.SecretMasker.AddValue(jitToken.Token);
                runnerToken = jitToken.Token;
            }

            if (string.IsNullOrEmpty(runnerToken))
            {
                if (string.Equals("registration", tokenType, StringComparison.OrdinalIgnoreCase))
                {
                    runnerToken = command.GetRunnerRegisterToken();
                }
                else
                {
                    runnerToken = command.GetRunnerDeletionToken();
                }
            }

            return runnerToken;
        }

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

private async Task<GitHubRunnerRegisterToken> GetJITRunnerTokenAsync(string githubUrl, string githubToken, string tokenType)
        {
            var githubApiUrl = "";
            var gitHubUrlBuilder = new UriBuilder(githubUrl);
            var path = gitHubUrlBuilder.Path.Split('/', '\\', StringSplitOptions.RemoveEmptyEntries);
            if (path.Length == 1)
            {
                // org runner
                if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/orgs/{path[0]}/actions/runners/{tokenType}-token";
                }
                else
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/orgs/{path[0]}/actions/runners/{tokenType}-token";
                }
            }
            else if (path.Length == 2)
            {
                // repo or enterprise runner.
                var repoScope = "repos/";
                if (string.Equals(path[0], "enterprises", StringComparison.OrdinalIgnoreCase))
                {
                    repoScope = "";
                }

                if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
                }
                else
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
                }
            }
            else
            {
                throw new ArgumentException($"'{githubUrl}' should point to an org or repository.");
            }

            using (var httpClientHandler = HostContext.CreateHttpClientHandler())
            using (var httpClient = new HttpClient(httpClientHandler))
            {
                var base64EncodingToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"github:{githubToken}"));
                HostContext.SecretMasker.AddValue(base64EncodingToken);
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", base64EncodingToken);
                httpClient.DefaultRequestHeaders.UserAgent.AddRange(HostContext.UserAgents);
                httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github.v3+json");

                var response = await httpClient.PostAsync(githubApiUrl, new StringContent(string.Empty));

                if (response.IsSuccessStatusCode)
                {
                    Trace.Info($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
                    var jsonResponse = await response.Content.ReadreplacedtringAsync();
                    return StringUtil.ConvertFromJson<GitHubRunnerRegisterToken>(jsonResponse);
                }
                else
                {
                    _term.WriteError($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
                    var errorResponse = await response.Content.ReadreplacedtringAsync();
                    _term.WriteError(errorResponse);
                    response.EnsureSuccessStatusCode();
                    return null;
                }
            }
        }

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

public VssCredentials ToVssCredentials()
        {
            ArgUtil.NotNullOrEmpty(TokenSchema, nameof(TokenSchema));
            ArgUtil.NotNullOrEmpty(Token, nameof(Token));

            if (string.Equals(TokenSchema, "OAuthAccessToken", StringComparison.OrdinalIgnoreCase))
            {
                return new VssCredentials(new VssOAuthAccessTokenCredential(Token), CredentialPromptType.DoNotPrompt);
            }
            else
            {
                throw new NotSupportedException($"Not supported token schema: {TokenSchema}");
            }
        }

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

public bool ReadBool(
            string argName,
            string description,
            bool defaultValue,
            bool unattended)
        {
            string answer = ReadValue(
                argName: argName,
                description: description,
                secret: false,
                defaultValue: defaultValue ? "Y" : "N",
                validator: Validators.BoolValidator,
                unattended: unattended);
            return String.Equals(answer, "true", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(answer, "Y", StringComparison.CurrentCultureIgnoreCase);
        }

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

public static bool BoolValidator(string value)
        {
            return string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) ||
                   string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) ||
                   string.Equals(value, "Y", StringComparison.CurrentCultureIgnoreCase) ||
                   string.Equals(value, "N", StringComparison.CurrentCultureIgnoreCase);
        }

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

public static bool IsHostedServer(UriBuilder gitHubUrl)
        {
            return string.Equals(gitHubUrl.Host, "github.com", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(gitHubUrl.Host, "www.github.com", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(gitHubUrl.Host, "github.localhost", StringComparison.OrdinalIgnoreCase);
        }

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

private bool IsUriInBypreplacedList(Uri input)
        {
            foreach (var noProxy in _noProxyList)
            {
                var matchHost = false;
                var matchPort = false;

                if (string.IsNullOrEmpty(noProxy.Port))
                {
                    matchPort = true;
                }
                else
                {
                    matchPort = string.Equals(noProxy.Port, input.Port.ToString());
                }

                if (noProxy.Host.StartsWith('.'))
                {
                    matchHost = input.Host.EndsWith(noProxy.Host, StringComparison.OrdinalIgnoreCase);
                }
                else
                {
                    matchHost = string.Equals(input.Host, noProxy.Host, StringComparison.OrdinalIgnoreCase) || input.Host.EndsWith($".{noProxy.Host}", StringComparison.OrdinalIgnoreCase);
                }

                if (matchHost && matchPort)
                {
                    return true;
                }
            }

            return false;
        }

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

private void ParseVolumeString(string volume)
        {
            var volumeSplit = volume.Split(":");
            if (volumeSplit.Length == 3)
            {
                // source:target:ro
                SourceVolumePath = volumeSplit[0];
                TargetVolumePath = volumeSplit[1];
                ReadOnly = String.Equals(volumeSplit[2], "ro", StringComparison.OrdinalIgnoreCase);
            }
            else if (volumeSplit.Length == 2)
            {
                if (String.Equals(volumeSplit[1], "ro", StringComparison.OrdinalIgnoreCase))
                {
                    // target:ro
                    TargetVolumePath = volumeSplit[0];
                    ReadOnly = true;
                }
                else
                {
                    // source:target
                    SourceVolumePath = volumeSplit[0];
                    TargetVolumePath = volumeSplit[1];
                    ReadOnly = false;
                }
            }
            else
            {
                // target - or, default to preplaceding straight through
                TargetVolumePath = volume;
                ReadOnly = false;
            }
        }

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

public void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc)
        {
            Trace.Entering();
            ArgUtil.NotNull(jobContext, nameof(jobContext));

            // create a new timeline record node for 'Finalize job'
            IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Complete job", $"{nameof(JobExtension)}_Final", null, null, ActionRunStage.Post);
            using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
            {
                try
                {
                    context.Start();
                    context.Debug("Starting: Complete job");

                    Trace.Info("Initialize Env context");

#if OS_WINDOWS
                    var envContext = new DictionaryContextData();
#else
                    var envContext = new CaseSensitiveDictionaryContextData();
#endif
                    context.ExpressionValues["env"] = envContext;
                    foreach (var pair in context.Global.EnvironmentVariables)
                    {
                        envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
                    }

                    // Populate env context for each step
                    Trace.Info("Initialize steps context");
                    context.ExpressionValues["steps"] = context.Global.StepsContext.GetScope(context.ScopeName);

                    var templateEvaluator = context.ToPipelineTemplateEvaluator();
                    // Evaluate job outputs
                    if (message.JobOutputs != null && message.JobOutputs.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set job outputs");

                            // Populate env context for each step
                            Trace.Info("Initialize Env context for evaluating job outputs");

                            var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
                            foreach (var output in outputs)
                            {
                                if (string.IsNullOrEmpty(output.Value))
                                {
                                    context.Debug($"Skip output '{output.Key}' since it's empty");
                                    continue;
                                }

                                if (!string.Equals(output.Value, HostContext.SecretMasker.MaskSecrets(output.Value)))
                                {
                                    context.Warning($"Skip output '{output.Key}' since it may contain secret.");
                                    continue;
                                }

                                context.Output($"Set output '{output.Key}'");
                                jobContext.JobOutputs[output.Key] = output.Value;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Fail to evaluate job outputs");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    // Evaluate environment data
                    if (jobContext.ActionsEnvironment?.Url != null && jobContext.ActionsEnvironment?.Url.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set environment url");

                            var environmentUrlToken = templateEvaluator.EvaluateEnvironmentUrl(jobContext.ActionsEnvironment.Url, context.ExpressionValues, context.ExpressionFunctions);
                            var environmentUrl = environmentUrlToken.replacedertString("environment.url");
                            if (!string.Equals(environmentUrl.Value, HostContext.SecretMasker.MaskSecrets(environmentUrl.Value)))
                            {
                                context.Warning($"Skip setting environment url as environment '{jobContext.ActionsEnvironment.Name}' may contain secret.");
                            }
                            else
                            {
                                context.Output($"Evaluated environment url: {environmentUrl}");
                                jobContext.ActionsEnvironment.Url = environmentUrlToken;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Failed to evaluate environment url");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    if (context.Global.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
                    {
                        Trace.Info("Support log upload starting.");
                        context.Output("Uploading runner diagnostic logs");

                        IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>();

                        try
                        {
                            diagnosticLogManager.UploadDiagnosticLogs(executionContext: context, parentContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc);

                            Trace.Info("Support log upload complete.");
                            context.Output("Completed runner diagnostic log upload");
                        }
                        catch (Exception ex)
                        {
                            // Log the error but make sure we continue gracefully.
                            Trace.Info("Error uploading support logs.");
                            context.Output("Error uploading runner diagnostic logs");
                            Trace.Error(ex);
                        }
                    }

                    if (_processCleanup)
                    {
                        context.Output("Cleaning up orphan processes");

                        // Only check environment variable for any process that doesn't run before we invoke our process.
                        Dictionary<int, Process> currentProcesses = SnapshotProcesses();
                        foreach (var proc in currentProcesses)
                        {
                            if (proc.Key == Process.GetCurrentProcess().Id)
                            {
                                // skip for current process.
                                continue;
                            }

                            if (_existingProcesses.Contains($"{proc.Key}_{proc.Value.ProcessName}"))
                            {
                                Trace.Verbose($"Skip existing process. PID: {proc.Key} ({proc.Value.ProcessName})");
                            }
                            else
                            {
                                Trace.Info($"Inspecting process environment variables. PID: {proc.Key} ({proc.Value.ProcessName})");

                                string lookupId = null;
                                try
                                {
                                    lookupId = proc.Value.GetEnvironmentVariable(HostContext, Constants.ProcessTrackingId);
                                }
                                catch (Exception ex)
                                {
                                    Trace.Warning($"Ignore exception during read process environment variables: {ex.Message}");
                                    Trace.Verbose(ex.ToString());
                                }

                                if (string.Equals(lookupId, _processLookupId, StringComparison.OrdinalIgnoreCase))
                                {
                                    context.Output($"Terminate orphan process: pid ({proc.Key}) ({proc.Value.ProcessName})");
                                    try
                                    {
                                        proc.Value.Kill();
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.Error("Catch exception during orphan process cleanup.");
                                        Trace.Error(ex);
                                    }
                                }
                            }
                        }
                    }

                    if (_diskSpaceCheckTask != null)
                    {
                        _diskSpaceCheckToken.Cancel();
                    }
                }
                catch (Exception ex)
                {
                    // Log and ignore the error from JobExtension finalization.
                    Trace.Error($"Caught exception from JobExtension finalization: {ex}");
                    context.Output(ex.Message);
                }
                finally
                {
                    context.Debug("Finishing: Complete job");
                    context.Complete();
                }
            }
        }

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 = [email protected]{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 : ContainerOperationProvider.cs
License : MIT License
Project Creator : actions

private async Task ContainerHealthcheck(IExecutionContext executionContext, ContainerInfo container)
        {
            string healthCheck = "--format=\"{{if .Config.Healthcheck}}{{print .State.Health.Status}}{{end}}\"";
            string serviceHealth = (await _dockerManager.DockerInspect(context: executionContext, dockerObject: container.ContainerId, options: healthCheck)).FirstOrDefault();
            if (string.IsNullOrEmpty(serviceHealth))
            {
                // Container has no HEALTHCHECK
                return;
            }
            var retryCount = 0;
            while (string.Equals(serviceHealth, "starting", StringComparison.OrdinalIgnoreCase))
            {
                TimeSpan backoff = BackoffTimerHelper.GetExponentialBackoff(retryCount, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(32), TimeSpan.FromSeconds(2));
                executionContext.Output($"{container.ContainerNetworkAlias} service is starting, waiting {backoff.Seconds} seconds before checking again.");
                await Task.Delay(backoff, executionContext.CancellationToken);
                serviceHealth = (await _dockerManager.DockerInspect(context: executionContext, dockerObject: container.ContainerId, options: healthCheck)).FirstOrDefault();
                retryCount++;
            }
            if (string.Equals(serviceHealth, "healthy", StringComparison.OrdinalIgnoreCase))
            {
                executionContext.Output($"{container.ContainerNetworkAlias} service is healthy.");
            }
            else
            {
                throw new InvalidOperationException($"Failed to initialize, {container.ContainerNetworkAlias} service is {serviceHealth}.");
            }
        }

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

public override bool Equals(string x, string y) { return String.Equals(x, y, m_stringComparison); }

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

private static Boolean AbstractEqual(
            Object canonicalLeftValue,
            Object canonicalRightValue)
        {
            CoerceTypes(ref canonicalLeftValue, ref canonicalRightValue, out var leftKind, out var rightKind);

            // Same kind
            if (leftKind == rightKind)
            {
                switch (leftKind)
                {
                    // Null, Null
                    case ValueKind.Null:
                        return true;

                    // Number, Number
                    case ValueKind.Number:
                        var leftDouble = (Double)canonicalLeftValue;
                        var rightDouble = (Double)canonicalRightValue;
                        if (Double.IsNaN(leftDouble) || Double.IsNaN(rightDouble))
                        {
                            return false;
                        }
                        return leftDouble == rightDouble;

                    // String, String
                    case ValueKind.String:
                        var leftString = (String)canonicalLeftValue;
                        var rightString = (String)canonicalRightValue;
                        return String.Equals(leftString, rightString, StringComparison.OrdinalIgnoreCase);

                    // Boolean, Boolean
                    case ValueKind.Boolean:
                        var leftBoolean = (Boolean)canonicalLeftValue;
                        var rightBoolean = (Boolean)canonicalRightValue;
                        return leftBoolean == rightBoolean;

                    // Object, Object
                    case ValueKind.Object:
                    case ValueKind.Array:
                        return Object.ReferenceEquals(canonicalLeftValue, canonicalRightValue);
                }
            }

            return false;
        }

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

public override Boolean Equals(Object obj)
        {
            var item = obj as RegexSecret;
            if (item == null)
            {
                return false;
            }
            return String.Equals(m_pattern, item.m_pattern, StringComparison.Ordinal);
        }

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

public override Boolean Equals(Object obj)
        {
            var item = obj as ValueSecret;
            if (item == null)
            {
                return false;
            }
            return String.Equals(m_value, item.m_value, StringComparison.Ordinal);
        }

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

private static bool TryConvertToRegexOptions(
            String regexOptions,
            out RegexOptions result)
        {
            // Eg: "IgnoreCase, MultiLine" or "IgnoreCase"
            result = RegexOptions.ECMAScript | RegexOptions.CultureInvariant;

            if (String.IsNullOrEmpty(regexOptions))
            {
                return false;
            }

            String[] regexOptionValues = regexOptions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < regexOptionValues.Length; i++)
            {
                String option = regexOptionValues[i];

                if (String.Equals(option, WellKnownRegexOptions.IgnoreCase, StringComparison.OrdinalIgnoreCase))
                {
                    result = result | RegexOptions.IgnoreCase;
                }
                else if (String.Equals(option, WellKnownRegexOptions.Multiline, StringComparison.OrdinalIgnoreCase))
                {
                    result = result | RegexOptions.Multiline;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

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

public override Object ReadJson(
            JsonReader reader,
            Type objectType,
            Object existingValue,
            JsonSerializer serializer)
        {
            var eventObject = JObject.Load(reader);

            JToken propertyValue;
            JobEvent jobEvent = null;
            if (eventObject.TryGetValue("Name", StringComparison.OrdinalIgnoreCase, out propertyValue))
            {
                if (propertyValue.Type == JTokenType.String)
                {
                    String nameValue = (String)propertyValue;
                    if (String.Equals(nameValue, JobEventTypes.Jobreplacedigned, StringComparison.Ordinal))
                    {
                        jobEvent = new JobreplacedignedEvent();
                    }
                    else if (String.Equals(nameValue, JobEventTypes.JobCompleted, StringComparison.Ordinal))
                    {
                        jobEvent = new JobCompletedEvent();
                    }
                    else if (String.Equals(nameValue, JobEventTypes.JobStarted, StringComparison.Ordinal))
                    {
                        jobEvent = new JobStartedEvent();
                    }
                }
            }

            if (jobEvent == null)
            {
                if (eventObject.TryGetValue("Request", StringComparison.OrdinalIgnoreCase, out propertyValue))
                {
                    jobEvent = new JobreplacedignedEvent();
                }
                else if (eventObject.TryGetValue("Result", StringComparison.OrdinalIgnoreCase, out propertyValue))
                {
                    jobEvent = new JobCompletedEvent();
                }
            }

            if (jobEvent == null)
            {
                return existingValue;
            }

            using (var objectReader = eventObject.CreateReader())
            {
                serializer.Populate(objectReader, jobEvent);
            }

            return jobEvent;
        }

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

public override Boolean Equals(Object obj)
        {
            var otherHint = obj as MaskHint;
            if (otherHint != null)
            {
                return this.Type == otherHint.Type && String.Equals(this.Value ?? String.Empty, otherHint.Value ?? String.Empty, StringComparison.Ordinal);
            }

            return false;
        }

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

public static object Parse(Type enumType, string stringValue)
        {
            var underlyingType = Nullable.GetUnderlyingType(enumType);
            enumType = underlyingType != null ? underlyingType : enumType;

            var names = Enum.GetNames(enumType);
            if (!string.IsNullOrEmpty(stringValue))
            {
                var match = names.FirstOrDefault(name => string.Equals(name, stringValue, StringComparison.OrdinalIgnoreCase));
                if (match != null)
                {
                    return Enum.Parse(enumType, match);
                }

                // maybe we have an enum member with an EnumMember attribute specifying a custom name
                foreach (var field in enumType.GetFields())
                {
                    var enumMemberAttribute = field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() as EnumMemberAttribute;
                    if (enumMemberAttribute != null && string.Equals(enumMemberAttribute.Value, stringValue, StringComparison.OrdinalIgnoreCase))
                    {
                        // we already have the field, no need to do enum.parse on it
                        return field.GetValue(null);
                    }
                }
            }

            return Enum.Parse(enumType, UnknownName);
        }

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

public override bool CanConvert(Type objectType)
        {
            // we require one member to be named "Unknown"
            return objectType.IsEnum && Enum.GetNames(objectType).Any(name => string.Equals(name, UnknownName, StringComparison.OrdinalIgnoreCase));
        }

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

public override bool Equals(object obj)
        {
            IdenreplacedyBase other = obj as IdenreplacedyBase;
            if (other != null)
            {
                return (Id == other.Id &&
                    IdenreplacedyDescriptorComparer.Instance.Equals(Descriptor, other.Descriptor) &&
                    string.Equals(ProviderDisplayName, other.ProviderDisplayName, StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(CustomDisplayName, other.CustomDisplayName, StringComparison.OrdinalIgnoreCase) &&
                    IsActive == other.IsActive &&
                    UniqueUserId == other.UniqueUserId &&
                    IsContainer == other.IsContainer);
            }

            return false;
        }

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

public static bool ContainsUnmaskedSecret(string message)
        {
            return !String.Equals(message, ScrubSecrets(message, false), StringComparison.Ordinal);
        }

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

public static bool ContainsUnmaskedSecret(string message, out bool onlyJwtsFound)
        {
            if (string.IsNullOrEmpty(message))
            {
                onlyJwtsFound = false;
                return false;
            }

            string scrubbedMessage = ScrubJwts(message, replacedertOnDetection: false);
            bool jwtsFound = !String.Equals(message, scrubbedMessage, StringComparison.Ordinal);
            scrubbedMessage = ScrubTraditionalSecrets(message, replacedertOnDetection: false);
            bool secretsFound = !String.Equals(message, scrubbedMessage, StringComparison.Ordinal);
            onlyJwtsFound = !secretsFound && jwtsFound;
            return secretsFound || jwtsFound;
        }

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

private void TraceTreeResult(
            EvaluationContext context,
            Object result,
            ValueKind kind)
        {
            // Get the realized expression
            String realizedExpression = ConvertToRealizedExpression(context);

            // Format the result
            String traceValue = ExpressionUtility.FormatValue(context.SecretMasker, result, kind);

            // Only trace the realized expression if it is meaningfully different
            if (!String.Equals(realizedExpression, traceValue, StringComparison.Ordinal))
            {
                if (kind == ValueKind.Number &&
                    String.Equals(realizedExpression, $"'{traceValue}'", StringComparison.Ordinal))
                {
                    // Don't bother tracing the realized expression when the result is a number and the
                    // realized expresion is a precisely matching string.
                }
                else
                {
                    context.Trace.Info($"Expanded: {realizedExpression}");
                }
            }

            // Always trace the result
            context.Trace.Info($"Result: {traceValue}");
        }

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

private void ValidateStopToken(IExecutionContext context, string stopToken)
        {
#if OS_WINDOWS
            var envContext = context.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = context.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            var allowUnsecureStopCommandTokens = false;
            allowUnsecureStopCommandTokens = StringUtil.ConvertToBoolean(Environment.GetEnvironmentVariable(Constants.Variables.Actions.AllowUnsupportedStopCommandTokens));
            if (!allowUnsecureStopCommandTokens && envContext.ContainsKey(Constants.Variables.Actions.AllowUnsupportedStopCommandTokens))
            {
                allowUnsecureStopCommandTokens = StringUtil.ConvertToBoolean(envContext[Constants.Variables.Actions.AllowUnsupportedStopCommandTokens].ToString());
            }

            bool isTokenInvalid = _registeredCommands.Contains(stopToken)
                || string.IsNullOrEmpty(stopToken)
                || string.Equals(stopToken, "pause-logging", StringComparison.OrdinalIgnoreCase);

            if (isTokenInvalid)
            {
                var telemetry = new JobTelemetry
                {
                    Message = $"Invoked ::stopCommand:: with token: [{stopToken}]",
                    Type = JobTelemetryType.ActionCommand
                };
                context.JobTelemetry.Add(telemetry);
            }

            if (isTokenInvalid && !allowUnsecureStopCommandTokens)
            {
                throw new Exception(Constants.Runner.UnsupportedStopCommandTokenDisabled);
            }
        }

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

public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
        {
            var allowUnsecureCommands = false;
            bool.TryParse(Environment.GetEnvironmentVariable(Constants.Variables.Actions.AllowUnsupportedCommands), out allowUnsecureCommands);

            // Apply environment from env context, env context contains job level env and action's env block
#if OS_WINDOWS
            var envContext = context.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = context.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            if (!allowUnsecureCommands && envContext.ContainsKey(Constants.Variables.Actions.AllowUnsupportedCommands))
            {
                bool.TryParse(envContext[Constants.Variables.Actions.AllowUnsupportedCommands].ToString(), out allowUnsecureCommands);
            }

            if (!allowUnsecureCommands)
            {
                throw new Exception(String.Format(Constants.Runner.UnsupportedCommandMessageDisabled, this.Command));
            }

            if (!command.Properties.TryGetValue(SetEnvCommandProperties.Name, out string envName) || string.IsNullOrEmpty(envName))
            {
                throw new Exception("Required field 'name' is missing in ##[set-env] command.");
            }


            foreach (var blocked in _setEnvBlockList)
            {
                if (string.Equals(blocked, envName, StringComparison.OrdinalIgnoreCase))
                {
                    // Log Telemetry and let user know they shouldn't do this
                    var issue = new Issue()
                    {
                        Type = IssueType.Error,
                        Message = $"Can't update {blocked} environment variable using ::set-env:: command."
                    };
                    issue.Data[Constants.Runner.InternalTelemetryIssueDataKey] = $"{Constants.Runner.UnsupportedCommand}_{envName}";
                    context.AddIssue(issue);

                    return;
                }
            }

            context.Global.EnvironmentVariables[envName] = command.Data;
            context.SetEnvContext(envName, command.Data);
            context.Debug($"{envName}='{command.Data}'");
        }

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

public void ProcessCommand(IExecutionContext context, string filePath, ContainerInfo container)
        {
            try
            {
                var text = File.ReadAllText(filePath) ?? string.Empty;
                var index = 0;
                var line = ReadLine(text, ref index);
                while (line != null)
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        var equalsIndex = line.IndexOf("=", StringComparison.Ordinal);
                        var heredocIndex = line.IndexOf("<<", StringComparison.Ordinal);

                        // Normal style NAME=VALUE
                        if (equalsIndex >= 0 && (heredocIndex < 0 || equalsIndex < heredocIndex))
                        {
                            var split = line.Split(new[] { '=' }, 2, StringSplitOptions.None);
                            if (string.IsNullOrEmpty(line))
                            {
                                throw new Exception($"Invalid environment variable format '{line}'. Environment variable name must not be empty");
                            }
                            SetEnvironmentVariable(context, split[0], split[1]);
                        }
                        // Heredoc style NAME<<EOF
                        else if (heredocIndex >= 0 && (equalsIndex < 0 || heredocIndex < equalsIndex))
                        {
                            var split = line.Split(new[] { "<<" }, 2, StringSplitOptions.None);
                            if (string.IsNullOrEmpty(split[0]) || string.IsNullOrEmpty(split[1]))
                            {
                                throw new Exception($"Invalid environment variable format '{line}'. Environment variable name must not be empty and delimiter must not be empty");
                            }
                            var name = split[0];
                            var delimiter = split[1];
                            var startIndex = index; // Start index of the value (inclusive)
                            var endIndex = index;   // End index of the value (exclusive)
                            var tempLine = ReadLine(text, ref index, out var newline);
                            while (!string.Equals(tempLine, delimiter, StringComparison.Ordinal))
                            {
                                if (tempLine == null)
                                {
                                    throw new Exception($"Invalid environment variable value. Matching delimiter not found '{delimiter}'");
                                }
                                endIndex = index - newline.Length;
                                tempLine = ReadLine(text, ref index, out newline);
                            }

                            var value = endIndex > startIndex ? text.Substring(startIndex, endIndex - startIndex) : string.Empty;
                            SetEnvironmentVariable(context, name, value);
                        }
                        else
                        {
                            throw new Exception($"Invalid environment variable format '{line}'");
                        }
                    }

                    line = ReadLine(text, ref index);
                }
            }
            catch (DirectoryNotFoundException)
            {
                context.Debug($"Environment variables file does not exist '{filePath}'");
            }
            catch (FileNotFoundException)
            {
                context.Debug($"Environment variables file does not exist '{filePath}'");
            }
        }

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

public DictionaryContextData ToSecretsContext()
        {
            var result = new DictionaryContextData();
            foreach (var variable in _variables.Values)
            {
                if (variable.Secret &&
                    !string.Equals(variable.Name, Constants.Variables.System.AccessToken, StringComparison.OrdinalIgnoreCase) &&
                    !string.Equals(variable.Name, "system.github.token", StringComparison.OrdinalIgnoreCase))
                {
                    result[variable.Name] = new StringContextData(variable.Value);
                }
            }
            return result;
        }

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

private static bool IsLowPriority(HttpRequestMessage request)
        {
            bool isLowPriority = false;
            
            IEnumerable<string> headers;

            if (request.Headers.TryGetValues(HttpHeaders.VssRequestPriority, out headers) && headers != null)
            {
                string header = headers.FirstOrDefault();
                isLowPriority = string.Equals(header, "Low", StringComparison.OrdinalIgnoreCase);
            }

            return isLowPriority;
        }

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

private String GetAcceptHeaderOptionValue(HttpRequestMessage request, String acceptOptionName)
        {
            foreach (var header in request.Headers.Accept)
            {
                foreach (var parameter in header.Parameters)
                {
                    if (String.Equals(parameter.Name, acceptOptionName, StringComparison.OrdinalIgnoreCase))
                    {
                        return parameter.Value;
                    }
                }
            }

            return null;
        }

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

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

                string relativePath;
#if OS_WINDOWS
                /// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src") -> @"project\foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project\foo.cpp", @"d:\src");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\", @"d:\specs") -> @"d:\"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\", @"d:\specs");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"d:\", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\proj") -> @"d:\src\project\foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\proj");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"d:\src\project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\src\project\foo", @"d:\src") -> @"project\foo"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project\foo", @"d:\src");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"project\foo", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\project\foo.cpp") -> @""
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project", @"d:\src\project");
                // replacedert.
                replacedert.True(string.Equals(relativePath, string.Empty, StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:/src/project/foo.cpp", @"d:/src") -> @"project/foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:/src/project/foo.cpp", @"d:/src");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:/src/project/foo.cpp", @"d:\src") -> @"d:/src/project/foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:/src/project/foo.cpp", @"d:/src");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:/src/project/foo", @"d:/src") -> @"project/foo"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:/src/project/foo", @"d:/src");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"project\foo", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d\src\project", @"d:/src/project") -> @""
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project", @"d:/src/project");
                // replacedert.
                replacedert.True(string.Equals(relativePath, string.Empty, StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");
#else
                /// MakeRelative(@"/user/src/project/foo.cpp", @"/user/src") -> @"project/foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"/user/src/project/foo.cpp", @"/user/src");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"project/foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"/user", @"/user/specs") -> @"/user"
                // Act.
                relativePath = IOUtil.MakeRelative(@"/user", @"/user/specs");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"/user", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"/user/src/project/foo.cpp", @"/user/src/proj") -> @"/user/src/project/foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"/user/src/project/foo.cpp", @"/user/src/proj");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"/user/src/project/foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"/user/src/project/foo", @"/user/src") -> @"project/foo"
                // Act.
                relativePath = IOUtil.MakeRelative(@"/user/src/project/foo", @"/user/src");
                // replacedert.
                replacedert.True(string.Equals(relativePath, @"project/foo", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"/user/src/project", @"/user/src/project") -> @""
                // Act.
                relativePath = IOUtil.MakeRelative(@"/user/src/project", @"/user/src/project");
                // replacedert.
                replacedert.True(string.Equals(relativePath, string.Empty, StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");
#endif
            }
        }

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

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

                string resolvePath;
#if OS_WINDOWS
                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:\src\project\", @"foo");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\src\project\foo", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:\", @"specs");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\specs", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:\src\project\", @"src\proj");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\src\project\src\proj", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:\src\project\foo", @"..");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\src\project", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:\src\project", @"..\..\");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:/src/project", @"../.");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\src", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:/src/project/", @"../../foo");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\foo", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:/src/project/foo", @".././bar/.././../foo");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\src\foo", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"d:\", @".");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"d:\", StringComparison.OrdinalIgnoreCase), $"resolvePath does not expected: {resolvePath}");
#else
                // Act.
                resolvePath = IOUtil.ResolvePath(@"/user/src/project", @"foo");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/user/src/project/foo", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"/root", @"./user/./specs");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/root/user/specs", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"/", @"user/specs/.");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/user/specs", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"/user/src/project", @"../");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/user/src", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"/user/src/project", @"../../");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/user", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"/user/src/project/foo", @"../../../../user/./src");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/user/src", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"/user/src", @"../../.");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");

                // Act.
                resolvePath = IOUtil.ResolvePath(@"/", @"./");
                // replacedert.
                replacedert.True(string.Equals(resolvePath, @"/", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}");
#endif
            }
        }

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

private static Boolean IsJsonResponse(HttpResponseMessage response)
        {
            if (HasContent(response) &&
                response.Content.Headers != null &&
                response.Content.Headers.ContentType != null &&
                !String.IsNullOrEmpty(response.Content.Headers.ContentType.MediaType))
            {
                return String.Equals("application/json", response.Content.Headers.ContentType.MediaType, StringComparison.OrdinalIgnoreCase);
            }

            return false;
        }

See More Examples