Example #1
0
        public WebProxy GetUserConfiguredProxy()
        {
            // Try reading from the settings. The values are stored as 3 config values http_proxy, http_proxy_user, http_proxy_password
            var host = _settings.GetValue(SettingsUtility.ConfigSection, ConfigurationConstants.HostKey);

            if (!string.IsNullOrEmpty(host))
            {
                // The host is the minimal value we need to assume a user configured proxy.
                var webProxy = new WebProxy(host);

#if !IS_CORECLR
                var userName = _settings.GetValue(SettingsUtility.ConfigSection, ConfigurationConstants.UserKey);
                var password = SettingsUtility.GetDecryptedValue(_settings, SettingsUtility.ConfigSection, ConfigurationConstants.PasswordKey);

                if (!string.IsNullOrEmpty(userName) &&
                    !string.IsNullOrEmpty(password))
                {
                    webProxy.Credentials = new NetworkCredential(userName, password);
                }
#endif

                var noProxy = _settings.GetValue(SettingsUtility.ConfigSection, ConfigurationConstants.NoProxy);
                if (!string.IsNullOrEmpty(noProxy))
                {
                    // split comma-separated list of domains
                    webProxy.BypassList = noProxy.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }

                return(webProxy);
            }

            // Next try reading from the environment variable http_proxy. This would be specified as http://<username>:<password>@proxy.com
            host = _environment.GetEnvironmentVariable(ConfigurationConstants.HostKey);
            Uri uri;
            if (!string.IsNullOrEmpty(host) &&
                Uri.TryCreate(host, UriKind.Absolute, out uri))
            {
                var webProxy = new WebProxy(uri.GetComponents(
                                                UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped));
                if (!string.IsNullOrEmpty(uri.UserInfo))
                {
                    var credentials = uri.UserInfo.Split(':');
                    if (credentials.Length > 1)
                    {
                        webProxy.Credentials = new NetworkCredential(
                            userName: credentials[0], password: credentials[1]);
                    }
                }

                var noProxy = _environment.GetEnvironmentVariable(ConfigurationConstants.NoProxy);
                if (!string.IsNullOrEmpty(noProxy))
                {
                    // split comma-separated list of domains
                    webProxy.BypassList = noProxy.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }

                return(webProxy);
            }
            return(null);
        }
        internal NuGetFileLogger(IEnvironmentVariableReader environmentVariableReader)
        {
            if (environmentVariableReader == null)
            {
                throw new ArgumentNullException(nameof(environmentVariableReader));
            }

            _logDirectoryPath = environmentVariableReader.GetEnvironmentVariable("NUGET_VS_RESTORE_LOGGING_PATH");

            if (!string.IsNullOrWhiteSpace(_logDirectoryPath))
            {
                IsEnabled = true;
            }

            var formatWithTime = environmentVariableReader.GetEnvironmentVariable("NUGET_VS_RESTORE_FORMAT_WITH_TIME");

            if (!string.IsNullOrWhiteSpace(formatWithTime))
            {
                _ = bool.TryParse(formatWithTime, out bool formatWithTimeOverride);

                ShouldFormatWithTime = formatWithTimeOverride;
            }

            _startTime = DateTimeOffset.UtcNow;
            _stopwatch = Stopwatch.StartNew();

            // Created outside of the lambda below to capture the current time.
            var message = $"The stopwatch frequency is {Stopwatch.Frequency}";

            _streamWriter     = new Lazy <StreamWriter>(() => CreateStreamWriter(message));
            _streamWriterLock = new object();
        }
Example #3
0
        internal PluginLogger(IEnvironmentVariableReader environmentVariableReader)
        {
            if (environmentVariableReader == null)
            {
                throw new ArgumentNullException(nameof(environmentVariableReader));
            }

            var value = environmentVariableReader.GetEnvironmentVariable(EnvironmentVariableConstants.EnableLog);

            IsEnabled = bool.TryParse(value, out var enable) && enable;

            if (IsEnabled)
            {
                _logDirectoryPath = environmentVariableReader.GetEnvironmentVariable(EnvironmentVariableConstants.LogDirectoryPath);

                if (string.IsNullOrWhiteSpace(_logDirectoryPath))
                {
                    _logDirectoryPath = Environment.CurrentDirectory;
                }
            }

            _startTime = DateTimeOffset.UtcNow;
            _stopwatch = Stopwatch.StartNew();

            // Created outside of the lambda below to capture the current time.
            var message = new StopwatchLogMessage(Now, Stopwatch.Frequency);

            _streamWriter     = new Lazy <StreamWriter>(() => CreateStreamWriter(message));
            _streamWriterLock = new object();
        }
Example #4
0
        private void Initialize(IEnvironmentVariableReader reader,
                                Lazy <IPluginDiscoverer> pluginDiscoverer,
                                Func <TimeSpan, IPluginFactory> pluginFactoryCreator,
                                Lazy <string> pluginsCacheDirectoryPath)
        {
            EnvironmentVariableReader = reader ?? throw new ArgumentNullException(nameof(reader));
            _discoverer = pluginDiscoverer ?? throw new ArgumentNullException(nameof(pluginDiscoverer));
            _pluginsCacheDirectoryPath = pluginsCacheDirectoryPath ?? throw new ArgumentNullException(nameof(pluginsCacheDirectoryPath));

            if (pluginFactoryCreator == null)
            {
                throw new ArgumentNullException(nameof(pluginFactoryCreator));
            }
#if IS_DESKTOP
            _rawPluginPaths = reader.GetEnvironmentVariable(EnvironmentVariableConstants.DesktopPluginPaths);
#else
            _rawPluginPaths = reader.GetEnvironmentVariable(EnvironmentVariableConstants.CorePluginPaths);
#endif
            if (string.IsNullOrEmpty(_rawPluginPaths))
            {
                _rawPluginPaths = reader.GetEnvironmentVariable(EnvironmentVariableConstants.PluginPaths);
            }

            _connectionOptions = ConnectionOptions.CreateDefault(reader);

            var idleTimeoutInSeconds = EnvironmentVariableReader.GetEnvironmentVariable(EnvironmentVariableConstants.IdleTimeout);
            var idleTimeout          = TimeoutUtilities.GetTimeout(idleTimeoutInSeconds, PluginConstants.IdleTimeout);

            _pluginFactory         = pluginFactoryCreator(idleTimeout);
            _pluginOperationClaims = new ConcurrentDictionary <PluginRequestKey, Lazy <Task <IReadOnlyList <OperationClaim> > > >();
            _pluginUtilities       = new ConcurrentDictionary <string, Lazy <IPluginMulticlientUtilities> >(
                StringComparer.OrdinalIgnoreCase);
        }
Example #5
0
        /// <summary>
        /// Reinitializes static state.
        /// </summary>
        /// <remarks>This is non-private only to facilitate unit testing.
        /// This should not be called by product code.</remarks>
        /// <param name="reader">An environment variable reader.</param>
        /// <param name="pluginDiscoverer">A lazy plugin discoverer.</param>
        /// <param name="pluginFactory">A plugin factory.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="reader" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="pluginDiscoverer" />
        /// is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="pluginFactory" />
        /// is <c>null</c>.</exception>
        public void Reinitialize(IEnvironmentVariableReader reader,
            Lazy<IPluginDiscoverer> pluginDiscoverer,
            IPluginFactory pluginFactory)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

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

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

            EnvironmentVariableReader = reader;
            _rawPluginPaths = reader.GetEnvironmentVariable(_pluginPathsEnvironmentVariable);

            var requestTimeoutInSeconds = reader.GetEnvironmentVariable(_pluginRequestTimeoutEnvironmentVariable);

            _requestTimeout = GetRequestTimeout(requestTimeoutInSeconds);
            _discoverer = pluginDiscoverer;
            _pluginFactory = pluginFactory;
            _pluginOperationClaims = new ConcurrentDictionary<PluginPackageSourceKey, Lazy<Task<IReadOnlyList<OperationClaim>>>>();
            _pluginUtilities = new ConcurrentDictionary<string, Lazy<IPluginMulticlientUtilities>>(
                StringComparer.OrdinalIgnoreCase);
        }
        // This is non-private only to facilitate testing.
        internal static IX509ChainBuildPolicy CreateWithoutCaching(IEnvironmentVariableReader reader)
        {
            if (reader is null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            if (RuntimeEnvironmentHelper.IsWindows)
            {
                string value = reader.GetEnvironmentVariable(EnvironmentVariableName);

                if (string.IsNullOrWhiteSpace(value))
                {
                    return(DefaultX509ChainBuildPolicy.Instance);
                }

                string[] parts = value.Split(ValueDelimiter);

                if (parts.Length == 2 &&
                    int.TryParse(parts[0], out int retryCount) &&
                    retryCount > 0 &&
                    int.TryParse(parts[1], out int sleepIntervalInMilliseconds) &&
                    sleepIntervalInMilliseconds >= 0)
                {
                    TimeSpan sleepInterval = TimeSpan.FromMilliseconds(sleepIntervalInMilliseconds);

                    return(new RetriableX509ChainBuildPolicy(DefaultX509ChainBuildPolicy.Instance, retryCount, sleepInterval));
                }
            }

            return(DefaultX509ChainBuildPolicy.Instance);
        }
Example #7
0
        /// <summary>
        /// Reinitializes static state.
        /// </summary>
        /// <remarks>This is non-private only to facilitate unit testing.
        /// This should not be called by product code.</remarks>
        /// <param name="reader">An environment variable reader.</param>
        /// <param name="pluginDiscoverer">A lazy plugin discoverer.</param>
        /// <param name="pluginFactoryCreator">A plugin factory creator.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="reader" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="pluginDiscoverer" />
        /// is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="pluginFactoryCreator" />
        /// is <c>null</c>.</exception>
        public void Reinitialize(IEnvironmentVariableReader reader,
                                 Lazy <IPluginDiscoverer> pluginDiscoverer,
                                 Func <TimeSpan, IPluginFactory> pluginFactoryCreator)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

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

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

            EnvironmentVariableReader = reader;
            _rawPluginPaths           = reader.GetEnvironmentVariable(_pluginPathsEnvironmentVariable);

            _connectionOptions = ConnectionOptions.CreateDefault(reader);

            var idleTimeoutInSeconds = EnvironmentVariableReader.GetEnvironmentVariable(_idleTimeoutEnvironmentVariable);
            var idleTimeout          = TimeoutUtilities.GetTimeout(idleTimeoutInSeconds, PluginConstants.IdleTimeout);

            _discoverer            = pluginDiscoverer;
            _pluginFactory         = pluginFactoryCreator(idleTimeout);
            _pluginOperationClaims = new ConcurrentDictionary <PluginPackageSourceKey, Lazy <Task <IReadOnlyList <OperationClaim> > > >();
            _pluginUtilities       = new ConcurrentDictionary <string, Lazy <IPluginMulticlientUtilities> >(
                StringComparer.OrdinalIgnoreCase);
        }
        /// <summary>
        /// Gets the (first) path of MSBuild to appear in environment variable PATH.
        /// </summary>
        /// <returns>The path of MSBuild in PATH environment variable. Returns null if MSBuild location does not exist
        /// in the variable string.</returns>
        private static string GetMsBuildPathInPathVar(IEnvironmentVariableReader reader)
        {
            var path  = reader.GetEnvironmentVariable("PATH");
            var paths = path?.Split(new char[] { ';' });

            return(paths?.Select(p =>
            {
                // Strip leading/trailing quotes
                if (p.Length > 0 && p[0] == '\"')
                {
                    p = p.Substring(1);
                }
                if (p.Length > 0 && p[p.Length - 1] == '\"')
                {
                    p = p.Substring(0, p.Length - 1);
                }

                return p;
            }).FirstOrDefault(p =>
            {
                try
                {
                    return File.Exists(Path.Combine(p, "msbuild.exe"));
                }
                catch
                {
                    return false;
                }
            }));
        }
        internal static string GetMSBuild(IEnvironmentVariableReader reader)
        {
            var exeNames = new[] { "msbuild.exe" };

            if (RuntimeEnvironmentHelper.IsMono)
            {
                exeNames = new[] { "msbuild", "xbuild" };
            }

            // Try to find msbuild or xbuild in $Path.
            var pathDirs = reader.GetEnvironmentVariable("PATH")?.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);

            if (pathDirs?.Length > 0)
            {
                foreach (var exeName in exeNames)
                {
                    var exePath = pathDirs.Select(dir => Path.Combine(dir.Trim('\"'), exeName)).FirstOrDefault(File.Exists);
                    if (exePath != null)
                    {
                        return(exePath);
                    }
                }
            }

            return(null);
        }
Example #10
0
        public bool IsExperimentEnabled(ExperimentationConstants experimentation)
        {
            var isEnvVarEnabled = !string.IsNullOrEmpty(experimentation.FlightEnvironmentVariable) &&
                                  _environmentVariableReader.GetEnvironmentVariable(experimentation.FlightEnvironmentVariable) == "1";

            return(isEnvVarEnabled || _experimentationService.IsCachedFlightEnabled(experimentation.FlightFlag));
        }
Example #11
0
        /// <summary>
        /// Instantiates a <see cref="ConnectionOptions" /> class with default values.
        /// </summary>
        /// <param name="reader">An environment variable reader.</param>
        /// <returns>A <see cref="ConnectionOptions" />.</returns>
        public static ConnectionOptions CreateDefault(IEnvironmentVariableReader reader = null)
        {
            reader = reader ?? new EnvironmentVariableWrapper();

            var handshakeTimeoutInSeconds = reader.GetEnvironmentVariable(EnvironmentVariableConstants.HandshakeTimeout);
            var requestTimeoutInSeconds   = reader.GetEnvironmentVariable(EnvironmentVariableConstants.RequestTimeout);

            var handshakeTimeout = TimeoutUtilities.GetTimeout(handshakeTimeoutInSeconds, ProtocolConstants.HandshakeTimeout);
            var requestTimeout   = TimeoutUtilities.GetTimeout(requestTimeoutInSeconds, ProtocolConstants.RequestTimeout);

            return(new ConnectionOptions(
                       protocolVersion: ProtocolConstants.CurrentVersion,
                       minimumProtocolVersion: ProtocolConstants.Version100,
                       handshakeTimeout: handshakeTimeout,
                       requestTimeout: requestTimeout));
        }
Example #12
0
        public async Task Run()
        {
            _client.BaseUrl = new Uri(_envReader.GetEnvironmentVariable("PING_URL"));
            _client.Timeout = _timeout;
            var request = new RestRequest(Method.GET);

            try
            {
                var response = await _client.ExecuteGetTaskAsync(request);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    await _secretHandler.PutParameter("LAST_SUCCESSFUL_CONNECTION_TIME",
                                                      DateTime.UtcNow.ToString(CultureInfo.InvariantCulture), false);

                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SendMessage();
            }
            await SendMessage();
        }
Example #13
0
 internal Testable(IEnvironmentVariableReader environmentVariableReader)
 {
     _isMMapEnabled = environmentVariableReader.GetEnvironmentVariable(MMAP_VARIABLE_NAME) switch
     {
         "0" => false,
         "1" => true,
         _ => RuntimeEnvironmentHelper.IsWindows
     };
 }
            internal Testable(IEnvironmentVariableReader environmentVariableReader)
            {
                _updateFileTimeFromEntryMaxRetries = 9;
                string value = environmentVariableReader.GetEnvironmentVariable("NUGET_UPDATEFILETIME_MAXRETRIES");

                if (int.TryParse(value, out int maxRetries) && maxRetries > 0)
                {
                    _updateFileTimeFromEntryMaxRetries = maxRetries;
                }
            }
Example #15
0
        private static int?Read(IEnvironmentVariableReader reader, string variableName)
        {
            var variableValue = reader.GetEnvironmentVariable(variableName);

            if (int.TryParse(variableValue, out var value))
            {
                return(value);
            }

            return(null);
        }
Example #16
0
        private static bool ShouldShowStack(IEnvironmentVariableReader reader)
        {
            var rawShowStack = reader.GetEnvironmentVariable("NUGET_SHOW_STACK");

            if (rawShowStack == null)
            {
                return(false);
            }

            return(string.Equals(rawShowStack.Trim(), "true", StringComparison.OrdinalIgnoreCase));
        }
        private void GetEnvironmentVariablesForFeature(NuGetFeatureFlagConstants featureFlag, out bool isFeatureForcedEnabled, out bool isFeatureForcedDisabled)
        {
            isFeatureForcedEnabled  = false;
            isFeatureForcedDisabled = false;
            if (!string.IsNullOrEmpty(featureFlag.EnvironmentVariable))
            {
                string envVarOverride = _environmentVariableReader.GetEnvironmentVariable(featureFlag.EnvironmentVariable);

                isFeatureForcedDisabled = envVarOverride == "0";
                isFeatureForcedEnabled  = envVarOverride == "1";
            }
        }
Example #18
0
        /// <summary>
        /// Gets a <see cref="bool" /> value from the specified environment variable.
        /// </summary>
        /// <param name="variableName">The name of the environment variable to get the value.</param>
        /// <param name="defaultValue">The default value to return if the environment variable is not defined or is not a valid <see cref="bool" />.</param>
        /// <param name="environmentVariableReader">An <see cref="IEnvironmentVariableReader" /> to use when reading the environment variable.</param>
        /// <returns>The value of the specified as a <see cref="bool" /> if the specified environment variable is defined and is a valid value for <see cref="bool" />.</returns>
        private static bool GetBoolFromEnvironmentVariable(string variableName, bool defaultValue, IEnvironmentVariableReader environmentVariableReader)
        {
            try
            {
                if (bool.TryParse(environmentVariableReader.GetEnvironmentVariable(variableName), out bool parsedValue))
                {
                    return(parsedValue);
                }
            }
            catch (Exception) { }

            return(defaultValue);
        }
Example #19
0
        /// <summary>
        /// Gets an <see cref="int" /> value from the specified environment variable.
        /// </summary>
        /// <param name="variableName">The name of the environment variable to get the value.</param>
        /// <param name="defaultValue">The default value to return if the environment variable is not defined or is not a valid <see cref="int" />.</param>
        /// <param name="environmentVariableReader">An <see cref="IEnvironmentVariableReader" /> to use when reading the environment variable.</param>
        /// <returns>The value of the specified as a <see cref="int" /> if the specified environment variable is defined and is a valid value for <see cref="int" />.</returns>
        private static int GetIntFromEnvironmentVariable(string variableName, int defaultValue, IEnvironmentVariableReader environmentVariableReader)
        {
            try
            {
                if (int.TryParse(environmentVariableReader.GetEnvironmentVariable(variableName), out int parsedValue))
                {
                    return(parsedValue);
                }
            }
            catch (Exception) { }

            return(defaultValue);
        }
Example #20
0
        public bool IsExperimentEnabled(ExperimentationConstants experiment)
        {
            var isExpForcedEnabled  = false;
            var isExpForcedDisabled = false;

            if (!string.IsNullOrEmpty(experiment.FlightEnvironmentVariable))
            {
                string envVarOverride = _environmentVariableReader.GetEnvironmentVariable(experiment.FlightEnvironmentVariable);

                isExpForcedDisabled = envVarOverride == "0";
                isExpForcedEnabled  = envVarOverride == "1";
            }

            return(!isExpForcedDisabled && (isExpForcedEnabled || _experimentationService.IsCachedFlightEnabled(experiment.FlightFlag)));
        }
Example #21
0
        private static int GetIntFromEnvironmentVariable(string variableName, int defaultValue, IEnvironmentVariableReader environmentVariableReader)
        {
            int retrievedValue = defaultValue;

            try
            {
                var variableValue = environmentVariableReader.GetEnvironmentVariable(variableName);
                if (!string.IsNullOrEmpty(variableValue))
                {
                    if (int.TryParse(variableValue, out int parsed))
                    {
                        retrievedValue = parsed;
                    }
                }
            }
            catch (Exception) { }
            return(retrievedValue);
        }
Example #22
0
        private static bool GetBooleanFromEnvironmentVariable(string variableName, bool defaultValue, IEnvironmentVariableReader environmentVariableReader)
        {
            bool retrievedValue = defaultValue;

            try
            {
                var variableValue = environmentVariableReader.GetEnvironmentVariable(variableName);
                if (!string.IsNullOrEmpty(variableValue))
                {
                    if (bool.TryParse(variableValue, out bool parsed))
                    {
                        retrievedValue = parsed;
                    }
                }
            }
            catch (Exception) { }
            return(retrievedValue);
        }
        internal PackageSpecReferenceDependencyProvider(
            IEnumerable <ExternalProjectReference> externalProjects,
            ILogger logger,
            IEnvironmentVariableReader environmentVariableReader)
        {
            if (externalProjects == null)
            {
                throw new ArgumentNullException(nameof(externalProjects));
            }

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

            _logger = logger;

            foreach (var project in externalProjects)
            {
                Debug.Assert(
                    !_externalProjectsByPath.ContainsKey(project.UniqueName),
                    $"Duplicate project {project.UniqueName}");

                if (!_externalProjectsByPath.ContainsKey(project.UniqueName))
                {
                    _externalProjectsByPath.Add(project.UniqueName, project);
                }

                Debug.Assert(
                    !_externalProjectsByUniqueName.ContainsKey(project.ProjectName),
                    $"Duplicate project {project.ProjectName}");

                if (!_externalProjectsByUniqueName.ContainsKey(project.ProjectName))
                {
                    _externalProjectsByUniqueName.Add(project.ProjectName, project);
                }

                if (!_externalProjectsByUniqueName.ContainsKey(project.UniqueName))
                {
                    _externalProjectsByUniqueName.Add(project.UniqueName, project);
                }
            }
            _useLegacyAssetTargetFallbackBehavior = MSBuildStringUtility.IsTrue(environmentVariableReader.GetEnvironmentVariable("NUGET_USE_LEGACY_ASSET_TARGET_FALLBACK_DEPENDENCY_RESOLUTION"));
        }
 internal SourceRepositoryDependencyProvider(
     SourceRepository sourceRepository,
     ILogger logger,
     SourceCacheContext cacheContext,
     bool ignoreFailedSources,
     bool ignoreWarning,
     LocalPackageFileCache fileCache,
     bool isFallbackFolderSource,
     IEnvironmentVariableReader environmentVariableReader)
 {
     _sourceRepository       = sourceRepository ?? throw new ArgumentNullException(nameof(sourceRepository));
     _logger                 = logger ?? throw new ArgumentNullException(nameof(logger));
     _cacheContext           = cacheContext ?? throw new ArgumentNullException(nameof(cacheContext));
     _ignoreFailedSources    = ignoreFailedSources;
     _ignoreWarning          = ignoreWarning;
     _packageFileCache       = fileCache;
     _isFallbackFolderSource = isFallbackFolderSource;
     _useLegacyAssetTargetFallbackBehavior = MSBuildStringUtility.IsTrue(environmentVariableReader.GetEnvironmentVariable("NUGET_USE_LEGACY_ASSET_TARGET_FALLBACK_DEPENDENCY_RESOLUTION"));
 }
Example #25
0
        internal WebProxy GetUserConfiguredProxy()
        {
            // Try reading from the settings. The values are stored as 3 config values http_proxy, http_proxy_user, http_proxy_password
            var host = _settings.GetConfigValue(HostKey);

            if (!String.IsNullOrEmpty(host))
            {
                // The host is the minimal value we need to assume a user configured proxy.
                var    webProxy = new WebProxy(host);
                string userName = _settings.GetConfigValue(UserKey);
                string password = _settings.GetConfigValue(PasswordKey, decrypt: true);

                if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password))
                {
                    webProxy.Credentials = new NetworkCredential(userName, password);
                }
                return(webProxy);
            }

            // Next try reading from the environment variable http_proxy. This would be specified as http://<username>:<password>@proxy.com
            host = _environment.GetEnvironmentVariable(HostKey);
            Uri uri;

            if (!String.IsNullOrEmpty(host) && Uri.TryCreate(host, UriKind.Absolute, out uri))
            {
                var webProxy = new WebProxy(uri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped));
                if (!String.IsNullOrEmpty(uri.UserInfo))
                {
                    var credentials = uri.UserInfo.Split(':');
                    if (credentials.Length > 1)
                    {
                        webProxy.Credentials = new NetworkCredential(userName: credentials[0], password: credentials[1]);
                    }
                }
                return(webProxy);
            }
            return(null);
        }
        internal NuGetFileLogger(IEnvironmentVariableReader environmentVariableReader)
        {
            if (environmentVariableReader == null)
            {
                throw new ArgumentNullException(nameof(environmentVariableReader));
            }

            _logDirectoryPath = environmentVariableReader.GetEnvironmentVariable("NUGET_SOLUTION_LOAD_LOGGING_PATH");

            if (!string.IsNullOrWhiteSpace(_logDirectoryPath))
            {
                IsEnabled = true;
            }

            _startTime = DateTimeOffset.UtcNow;
            _stopwatch = Stopwatch.StartNew();

            // Created outside of the lambda below to capture the current time.
            var message = $"The stopwatch frequency is {Stopwatch.Frequency}";

            _streamWriter     = new Lazy <StreamWriter>(() => CreateStreamWriter(message));
            _streamWriterLock = new object();
        }
        public static string GetMSBuildArguments(
            string entryPointTargetPath,
            string inputTargetPath,
            string nugetExePath,
            string solutionDirectory,
            string solutionName,
            string restoreConfigFile,
            string[] sources,
            string packagesDirectory,
            MsBuildToolset toolset,
            RestoreLockProperties restoreLockProperties,
            IEnvironmentVariableReader reader)
        {
            // args for MSBuild.exe
            var args = new List <string>()
            {
                EscapeQuoted(inputTargetPath),
                "/t:GenerateRestoreGraphFile",
                "/nologo",
                "/nr:false"
            };

            // Set the msbuild verbosity level if specified
            var msbuildVerbosity = reader.GetEnvironmentVariable("NUGET_RESTORE_MSBUILD_VERBOSITY");

            if (string.IsNullOrEmpty(msbuildVerbosity))
            {
                args.Add("/v:q");
            }
            else
            {
                args.Add($"/v:{msbuildVerbosity} ");
            }

            // Override the target under ImportsAfter with the current NuGet.targets version.
            AddProperty(args, "NuGetRestoreTargets", entryPointTargetPath);
            AddProperty(args, "RestoreUseCustomAfterTargets", bool.TrueString);

            // Set path to nuget.exe or the build task
            AddProperty(args, "RestoreTaskAssemblyFile", nugetExePath);

            // Settings
            AddRestoreSources(args, sources);
            AddPropertyIfHasValue(args, "RestoreSolutionDirectory", solutionDirectory);
            AddPropertyIfHasValue(args, "RestoreConfigFile", restoreConfigFile);
            AddPropertyIfHasValue(args, "RestorePackagesPath", packagesDirectory);
            AddPropertyIfHasValue(args, "SolutionDir", solutionDirectory);
            AddPropertyIfHasValue(args, "SolutionName", solutionName);

            // If the MSBuild version used does not support SkipNonextentTargets and BuildInParallel
            // use the performance optimization
            // When BuildInParallel is used with ContinueOnError it does not continue in some scenarios
            if (toolset.ParsedVersion.CompareTo(new Version(15, 5)) < 0)
            {
                AddProperty(args, "RestoreBuildInParallel", bool.FalseString);
                AddProperty(args, "RestoreUseSkipNonexistentTargets", bool.FalseString);
            }

            // Add additional args to msbuild if needed
            var msbuildAdditionalArgs = reader.GetEnvironmentVariable("NUGET_RESTORE_MSBUILD_ARGS");

            if (!string.IsNullOrEmpty(msbuildAdditionalArgs))
            {
                args.Add(msbuildAdditionalArgs);
            }

            AddPropertyIfHasValue(args, "RestorePackagesWithLockFile", restoreLockProperties.RestorePackagesWithLockFile);
            AddPropertyIfHasValue(args, "NuGetLockFilePath", restoreLockProperties.NuGetLockFilePath);
            if (restoreLockProperties.RestoreLockedMode)
            {
                AddProperty(args, "RestoreLockedMode", bool.TrueString);
            }

            return(string.Join(" ", args));
        }