System.Environment.GetEnvironmentVariable(string)

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

2541 Examples 7

19 Source : GameForm.cs
with zlib License
from 0x0ade

public void ApplyChanges() {
            if (!Dirty || Environment.GetEnvironmentVariable("FNADROID") == "1")
                return;

            XnaToFnaGame game = XnaToFnaHelper.Game;
            IntPtr window = game.Window.Handle;
            GraphicsDeviceManager gdm = XnaToFnaHelper.GetService<IGraphicsDeviceManager, GraphicsDeviceManager>();
            bool fullscreen = gdm.IsFullScreen;

            bool borderless = FormBorderStyle == FormBorderStyle.None;
            bool maximized = WindowState == FormWindowState.Maximized;
            bool wasFakeFullscreenWindow = FakeFullscreenWindow;
            FakeFullscreenWindow = maximized && borderless;

            XnaToFnaHelper.Log("[ProxyForms] Applying changes from ProxyForms.Form to SDL window");
            XnaToFnaHelper.Log($"[ProxyForms] Currently fullscreen: {fullscreen}; Fake fullscreen window: {FakeFullscreenWindow}; Border: {FormBorderStyle}; State: {WindowState}");

            if (FakeFullscreenWindow) {
                XnaToFnaHelper.Log("[ProxyForms] Game expects borderless fullscreen... give it proper fullscreen instead.");

                if (!fullscreen)
                    _WindowedBounds = SDLBounds;

                XnaToFnaHelper.Log($"[ProxyForms] Last window size: {_WindowedBounds.Width} x {_WindowedBounds.Height}");

                DisplayMode dm = gdm.GraphicsDevice.DisplayMode;
                // This feels so wrong.
                gdm.PreferredBackBufferWidth = dm.Width;
                gdm.PreferredBackBufferHeight = dm.Height;
                gdm.IsFullScreen = true;
                gdm.ApplyChanges();

                _Bounds = SDLBounds;

            } else {
                if (wasFakeFullscreenWindow) {
                    XnaToFnaHelper.Log("[ProxyForms] Leaving fake borderless fullscreen.");
                    gdm.IsFullScreen = false;
                }

                // Shows the ugly replacedle bar on Android
                game.Window.IsBorderlessEXT = borderless;

                if (maximized) {
                    SDL.SDL_MaximizeWindow(window);
                    _Bounds = SDLBounds;
                } else {
                    SDL.SDL_RestoreWindow(window);
                    SDLBounds = _Bounds = _WindowedBounds;
                }

                // This also feels so wrong.
                XnaToFnaHelper.Log($"[ProxyForms] New window size: {_Bounds.Width} x {_Bounds.Height}");
                gdm.PreferredBackBufferWidth = _Bounds.Width;
                gdm.PreferredBackBufferHeight = _Bounds.Height;
                gdm.ApplyChanges();
            }

            Dirty = false;
        }

19 Source : XnaToFnaHelper.cs
with zlib License
from 0x0ade

public static void Initialize(XnaToFnaGame game) {
            Game = game;

            TextInputEXT.TextInput += KeyboardEvents.CharEntered;

            game.Window.ClientSizeChanged += SDLWindowSizeChanged;

            string maximumGamepadCountStr = Environment.GetEnvironmentVariable(
                "FNA_GAMEPAD_NUM_GAMEPADS"
            );
            if (string.IsNullOrEmpty(maximumGamepadCountStr) ||
                !int.TryParse(maximumGamepadCountStr, out MaximumGamepadCount) ||
                MaximumGamepadCount < 0) {
                MaximumGamepadCount = Enum.GetNames(typeof(PlayerIndex)).Length;
            }
            DeviceEvents.IsGamepadConnected = new bool[MaximumGamepadCount];

            PlatformHook("ApplyWindowChanges");
        }

19 Source : XnaToFnaHelper.cs
with zlib License
from 0x0ade

public static bool get_IsTrialMode()
            => Environment.GetEnvironmentVariable("XNATOFNA_ISTRIALMODE") != "0";

19 Source : XnaToFnaHelper.cs
with zlib License
from 0x0ade

public static void ApplyChanges(GraphicsDeviceManager self) {
            string forceFullscreen = Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_FULLSCREEN");
            if (forceFullscreen == "0")
                self.IsFullScreen = false;
            else if (forceFullscreen == "1")
                self.IsFullScreen = true;

            int forceWidth;
            if (int.TryParse(Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_WIDTH") ?? "", out forceWidth))
                self.PreferredBackBufferWidth = forceWidth;
            int forceHeight;
            if (int.TryParse(Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_HEIGHT") ?? "", out forceHeight))
                self.PreferredBackBufferHeight = forceHeight;
            string[] forceSize = (Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_SIZE") ?? "").Split('x');
            if (forceSize.Length == 2) {
                if (int.TryParse(forceSize[0], out forceWidth))
                    self.PreferredBackBufferWidth = forceWidth;
                if (int.TryParse(forceSize[1], out forceHeight))
                    self.PreferredBackBufferHeight = forceHeight;
            }

            self.ApplyChanges();
        }

19 Source : EnvironmentVariableReader.cs
with MIT License
from 1100100

public static T Get<T>(string variable, T defaultValue = default)
        {
            var value = Environment.GetEnvironmentVariable(variable);
            if (string.IsNullOrWhiteSpace(value))
                return defaultValue;

            value = value.ReplaceIpPlaceholder();

            var matches = Regex.Matches(value, "[{](.*?)[}]");
            if (matches.Count > 0)
            {
                foreach (var match in matches)
                {
                    value = value.Replace(match.ToString(), Environment.GetEnvironmentVariable(match.ToString().TrimStart('{').TrimEnd('}')));
                }
            }
            return (T)Convert.ChangeType(value, typeof(T));
        }

19 Source : HostBootstrap.cs
with MIT License
from 17MKH

private HostOptions LoadOptions()
    {
        var configBuilder = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json", false);

        var environmentVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        if (environmentVariable.NotNull())
        {
            configBuilder.AddJsonFile($"appsettings.{environmentVariable}.json", false);
        }

        var config = configBuilder.Build();

        var hostOptions = new HostOptions();
        config.GetSection("Host").Bind(hostOptions);

        //设置默认端口
        if (hostOptions.Urls.IsNull())
            hostOptions.Urls = "http://*:6220";

        return hostOptions;
    }

19 Source : Form1.cs
with Mozilla Public License 2.0
from 1M50RRY

private void button3_Click(object sender, EventArgs e)
        {
            //Crypt
            string result = Properties.Resources.stub;
            result = result.Replace("%startup%", startup.Checked.ToString().ToLower());
            result = result.Replace("%native%", native.Checked.ToString().ToLower());
            result = result.Replace("%selfinj%", si.Checked.ToString().ToLower());
            result = result.Replace("%antivm%", antivm.Checked.ToString().ToLower());
            result = result.Replace("%key%", key.Text);
            result = result.Replace("%asm%", GenerateKey());
            var providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v4.0"}
            };
            CompilerResults results;
            using (var provider = new CSharpCodeProvider(providerOptions))
            {
                var Params = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, Environment.GetEnvironmentVariable("temp") + "\\Crypted.exe", true);
                if (ico !=  null)
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86 /win32icon:\"" + ico + "\"";
                else
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86";

                Params.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
                Params.Referencedreplacedemblies.Add("System.dll");
                Params.Referencedreplacedemblies.Add("System.Drawing.Dll");
                Params.Referencedreplacedemblies.Add("System.Security.Dll");
                Params.Referencedreplacedemblies.Add("System.Management.dll");

                string fname = "";
                if (punp.Checked)
                {
                    fname = Pump();
                    Params.EmbeddedResources.Add(fname); 
                }
                
                string tmp = "payload";
                File.WriteAllBytes(tmp, EncryptAES(encFile, key.Text));
                Params.EmbeddedResources.Add(tmp);
                results = provider.CompilereplacedemblyFromSource(Params, result);
                try
                {
                    File.Delete(tmp);
                    File.Delete(fname);
                }
                catch(Exception)
                {

                } 
            }
            if (results.Errors.Count == 0)
            {
                String temp = Environment.GetEnvironmentVariable("temp");
                if (obf.Checked)
                {
                   
                    File.WriteAllBytes(temp + "\\cli.exe", Properties.Resources.cli);
                    File.WriteAllBytes(temp + "\\Confuser.Core.dll", Properties.Resources.Confuser_Core);
                    File.WriteAllBytes(temp + "\\Confuser.DynCipher.dll", Properties.Resources.Confuser_DynCipher);
                    File.WriteAllBytes(temp + "\\Confuser.Protections.dll", Properties.Resources.Confuser_Protections);
                    File.WriteAllBytes(temp + "\\Confuser.Renamer.dll", Properties.Resources.Confuser_Renamer);
                    File.WriteAllBytes(temp + "\\Confuser.Runtime.dll", Properties.Resources.Confuser_Runtime);
                    File.WriteAllBytes(temp + "\\dnlib.dll", Properties.Resources.dnlib);

                    String crproj = Properties.Resources.def.Replace("%out%", Environment.CurrentDirectory);
                    crproj = crproj.Replace("%base%", temp);
                    crproj = crproj.Replace("%file%", temp + "\\Crypted.exe");
                    File.WriteAllText(temp + "\\def.crproj", crproj);

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.Arguments = "/C " + temp + "\\cli.exe " + temp + "\\def.crproj";
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.CreateNoWindow = true;
                    startInfo.FileName = "cmd.exe";
                    Thread pr = new Thread(() => Process.Start(startInfo));
                    pr.Start();
                    pr.Join();
                }
                else
                {
                    String file = Environment.CurrentDirectory + "\\Crypted.exe";
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception)
                    {

                    }
                    File.Move(temp + "\\Crypted.exe", file);
                }
                    

                MessageBox.Show("Done! Check Crypted.exe in the same folder.", "Crypting", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            
            foreach (CompilerError compilerError in results.Errors)
            {
                MessageBox.Show(string.Format("Error: {0}, At line {1}", compilerError.ErrorText, compilerError.Line));
            }
            
            
                
        }

19 Source : RedisEnvironmentHelper.cs
with MIT License
from 2881099

public static string GetHost(string serviceName)
        {
            return Environment.GetEnvironmentVariable($"DOCKER_HOST_{serviceName}");
        }

19 Source : GodotOnReadySourceGenerator.cs
with MIT License
from 31

public void Execute(GeneratorExecutionContext context)
		{
			// If this isn't working, run 'dotnet build-server shutdown' first.
			if (Environment
				.GetEnvironmentVariable($"Debug{nameof(GodotOnReadySourceGenerator)}") == "true")
			{
				Debugger.Launch();
			}

			var receiver = context.SyntaxReceiver as OnReadyReceiver ?? throw new Exception();

			INamedTypeSymbol GetSymbolByName(string fullName) =>
				context.Compilation.GetTypeByMetadataName(fullName)
				?? throw new Exception($"Can't find {fullName}");

			var onReadyGetSymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyGetAttribute");
			var onReadySymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyAttribute");
			var generateDataSelectorEnumSymbol =
				GetSymbolByName("GodotOnReady.Attributes.GenerateDataSelectorEnumAttribute");

			var resourceSymbol = GetSymbolByName("Godot.Resource");
			var nodeSymbol = GetSymbolByName("Godot.Node");

			List<PartialClreplacedAddition> additions = new();

			var clreplacedSymbols = receiver.AllClreplacedes
				.Select(clreplacedDecl =>
				{
					INamedTypeSymbol? clreplacedSymbol = context.Compilation
						.GetSemanticModel(clreplacedDecl.SyntaxTree)
						.GetDeclaredSymbol(clreplacedDecl);

					if (clreplacedSymbol is null)
					{
						context.ReportDiagnostic(
							Diagnostic.Create(
								new DiagnosticDescriptor(
									"GORSG0001",
									"Inspection",
									$"Unable to find declared symbol for {clreplacedDecl}. Skipping.",
									"GORSG.Parsing",
									DiagnosticSeverity.Warning,
									true
								),
								clreplacedDecl.GetLocation()
							)
						);
					}

					return clreplacedSymbol;
				})
				.Distinct(SymbolEqualityComparer.Default)
				.OfType<INamedTypeSymbol>();

			foreach (var clreplacedSymbol in clreplacedSymbols)
			{
				foreach (var attribute in clreplacedSymbol.GetAttributes()
					.Where(a => Equal(a.AttributeClreplaced, generateDataSelectorEnumSymbol)))
				{
					var fields = clreplacedSymbol.GetMembers()
						.OfType<IFieldSymbol>()
						.Where(f => f.IsReadOnly && f.IsStatic)
						.ToArray();

					additions.Add(new DataSelectorEnumAddition(
						fields,
						new AttributeSite(clreplacedSymbol, attribute)));
				}

				var members = Enumerable
					.Concat(
						clreplacedSymbol.GetMembers().OfType<IPropertySymbol>().Select(MemberSymbol.Create),
						clreplacedSymbol.GetMembers().OfType<IFieldSymbol>().Select(MemberSymbol.Create))
					.ToArray();

				foreach (var member in members)
				{
					foreach (var attribute in member.Symbol
						.GetAttributes()
						.Where(a => Equal(a.AttributeClreplaced, onReadyGetSymbol)))
					{
						var site = new MemberAttributeSite(
							member,
							new AttributeSite(clreplacedSymbol, attribute));

						if (site.AttributeSite.Attribute.NamedArguments.Any(
							a => a.Key == "Property" && a.Value.Value is string { Length: > 0 }))
						{
							additions.Add(new OnReadyGetNodePropertyAddition(site));
						}
						else if (member.Type.IsOfBaseType(nodeSymbol))
						{
							additions.Add(new OnReadyGetNodeAddition(site));
						}
						else if (member.Type.IsOfBaseType(resourceSymbol))
						{
							additions.Add(new OnReadyGetResourceAddition(site));
						}
						else
						{
							string issue =
								$"The type '{member.Type}' of '{member.Symbol}' is not supported." +
								" Expected a Resource or Node subclreplaced.";

							context.ReportDiagnostic(
								Diagnostic.Create(
									new DiagnosticDescriptor(
										"GORSG0002",
										"Inspection",
										issue,
										"GORSG.Parsing",
										DiagnosticSeverity.Error,
										true
									),
									member.Symbol.Locations.FirstOrDefault()
								)
							);
						}
					}
				}

				foreach (var methodSymbol in clreplacedSymbol.GetMembers().OfType<IMethodSymbol>())
				{
					foreach (var attribute in methodSymbol
						.GetAttributes()
						.Where(a => Equal(a.AttributeClreplaced, onReadySymbol)))
					{
						additions.Add(new OnReadyAddition(methodSymbol, attribute, clreplacedSymbol));
					}
				}
			}

			foreach (var clreplacedAdditionGroup in additions.GroupBy(a => a.Clreplaced))
			{
				SourceStringBuilder source = CreateInitializedSourceBuilder();

				if (clreplacedAdditionGroup.Key is not { } clreplacedSymbol) continue;

				source.NamespaceBlockBraceIfExists(clreplacedSymbol.GetSymbolNamespaceName(), () =>
				{
					source.Line("public partial clreplaced ", clreplacedAdditionGroup.Key.Name);
					source.BlockBrace(() =>
					{
						foreach (var addition in clreplacedAdditionGroup)
						{
							addition.DeclarationWriter?.Invoke(source);
						}

						if (clreplacedAdditionGroup.Any(a => a.ConstructorStatementWriter is not null))
						{
							source.Line();
							source.Line("public ", clreplacedAdditionGroup.Key.Name, "()");
							source.BlockBrace(() =>
							{
								foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
								{
									addition.ConstructorStatementWriter?.Invoke(source);
								}

								source.Line("Constructor();");
							});

							source.Line("partial void Constructor();");
						}

						if (clreplacedAdditionGroup.Any(a => a.OnReadyStatementWriter is not null))
						{
							source.Line();
							source.Line("public override void _Ready()");
							source.BlockBrace(() =>
							{
								source.Line("base._Ready();");

								// OrderBy is a stable sort.
								// Sort by Order, then by discovery order (implicitly).
								foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
								{
									addition.OnReadyStatementWriter?.Invoke(source);
								}
							});
						}
					});

					foreach (var addition in clreplacedAdditionGroup)
					{
						addition.OutsideClreplacedStatementWriter?.Invoke(source);
					}
				});

				string escapedNamespace =
					clreplacedAdditionGroup.Key.GetSymbolNamespaceName()?.Replace(".", "_") ?? "";

				context.AddSource(
					$"Partial_{escapedNamespace}_{clreplacedAdditionGroup.Key.Name}",
					source.ToString());
			}
		}

19 Source : Function.cs
with GNU Affero General Public License v3.0
from 3CORESec

private void initConfig()
        {
            _alerts = new List<ISender>();
            config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
            if (string.IsNullOrEmpty(config.SlackPath))
                config.SlackPath = Environment.GetEnvironmentVariable("SLACKPATH");
            if (string.IsNullOrEmpty(config.WebhookChannel))
                config.WebhookChannel = Environment.GetEnvironmentVariable("WEBHOOKCHANNEL");
            if (string.IsNullOrEmpty(config.WebHookToken))
                config.WebHookToken = Environment.GetEnvironmentVariable("WEBHOOKTOKEN");
            if (string.IsNullOrEmpty(config.PostUrl))
                config.PostUrl = Environment.GetEnvironmentVariable("POSTURL");
            var type = typeof(ISender);
            var types = AppDomain.CurrentDomain.Getreplacedemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsreplacedignableFrom(p) && !p.IsInterface && !p.IsAbstract);
            types.ToList().ForEach(type => {
                ConstructorInfo ctor = type.GetConstructor(new[] { typeof(Storage<SessionLog>), typeof(Config), typeof(IMemoryCache) });
                ISender instance = ctor.Invoke(new object[] { _storage, config, memoryCache }) as ISender;
                _alerts.Add(instance);
            });
        }

19 Source : EnvironmentReader.cs
with MIT License
from 5minlab

internal static bool TryRead(string key, out string val) {
            var parser = new Parser_String();
            try {
                var s = Environment.GetEnvironmentVariable(key);
                return parser.Parse(s, out val);

            } catch (ArgumentNullException e) {
                Debug.LogError(e.Message);
                val = "";
                return false;
            }
        }

19 Source : ContextIsolatedTask.cs
with Microsoft Public License
from AArnott

public sealed override bool Execute()
        {
            try
            {
                // We have to hook our own AppDomain so that the TransparentProxy works properly.
                AppDomain.CurrentDomain.replacedemblyResolve += this.CurrentDomain_replacedemblyResolve;

                // On .NET Framework (on Windows), we find native binaries by adding them to our PATH.
                if (this.UnmanagedDllDirectory != null)
                {
                    string pathEnvVar = Environment.GetEnvironmentVariable("PATH");
                    string[] searchPaths = pathEnvVar.Split(Path.PathSeparator);
                    if (!searchPaths.Contains(this.UnmanagedDllDirectory, StringComparer.OrdinalIgnoreCase))
                    {
                        pathEnvVar += Path.PathSeparator + this.UnmanagedDllDirectory;
                        Environment.SetEnvironmentVariable("PATH", pathEnvVar);
                    }
                }

                // Run under our own AppDomain so we can apply the .config file of the MSBuild Task we're hosting.
                // This gives the owner the control over binding redirects to be applied.
                var appDomainSetup = new AppDomainSetup();
                string pathToTaskreplacedembly = this.GetType().replacedembly.Location;
                appDomainSetup.ApplicationBase = Path.GetDirectoryName(pathToTaskreplacedembly);
                appDomainSetup.ConfigurationFile = pathToTaskreplacedembly + ".config";
                var appDomain = AppDomain.CreateDomain("ContextIsolatedTask: " + this.GetType().Name, AppDomain.CurrentDomain.Evidence, appDomainSetup);
                string taskreplacedemblyFullName = this.GetType().replacedembly.GetName().FullName;
                string taskFullName = this.GetType().FullName;
                var isolatedTask = (ContextIsolatedTask)appDomain.CreateInstanceAndUnwrap(taskreplacedemblyFullName, taskFullName);

                return this.ExecuteInnerTask(isolatedTask, this.GetType());
            }
            catch (OperationCanceledException)
            {
                this.Log.LogMessage(MessageImportance.High, "Canceled.");
                return false;
            }
            finally
            {
                AppDomain.CurrentDomain.replacedemblyResolve -= this.CurrentDomain_replacedemblyResolve;
            }
        }

19 Source : Program.cs
with Apache License 2.0
from Aaronontheweb

static int Main(string[] args)
        {
            var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STR")?.Trim();
            if (string.IsNullOrEmpty(mongoConnectionString))
            {
                Console.WriteLine("ERROR! MongoDb connection string not provided. Can't start.");
                return -1;
            }
            else
            {
                Console.WriteLine("Connecting to MongoDb at {0}", mongoConnectionString);
            }

            var config = File.ReadAllText("app.conf");
            var conf = ConfigurationFactory.ParseString(config).WithFallback(GetMongoHocon(mongoConnectionString))
                .WithFallback(OpsConfig.GetOpsConfig())
                .WithFallback(ClusterSharding.DefaultConfig())
                .WithFallback(DistributedPubSub.DefaultConfig());

            var actorSystem = ActorSystem.Create("AkkaTrader", conf.BootstrapFromDocker());

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
                var sharding = ClusterSharding.Get(actorSystem);

                var shardRegion = sharding.Start("orderBook", s => OrderBookActor.PropsFor(s), ClusterShardingSettings.Create(actorSystem),
                    new StockShardMsgRouter());
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);
            pbm.RegisterCommandPalette(ClusterCommands.Instance);
            pbm.RegisterCommandPalette(ClusterShardingCommands.Instance);
            pbm.RegisterCommandPalette(RemoteCommands.Instance);
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return 0;
        }

19 Source : Program.cs
with Apache License 2.0
from Aaronontheweb

static int Main(string[] args)
        {
            var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STR")?.Trim();
            if (string.IsNullOrEmpty(mongoConnectionString))
            {
                Console.WriteLine("ERROR! MongoDb connection string not provided. Can't start.");
                return -1;
            }
            else
            {
                Console.WriteLine("Connecting to MongoDb at {0}", mongoConnectionString);
            }

            var config = File.ReadAllText("app.conf");
            var conf = ConfigurationFactory.ParseString(config).WithFallback(GetMongoHocon(mongoConnectionString))
                .WithFallback(OpsConfig.GetOpsConfig())
                .WithFallback(ClusterSharding.DefaultConfig())
                .WithFallback(DistributedPubSub.DefaultConfig());

            var actorSystem = ActorSystem.Create("AkkaPricing", conf.BootstrapFromDocker());
            var readJournal = actorSystem.ReadJournalFor<MongoDbReadJournal>(MongoDbReadJournal.Identifier);
            var priceViewMaster = actorSystem.ActorOf(Props.Create(() => new PriceViewMaster()), "prices");

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
            var sharding = ClusterSharding.Get(actorSystem);

            var shardRegion = sharding.Start("priceAggregator",
                s => Props.Create(() => new MatchAggregator(s, readJournal)),
                ClusterShardingSettings.Create(actorSystem),
                new StockShardMsgRouter());

            // used to seed pricing data
            var singleton = ClusterSingletonManager.Props(
                Props.Create(() => new PriceInitiatorActor(readJournal, shardRegion)),
                ClusterSingletonManagerSettings.Create(
                    actorSystem.Settings.Config.GetConfig("akka.cluster.price-singleton")));

                // start the creation of the pricing views
                priceViewMaster.Tell(new PriceViewMaster.BeginTrackPrices(shardRegion));
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);
            void RegisterPalette(CommandPaletteHandler h)
            {
                if (pbm.RegisterCommandPalette(h))
                {
                    Console.WriteLine("Petabridge.Cmd - Registered {0}", h.Palette.ModuleName);
                }
                else
                {
                    Console.WriteLine("Petabridge.Cmd - DID NOT REGISTER {0}", h.Palette.ModuleName);
                }
            }


            RegisterPalette(ClusterCommands.Instance);
            RegisterPalette(RemoteCommands.Instance);
            RegisterPalette(ClusterShardingCommands.Instance);
            RegisterPalette(new PriceCommands(priceViewMaster));
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return 0;
        }

19 Source : OVRConfig.cs
with MIT License
from absurd-joy

public string GetAndroidSDKPath(bool throwError = true)
	{
#if UNITY_2019_1_OR_NEWER
		// Check for use of embedded path or user defined 
		bool useEmbedded = EditorPrefs.GetBool("SdkUseEmbedded") || string.IsNullOrEmpty(EditorPrefs.GetString("AndroidSdkRoot"));
		if (useEmbedded)
		{
			androidSDKPath = Path.Combine(BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.Android, BuildOptions.None), "SDK");
		}
		else
#endif
		{
			androidSDKPath = EditorPrefs.GetString("AndroidSdkRoot");
		}

		androidSDKPath = androidSDKPath.Replace("/", "\\");
		// Validate sdk path and notify user if path does not exist.
		if (!Directory.Exists(androidSDKPath))
		{
			androidSDKPath = Environment.GetEnvironmentVariable("ANDROID_SDK_ROOT");
			if (!string.IsNullOrEmpty(androidSDKPath))
			{
				return androidSDKPath;
			}

			if (throwError)
			{
				EditorUtility.DisplayDialog("Android SDK not Found",
						"Android SDK not found. Please ensure that the path is set correctly in (Edit -> Preferences -> External Tools) or that the Untiy Android module is installed correctly.",
						"Ok");
			}
			return string.Empty;
		}

		EditorUtility.SetDirty(Instance);
		return androidSDKPath;
	}

19 Source : PowerManager.cs
with MIT License
from ABTSoftware

public void OpenControlPanel()
        {
            var root = Environment.GetEnvironmentVariable("SystemRoot");
            Process.Start(root + "\\system32\\control.exe", "/name Microsoft.PowerOptions");
        }

19 Source : Program_Setup.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void DoOutOfBoxSetup(string configFile)
        {
            var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
            var configJsExample = Path.Combine(exeLocation, "Config.js.example");
            var exampleFile = new FileInfo(configJsExample);
            if (!exampleFile.Exists)
            {
                log.Error("config.js.example Configuration file is missing.  Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
                throw new Exception("missing config.js configuration file");
            }
            else
            {
                if (!IsRunningInContainer)
                {
                    Console.WriteLine("config.js Configuration file is missing,  cloning from example file.");
                    File.Copy(configJsExample, configFile, true);
                }
                else
                {
                    Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                    var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
                    File.Copy(configJsDocker, configFile, true);
                }
            }

            var fileText = File.ReadAllText(configFile);
            var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));

            Console.WriteLine("Performing setup for ACEmulator...");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
            var variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.WorldName = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Host = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
            if (!string.IsNullOrWhiteSpace(variable))
            {
                var path = Path.GetFullPath(variable.Trim());
                if (!Path.EndsInDirectorySeparator(path))
                    path += Path.DirectorySeparatorChar;
                //path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");

                config.Server.DatFilesDirectory = path;
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
            Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
            Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
            Console.WriteLine("As before, pressing enter will use default value.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Authentication.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Shard.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.World.Database = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Host = variable.Trim();
                    config.MySql.Shard.Host = variable.Trim();
                    config.MySql.World.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();
            }
            else
            {
                Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "y";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Username = variable.Trim();
                    config.MySql.Shard.Username = variable.Trim();
                    config.MySql.World.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                    config.MySql.Shard.Preplacedword = variable.Trim();
                    config.MySql.World.Preplacedword = variable.Trim();
                }
            }
            else
            {
                Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Preplacedword = variable.Trim();
            }

            Console.WriteLine("commiting configuration to memory...");
            using (StreamWriter file = File.CreateText(configFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
                serializer.Serialize(file, config);
            }


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                for (; ; )
                {
                    try
                    {
                        using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
                        {
                            Console.Write(".");
                            sqlTestConnection.Open();
                        }

                        break;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                        Console.Write(".");
                        Thread.Sleep(5000);
                    }
                }
                Console.WriteLine(" connected!");

                if (IsRunningInContainer)
                {
                    Console.Write("Clearing out temporary ace% database .... ");
                    var sqlDBFile = "DROP DATABASE `ace%`;";
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" done!");
                }

                Console.WriteLine("Searching for base SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile = File.ReadAllText(file.FullName);
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    switch (file.Name)
                    {
                        case "AuthenticationBase":
                            sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
                            break;
                        case "ShardBase":
                            sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
                            break;
                    }
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Base SQL scripts import complete!");

                Console.WriteLine("Searching for Update SQL scripts .... ");

                PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);

                PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);

                PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                if (IsRunningInContainer)
                {
                    Console.WriteLine(" ");
                    Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
                    Console.WriteLine(" ");
                }

                Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");

                // webrequest code provided by OptimShi
                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;
                // webrequest code provided by OptimShi

                Console.WriteLine($"Found {tag} !");

                Console.Write($"Downloading {dbFileName} .... ");
                using (var client = new WebClient())
                {
                    client.DownloadFile(dbURL, dbFileName);
                }
                Console.WriteLine("download complete!");

                Console.Write($"Extracting {dbFileName} .... ");
                ZipFile.ExtractToDirectory(dbFileName, ".", true);
                Console.WriteLine("extraction complete!");
                Console.Write($"Deleting {dbFileName} .... ");
                File.Delete(dbFileName);
                Console.WriteLine("Deleted!");

                var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
                Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
                using (var sr = File.OpenText(sqlFile))
                {
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");

                    var line = string.Empty;
                    var completeSQLline = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        //do minimal amount of work here
                        if (line.EndsWith(";"))
                        {
                            completeSQLline += line + Environment.NewLine;

                            var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
                            try
                            {
                                script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                                var count = script.Execute();
                            }
                            catch (MySql.Data.MySqlClient.MySqlException)
                            {

                            }
                            completeSQLline = string.Empty;
                        }
                        else
                            completeSQLline += line + Environment.NewLine;
                    }
                }
                Console.WriteLine(" complete!");

                Console.Write($"Deleting {sqlFile} .... ");
                File.Delete(sqlFile);
                Console.WriteLine("Deleted!");
            }

            Console.WriteLine("exiting setup for ACEmulator.");
        }

19 Source : HostContext.cs
with MIT License
from 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 Source : ConfigurationManager.cs
with MIT License
from actions

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

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

            RunnerSettings runnerSettings = new RunnerSettings();

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

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

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

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

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

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

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

            _term.WriteSection("Runner Registration");

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

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

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

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

                _term.WriteLine();

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

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

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

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

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

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

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

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

            _term.WriteSection("Runner settings");

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

            runnerSettings.MonitorSocketAddress = command.GetMonitorSocketAddress();

            _store.SaveSettings(runnerSettings);

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

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

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

19 Source : SelfUpdater.cs
with MIT License
from actions

private async Task DownloadLatestRunner(CancellationToken token)
        {
            string latestRunnerDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Path.UpdateDirectory);
            IOUtil.DeleteDirectory(latestRunnerDirectory, token);
            Directory.CreateDirectory(latestRunnerDirectory);

            int runnerSuffix = 1;
            string archiveFile = null;
            bool downloadSucceeded = false;

            try
            {
                // Download the runner, using multiple attempts in order to be resilient against any networking/CDN issues
                for (int attempt = 1; attempt <= Constants.RunnerDownloadRetryMaxAttempts; attempt++)
                {
                    // Generate an available package name, and do our best effort to clean up stale local zip files
                    while (true)
                    {
                        if (_targetPackage.Platform.StartsWith("win"))
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.zip");
                        }
                        else
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.tar.gz");
                        }

                        try
                        {
                            // delete .zip file
                            if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                            {
                                Trace.Verbose("Deleting latest runner package zip '{0}'", archiveFile);
                                IOUtil.DeleteFile(archiveFile);
                            }

                            break;
                        }
                        catch (Exception ex)
                        {
                            // couldn't delete the file for whatever reason, so generate another name
                            Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                            runnerSuffix++;
                        }
                    }

                    // Allow a 15-minute package download timeout, which is good enough to update the runner from a 1 Mbit/s ADSL connection.
                    if (!int.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_DOWNLOAD_TIMEOUT") ?? string.Empty, out int timeoutSeconds))
                    {
                        timeoutSeconds = 15 * 60;
                    }

                    Trace.Info($"Attempt {attempt}: save latest runner into {archiveFile}.");

                    using (var downloadTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)))
                    using (var downloadCts = CancellationTokenSource.CreateLinkedTokenSource(downloadTimeout.Token, token))
                    {
                        try
                        {
                            Trace.Info($"Download runner: begin download");

                            //open zip stream in async mode
                            using (HttpClient httpClient = new HttpClient(HostContext.CreateHttpClientHandler()))
                            {
                                if (!string.IsNullOrEmpty(_targetPackage.Token))
                                {
                                    Trace.Info($"Adding authorization token ({_targetPackage.Token.Length} chars)");
                                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _targetPackage.Token);
                                }

                                Trace.Info($"Downloading {_targetPackage.DownloadUrl}");

                                using (FileStream fs = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
                                using (Stream result = await httpClient.GetStreamAsync(_targetPackage.DownloadUrl))
                                {
                                    //81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
                                    await result.CopyToAsync(fs, 81920, downloadCts.Token);
                                    await fs.FlushAsync(downloadCts.Token);
                                }
                            }

                            Trace.Info($"Download runner: finished download");
                            downloadSucceeded = true;
                            break;
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            Trace.Info($"Runner download has been canceled.");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            if (downloadCts.Token.IsCancellationRequested)
                            {
                                Trace.Warning($"Runner download has timed out after {timeoutSeconds} seconds");
                            }

                            Trace.Warning($"Failed to get package '{archiveFile}' from '{_targetPackage.DownloadUrl}'. Exception {ex}");
                        }
                    }
                }

                if (!downloadSucceeded)
                {
                    throw new TaskCanceledException($"Runner package '{archiveFile}' failed after {Constants.RunnerDownloadRetryMaxAttempts} download attempts");
                }

                // If we got this far, we know that we've successfully downloaded the runner package
                // Validate Hash Matches if it is provided
                using (FileStream stream = File.OpenRead(archiveFile))
                {
                    if (!String.IsNullOrEmpty(_targetPackage.HashValue))
                    {
                        using (SHA256 sha256 = SHA256.Create())
                        {
                            byte[] srcHashBytes = await sha256.ComputeHashAsync(stream);
                            var hash = PrimitiveExtensions.ConvertToHexString(srcHashBytes);
                            if (hash != _targetPackage.HashValue)
                            {
                                // Hash did not match, we can't recover from this, just throw
                                throw new Exception($"Computed runner hash {hash} did not match expected Runner Hash {_targetPackage.HashValue} for {_targetPackage.Filename}");
                            }
                            Trace.Info($"Validated Runner Hash matches {_targetPackage.Filename} : {_targetPackage.HashValue}");
                        }
                    }
                }
                if (archiveFile.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    ZipFile.ExtractToDirectory(archiveFile, latestRunnerDirectory);
                }
                else if (archiveFile.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
                {
                    string tar = WhichUtil.Which("tar", trace: Trace);

                    if (string.IsNullOrEmpty(tar))
                    {
                        throw new NotSupportedException($"tar -xzf");
                    }

                    // tar -xzf
                    using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
                    {
                        processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Info(args.Data);
                            }
                        });

                        processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Error(args.Data);
                            }
                        });

                        int exitCode = await processInvoker.ExecuteAsync(latestRunnerDirectory, tar, $"-xzf \"{archiveFile}\"", null, token);
                        if (exitCode != 0)
                        {
                            throw new NotSupportedException($"Can't use 'tar -xzf' extract archive file: {archiveFile}. return code: {exitCode}.");
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException($"{archiveFile}");
                }

                Trace.Info($"Finished getting latest runner package at: {latestRunnerDirectory}.");
            }
            finally
            {
                try
                {
                    // delete .zip file
                    if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                    {
                        Trace.Verbose("Deleting latest runner package zip: {0}", archiveFile);
                        IOUtil.DeleteFile(archiveFile);
                    }
                }
                catch (Exception ex)
                {
                    //it is not critical if we fail to delete the .zip file
                    Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                }
            }

            // copy latest runner into runner root folder
            // copy bin from _work/_update -> bin.version under root
            string binVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.BinDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(binVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory)} to {binVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory), binVersionDir, token);

            // copy externals from _work/_update -> externals.version under root
            string externalsVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.ExternalsDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(externalsVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory)} to {externalsVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory), externalsVersionDir, token);

            // copy and replace all .sh/.cmd files
            Trace.Info($"Copy any remaining .sh/.cmd files into runner root.");
            foreach (FileInfo file in new DirectoryInfo(latestRunnerDirectory).GetFiles() ?? new FileInfo[0])
            {
                string destination = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), file.Name);

                // Removing the file instead of just trying to overwrite it works around permissions issues on linux.
                // https://github.com/actions/runner/issues/981
                Trace.Info($"Copy {file.FullName} to {destination}");
                IOUtil.DeleteFile(destination);
                file.CopyTo(destination, true);
            }
        }

19 Source : AppSettings.cs
with MIT License
from action-bi-toolkit

public static string GetEnvironmentSetting(string name) => System.Environment.GetEnvironmentVariable(name);

19 Source : GitSourceProvider.cs
with MIT License
from actions

public async Task CleanupAsync(RunnerActionPluginExecutionContext executionContext)
        {
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            var repositoryPath = Environment.GetEnvironmentVariable("STATE_repositoryPath");
            ArgUtil.NotNullOrEmpty(repositoryPath, nameof(repositoryPath));
            executionContext.Output($"Cleanup cached git credential from {repositoryPath}.");

            // Initialize git command manager
            GitCliManager gitCommandManager = new GitCliManager();
            await gitCommandManager.LoadGitExecutionInfo(executionContext);

            executionContext.Debug("Remove any extraheader setting from git config.");
            var configKeys = JsonUtility.FromString<List<string>>(Environment.GetEnvironmentVariable("STATE_modifiedgitconfig"));
            if (configKeys?.Count > 0)
            {
                foreach (var config in configKeys)
                {
                    var configValue = Environment.GetEnvironmentVariable($"STATE_{config}");
                    if (!string.IsNullOrEmpty(configValue))
                    {
                        await RemoveGitConfig(executionContext, gitCommandManager, repositoryPath, config, configValue);
                    }
                }
            }
        }

19 Source : VssUtil.cs
with MIT License
from actions

public static VssConnection CreateConnection(Uri serverUri, VssCredentials credentials, IEnumerable<DelegatingHandler> additionalDelegatingHandler = null, TimeSpan? timeout = null)
        {
            VssClientHttpRequestSettings settings = VssClientHttpRequestSettings.Default.Clone();

            int maxRetryRequest;
            if (!int.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_HTTP_RETRY") ?? string.Empty, out maxRetryRequest))
            {
                maxRetryRequest = 3;
            }

            // make sure MaxRetryRequest in range [3, 10]
            settings.MaxRetryRequest = Math.Min(Math.Max(maxRetryRequest, 3), 10);

            if (!int.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_HTTP_TIMEOUT") ?? string.Empty, out int httpRequestTimeoutSeconds))
            {
                settings.SendTimeout = timeout ?? TimeSpan.FromSeconds(100);
            }
            else
            {
                // prefer environment variable
                settings.SendTimeout = TimeSpan.FromSeconds(Math.Min(Math.Max(httpRequestTimeoutSeconds, 100), 1200));
            }


            // Remove Invariant from the list of accepted languages.
            //
            // The constructor of VssHttpRequestSettings (base clreplaced of VssClientHttpRequestSettings) adds the current
            // UI culture to the list of accepted languages. The UI culture will be Invariant on OSX/Linux when the
            // LANG environment variable is not set when the program starts. If Invariant is in the list of accepted
            // languages, then "System.ArgumentException: The value cannot be null or empty." will be thrown when the
            // settings are applied to an HttpRequestMessage.
            settings.AcceptLanguages.Remove(CultureInfo.InvariantCulture);

            VssConnection connection = new VssConnection(serverUri, new VssHttpMessageHandler(credentials, settings), additionalDelegatingHandler);
            return connection;
        }

19 Source : IOUtil.cs
with MIT License
from actions

public static void ValidateExecutePermission(string directory)
        {
            ArgUtil.Directory(directory, nameof(directory));
            string dir = directory;
            string failsafeString = Environment.GetEnvironmentVariable("AGENT_TEST_VALIDATE_EXECUTE_PERMISSIONS_FAILSAFE");
            int failsafe;
            if (string.IsNullOrEmpty(failsafeString) || !int.TryParse(failsafeString, out failsafe))
            {
                failsafe = 100;
            }

            for (int i = 0; i < failsafe; i++)
            {
                try
                {
                    Directory.EnumerateFileSystemEntries(dir).FirstOrDefault();
                }
                catch (UnauthorizedAccessException ex)
                {
                    // Permission to read the directory contents is required for '{0}' and each directory up the hierarchy. {1}
                    string message = $"Permission to read the directory contents is required for '{directory}' and each directory up the hierarchy. {ex.Message}";
                    throw new UnauthorizedAccessException(message, ex);
                }

                dir = Path.GetDirectoryName(dir);
                if (string.IsNullOrEmpty(dir))
                {
                    return;
                }
            }

            // This should never happen.
            throw new NotSupportedException($"Unable to validate execute permissions for directory '{directory}'. Exceeded maximum iterations.");
        }

19 Source : ProcessInvoker.cs
with MIT License
from actions

public async Task<int> ExecuteAsync(
            string workingDirectory,
            string fileName,
            string arguments,
            IDictionary<string, string> environment,
            bool requireExitCodeZero,
            Encoding outputEncoding,
            bool killProcessOnCancel,
            Channel<string> redirectStandardIn,
            bool inheritConsoleHandler,
            bool keepStandardInOpen,
            bool highPriorityProcess,
            CancellationToken cancellationToken)
        {
            ArgUtil.Null(_proc, nameof(_proc));
            ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));

            Trace.Info("Starting process:");
            Trace.Info($"  File name: '{fileName}'");
            Trace.Info($"  Arguments: '{arguments}'");
            Trace.Info($"  Working directory: '{workingDirectory}'");
            Trace.Info($"  Require exit code zero: '{requireExitCodeZero}'");
            Trace.Info($"  Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
            Trace.Info($"  Force kill process on cancellation: '{killProcessOnCancel}'");
            Trace.Info($"  Redirected STDIN: '{redirectStandardIn != null}'");
            Trace.Info($"  Persist current code page: '{inheritConsoleHandler}'");
            Trace.Info($"  Keep redirected STDIN open: '{keepStandardInOpen}'");
            Trace.Info($"  High priority process: '{highPriorityProcess}'");

            _proc = new Process();
            _proc.StartInfo.FileName = fileName;
            _proc.StartInfo.Arguments = arguments;
            _proc.StartInfo.WorkingDirectory = workingDirectory;
            _proc.StartInfo.UseShellExecute = false;
            _proc.StartInfo.CreateNoWindow = !inheritConsoleHandler;
            _proc.StartInfo.RedirectStandardInput = true;
            _proc.StartInfo.RedirectStandardError = true;
            _proc.StartInfo.RedirectStandardOutput = true;

            // Ensure we process STDERR even the process exit event happen before we start read STDERR stream. 
            if (_proc.StartInfo.RedirectStandardError)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

            // Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

#if OS_WINDOWS
            // If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
            // ProcessStartInfo object, then .NET PInvokes to resolve the default console output
            // code page:
            //      [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
            //      public extern static uint GetConsoleOutputCP();
            StringUtil.EnsureRegisterEncodings();
#endif
            if (outputEncoding != null)
            {
                _proc.StartInfo.StandardErrorEncoding = outputEncoding;
                _proc.StartInfo.StandardOutputEncoding = outputEncoding;
            }

            // Copy the environment variables.
            if (environment != null && environment.Count > 0)
            {
                foreach (KeyValuePair<string, string> kvp in environment)
                {
                    _proc.StartInfo.Environment[kvp.Key] = kvp.Value;
                }
            }

            // Indicate GitHub Actions process.
            _proc.StartInfo.Environment["GITHUB_ACTIONS"] = "true";

            // Set CI=true when no one else already set it.
            // CI=true is common set in most CI provider in GitHub
            if (!_proc.StartInfo.Environment.ContainsKey("CI") &&
                Environment.GetEnvironmentVariable("CI") == null)
            {
                _proc.StartInfo.Environment["CI"] = "true";
            }

            // Hook up the events.
            _proc.EnableRaisingEvents = true;
            _proc.Exited += ProcessExitedHandler;

            // Start the process.
            _stopWatch = Stopwatch.StartNew();
            _proc.Start();

            // Decrease invoked process priority, in platform specifc way, relative to parent
            if (!highPriorityProcess)
            {
                DecreaseProcessPriority(_proc);
            }

            // Start the standard error notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardError)
            {
                StartReadStream(_proc.StandardError, _errorData);
            }

            // Start the standard output notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                StartReadStream(_proc.StandardOutput, _outputData);
            }

            if (_proc.StartInfo.RedirectStandardInput)
            {
                if (redirectStandardIn != null)
                {
                    StartWriteStream(redirectStandardIn, _proc.StandardInput, keepStandardInOpen);
                }
                else
                {
                    // Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
                    _proc.StandardInput.Close();
                }
            }

            var cancellationFinished = new TaskCompletionSource<bool>();
            using (var registration = cancellationToken.Register(async () =>
            {
                await CancelAndKillProcessTree(killProcessOnCancel);
                cancellationFinished.TrySetResult(true);
            }))
            {
                Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
                while (true)
                {
                    Task outputSignal = _outputProcessEvent.WaitAsync();
                    var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);

                    if (signaled == outputSignal)
                    {
                        ProcessOutput();
                    }
                    else
                    {
                        _stopWatch.Stop();
                        break;
                    }
                }

                // Just in case there was some pending output when the process shut down go ahead and check the
                // data buffers one last time before returning
                ProcessOutput();

                if (cancellationToken.IsCancellationRequested)
                {
                    // Ensure cancellation also finish on the cancellationToken.Register thread.
                    await cancellationFinished.Task;
                    Trace.Info($"Process Cancellation finished.");
                }

                Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Wait for process to finish.
            if (_proc.ExitCode != 0 && requireExitCodeZero)
            {
                throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
            }

            return _proc.ExitCode;
        }

19 Source : Program.cs
with MIT License
from actions

public static async Task<int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace(nameof(GitHub.Runner.Worker));
            if (StringUtil.ConvertToBoolean(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_ATTACH_DEBUGGER")))
            {
                await WaitForDebugger(trace);
            }

            // We may want to consider registering this handler in Worker.cs, similiar to the unloading/SIGTERM handler
            //ITerminal registers a CTRL-C handler, which keeps the Runner.Worker process running
            //and lets the Runner.Listener handle gracefully the exit.
            var term = context.GetService<ITerminal>();
            try
            {
                trace.Info($"Version: {BuildConstants.RunnerPackage.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");
                context.WritePerfCounter("WorkerProcessStarted");

                // Validate args.
                ArgUtil.NotNull(args, nameof(args));
                ArgUtil.Equal(3, args.Length, nameof(args.Length));
                ArgUtil.NotNullOrEmpty(args[0], $"{nameof(args)}[0]");
                ArgUtil.Equal("spawnclient", args[0].ToLowerInvariant(), $"{nameof(args)}[0]");
                ArgUtil.NotNullOrEmpty(args[1], $"{nameof(args)}[1]");
                ArgUtil.NotNullOrEmpty(args[2], $"{nameof(args)}[2]");
                var worker = context.GetService<IWorker>();

                // Run the worker.
                return await worker.RunAsync(
                    pipeIn: args[1],
                    pipeOut: args[2]);
            }
            catch (Exception ex)
            {
                // Populate any exception that cause worker failure back to runner.
                Console.WriteLine(ex.ToString());
                try
                {
                    trace.Error(ex);
                }
                catch (Exception e)
                {
                    // make sure we don't crash the app on trace error.
                    // since IOException will throw when we run out of disk space.
                    Console.WriteLine(e.ToString());
                }
            }

            return 1;
        }

19 Source : CommandSettingsL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", nameof(CommandSettings))]
        public void GetsNameArgFromEnvVar()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                try
                {
                    // Arrange.
                    Environment.SetEnvironmentVariable("ACTIONS_RUNNER_INPUT_NAME", "some runner");
                    var command = new CommandSettings(hc, args: new string[0]);

                    // Act.
                    string actual = command.GetRunnerName();

                    // replacedert.
                    replacedert.Equal("some runner", actual);
                    replacedert.Equal(string.Empty, Environment.GetEnvironmentVariable("ACTIONS_RUNNER_INPUT_NAME") ?? string.Empty); // Should remove.
                    replacedert.Equal("some runner", hc.SecretMasker.MaskSecrets("some runner"));
                }
                finally
                {
                    Environment.SetEnvironmentVariable("ACTIONS_RUNNER_INPUT_NAME", null);
                }
            }
        }

19 Source : CommandSettingsL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", nameof(CommandSettings))]
        public void GetsArgSecretFromEnvVar()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                try
                {
                    // Arrange.
                    Environment.SetEnvironmentVariable("ACTIONS_RUNNER_INPUT_TOKEN", "some secret token value");
                    var command = new CommandSettings(hc, args: new string[0]);

                    // Act.
                    string actual = command.GetToken();

                    // replacedert.
                    replacedert.Equal("some secret token value", actual);
                    replacedert.Equal(string.Empty, Environment.GetEnvironmentVariable("ACTIONS_RUNNER_INPUT_TOKEN") ?? string.Empty); // Should remove.
                    replacedert.Equal("***", hc.SecretMasker.MaskSecrets("some secret token value"));
                }
                finally
                {
                    Environment.SetEnvironmentVariable("ACTIONS_RUNNER_INPUT_TOKEN", null);
                }
            }
        }

19 Source : CommandSettingsL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", nameof(CommandSettings))]
        public void GetsFlagUnattendedFromEnvVar()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                try
                {
                    // Arrange.
                    Environment.SetEnvironmentVariable("ACTIONS_RUNNER_INPUT_UNATTENDED", "true");
                    var command = new CommandSettings(hc, args: new string[0]);

                    // Act.
                    bool actual = command.Unattended;

                    // replacedert.
                    replacedert.True(actual);
                    replacedert.Equal(string.Empty, Environment.GetEnvironmentVariable("ACTIONS_RUNNER_INPUT_UNATTENDED") ?? string.Empty); // Should remove.
                }
                finally
                {
                    Environment.SetEnvironmentVariable("ACTIONS_RUNNER_INPUT_UNATTENDED", null);
                }
            }
        }

19 Source : TestHostContext.cs
with MIT License
from 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:
                    path = Environment.GetEnvironmentVariable("RUNNER_TOOL_CACHE");

                    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:
                    path = Path.Combine(
                        _tempDirectoryRoot,
                        WellKnownDirectory.Work.ToString());
                    break;

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

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

19 Source : ProcessInvokerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task KeepExistingCIEnv()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                var existingCI = Environment.GetEnvironmentVariable("CI");
                try
                {
                    // Clear out CI and make sure process invoker sets it.
                    Environment.SetEnvironmentVariable("CI", null);

                    Tracing trace = hc.GetTrace();

                    Int32 exitCode = -1;
                    var processInvoker = new ProcessInvokerWrapper();
                    processInvoker.Initialize(hc);
                    var stdout = new List<string>();
                    var stderr = new List<string>();
                    processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stdout.Add(e.Data);
                    };
                    processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stderr.Add(e.Data);
                    };
#if OS_WINDOWS
                    exitCode = await processInvoker.ExecuteAsync("", "cmd.exe", "/c \"echo %CI%\"", new Dictionary<string, string>() { { "CI", "false" } }, CancellationToken.None);
#else
                    exitCode = await processInvoker.ExecuteAsync("", "bash", "-c \"echo $CI\"", new Dictionary<string, string>() { { "CI", "false" } }, CancellationToken.None);
#endif

                    trace.Info("Exit Code: {0}", exitCode);
                    replacedert.Equal(0, exitCode);

                    replacedert.Equal("false", stdout.First(x => !string.IsNullOrWhiteSpace(x)));
                }
                finally
                {
                    Environment.SetEnvironmentVariable("CI", existingCI);
                }
            }
        }

19 Source : RunnerWebProxyL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesWithPort80()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://127.0.0.1:80");
                Environment.SetEnvironmentVariable("https_proxy", "http://user:[email protected]:80");
                Environment.SetEnvironmentVariable("no_proxy", "github.com, google.com,");
                var proxy = new RunnerWebProxy();

                replacedert.Equal("http://127.0.0.1:80", Environment.GetEnvironmentVariable("http_proxy"));
                replacedert.Null(proxy.HttpProxyUsername);
                replacedert.Null(proxy.HttpProxyPreplacedword);

                replacedert.Equal("http://user:[email protected]:80", Environment.GetEnvironmentVariable("https_proxy"));
                replacedert.Equal("user", proxy.HttpsProxyUsername);
                replacedert.Equal("preplaced", proxy.HttpsProxyPreplacedword);

                replacedert.Equal(2, proxy.NoProxyList.Count);
                replacedert.Equal("github.com", proxy.NoProxyList[0].Host);
                replacedert.Equal("google.com", proxy.NoProxyList[1].Host);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

19 Source : ProcessInvokerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task SetCIEnv()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                var existingCI = Environment.GetEnvironmentVariable("CI");
                try
                {
                    // Clear out CI and make sure process invoker sets it.
                    Environment.SetEnvironmentVariable("CI", null);

                    Tracing trace = hc.GetTrace();

                    Int32 exitCode = -1;
                    var processInvoker = new ProcessInvokerWrapper();
                    processInvoker.Initialize(hc);
                    var stdout = new List<string>();
                    var stderr = new List<string>();
                    processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stdout.Add(e.Data);
                    };
                    processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stderr.Add(e.Data);
                    };
#if OS_WINDOWS
                    exitCode = await processInvoker.ExecuteAsync("", "cmd.exe", "/c \"echo %CI%\"", null, CancellationToken.None);
#else
                    exitCode = await processInvoker.ExecuteAsync("", "bash", "-c \"echo $CI\"", null, CancellationToken.None);
#endif

                    trace.Info("Exit Code: {0}", exitCode);
                    replacedert.Equal(0, exitCode);

                    replacedert.Equal("true", stdout.First(x => !string.IsNullOrWhiteSpace(x)));
                }
                finally
                {
                    Environment.SetEnvironmentVariable("CI", existingCI);
                }
            }
        }

19 Source : HostExtensions.cs
with Apache License 2.0
from adamralph

public static Host DetectIfNull(this Host? host)
        {
            if (host.HasValue)
            {
                return host.Value;
            }

            if (Environment.GetEnvironmentVariable("APPVEYOR")?.ToUpperInvariant() == "TRUE")
            {
                return Host.AppVeyor;
            }
            else if (Environment.GetEnvironmentVariable("TF_BUILD")?.ToUpperInvariant() == "TRUE")
            {
                return Host.AzurePipelines;
            }
            else if (Environment.GetEnvironmentVariable("GITHUB_ACTIONS")?.ToUpperInvariant() == "TRUE")
            {
                return Host.GitHubActions;
            }
            else if (Environment.GetEnvironmentVariable("GITLAB_CI")?.ToUpperInvariant() == "TRUE")
            {
                return Host.GitLabCI;
            }
            else if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("TRAVIS_OS_NAME")))
            {
                return Host.Travis;
            }
            else if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME")))
            {
                return Host.TeamCity;
            }
            else if (Environment.GetEnvironmentVariable("TERM_PROGRAM")?.ToUpperInvariant() == "VSCODE")
            {
                return Host.VisualStudioCode;
            }

            return Host.Console;
        }

19 Source : TargetCollectionExtensions.cs
with Apache License 2.0
from adamralph

private static async Task RunAsync(
            this TargetCollection targets,
            IReadOnlyCollection<string> args,
            IReadOnlyCollection<string> names,
            IOptions options,
            IReadOnlyCollection<string> unknownOptions,
            bool showHelp,
            Func<Exception, bool> messageOnly,
            string messagePrefix,
            TextWriter outputWriter,
            TextWriter diagnosticsWriter)
        {
            if (options.Clear)
            {
                try
                {
                    Console.Clear();
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    await diagnosticsWriter.WriteLineAsync($"{messagePrefix}: Failed to clear the console: {ex}").Tax();
                }
            }

            var noColor = options.NoColor;

            if (Environment.GetEnvironmentVariable("NO_COLOR") != null)
            {
                if (options.Verbose)
                {
                    await diagnosticsWriter.WriteLineAsync($"{messagePrefix}: NO_COLOR environment variable is set. Colored output is disabled.").Tax();
                }

                noColor = true;
            }

            var host = options.Host.DetectIfNull();

            var operatingSystem =
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? OperatingSystem.Windows
                    : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                        ? OperatingSystem.Linux
                        : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                            ? OperatingSystem.MacOS
                            : OperatingSystem.Unknown;

            var output = new Output(
                outputWriter,
                args,
                options.DryRun,
                host,
                options.Host.HasValue,
                noColor,
                options.NoExtendedChars,
                operatingSystem,
                options.Parallel,
                messagePrefix,
                options.SkipDependencies,
                options.Verbose);

            var outputState = await output.Initialize(options.Verbose ? diagnosticsWriter : TextWriter.Null).Tax();

            try
            {
                await output.Header(() => typeof(TargetCollection).replacedembly.GetVersion()).Tax();

                await targets.RunAsync(
                    names,
                    options.DryRun,
                    options.ListDependencies,
                    options.ListInputs,
                    options.ListTargets,
                    options.ListTree,
                    options.Parallel,
                    options.SkipDependencies,
                    unknownOptions,
                    showHelp,
                    messageOnly,
                    output).Tax();
            }
            finally
            {
                await outputState.DisposeAsync().Tax();
            }
        }

19 Source : Program.cs
with Apache License 2.0
from adamralph

public static int Main(string[] args)
        {
            if (args.Contains("unicode"))
            {
                Console.OutputEncoding = Encoding.Unicode;
                args = args.Concat(new[] { "Pi (\u03a0)" }).ToArray();
            }

            var input = args.Contains("in")
                ? Console.In.ReadToEnd()
                    .Replace("\r", "\\r", StringComparison.Ordinal)
                    .Replace("\n", "\\n", StringComparison.Ordinal)
                : null;

            Console.Out.WriteLine($"SimpleExecTester (stdin): {input}");
            Console.Out.WriteLine($"SimpleExecTester (stdout): {string.Join(" ", args)}");
            Console.Error.WriteLine($"SimpleExecTester (stderr): {string.Join(" ", args)}");

            if (args.Contains("large"))
            {
                Console.Out.WriteLine(new string('x', (int)Math.Pow(2, 12)));
                Console.Error.WriteLine(new string('x', (int)Math.Pow(2, 12)));
            }

            var exitCode = 0;
            if (args.FirstOrDefault(arg => int.TryParse(arg, out exitCode)) != null)
            {
                return exitCode;
            }

            if (args.Contains("sleep"))
            {
                Thread.Sleep(Timeout.Infinite);
                return 0;
            }

            Console.WriteLine($"foo={Environment.GetEnvironmentVariable("foo")}");

            return 0;
        }

19 Source : WebAppSettings.cs
with MIT License
from Adoxio

private static string GetAppSettingOrEnvironmentVariable(string name)
		{
			return name.ResolveAppSetting() ?? Environment.GetEnvironmentVariable(name);
		}

19 Source : DLLCreatorWindow.cs
with MIT License
from adrenak

List<string> GetNETPaths() {
			return Environment.GetEnvironmentVariable("Path").Split(';').Where(x => x.Contains(".NET")).ToList();
		}

19 Source : EnvironmentVariablePrivateKeySource.cs
with MIT License
from adriangodong

public TextReader GetPrivateKeyReader()
        {
            var privateKeyPem = Environment.GetEnvironmentVariable(environmentVariableName).HydrateRsaVariable();
            return new StringReader(privateKeyPem);
        }

19 Source : IgnoreOnCIFact.cs
with MIT License
from AElfProject

private static bool IsOnCI()
            => Environment.GetEnvironmentVariable("CI_TEST") != null;

19 Source : Program.cs
with MIT License
from AeonLucid

private static async Task Main(string[] args)
        {
            // Get user credentials from environment variables.
            //      Environment is used for this example because it makes it easier to rest the library.
            var username = Environment.GetEnvironmentVariable("USERNAME");
            var preplacedword = Environment.GetEnvironmentVariable("PreplacedWORD");

            // Initialize cache.
            //      This makes sure there is consistency between device identifiers per user and gets rid of
            //      repeated authentications.
            var cacheDirectory = Path.Combine(Path.GetDirectoryName(typeof(Program).replacedembly.Location), "Cache");
            var cacheHandler = new FileCacheHandler(cacheDirectory);

            // Create a musical.ly client.
            //      Using to dispose properly.
            using (var client = new MusicallyClient(username, cacheHandler))
            {
                DiscoverUserMe profile = null;

                // Check if this instance is not logged in yet.
                //      ALWAYS do this check, because the access token gets cached and loaded when the client is created.
                if (!client.IsLoggedIn())
                {
                    var login = await client.LoginAsync(preplacedword);
                    if (login.success)
                    {
                        profile = await client.DiscoverUserMeAsync();
                    }
                }
                else
                {
                    profile = await client.DiscoverUserMeAsync();
                }

                // Sanity check.
                if (profile == null)
                {
                    throw new Exception("Profile was null..?");
                }

                // We are now properly authenticated.
                if (client.IsLoggedIn())
                {
                    Console.WriteLine($"Logged in as {profile.result.displayName}.");

                    // Do stuff with client.*
                }
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }

19 Source : Program.cs
with MIT License
from AeonLucid

private static async Task DoStuff()
        {
            using (var client = new FortniteClient(Environment.GetEnvironmentVariable("TRN_KEY")))
            {
                Console.WriteLine("Looking up player ids..");
                var players = new[]
                {
                    "AeonLuciid",
                    "AeonLucidUtil"
                };

                foreach (var player in players)
                {
                    Console.WriteLine($"Looking up {player}");

                    var response = await client.FindPlayerAsync(Platform.Pc, player);

                    var soloKills = response.Stats[Playlist.Solo][Stat.Kills].ValueInt;
                }
            }
        }

19 Source : Program.cs
with MIT License
from agc93

static async Task<int> Main(string[] args)
        {
            var confOverride = Environment.GetEnvironmentVariable("UNEX_CONFIG");
             IConfigurationBuilder configBuilder = new ConfigurationBuilder()
                .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                .AddFile("unex")
                .AddEnvironmentVariables("UNEX_");
            if (confOverride.IsSet() && System.IO.File.Exists(confOverride)) {
                configBuilder.AddFile(confOverride);
            }
            IConfiguration config = configBuilder.Build();
            var opts = config.Get<ModConfiguration>();
            var services = new ServiceCollection();
            services.AddLogging(logging => {
                logging.SetMinimumLevel(LogLevel.Trace);
                logging.AddInlineSpectreConsole(c => {
                    c.LogLevel = GetLogLevel();
                });
                logging.AddFilter("System.Net.Http", LogLevel.Warning);
            });
            services.AddNexusApiClient();
            services.AddNexusClient();
            services.AddUploadClient();
            services.AddSingleton<ModConfiguration>(opts ?? new ModConfiguration());
            services.AddSingleton<CookieService>();
            // services.AddSingleton<ILoggingConfiguration>(GetDefaultLogging());
            var app = new CommandApp(new DependencyInjectionRegistrar(services));
            app.Configure(c => {
                c.SetApplicationName("unex");
                if (GetLogLevel() < LogLevel.Information) {
                    c.PropagateExceptions();
                }
                c.AddCommand<InfoCommand>("info");
                c.AddCommand<ChangelogCommand>("changelog");
                c.AddCommand<UploadCommand>("upload");
                c.AddCommand<CheckCommand>("check");
            });
            return await app.RunAsync(args);
        }

19 Source : Program.cs
with MIT License
from agc93

private static LogLevel GetLogLevel() {
            var envVar = System.Environment.GetEnvironmentVariable("UNEX_DEBUG");
            return string.IsNullOrWhiteSpace(envVar) 
                ? LogLevel.Information
                :  envVar.ToLower() == "trace"
                    ? LogLevel.Trace
                    : LogLevel.Debug;
        }

19 Source : Platform.Win32.cs
with Mozilla Public License 2.0
from agebullhu

public static string[] EnumeratePATH()
			{
				string PATH = System.Environment.GetEnvironmentVariable("PATH");
				if (PATH == null) return new string[] { };

				string[] paths = PATH.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

				var pathList = new List<string>();
				foreach (string path in paths)
				{
					string _path =
						EnsureNotDoubleQuoted(
							EnsureNotEndingBackSlash(path));
					
					if (_path != null && Directory.Exists(_path)) pathList.Add(_path);
				}
				return pathList.ToArray();
			}

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

public static string ProgramFilesx86()
        {
            if (IntPtr.Size == 8 || !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))
                return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
            else
                return Environment.GetEnvironmentVariable("ProgramFiles");
        }

19 Source : IdentityBuilderExtensionsTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void AddFirebaseStores_with_project_id_Test()
        {
            var builder = new ConfigurationBuilder();
            var configuration = builder
                .AddEnvironmentVariables()
                .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "../../../../idenreplacedyfirestore.json"))
                .Build();

            var authOptions = configuration.GetSection("FirestoreAuthTokenOptions").Get<OAuthServiceAccountKey>();
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")))
            {
                var path = Path.GetTempFileName();

                var json = JsonConvert.SerializeObject(authOptions);
                using var writer = File.CreateText(path);
                writer.Write(json);
                writer.Flush();
                writer.Close();
                Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
            }

            var services = new ServiceCollection();
            services
                .AddIdenreplacedy<IdenreplacedyUser, IdenreplacedyRole>()
                .AddFirestoreStores(authOptions.project_id);

            var provider = services.BuildServiceProvider();

            replacedert.NotNull(provider.GetService<IUserStore<IdenreplacedyUser>>());
            replacedert.NotNull(provider.GetService<IRoleStore<IdenreplacedyRole>>());
        }

19 Source : Startup.cs
with MIT License
from ahydrax

public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(configuration =>
                configuration
                    .UseRedisStorage(Environment.GetEnvironmentVariable("REDIS"))
                    .UseHeartbeatPage(TimeSpan.FromMilliseconds(500)));
        }

19 Source : Program.cs
with MIT License
from ai-traders

public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
            var b = WebHost.CreateDefaultBuilder(args);
            string threadCount = Environment.GetEnvironmentVariable("LIGET_LIBUV_THREAD_COUNT");
            if(!string.IsNullOrEmpty(threadCount))
                b.UseLibuv(opts => opts.ThreadCount = int.Parse(threadCount));
            
            var port = Environment.GetEnvironmentVariable("LIGET_LISTEN_PORT");
            if (string.IsNullOrEmpty(port))
                port = "9011";
            
            b.UseStartup<Startup>()
                .ConfigureLogging((context, builder) =>
                {
                    var graylogSection = context.Configuration.GetSection("Graylog");
                    // Read GelfLoggerOptions from appsettings.json
                    if(graylogSection.GetChildren().Any())
                        builder.Services.Configure<GelfLoggerOptions>(graylogSection);

                    // Read Logging settings from appsettings.json and add providers.
                    var cfg = builder.AddConfiguration(context.Configuration.GetSection("Logging"))
                        .AddConsole()
                        .AddDebug();
                    if(graylogSection.GetChildren().Any())
                        cfg.AddGelf();
                })
                .UseUrls($"http://0.0.0.0:{port}")
                .UseKestrel(options =>
                {
                    // Remove the upload limit from Kestrel. If needed, an upload limit can
                    // be enforced by a reverse proxy server, like IIS.
                    options.Limits.MaxRequestBodySize = null;
                });
            return b;
        }

19 Source : Startup.cs
with MIT License
from ahydrax

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddHangfire(configuration =>
            {
                configuration.UsePostgreSqlStorage(Environment.GetEnvironmentVariable("Hangfire_PostgreSql_ConnectionString"));
                configuration.UsePostgreSqlMetrics();
                //configuration.UseRedisStorage("192.168.5.32");
                configuration.UseAtoms();
            });
        }

See More Examples