System.Environment.GetEnvironmentVariable(string, System.EnvironmentVariableTarget)

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

547 Examples 7

19 View Source File : MachinePath.cs
License : MIT License
Project Creator : awaescher

public string Get()
		{
			return Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
		}

19 View Source File : WindowsUtility.cs
License : Apache License 2.0
Project Creator : awslabs

public static string ResolveEnvironmentVariable(string variable)
        {
            return Environment.GetEnvironmentVariable(variable, EnvironmentVariableTarget.Machine)
                ?? Environment.GetEnvironmentVariable(variable, EnvironmentVariableTarget.User)
                ?? Environment.GetEnvironmentVariable(variable, EnvironmentVariableTarget.Process);
        }

19 View Source File : UserPath.cs
License : MIT License
Project Creator : ANF-Studios

public async Task AddToPath(string value, bool backup = false, string backupFilename = null)
        {
            if (value != null || value != string.Empty)
            {
                string initialPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
                if (backup)
                    await BackupPath(initialPath, backupFilename);
                Environment.SetEnvironmentVariable(
                    "Path",
                    (initialPath.EndsWith(";")                 // If the initial path does end with a semicolon,
                        ? (initialPath + value + ";")          // Add the initial path without a semicolon.
                        : (";" + initialPath + value + ";")),  // Otherwise add it to the Path starting with a semicolon.
                    EnvironmentVariableTarget.User
                );
            }
            else
                throw new ArgumentNullException(nameof(value));
        }

19 View Source File : SecretsResolver.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public static string GetSecret(Func<string> getConfigValue)
        {
            if (getConfigValue().StartsWith("env_"))
            {
                string environmentalVariable = Environment.GetEnvironmentVariable(getConfigValue().Replace("env_", string.Empty), EnvironmentVariableTarget.Machine);
                return environmentalVariable;
            }
            else if (getConfigValue().StartsWith("vault_"))
            {
                string keyVaultValue = KeyVault.GetSecret(getConfigValue().Replace("vault_", string.Empty));
                return keyVaultValue;
            }
            else
            {
                return getConfigValue();
            }
        }

19 View Source File : KubernetesEnricher.cs
License : MIT License
Project Creator : arcus-azure

private static void EnrichEnvironmentVariable(
            string environmentVariableName,
            string logPropertyName,
            LogEvent logEvent,
            ILogEventPropertyFactory propertyFactory)
        {
            string value = Environment.GetEnvironmentVariable(environmentVariableName, EnvironmentVariableTarget.Process);
            if (!String.IsNullOrWhiteSpace(value))
            {
                LogEventProperty property = propertyFactory.CreateProperty(logPropertyName, value);
                logEvent.AddPropertyIfAbsent(property);
            }
        }

19 View Source File : Backup.cs
License : MIT License
Project Creator : ANF-Studios

public static void ApplyBackup(in BackupOptions.BackupApplyOptions options)
        {
            // Seems like this not needed, but we're not sure just yet.
            //if (options.BackupDirectory.Contains("-n"))
            //{
            //    Console.WriteLine("Whoops, seems like there's an issue on our end. Please use the --name (-n) flag before --directory (-d).");
            //    return;
            //}

            if (options.RestoreUserVariables && options.RestoreSystemVariables)
            {
                Console.WriteLine("Both user and system variables cannot be restored at the same time (this is to protect you).");
                return;
            }

            if (options.RestoreSystemVariables)
            {
                Console.WriteLine("System variables are not yet supported by the API.");
                return;
            }

            // Invalid chars that may be in the provided directory.
            // For example:
            // When using a command argument `--directory "D:\backups\path\"` It takes the `\"` part
            // as a literal escape character which causes the value to be invalid.
            options.BackupDirectory = options.BackupDirectory.Trim(Path.GetInvalidFileNameChars());

            string file = Path.Combine(options.BackupDirectory, options.BackupFilename);
            string initialUserPath = options.RestoreUserVariables
                                        ? Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User)
                                        : null;
            string initialSystemPath = options.RestoreSystemVariables
                                        ? Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine)
                                        : null;

            if (!File.Exists(file))
            {
                Console.WriteLine(file + " not found! Aborting restore.");
                return;
            }
            else
            {
                string newPath = File.ReadAllText(file);

                if (string.IsNullOrEmpty(newPath))
                {
                    Console.WriteLine("Given file is empty! Aborting restore.");
                    return;
                }

                if (options.RestoreUserVariables)
                {
                    string tempDir = Path.Combine(Path.GetTempPath(), "WinPath");

                    try
                    {
                        if (!Directory.Exists(tempDir))
                            Directory.CreateDirectory(tempDir);
                        File.WriteAllText(userinitialBackup, initialUserPath);
                    }
                    catch (UnauthorizedAccessException) { Console.WriteLine("Whoops, we do not have enough permissions to create a backup before replacing, it's okay though!"); }
                    catch (Exception exception) { Console.WriteLine("There seems to be an error backing up the path before replacing, it's okay though!\nDetails: " + exception.Message); }

                    Environment.SetEnvironmentVariable("Path", newPath, EnvironmentVariableTarget.User);

                    Console.WriteLine("Successfully restored file as new Path!");
                    Console.WriteLine("In case if you changed your mind, there is a backup at: " + userinitialBackup);
                }
                if (options.RestoreSystemVariables)
                {
                    File.WriteAllText(systeminitialBackup, initialSystemPath);

                    Environment.SetEnvironmentVariable("Path", newPath, EnvironmentVariableTarget.Machine);

                    Console.WriteLine("Successfully restored file as new Path!");
                    Console.WriteLine("In case if you changed your mind, there is a backup at: " + systeminitialBackup);
                }
            }
        }

19 View Source File : Utility.cs
License : Apache License 2.0
Project Creator : awslabs

public static string GetKinesisTapConfigPath()
        {
            var kinesisTapConfigPath = Environment.GetEnvironmentVariable(ConfigConstants.KINESISTAP_CONFIG_PATH);
            if (string.IsNullOrWhiteSpace(kinesisTapConfigPath))
            {
                if (IsWindows)
                {
                    // For windows, use the installation path
                    kinesisTapConfigPath = AppContext.BaseDirectory;
                }
                else
                {
#if DEBUG
                    kinesisTapConfigPath = AppContext.BaseDirectory;
#else
                    kinesisTapConfigPath = ConfigConstants.UNIX_DEFAULT_CONFIG_PATH;
#endif
                }
            }
            return kinesisTapConfigPath;
        }

19 View Source File : Netch.cs
License : MIT License
Project Creator : AmazingDM

[STAThread]
        public static void Main(string[] args)
        {
            if (args.Contains("-console"))
            {
                if (!NativeMethods.AttachConsole(-1))
                {
                    NativeMethods.AllocConsole();
                }
            }

            // 创建互斥体防止多次运行
            using (var mutex = new Mutex(false, "Global\\Netch"))
            {
                // 设置当前目录
                Directory.SetCurrentDirectory(Global.NetchDir);
                Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process) + ";" + Path.Combine(Global.NetchDir, "bin"), EnvironmentVariableTarget.Process);

                // 预创建目录
                var directories = new[] {"mode", "data", "i18n", "logging"};
                foreach (var item in directories)
                {
                    if (!Directory.Exists(item))
                    {
                        Directory.CreateDirectory(item);
                    }
                }

                // 加载配置
                Configuration.Load();

                // 加载语言
                i18N.Load(Global.Settings.Language);

                // 检查是否已经运行
                /*if (!mutex.WaitOne(0, false))
                {
                    OnlyInstance.Send(OnlyInstance.Commands.Show);
                    Logging.Info("唤起单实例");

                    // 退出进程
                    Environment.Exit(1);
                }*/

                // 清理上一次的日志文件,防止淤积占用磁盘空间
                if (Directory.Exists("logging"))
                {
                    var directory = new DirectoryInfo("logging");

                    foreach (var file in directory.GetFiles())
                    {
                        file.Delete();
                    }

                    foreach (var dir in directory.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                }

                Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}");
                Task.Run(() =>
                {
                    Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Application.ExecutablePath)}");
                });
                Task.Run(() =>
                {
                    Logging.Info("启动单实例");
                    OnlyInstance.Server();
                });

                // 绑定错误捕获
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += Application_OnException;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(Global.MainForm = new MainForm());
            }
        }

19 View Source File : ProgramBody.cs
License : MIT License
Project Creator : azist

static void run(string[] args)
    {
      using (var app = new AzosApplication(allowNesting: true, cmdArgs: args, rootConfig: null))
      {
        var silent = app.CommandArgs["s", "silent"].Exists;
        if (!silent)
        {
          ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt"));

          ConsoleUtils.Info("Build information:");
          Console.WriteLine(" Azos:     " + BuildInformation.ForFramework);
          Console.WriteLine(" Tool:     " + new BuildInformation(typeof(amm.ProgramBody).replacedembly));
        }

        if (app.CommandArgs["?", "h", "help"].Exists)
        {
          ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Help.txt"));
          return;
        }


        var mbPath = app.CommandArgs
                        .AttrByIndex(0)
                        .Valuereplacedtring(System.Environment.GetEnvironmentVariable(BootConfLoader.ENV_VAR_METABASE_FS_ROOT));

        if (!Directory.Exists(mbPath))
          throw new Exception("Specified metabase path not found");

        var fromHost = app.CommandArgs["host", "from"].AttrByIndex(0).Value;
        if (fromHost.IsNullOrWhiteSpace())
          fromHost = System.Environment.GetEnvironmentVariable(BootConfLoader.ENV_VAR_HOST_NAME);

        if (!silent)
        {
          ConsoleUtils.Info("Metabase path: " + mbPath);
          ConsoleUtils.Info("Host (this machine): " + fromHost);
        }

        var w = System.Diagnostics.Stopwatch.StartNew();

        using (var fs = new LocalFileSystem(app))
        {
          using (var skyApp = new SkyApplication(app, SystemApplicationType.Tool, fs, new FileSystemSessionConnectParams(),mbPath,fromHost, allowNesting: false, cmdArgs: null, rootConfig: null))
          {
            if (app.CommandArgs["gbm"].Exists)
              generateManifests(skyApp.Metabase, silent);
            else
              validate(skyApp.Metabase, silent);
          }
        }

        if (!silent)
        {
          Console.WriteLine();
          ConsoleUtils.Info("Run time: " + w.Elapsed.ToString());
        }
      }//using APP

    }

19 View Source File : DeleteOriginalImage.cs
License : MIT License
Project Creator : AndrewBrianHall

[FunctionName("DeleteOriginalImage")]
        public static async Task Run([BlobTrigger(Config.WatermarkedContainer + "/{name}", 
            Connection = "AzureWebJobsStorage")]Stream myBlob, 
            string name, 
            ILogger log)
        {
            string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage", EnvironmentVariableTarget.Process);
            CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);
            CloudBlobClient client = account.CreateCloudBlobClient();
            CloudBlobContainer uploadContainer = client.GetContainerReference(Config.UploadContainer);

            CloudBlobContainer container = client.GetContainerReference(Config.UploadContainer);
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(name);

            await blockBlob.DeleteIfExistsAsync();

            log.LogInformation("Deleted original: {0}", name);
        }

19 View Source File : InteractWithSqlServerDatabase.cs
License : MIT License
Project Creator : aspose-gis

public static void Run()
        {
            // In order to run this examples, please set SQL_SERVER_CONN_STRING environment variable to the SQL Server connection string.
            // Alternatively, you can just replacedign connection string to the connectionString variable.
            // Connection string should look like "Data Source=<ip>;User ID=<username>;Initial Catalog=<database>;Preplacedword=<preplacedword>" or
            // "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=<database>;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            var connectionString =
                Environment.GetEnvironmentVariable("SQL_SERVER_CONN_STRING") ??
                Environment.GetEnvironmentVariable("SQL_SERVER_CONN_STRING", EnvironmentVariableTarget.Machine);
            if (connectionString == null)
            {
                Console.WriteLine(
                    "In order to run SqlServer examples, please set environment variable SQL_SERVER_CONN_STRING to the SQL Server connection string.");
                return;
            }

            RemoveSqlServerTable(connectionString);
            CreateSqlServerTable(connectionString);
            ListSqlServerTables(connectionString);
            ExportSqlServerTable(connectionString);
        }

19 View Source File : ConfigService.cs
License : GNU General Public License v3.0
Project Creator : arduosoft

public ConfigFile Load()
        {
            ConfigFile ConfigContent = new ConfigFile();

            _loggerService.Debug("get configuration file...");

            string filePath = Environment.GetEnvironmentVariable("RAWCMSCONFIG", EnvironmentVariableTarget.Process);

            if (string.IsNullOrEmpty(filePath))
            {
                return null;
            }

            _loggerService.Debug($"Config file: {filePath}");

            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader(filePath))
                {
                    string data = sr.ReadToEnd();
                    ConfigContent = new ConfigFile(data);

                    _loggerService.Debug($"config loaded.");
                }
            }
            catch (Exception e)
            {
                _loggerService.Error("The file could not be read:", e);
            }
            return ConfigContent;
        }

19 View Source File : UpdateTests.cs
License : MIT License
Project Creator : ANF-Studios

[Fact]
        public void WinPathIsInPath()
        {
            var path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
            var isOnPath = path.Contains("%PROGRAMFILES%\\WinPath") || path.Contains("C:\\Program Files\\WinPath");
            output.WriteLine("WinPath is added to the Path: " + isOnPath);
            replacedert.True(isOnPath); // FIXME: Set up a proper testing solution.
        }

19 View Source File : ImageRecognitionService.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

private string GetJavaPath()
        {
            string javaHomePath = Environment.GetEnvironmentVariable("JAVA_HOME", EnvironmentVariableTarget.Machine);

            if (string.IsNullOrEmpty(javaHomePath))
            {
                throw new FileNotFoundException("Java path not found. Is it installed? If yes, set the JAVA_HOME environment variable.");
            }

            if (!javaHomePath.Contains("\\bin") && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                javaHomePath = Path.Combine(javaHomePath, "bin");
            }

            var javaPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Path.Combine(javaHomePath, "java.exe") : Path.Combine(javaHomePath, "java");

            if (!File.Exists(javaPath))
            {
                throw new Exception($"Java executable not found in expected folder: {javaPath}. If you have multiple Java installations, you may want to set the JAVA_HOME environment variable.");
            }

            return javaPath;
        }

19 View Source File : AllureLifecycle.cs
License : Apache License 2.0
Project Creator : allure-framework

private static JObject GetConfiguration()
        {
            var jsonConfigPath = Environment.GetEnvironmentVariable(AllureConstants.ALLURE_CONFIG_ENV_VARIABLE);

            if (jsonConfigPath != null && !File.Exists(jsonConfigPath))
                throw new FileNotFoundException(
                    $"Couldn't find '{jsonConfigPath}' specified in {AllureConstants.ALLURE_CONFIG_ENV_VARIABLE} environment variable");

            if (File.Exists(jsonConfigPath))
                return JObject.Parse(File.ReadAllText(jsonConfigPath));

            var defaultJsonConfigPath =
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AllureConstants.CONFIG_FILENAME);

            if (File.Exists(defaultJsonConfigPath))
                return JObject.Parse(File.ReadAllText(defaultJsonConfigPath));

            return JObject.Parse("{}");
        }

19 View Source File : CredentialsArguments.cs
License : Apache License 2.0
Project Creator : aws

public static bool TryGetCredentials(this IAWSCredentialsArguments self, PSHost psHost, out AWSPSCredentials credentials, SessionState sessionState)
        {
            if (self == null) throw new ArgumentNullException("self");

            credentials = null;
            AWSCredentials innerCredentials = null;
            string name = null;
            var source = CredentialsSource.Unknown;
            var userSpecifiedProfile = !string.IsNullOrEmpty(self.ProfileName);

            var profileChain = new CredentialProfileStoreChain(self.ProfileLocation);

            // we probe for credentials by first checking the bound parameters to see if explicit credentials 
            // were supplied (keys, profile name, credential object), overriding anything in the shell environment
            if (AWSCredentialsFactory.TryGetAWSCredentials(self.GetCredentialProfileOptions(), profileChain, out innerCredentials))
            {
                source = CredentialsSource.Strings;
                name = "Supplied Key Parameters";
                SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
            }

            // user gave us the profile name?
            if (innerCredentials == null && userSpecifiedProfile)
            {
                CredentialProfile credentialProfile;
                if (profileChain.TryGetProfile(self.ProfileName, out credentialProfile))
                {
                    innerCredentials = AWSCredentialsFactory.GetAWSCredentials(credentialProfile, profileChain);
                    source = CredentialsSource.Profile;
                    name = self.ProfileName;
                    SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
                }
                else
                {
                    // if the user gave us an explicit profile name (and optional location) it's an error if we
                    // don't find it as otherwise we could drop through and pick up a 'default' profile that is
                    // for a different account
                    return false;
                }
           }

            // how about an aws credentials object?
            if (innerCredentials == null && self.Credential != null)
            {
                innerCredentials = self.Credential;
                source = CredentialsSource.CredentialsObject;
                name = "Credentials Object";
                // don't set proxy and callback, use self.Credential as-is
            }

            // shell session variable set (this allows override of machine-wide environment variables)
            if (innerCredentials == null && sessionState != null)
            {
                var variableValue = sessionState.PSVariable.GetValue(SessionKeys.AWSCredentialsVariableName);
                if (variableValue is AWSPSCredentials)
                {
                    credentials = variableValue as AWSPSCredentials;
                    source = CredentialsSource.Session;
                    innerCredentials = credentials.Credentials; // so remaining probes are skipped
                    // don't set proxy and callback, use credentials.Credentials as-is
                }
            }

            // no explicit command-level or shell instance override set, start to inspect the environment
            // starting environment variables
            if (innerCredentials == null)
            {
                try
                {
                    var environmentCredentials = new EnvironmentVariablesAWSCredentials();
                    innerCredentials = environmentCredentials;
                    source = CredentialsSource.Environment;
                    name = "Environment Variables";
                    // no need to set proxy and callback - only basic or session credentials
                }
                catch { }
            }

            // get credentials from a 'default' profile?
            if (innerCredentials == null && !userSpecifiedProfile)
            {
                CredentialProfile credentialProfile;
                if (profileChain.TryGetProfile(SettingsStore.PSDefaultSettingName, out credentialProfile) &&
                    credentialProfile.CanCreateAWSCredentials)
                {
                    innerCredentials = AWSCredentialsFactory.GetAWSCredentials(credentialProfile, profileChain);
                    source = CredentialsSource.Profile;
                    name = SettingsStore.PSDefaultSettingName;
                    SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
                }
            }

            // get credentials from a legacy default profile name?
            if (innerCredentials == null)
            {
                CredentialProfile credentialProfile;
                if (profileChain.TryGetProfile(SettingsStore.PSLegacyDefaultSettingName, out credentialProfile) &&
                    credentialProfile.CanCreateAWSCredentials)
                {
                    if (AWSCredentialsFactory.TryGetAWSCredentials(credentialProfile, profileChain, out innerCredentials))
                    {
                        source = CredentialsSource.Profile;
                        name = SettingsStore.PSLegacyDefaultSettingName;
                        SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
                    }
                }
            }

            if (innerCredentials == null)
            {
                // try and load credentials from ECS endpoint (if the relevant environment variable is set)
                // or EC2 Instance Profile as a last resort
                try
                {
                    string relativeUri = System.Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable);
                    string fullUri = System.Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsFullURIEnvVariable);

                    if (!string.IsNullOrEmpty(relativeUri) || !string.IsNullOrEmpty(fullUri))
                    {
                        innerCredentials = new ECSTaskCredentials();
                        source = CredentialsSource.Container;
                        name = "Container";
                        // no need to set proxy and callback
                    }
                    else
                    {
                        innerCredentials = new InstanceProfileAWSCredentials();
                        source = CredentialsSource.InstanceProfile;
                        name = "Instance Profile";
                        // no need to set proxy and callback
                    }
                }
                catch
                {
                    innerCredentials = null;
                }
            }

            if (credentials == null && innerCredentials != null)
            {
                credentials = new AWSPSCredentials(innerCredentials, name, source);
            }

            return (credentials != null);
        }

19 View Source File : Update.cs
License : MIT License
Project Creator : ANF-Studios

public void DownloadWinPath(in ReleaseInfo releaseInfo, Action finalJob = null)
        {
            bool appveyor = Environment.GetEnvironmentVariable("APPVEYOR", EnvironmentVariableTarget.Process) == "True";
            if (!confirmDownload)
            {
                Console.WriteLine("Release Information:\n"
                    + $"replacedle: {releaseInfo.ReleaseName}\n"
                    + $"Version: v{releaseInfo.TagName}"
                    + (releaseInfo.IsPrerelease ? " (Prerelease)\n" : "\n")
                    + $"File: {releaseInfo.Releasereplacedet.ExecutableName}\n");
                Console.Write($"Confirm installation of WinPath v{releaseInfo.TagName} (y/n): ");

                if (!appveyor)
                    if ((Console.ReadKey()).Key == ConsoleKey.Y)
                        confirmDownload = true;
                    else
                        Environment.Exit(Environment.ExitCode);
                else
                    return;
            }

            Directory.CreateDirectory(downloadDirectory);

            Console.WriteLine("\nDownloading " + releaseInfo.Releasereplacedet.ExecutableName + "...");
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers.Add(HttpRequestHeader.UserAgent, "WinPath");
                    webClient.DownloadFile(releaseInfo.Releasereplacedet.DownloadUrl, downloadDirectory + "WinPath.exe");
                    webClient.DownloadFile(releaseInfo.Updater.DownloadUrl, downloadDirectory + "WinPath.Updater.exe");
                }
            }
            catch (WebException exception)
            {
                Console.WriteLine("Couldn't download WinPath due to an error in networking:\n" + exception);
                Environment.Exit(1);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Couldn't download WinPath:\n" + exception.Message);
                Environment.Exit(1);
            }
            finally
            {
                Console.WriteLine("Downloaded WinPath v" + releaseInfo.TagName + "...");
                Console.WriteLine("Installing WinPath...");

                bool administratorPermissions = IsUserAnAdmin();
                int processExitCode = 1; // Default to unsuccessful.

                ProcessStartInfo process = new ProcessStartInfo
                {
                    FileName = downloadDirectory + "WinPath.Updater.exe",
                    Arguments = "launching_from_winpath", // To tell WinPath.Updater that a user isn't launching it.
                    UseShellExecute = !administratorPermissions,
                    Verb = administratorPermissions ? string.Empty : "runas",
                    CreateNoWindow = true
                };
                try
                {
                    Console.WriteLine("Starting update...");
                    if (appveyor)
                    {
                        const string installationPath = "C:\\Program Files\\WinPath\\";
                        Directory.CreateDirectory(installationPath);
                        File.Move(downloadDirectory + "\\WinPath.exe", installationPath + "WinPath.exe");
                        processExitCode = 0;
                    }
                    else
                    {
                        var application = Process.Start(process);
                        application.WaitForExit();
                        processExitCode = application.ExitCode;
                        Console.WriteLine("Installer exited with code: " + application.ExitCode);
                    }
                }
                catch (System.ComponentModel.Win32Exception exception)
                {
                    if (exception.NativeErrorCode == 1223)
                        Console.WriteLine("Could not install WinPath because administrator permissions were not provided!");
                    else
                        Console.WriteLine("Could not install WinPath: " + exception.Message);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Could not update WinPath: " + exception.Message);
                }
                if (processExitCode == 0) // If application exited successfully.
                {
                    WinPath.Library.UserPath userPath = WinPath.Program.GetUserPath();
                    string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
                    if (!path.EndsWith(";"))
                        Environment.SetEnvironmentVariable("Path", (path += ";"), EnvironmentVariableTarget.User);
                    path = path.Replace("/", "\\");
                    if (Environment.Is64BitOperatingSystem)
                       if (!(path.Contains("%programfiles%\\winpath", StringComparison.CurrentCultureIgnoreCase) || path.Contains("c:\\program files\\winpath", StringComparison.CurrentCultureIgnoreCase)))
                           userPath.AddToPath("%PROGRAMFILES%\\WinPath\\", true, DateTime.Now.ToFileTime().ToString());
                    else
                       if (!(path.Contains("%programfiles(x86)%\\winpath", StringComparison.CurrentCultureIgnoreCase) || path.Contains("c:\\program files (x86)\\winpath", StringComparison.CurrentCultureIgnoreCase)))
                           userPath.AddToPath("%PROGRAMFILES(X86)%\\WinPath\\", true, DateTime.Now.ToFileTime().ToString());
                    Console.WriteLine("[STATUS] Installed WinPath successfully!");
                    Environment.ExitCode = 0;
                }
                else // If not.
                {
                    Console.WriteLine("[STATUS] Could not update WinPath! Please see the log file: " + logDirectory + "log.txt");
                    Environment.ExitCode = 1;
                }
                finalJob?.Invoke();
            }
        }

19 View Source File : Worker.cs
License : Apache License 2.0
Project Creator : awslabs

private void GenerateUniqueClientID()
        {
            //Generate a unique client id for the KinesisTap based on the system properties
            string uniqueClientID = Utility.UniqueClientID;
            string currentUniqueClientID = _parameterStore.GetParameter(ConfigConstants.UNIQUE_CLIENT_ID);

            //Set Unique id here
            if (uniqueClientID != currentUniqueClientID)
            {
                _logger.LogInformation($"Unique Client ID of the system changed from '{currentUniqueClientID}' to '{uniqueClientID}' ");
                _parameterStore.SetParameter(ConfigConstants.UNIQUE_CLIENT_ID, uniqueClientID);
            }

            _logger.LogInformation($"Unique Client ID of the system is '{uniqueClientID}' ");
            _logger.LogInformation($"Unique System properties used to generate Unique Client ID is '{Utility.UniqueSystemProperties}' ");

            //Store the value in enviornment variable
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ConfigConstants.UNIQUE_CLIENT_ID)))
            {
                Environment.SetEnvironmentVariable(ConfigConstants.UNIQUE_CLIENT_ID, uniqueClientID);
            }

            return;
        }

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 : Utility.cs
License : Apache License 2.0
Project Creator : awslabs

public static string GetProfileDirectory()
        {
            var confPath = Environment.GetEnvironmentVariable(ConfigConstants.KINESISTAP_PROFILE_PATH);
            if (confPath is null)
            {
                //fall back to config path
                return GetKinesisTapConfigPath();
            }

            return confPath;
        }

19 View Source File : WinPathLib.Tests.cs
License : MIT License
Project Creator : ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void AddToUserPathWithBackup()
        {
            var userPath = new UserPath();
            userPath.AddToPath("LibraryTests_AddToUserPathWithBackup", true);

            string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
            bool isAddedToThePath = path.Contains("LibraryTests_AddToUserPathWithBackup;");
            bool backupExists = File.Exists(userPath.BackupDirectory + userPath.BackupFilename);

            output.WriteLine(isAddedToThePath ? "Variable is added to the path" : "Variable is NOT added to the path");
            output.WriteLine(backupExists ? "Path is backed up" : "Path is NOT backed up");
            output.WriteLine(userPath.BackupDirectory + userPath.BackupFilename);
            replacedert.True((isAddedToThePath && backupExists));
        }

19 View Source File : OpinionMining.cs
License : MIT License
Project Creator : arafattehsin

private static TextreplacedyticsClient GetTextreplacedyticsClient()
        {
            var apiKey = System.Environment.GetEnvironmentVariable("API_KEY", EnvironmentVariableTarget.Process);
            var endpointURL = System.Environment.GetEnvironmentVariable("ENDPOINT_URL", EnvironmentVariableTarget.Process);

            var credentials = !string.IsNullOrEmpty(apiKey) ? new AzureKeyCredential(apiKey) : null;
            var endpoint = !string.IsNullOrEmpty(endpointURL) && Uri.IsWellFormedUriString(endpointURL, UriKind.Absolute) ? new Uri(endpointURL) : null;

            if (apiKey != null && endpointURL != null)
                return new TextreplacedyticsClient(endpoint, credentials);
            else
                return null;
        }

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));
            }

            ArgUtil.NotNullOrEmpty(command.Data, "path");
            context.Global.PrependPath.RemoveAll(x => string.Equals(x, command.Data, StringComparison.CurrentCulture));
            context.Global.PrependPath.Add(command.Data);
        }

19 View Source File : EnvironmentVariableSecretProvider.cs
License : MIT License
Project Creator : arcus-azure

public Task<string> GetRawSecretAsync(string secretName)
        {
            Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Requires a non-blank secret name to look up the environment secret");
            
            string environmentVariable = Environment.GetEnvironmentVariable(_prefix + secretName, _target);
            return Task.FromResult(environmentVariable);
        }

19 View Source File : ImageResizer.cs
License : MIT License
Project Creator : andrewlock

async Task<bool> SetApiKeyAsync(IConsole console)
        {
            try
            {
                var apiKey = string.IsNullOrEmpty(ApiKey)
                    ? Environment.GetEnvironmentVariable(Constants.ApiKeyEnvironmentVariable)
                    : ApiKey;

                if (string.IsNullOrWhiteSpace(apiKey))
                {
                    console.Error.WriteLine("Error: No API Key provided");
                    return false;
                }

                Tinify.Key = apiKey;
                await Tinify.Validate();
                console.WriteLine("TinyPng API Key verified");
                return true;
            }
            catch (System.Exception ex)
            {
                console.Error.WriteLine("Validation of TinyPng API key failed.");
                console.Error.WriteLine(ex);
                return false;
            }
        }

19 View Source File : HostingEngine.cs
License : Apache License 2.0
Project Creator : aspnet

private static string GetPortEnvironmentVariable()
        {
            return Environment.GetEnvironmentVariable(Constants.EnvPort, EnvironmentVariableTarget.Process);
        }

19 View Source File : TimerToSBQueue.cs
License : MIT License
Project Creator : arthurhams

[FunctionName("MoveQueueMessageToBlob")]
        public static async Task MoveQueueMessageToBlob( 
    [ServiceBusTrigger("correlationqueue_process", Connection = "correlationservicebus_SERVICEBUS")] Message myQueueItem, ILogger log)
        {
            log.LogInformation($"Moving message to Blob: {Encoding.UTF8.GetString(myQueueItem.Body)}");
            string CustomId = "CID_not_Found";
            string BatchId = "BID_not_Found";
            string BatchItem = "BIt_not_Found";
            string BatchTotal = "BTo_not_Found";
            bool Success = true;
            try
            {
                var blobconn = System.Environment.GetEnvironmentVariable("correlationstorage_STORAGE", EnvironmentVariableTarget.Process);
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(blobconn);
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
                if (myQueueItem.UserProperties != null)
                {
                    try { CustomId = myQueueItem.UserProperties["CustomId"].ToString(); } catch { };
                    try { BatchId = myQueueItem.UserProperties["BatchId"].ToString(); } catch { };
                    try { BatchItem = myQueueItem.UserProperties["BatchItem"].ToString(); } catch { };
                    try { BatchTotal = myQueueItem.UserProperties["BatchTotal"].ToString(); } catch { };
                }
                string body = Encoding.UTF8.GetString(myQueueItem.Body);
                await container.CreateIfNotExistsAsync();
                var blob = container.GetAppendBlobReference(string.Format("{0}.txt", CustomId));
                if (!blob.ExistsAsync().Result)
                {
                    await blob.CreateOrReplaceAsync();
                }
                MemoryStream msWrite = new MemoryStream(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(myQueueItem.Body)));
                msWrite.Position = 0;
                blob.Metadata["CustomId"] = CustomId;
                blob.Metadata["BatchId"] = BatchId;
                blob.Metadata["BatchItem"] = BatchItem;
                blob.Metadata["BatchTotal"] = BatchTotal;
                using (msWrite)
                {
                    await blob.UploadFromStreamAsync(msWrite);
                }
            }
            catch(Exception ex)
            {
                log.LogInformation(ex.Message);
                Success = false;
            }

            LogActivity(CustomId, BatchId, BatchItem, BatchTotal, Success, log);
        }

19 View Source File : CliTests.cs
License : MIT License
Project Creator : ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void AddToUserPath()
        {
            Program.Main(new string[] {
                "add",
                "--user",
                "--backup",
                "--value",
                "replacedests_AddToUserPath"
            });
            //System.Threading.Tasks.Task.Delay(100);
            string path = System.Environment.GetEnvironmentVariable(
                "Path",
                System.EnvironmentVariableTarget.User
            );
            output.WriteLine(path);

            bool addedToPath = path.Contains("replacedests_AddToUserPath;");
            replacedert.True(addedToPath ? addedToPath : !addedToPath); // Temporary solution to fix this.
        }

19 View Source File : EnvironmentFacade.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable, EnvironmentVariableTarget.User);

19 View Source File : Environment.cs
License : Apache License 2.0
Project Creator : Algoryx

public static string[] GetAll( string name, System.EnvironmentVariableTarget target = System.EnvironmentVariableTarget.Process )
    {
      var result = System.Environment.GetEnvironmentVariable( name, target );
      if ( result == null )
        return new string[] { };
      return result.Split( Path.PathSeparator );
    }

19 View Source File : SecretsResolver.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public static string GetSecret(string name)
        {
            string environmentalVariable = Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Machine);
            if (!string.IsNullOrEmpty(environmentalVariable))
            {
                return environmentalVariable;
            }
            else if (KeyVault.IsAvailable)
            {
                string keyVaultValue = KeyVault.GetSecret(name);
                return keyVaultValue;
            }
            else
            {
                throw new ArgumentException("You need to initialize an environmental variable or key vault secret first.");
            }
        }

19 View Source File : Backup.cs
License : MIT License
Project Creator : ANF-Studios

public static void CreateBackup(in BackupOptions.BackupCreateOptions options)
        {
            // Seems like this method isn't effected unlike others.
            //if (options.BackupDirectory.Contains("-u") || options.BackupDirectory.Contains("-s"))
            //{
            //    Console.WriteLine("Whoops, seems like there's an error on our end. Please use --user (-u) and --system (-s) flags before --directory (-d).");
            //    return;
            //}

            if (!options.BackupUserVariables && !options.BackupSystemVariables)
            {
                Console.WriteLine("Did not modify any content because neither user or system flag is provided, exiting...");
                return;
            }

            // Invalid chars that may be in the provided directory.
            // For example:
            // When using a command argument `--directory "D:\backups\path\"` It takes the `\"` part
            // as a literal escape character which causes the value to be invalid.
            options.BackupDirectory = options.BackupDirectory.Trim(Path.GetInvalidFileNameChars());
            if (!options.BackupDirectory.EndsWith("\\") || !options.BackupDirectory.EndsWith("/"))
                options.BackupDirectory += "\\";

            string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
            string filename = DateTime.Now.ToFileTime().ToString();
            string finalPath = Path.Combine(options.BackupDirectory, filename);

            if (options.BackupSystemVariables)
                Console.WriteLine("System variables are not supported by the API.");
            else if (options.BackupUserVariables)
                Program.GetUserPath().BackupPath(
                    path,
                    filename,
                    options.BackupDirectory
                );
            if (File.Exists(finalPath))
                Console.WriteLine("Successfully backed up Path at: " + finalPath);
            else
                Console.WriteLine("Looks like something went wrong!");
        }

19 View Source File : DatabaseConsole.cs
License : MIT License
Project Creator : Avanade

private ValidationResult OnValidate()
        {
            _connectionString = _envVarNameOpt.HasValue() ? Environment.GetEnvironmentVariable(_envVarNameOpt.Value()!) : _connectionStringArg.Value;
            if (_connectionString == null)
                return new ValidationResult($"The connectionString command and/or --environmentVariableName option must be specified; with the latter at least resulting in a non-null value.");

            if (_commandArg.ParsedValue.HasFlag(DatabaseExecutorCommand.CodeGen) && _configOpt.Value() == null)
                return new ValidationResult($"The --config option is required when CodeGen is selected.");

            return ValidationResult.Success!;
        }

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 : LambdaUtilities.cs
License : Apache License 2.0
Project Creator : aws

public static string LoadPackageStoreManifest(IToolLogger logger, string targetFramework)
        {
            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(LambdaConstants.ENV_DOTNET_LAMBDA_CLI_LOCAL_MANIFEST_OVERRIDE)))
            {
                var filePath = Environment.GetEnvironmentVariable(LambdaConstants.ENV_DOTNET_LAMBDA_CLI_LOCAL_MANIFEST_OVERRIDE);
                if (File.Exists(filePath))
                {
                    logger?.WriteLine($"Using local manifest override: {filePath}");
                    return File.ReadAllText(filePath);
                }
                else
                {
                    logger?.WriteLine("Using local manifest override");
                    return null;
                }
            }

            string manifestFilename = null;
            if (string.Equals("netcoreapp2.0", targetFramework, StringComparison.OrdinalIgnoreCase))
                manifestFilename = "LambdaPackageStoreManifest.xml";
            else if (string.Equals("netcoreapp2.1", targetFramework, StringComparison.OrdinalIgnoreCase))
                manifestFilename = "LambdaPackageStoreManifest-v2.1.xml";

            if (manifestFilename == null)
                return null;

            return ToolkitConfigFileFetcher.Instance.GetFileContentAsync(logger, manifestFilename).Result;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : ANF-Studios

static void HandleArgument(HandleEventType eventType, AddOptions options = null)
        {
            switch (eventType)
            {
                case HandleEventType.NoValue:
                    Console.WriteLine("Please provide a value to be added.");
                    break;

                case HandleEventType.UserPath:
                    userPath.AddToPath(
                        options.Value,
                        options.BackupPathVariable,
                        DateTime.Now.ToFileTime().ToString()
                    );
                    if (Environment.GetEnvironmentVariable(
                            "Path",
                            EnvironmentVariableTarget.User)
                        .EndsWith(
                            $"{options.Value};"
                        )
                    ) Console.WriteLine($"Successfully added `{options.Value}` to the Path!");
                    else
                        Console.WriteLine(
                            "There seems to be an error, we could not verify if that value is actually added to the Path or not, it's nothing to worry about though!"
                        );
                    break;

                case HandleEventType.SystemPath:
                    throw new NotImplementedException("Cannot add to System Path as it's not implemented.");
                
                case HandleEventType.UserAndSystemPath:
                    throw new NotImplementedException("Cannot add to User and System Path as it's not implemented.");

                case HandleEventType.NoUserOrSystemPath:
                    Console.WriteLine("Did not modify any content, exiting...");
                    break;
            }
        }

19 View Source File : UdpSegmentEmitter.cs
License : Apache License 2.0
Project Creator : aws

public void SetDaemonAddress(string daemonAddress)
        {
            if (Environment.GetEnvironmentVariable(DaemonConfig.EnvironmentVariableDaemonAddress) == null)
            {
                SetEndPointOrDefault(daemonAddress);
            }
            else
            {
                _logger.InfoFormat("Ignoring call to SetDaemonAddress as " + DaemonConfig.EnvironmentVariableDaemonAddress + " is set.");
            }
        }

19 View Source File : InstantiationTests.cs
License : Apache License 2.0
Project Creator : allure-framework

[Test]
        public void ShouldReadConfigFromAppDomainDirectoryIfEnvVariableNotSpecified()
        {
            var configContent = @"{""allure"":{""directory"": ""bin""}}";
            replacedert.IsNull(Environment.GetEnvironmentVariable(AllureConstants.ALLURE_CONFIG_ENV_VARIABLE));
            File.WriteAllText(AllureConstants.CONFIG_FILENAME, configContent);

            replacedert.AreEqual("bin", new AllureLifecycle().AllureConfiguration.Directory);
        }

19 View Source File : Utility.cs
License : Apache License 2.0
Project Creator : awslabs

public static string GetNLogConfigDirectory()
        {
            var nlogPath = Environment.GetEnvironmentVariable(ConfigConstants.KINESISTAP_NLOG_PATH);
            if (nlogPath is null)
            {
                // fall back to config path
                return GetKinesisTapConfigPath();
            }

            return nlogPath;
        }

19 View Source File : WinPathLib.Tests.cs
License : MIT License
Project Creator : ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void AddToUserPath()
        {
            new UserPath().AddToPath("LibraryTests_AddToUserPath", false);

            string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
            bool isAddedToThePath = path.Contains("LibraryTests_AddToUserPath;");
            
            output.WriteLine(isAddedToThePath ? "Variable is added to the path" : "Variable is NOT added to the path");
            replacedert.True(isAddedToThePath);
        }

19 View Source File : AWSUtilities.cs
License : Apache License 2.0
Project Creator : awslabs

private static void ConfigureSTSRegionalEndpoint(IConfiguration config)
        {
            // Don't set unless the user has specified in the config that they want to use the regional endpoint.
            if (!bool.TryParse(config[ConfigConstants.USE_STS_REGIONAL_ENDPOINTS], out bool useRegionalSTSEndpoint)) return;
            if (!useRegionalSTSEndpoint) return;

            // Don't overwrite an existing value if it has already been set.
            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ConfigConstants.STS_REGIONAL_ENDPOINTS_ENV_VARIABLE))) return;

            // Don't set if we can't automatically resolve the region (required for using regional endpoints).
            var autoDiscoveredRegion = FallbackRegionFactory.GetRegionEndpoint();
            if (autoDiscoveredRegion == null || autoDiscoveredRegion.DisplayName == "Unknown") return;

            // Set the AWS_STS_REGIONAL_ENDPOINTS environment variable to Regional.
            // This will mean that customers don't have to set the system-level variable.
            Environment.SetEnvironmentVariable(ConfigConstants.STS_REGIONAL_ENDPOINTS_ENV_VARIABLE, StsRegionalEndpointsValue.Regional.ToString());
        }

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

protected void AddPrependPathToEnvironment()
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(ExecutionContext.Global.PrependPath, nameof(ExecutionContext.Global.PrependPath));
            if (ExecutionContext.Global.PrependPath.Count == 0)
            {
                return;
            }

            // Prepend path.
            string prepend = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
            var containerStepHost = StepHost as ContainerStepHost;
            if (containerStepHost != null)
            {
                containerStepHost.PrependPath = prepend;
            }
            else
            {
                string taskEnvPATH;
                Environment.TryGetValue(Constants.PathVariable, out taskEnvPATH);
                string originalPath = RuntimeVariables.Get(Constants.PathVariable) ?? // Prefer a job variable.
                    taskEnvPATH ?? // Then a task-environment variable.
                    System.Environment.GetEnvironmentVariable(Constants.PathVariable) ?? // Then an environment variable.
                    string.Empty;
                string newPath = PathUtil.PrependPath(prepend, originalPath);
                AddEnvironmentVariable(Constants.PathVariable, newPath);
            }
        }

19 View Source File : Utility.cs
License : Apache License 2.0
Project Creator : awslabs

public static string GetKinesisTapProgramDataPath()
        {
            var kinesisTapProgramDataPath = Environment.GetEnvironmentVariable(ConfigConstants.KINESISTAP_PROGRAM_DATA);
            if (string.IsNullOrWhiteSpace(kinesisTapProgramDataPath))
            {
                if (IsWindows)
                {
                    kinesisTapProgramDataPath = Path.Combine(Environment.GetEnvironmentVariable("ProgramData"), "Amazon", "AWSKinesisTap");
                }
                else
                {
                    kinesisTapProgramDataPath = ConfigConstants.UNIX_DEFAULT_PROGRAM_DATA_PATH;
                }
            }
            return kinesisTapProgramDataPath;
        }

19 View Source File : UpdateTests.cs
License : MIT License
Project Creator : ANF-Studios

[Fact]
        [System.Runtime.Versioning.SupportedOSPlatform("windows")]
        public void UpdatePathWithoutEndingSemicolon()
        {
            string initialPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
            if (initialPath.EndsWith(";"))
                initialPath = initialPath.TrimEnd(';');

            Environment.SetEnvironmentVariable("Path", initialPath, EnvironmentVariableTarget.User);

            Program.Main(
                new string[]
                {
                    "update",
                    "--prerelease",
                    "-y"
                }
            );
        }

19 View Source File : IAndcultureCodeWebHostBuilderExtensionsTest.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void PreloadAmazonElasticBeanstalk_When_Contains_AspNetCore_Environment_Sets_Global_EnvironmentVariable()
        {
            // Arrange
            var expected = $"testValue{Random.Int()}";
            var mockBuilder = new Mock<IAndcultureCodeWebHostBuilder>();
            var mockProvider = new Mock<AmazonEBConfigurationProvider>();
            mockProvider.Setup(e => e.Has(IAndcultureCodeWebHostBuilderExtensions.ASPNETCORE_ENVIRONMENT)).Returns(true);
            mockProvider.Setup(e => e.Get(IAndcultureCodeWebHostBuilderExtensions.ASPNETCORE_ENVIRONMENT)).Returns(expected);

            // Act
            var result = IAndcultureCodeWebHostBuilderExtensions.PreloadAmazonElasticBeanstalk(
                builder: mockBuilder.Object,
                stdoutEnabled: false,
                configurationProvider: mockProvider.Object
            );

            // replacedert
            result.ShouldNotBeNull();
            Environment.GetEnvironmentVariable(IAndcultureCodeWebHostBuilderExtensions.ASPNETCORE_ENVIRONMENT).ShouldBe(expected);
        }

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

public string GetDirectory(WellKnownDirectory directory)
        {
            string path;
            switch (directory)
            {
                case WellKnownDirectory.Bin:
                    path = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                    break;

                case WellKnownDirectory.Diag:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        Constants.Path.DiagDirectory);
                    break;

                case WellKnownDirectory.Externals:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        Constants.Path.ExternalsDirectory);
                    break;

                case WellKnownDirectory.Root:
                    path = new DirectoryInfo(GetDirectory(WellKnownDirectory.Bin)).Parent.FullName;
                    break;

                case WellKnownDirectory.Temp:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.TempDirectory);
                    break;

                case WellKnownDirectory.Actions:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.ActionsDirectory);
                    break;

                case WellKnownDirectory.Tools:
                    // TODO: Coallesce to just check RUNNER_TOOL_CACHE when images stabilize
                    path = Environment.GetEnvironmentVariable("RUNNER_TOOL_CACHE") ?? Environment.GetEnvironmentVariable("RUNNER_TOOLSDIRECTORY") ?? Environment.GetEnvironmentVariable("AGENT_TOOLSDIRECTORY") ?? Environment.GetEnvironmentVariable(Constants.Variables.Agent.ToolsDirectory);

                    if (string.IsNullOrEmpty(path))
                    {
                        path = Path.Combine(
                            GetDirectory(WellKnownDirectory.Work),
                            Constants.Path.ToolDirectory);
                    }
                    break;

                case WellKnownDirectory.Update:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.UpdateDirectory);
                    break;

                case WellKnownDirectory.Work:
                    var configurationStore = GetService<IConfigurationStore>();
                    RunnerSettings settings = configurationStore.GetSettings();
                    ArgUtil.NotNull(settings, nameof(settings));
                    ArgUtil.NotNullOrEmpty(settings.WorkFolder, nameof(settings.WorkFolder));
                    path = Path.GetFullPath(Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        settings.WorkFolder));
                    break;

                default:
                    throw new NotSupportedException($"Unexpected well known directory: '{directory}'");
            }

            _trace.Info($"Well known directory '{directory}': '{path}'");
            return path;
        }

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

public static string Which(string command, bool require = false, ITraceWriter trace = null, string prependPath = null)
        {
            ArgUtil.NotNullOrEmpty(command, nameof(command));
            trace?.Info($"Which: '{command}'");
            if (Path.IsPathFullyQualified(command) && File.Exists(command))
            {
                trace?.Info($"Fully qualified path: '{command}'");
                return command;
            }
            string path = Environment.GetEnvironmentVariable(PathUtil.PathVariable);
            if (string.IsNullOrEmpty(path))
            {
                trace?.Info("PATH environment variable not defined.");
                path = path ?? string.Empty;
            }
            if (!string.IsNullOrEmpty(prependPath))
            {
                path = PathUtil.PrependPath(prependPath, path);
            }

            string[] pathSegments = path.Split(new Char[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < pathSegments.Length; i++)
            {
                pathSegments[i] = Environment.ExpandEnvironmentVariables(pathSegments[i]);
            }

            foreach (string pathSegment in pathSegments)
            {
                if (!string.IsNullOrEmpty(pathSegment) && Directory.Exists(pathSegment))
                {
                    string[] matches = null;
#if OS_WINDOWS
                    string pathExt = Environment.GetEnvironmentVariable("PATHEXT");
                    if (string.IsNullOrEmpty(pathExt))
                    {
                        // XP's system default value for PATHEXT system variable
                        pathExt = ".com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh";
                    }

                    string[] pathExtSegments = pathExt.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

                    // if command already has an extension.
                    if (pathExtSegments.Any(ext => command.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
                    {
                        try
                        {
                            matches = Directory.GetFiles(pathSegment, command);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                            trace?.Verbose(ex.ToString());
                        }

                        if (matches != null && matches.Length > 0)
                        {
                            trace?.Info($"Location: '{matches.First()}'");
                            return matches.First();
                        }
                    }
                    else
                    {
                        string searchPattern;
                        searchPattern = StringUtil.Format($"{command}.*");
                        try
                        {
                            matches = Directory.GetFiles(pathSegment, searchPattern);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                            trace?.Verbose(ex.ToString());
                        }

                        if (matches != null && matches.Length > 0)
                        {
                            // add extension.
                            for (int i = 0; i < pathExtSegments.Length; i++)
                            {
                                string fullPath = Path.Combine(pathSegment, $"{command}{pathExtSegments[i]}");
                                if (matches.Any(p => p.Equals(fullPath, StringComparison.OrdinalIgnoreCase)))
                                {
                                    trace?.Info($"Location: '{fullPath}'");
                                    return fullPath;
                                }
                            }
                        }
                    }
#else
                    try
                    {
                        matches = Directory.GetFiles(pathSegment, command);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                        trace?.Verbose(ex.ToString());
                    }

                    if (matches != null && matches.Length > 0)
                    {
                        trace?.Info($"Location: '{matches.First()}'");
                        return matches.First();
                    }
#endif
                }
            }

#if OS_WINDOWS
            trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'Path' environment variable.");
#else
            trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'PATH' environment variable.");
#endif
            if (require)
            {
                throw new FileNotFoundException(
                    message: $"{command}: command not found",
                    fileName: command);
            }

            return null;
        }

19 View Source File : ConfigurationFactory.cs
License : MIT License
Project Creator : alfa-laboratory

public static IConfiguration Create(IDirectory directory)
        {
            try
            {
                var ASPNETCORE_ENVIRONMENT = Environment.GetEnvironmentVariable(Constants.LAUNCH_PROFILE);
                Log.Logger().LogInformation($"Variable \"ASPNETCORE_ENVIRONMENT\" is \"{(ASPNETCORE_ENVIRONMENT ?? "not set")}\"");

                var configuration = new ConfigurationBuilder()
                    .AddJsonFile(Path.Combine(directory.Get(), $"{Constants.DEFAULT_JSON}.json"), optional: true, reloadOnChange: true)
                    .AddJsonFile(Path.Combine(directory.Get(), $"{Constants.DEFAULT_JSON}{(ASPNETCORE_ENVIRONMENT != null ? $".{ASPNETCORE_ENVIRONMENT}" : string.Empty )}.json"), optional: true, reloadOnChange: true)
                    .AddEnvironmentVariables()
                    .Build();

                Log.Logger().LogInformation("Config file connected successfully");

                return configuration;
            }
            catch(FileNotFoundException ex)
            {
                Log.Logger().LogError($"Configuration file not found. Check the connection of the appsettings.json file to the project. Exception is \"{ex.Message}\"");
                throw new ConfigException($"Configuration file not found. Check the connection of the appsettings.json file to the project. Exception is \"{ex.Message}\"");
            }
        }

19 View Source File : UserPath.cs
License : MIT License
Project Creator : ANF-Studios

public async Task AddToPath(string value, string backupFilename = null, string backupDirectory = null, bool backup = false)
        {
            if (value != null || value != string.Empty)
            {
                string initialPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
                if (backup)
                    await BackupPath(initialPath, backupFilename, backupDirectory);
                Environment.SetEnvironmentVariable(
                    "Path",
                    (initialPath.EndsWith(";")                 // If the initial path does end with a semicolon,
                        ? (initialPath + value + ";")          // Add the initial path without a semicolon.
                        : (";" + initialPath + value + ";")),  // Otherwise add it to the Path starting with a semicolon.
                    EnvironmentVariableTarget.User
                );
            }
            else
                throw new ArgumentNullException(nameof(value));
        }

19 View Source File : HostingEngine.cs
License : Apache License 2.0
Project Creator : aspnet

private static string DetermineOwinServer(StartContext context)
        {
            StartOptions options = context.Options;
            IDictionary<string, string> settings = context.Options.Settings;

            string serverName = options.ServerFactory;
            if (!string.IsNullOrWhiteSpace(serverName))
            {
                return serverName;
            }

            if (settings != null &&
                settings.TryGetValue(Constants.SettingsOwinServer, out serverName) &&
                !string.IsNullOrWhiteSpace(serverName))
            {
                return serverName;
            }

            serverName = Environment.GetEnvironmentVariable(Constants.EnvOwnServer, EnvironmentVariableTarget.Process);
            if (!string.IsNullOrWhiteSpace(serverName))
            {
                return serverName;
            }

            return Constants.DefaultServer;
        }

See More Examples