public void All_environment_variables_from_spec_are_available_as_typed_properties() { var headers = new Dictionary<string, string>(); var body = new BodyDelegate((next, error, complete) => () => { }).ToAction(); var env = new Dictionary<string, object> { {"owin.RequestMethod", "GET"}, {"owin.RequestPath", "/foo"}, {"owin.RequestHeaders", headers}, {"owin.RequestBody", body}, {"owin.RequestPathBase", "/my-app"}, {"owin.RequestQueryString", "hello=world"}, {"owin.RequestScheme", "https"}, {"owin.Version", "1.0"}, }; var environment = new Environment(env); Assert.That(environment.Method, Is.EqualTo("GET")); Assert.That(environment.Path, Is.EqualTo("/foo")); Assert.That(environment.Headers, Is.SameAs(headers)); Assert.That(environment.Body, Is.SameAs(body)); Assert.That(environment.PathBase, Is.EqualTo("/my-app")); Assert.That(environment.QueryString, Is.EqualTo("hello=world")); Assert.That(environment.Scheme, Is.EqualTo("https")); Assert.That(environment.Version, Is.EqualTo("1.0")); }
public async Task<MiddlewareInvocationEnum> Invoke(Environment environment) { string[] setReplyHeader; bool shouldSetReply = false; if (environment.RequestHeaders.TryGetValue(SET_REPLY_HEADER_NAME, out setReplyHeader) && !string.IsNullOrWhiteSpace(setReplyHeader[0]) && bool.TryParse(setReplyHeader[0], out shouldSetReply) && shouldSetReply) { Replies[environment.RequestPath] = await ReadAllBytes(environment.RequestBody); return MiddlewareInvocationEnum.StopChain; } else { byte[] data; if (Replies.TryGetValue(environment.RequestPath, out data)) { await environment.ResponseBody.WriteAsync(data, 0, data.Length); environment.ResponseHeaders.ContentLength = data.Length; environment.ResponseHeaders.ContentType = "application/json"; return MiddlewareInvocationEnum.StopChain; } else return MiddlewareInvocationEnum.ContinueToNext; } }
public void TestAndConditionBlocked() { var env = new Environment(); env.Process(TestAndConditionBlockedProcess(env)); env.RunD(5); Assert.AreEqual(5, env.NowD); }
public ObstacleBuilder(Environment e) { InitializeComponent(); env = e; Pass = radioPassYes.Checked; Dyn = radioDynYes.Checked; }
private IEnumerable<Event> Customer(Environment env, string name, Resource counter, TimeSpan meanTimeInBank) { var arrive = env.Now; env.Log("{0} {1}: Here I am", arrive, name); using (var req = counter.Request()) { // Wait for the counter or abort at the end of our tether var timeout = env.TimeoutUniform(MinPatience, MaxPatience); yield return req | timeout; var wait = env.Now - arrive; if (req.IsProcessed) { // We got the counter env.Log("{0} {1}: waited {2}", env.Now, name, wait); yield return env.TimeoutExponential(meanTimeInBank); env.Log("{0} {1}: Finished", env.Now, name); } else { // We reneged env.Log("{0} {1}: RENEGED after {2}", env.Now, name, wait); } } }
private IEnumerable<Event> Car(string name, Environment env, Resource gasStation, Container fuelPump) { /* * A car arrives at the gas station for refueling. * * It requests one of the gas station's fuel pumps and tries to get the * desired amount of gas from it. If the stations reservoir is * depleted, the car has to wait for the tank truck to arrive. */ var fuelTankLevel = env.RandUniform(MinFuelTankLevel, MaxFuelTankLevel + 1); env.Log("{0} arriving at gas station at {1}", name, env.Now); using (var req = gasStation.Request()) { var start = env.Now; // Request one of the gas pumps yield return req; // Get the required amount of fuel var litersRequired = FuelTankSize - fuelTankLevel; yield return fuelPump.Get(litersRequired); // The "actual" refueling process takes some time yield return env.Timeout(TimeSpan.FromSeconds(litersRequired / RefuelingSpeed)); env.Log("{0} finished refueling in {1} seconds.", name, (env.Now - start).TotalSeconds); } }
public static void Main(string[] args) { // Change the console window Terminal term = new Terminal(); term.Title = "Terminal Window Title"; term.DisplayMode = (int)ConsoleDisplayModeForSet.CONSOLE_FULLSCREEN_MODE; //Console.WriteLine("Terminal Title: {0}", term.Title); term.WriteLine("Terminal Window Title - has been set"); COORD fontSize = term.FontSize; Console.WriteLine("Terminal Font Size: X = {0}, Y = {1}", fontSize.X, fontSize.Y); Console.WriteLine("mouse buttons: {0}", term.MouseButtons); // Instantiate a machine Machine aMachine = new Machine(); // Print some properties Console.WriteLine("Name: {0}", aMachine.ShortName); Console.WriteLine("Domain: {0}", aMachine.DomainName); Environment environ = new Environment(); Console.WriteLine("Command Line: {0}", environ.CommandLine); // Get the name of the process image that this process is running //Process aProc = new Process(); //PrintProcess(aProc); //PrintAllProcesses(); PrintAllDrives(); //PrintVolumes(); Console.ReadLine(); }
/// <summary> /// Creates instance of LISpMiner for existing location. /// </summary> /// <param name="lmpath">Path to LM folder.</param> /// <param name="env">Environment settings.</param> public LISpMiner(DirectoryInfo lmpath, Environment env) { if (!lmpath.Exists) { throw new Exception(String.Format("LISpMiner does not exist at location {0}", lmpath.FullName)); } this.Environment = env; this.Id = lmpath.Name.Substring("LISpMiner_".Length); this.LMPrivatePath = lmpath.FullName; this.SharedPool = !File.Exists(Path.Combine(this.LMPrivatePath, "LMTaskPooler.exe")); string metabaseFile; string devNull = string.Empty; string metabaseDSNFile; string databaseFile; string databaseDSNFile; this.GetDatabaseNames(string.Empty, out databaseFile, out databaseDSNFile); if (File.Exists(databaseFile)) { this.Database = new AccessConnection(databaseDSNFile, databaseFile, string.Empty); } else { this.Database = new MySQLConnection(databaseDSNFile); } this.GetMetabaseNames(out metabaseFile, ref devNull, out metabaseDSNFile); this.Metabase = new AccessConnection(metabaseDSNFile, metabaseFile, string.Empty); this.Created = lmpath.CreationTime; }
/// <summary>Composes a path name of a special folder and a string component</summary> public static string Compose(Environment.SpecialFolder special, params string[] components) { var args = new string[1 + components.Length]; args[0] = Environment.GetFolderPath(special); Array.Copy(components, 0, args, 1, components.Length); return Compose(args); }
public override bool EvalStep(out object answer, ref Control expression, ref Environment environment) { #if DEBUG Warm ("PrimitiveIsCharEqA.EvalStep"); #endif throw new NotImplementedException (); }
public override void Update(Environment environment, Camera cam, Mesh mesh) { base.Update(environment, cam, mesh); if (currentMaterial != null) { Texture diffuseTex = currentMaterial.GetTexture(Material.TEXTURE_DIFFUSE); if (diffuseTex != null) { Texture.ActiveTextureSlot(0); diffuseTex.Use(); SetUniform("Material_DiffuseMap", 0); SetUniform("Material_HasDiffuseMap", 1); } else { SetUniform("Material_HasDiffuseMap", 0); } Texture normalTex = currentMaterial.GetTexture(Material.TEXTURE_NORMAL); if (normalTex != null) { Texture.ActiveTextureSlot(1); normalTex.Use(); SetUniform("Material_NormalMap", 1); SetUniform("Material_HasNormalMap", 1); } else { SetUniform("Material_HasNormalMap", 0); } } }
public void All_environment_variables_from_spec_are_available_as_typed_properties() { var headers = new Dictionary<string, string>(); BodyDelegate body = (next, error, complete) => () => { }; var env = new Dictionary<string, object> { {"owin.RequestMethod", "GET"}, {"owin.RequestUri", "/foo"}, {"owin.RequestHeaders", headers}, {"owin.RequestBody", body}, {"owin.BaseUri", "/my-app"}, {"owin.ServerName", "localhost"}, {"owin.ServerPort", "8080"}, {"owin.UriScheme", "https"}, {"owin.RemoteEndPoint", new IPEndPoint(IPAddress.Parse("127.0.0.1") ?? IPAddress.None, 80)}, {"owin.Version", "1.0"}, }; var environment = new Environment(env); Assert.That(environment.Method, Is.EqualTo("GET")); Assert.That(environment.RequestUri, Is.EqualTo("/foo")); Assert.That(environment.Headers, Is.SameAs(headers)); Assert.That(environment.Body, Is.SameAs(body)); Assert.That(environment.BaseUri, Is.EqualTo("/my-app")); Assert.That(environment.ServerName, Is.EqualTo("localhost")); Assert.That(environment.ServerPort, Is.EqualTo("8080")); Assert.That(environment.UriScheme, Is.EqualTo("https")); Assert.That(environment.RemoteEndPoint.ToString(), Is.EqualTo("127.0.0.1:80")); Assert.That(environment.Version, Is.EqualTo("1.0")); }
public void All_environment_variables_from_spec_are_available_as_typed_properties() { var headers = new Dictionary<string, string[]>(); BodyDelegate body = (a, b, c) => { }; var env = new Dictionary<string, object> { {OwinConstants.RequestMethod, "GET"}, {OwinConstants.RequestPath, "/foo"}, {OwinConstants.RequestHeaders, headers}, {OwinConstants.RequestBody, body}, {OwinConstants.RequestPathBase, "/my-app"}, {OwinConstants.RequestQueryString, "hello=world"}, {OwinConstants.RequestScheme, "https"}, {OwinConstants.Version, "1.0"}, }; var environment = new Environment(env); Assert.That(environment.Method, Is.EqualTo("GET")); Assert.That(environment.Path, Is.EqualTo("/foo")); Assert.That(environment.Headers, Is.SameAs(headers)); Assert.That(environment.BodyDelegate, Is.SameAs(body)); Assert.That(environment.PathBase, Is.EqualTo("/my-app")); Assert.That(environment.QueryString, Is.EqualTo("hello=world")); Assert.That(environment.Scheme, Is.EqualTo("https")); Assert.That(environment.Version, Is.EqualTo("1.0")); }
public override bool EvalStep(out object answer, ref Control expression, ref Environment environment) { #if DEBUG Warm ("-"); NoteCalls (this.rand0); NoteCalls (this.rand1); rand0TypeHistogram.Note (this.rand0Type); rand1TypeHistogram.Note (this.rand1Type); SCode.location = "PCondRecordRef"; #endif Control unev = this.rand1; Environment env = environment; object ev1; while (unev.EvalStep (out ev1, ref unev, ref env)) { }; #if DEBUG SCode.location = "PCondRecordRef"; #endif if (ev1 == Interpreter.UnwindStack) { throw new NotImplementedException (); } unev = this.rand0; env = environment; object ev0; while (unev.EvalStep (out ev0, ref unev, ref env)) { }; #if DEBUG SCode.location = "PCondRecordRef"; #endif if (ev0 == Interpreter.UnwindStack) { throw new NotImplementedException (); //((UnwinderState) env).AddFrame (new PrimitiveCombination1Frame0 (this, environment)); //answer = Interpreter.UnwindStack; //environment = env; //return false; } object result = ((Record) ev0).Ref ((int) ev1); if (result is Boolean && (((bool) result) == false)) { #if DEBUG SCode.location = "-"; NoteCalls (this.alternative); alternativeTypeHistogram.Note (this.alternativeType); SCode.location = "PCondRecordRef"; #endif expression = this.alternative; answer = null; return true; } else { #if DEBUG SCode.location = "-"; NoteCalls (this.consequent); consequentTypeHistogram.Note (this.consequentType); SCode.location = "PCondRecordRef"; #endif expression = this.consequent; answer = null; return true; } }
public override bool EvalStep(out object answer, ref Control expression, ref Environment environment) { #if DEBUG Warm ("-"); NoteCalls (this.rand1); rand1TypeHistogram.Note (this.rand1Type); SCode.location = "PrimitiveIsCharEqQ"; #endif // Eval argument1 object ev1; Control unev = this.rand1; Environment env = environment; while (unev.EvalStep (out ev1, ref unev, ref env)) { }; if (ev1 == Interpreter.UnwindStack) { throw new NotImplementedException (); //((UnwinderState) env).AddFrame (new PrimitiveCombination2Frame0 (this, environment)); //answer = Interpreter.UnwindStack; //environment = env; //return false; } //bool x = (ev1 is char); //bool y = (ev1 is Character); //if (x != y) Debugger.Break (); answer = ((ev1 is char) && (this.rand0Value == (char) ev1)) ? Constant.sharpT : Constant.sharpF; return false; }
public Request(SHA sha, string shaInSignature, string pspID, int orderID, decimal price, Encoding encoding, Environment environment) { if (string.IsNullOrWhiteSpace(shaInSignature)) { throw new ArgumentException("SHA-IN is required"); } if (string.IsNullOrWhiteSpace(pspID)) { throw new ArgumentException("PSPID is required"); } if (orderID < 1) { throw new ArgumentException("Invalid Order ID"); } if (price <= 0) { throw new ArgumentException("Invalid price"); } this._sha = sha; this._shaInSignature = shaInSignature; this._pspID = pspID; this._orderID = orderID; this._price = price; extrafields = new Dictionary<InFields, string>(); this.Encoding = encoding; this.Environment = environment; }
private static UrchinAnalyticsClient CreateSampleClient(Action<Uri> sender) { var configuration = new UrchinConfiguration("UA-1234-5", "FindHostName"); var sessionManager = new SessionManager(TimeSpan.FromDays(1), null); var environment = new Environment("en-gb"); return new UrchinAnalyticsClient(configuration, sessionManager, environment, sender); }
private IEnumerable<Event> TestDiscreteTimeSteps(Environment env, List<DateTime> log) { while (true) { log.Add(env.Now); yield return env.Timeout(TimeSpan.FromSeconds(1)); } }
public Plant(int _x, int _y, Environment env) : base("bush", env) { x = _x; y = _y; init(); }
public override Statistics run() { Environment env = new Environment(); //dist List<double> valueList = new List<double>() { 1, 2, 3, 4, 5 }; List<double> distribution = new List<double>() { 0.5, 0.6, 0.7, 0.8, 1.0 }; Discrete d = new Discrete(valueList, distribution); //dist1 Uniform n = new Uniform(1, 3); Distribution dist = new Distribution(d); Distribution dist1 = new Distribution(n); Create c = new Create(env, 0, 20, dist); Dispose di = new Dispose(env, 1); Queue q = new Queue(env, 3); q.Capacity = 1; Resource r = new Resource(env, 2, 1, dist1, q); c.Next_AID.Add("First", 2); r.Next_AID.Add("First", 1); env.System_Time = new DateTime(1970, 1, 1, 0, 0, 0); env.Start_Time = new DateTime(1970, 1, 1, 0, 0, 0); env.Setup_Simulation(); return env.Simulate(); }
public object ExpandList(IList<object> node, int backquoteDepth, Environment environment) { var result = new List<object>(); foreach (var child in node) { var t = child.GetType(); if (t == typeof(SpliceNode)) { var spliceList = evaluator.Evaluate(Expand(((SpliceNode)child).InnerValue, backquoteDepth - 1, environment), environment) as IList<object>; if (spliceList == null) { throw new ArgumentException("Cannot splice non-list!"); } result.AddRange(spliceList); } else if (t == typeof(List<object>) || t == typeof(UnquoteNode)) { result.Add(Expand(child, backquoteDepth, environment)); } else { result.Add(child); } } return result; }
public void TestTriggeredTimeout() { var env = new Environment(); env.Process(TestTriggeredTimeout(env)); env.Run(); Assert.AreEqual(2, env.NowD); }
public Configuration() { EnvironmentSettings = new Environment(); AgentSettings = new Agent(); TagSettings = new Tag(); ResourceSettings = new Resource(); }
static IEnumerable<Event> Benchmark2Source(Environment env) { while (true) { yield return env.Process(Benchmark2Sink(env)); perf++; } }
/// <summary> /// Initializes a new instance of the <see cref="Subrule"/> class. /// </summary> /// <param name="rhs">The RHS.</param> /// <param name="env">The environment.</param> /// <param name="rule">The phonological rule.</param> /// <exception cref="System.ArgumentException">Thrown when the size of the RHS is greater than the /// size of the specified rule's LHS and the LHS's size is greater than 1. A standard phonological /// rule does not currently support this type of widening.</exception> public Subrule(PhoneticPattern rhs, Environment env, StandardPhonologicalRule rule) { m_rhs = rhs; m_env = env; m_rule = rule; switch (Type) { case ChangeType.NARROW: case ChangeType.EPENTHESIS: // analysis target is a copy of the RHS, because there is no LHS m_analysisTarget = m_rhs.Clone(); break; case ChangeType.WIDEN: // before generating the analysis we must extend the length of the LHS // to match the length of the RHS PhoneticPattern lhs = m_rule.m_lhs.Clone(); while (lhs.Count != m_rhs.Count) lhs.Add(lhs.First.Clone()); m_analysisTarget = m_rhs.Combine(lhs); break; case ChangeType.FEATURE: m_analysisTarget = m_rhs.Combine(m_rule.m_lhs); break; case ChangeType.UNKNOWN: throw new ArgumentException(HCStrings.kstidInvalidSubruleType, "rhs"); } }
public Schema(Environment env, IndexMap indexMap) { Id = env.NextPropertyMapId(); Env = env; IndexMap = indexMap; SubSchemas = new SchemaMap(); }
/// <summary> /// Performs an update of the mod loader. /// </summary> public async Task Update() { if (ApplicationInstanceTracker.GetAllProcesses(out var processes)) { ActionWrappers.ExecuteWithApplicationDispatcher(() => { // Accumulate list of processes. string allProcessString = $"\n{Resources.UpdateLoaderProcessList.Get()}:"; foreach (var process in processes) { allProcessString += $"\n({process.Id}) {process.ProcessName}"; } Actions.DisplayMessagebox.Invoke(Resources.UpdateLoaderRunningTitle.Get(), Resources.UpdateLoaderRunningMessage.Get() + allProcessString, new Actions.DisplayMessageBoxParams() { StartupLocation = Actions.WindowStartupLocation.CenterScreen }); }); } else { _manager.OnApplySelfUpdate += OnApplySelfUpdate; await _manager.PrepareUpdateAsync(_targetVersion, new Progress <double>(d => { Progress = d * 100; })); await _manager.StartUpdateAsync(_targetVersion, new OutOfProcessOptions() { Restart = true }, new UpdateOptions() { CleanupAfterUpdate = true }); Environment.Exit(0); } }
public OfWord(Environment env) : base("of", env) { OfBodyWord = new ControlFlowWord("of-body", env); PrimitiveExecuteAction = executeOf; }
static IEnumerable<Event> Benchmark1Proc(Environment env, int n) { while (true) { yield return env.TimeoutUniform(TimeSpan.Zero, TimeSpan.FromSeconds(2 * n)); perf++; } }
void getPath() { audioFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).Replace("\\", "/"); audioFolderPath += "/My Games/Containment Breach VR/Custom Radio Tracks/"; System.IO.Directory.CreateDirectory(audioFolderPath); Debug.Log(audioFolderPath); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = new Environment(); if (context != null) foreach (var kv in context) env[kv.Key] = kv.Value; env.Headers = head.Headers ?? new Dictionary<string, string>(); env.Method = head.Method ?? ""; env.Path = head.Path ?? ""; env.PathBase = ""; env.QueryString = head.QueryString ?? ""; env.Scheme = "http"; // XXX env.Version = "1.0"; if (body == null) env.Body = null; else env.Body = (onData, onError, onEnd) => { var d = body.Connect(new DataConsumer(onData, onError, onEnd)); return () => { if (d != null) d.Dispose(); }; }; appDelegate(env, HandleResponse(response), HandleError(response)); }
public void TestInitialiContainerCapacity() { var env = new Environment(); var container = new Container(env); Assert.AreEqual(0, container.Level); Assert.AreEqual(double.MaxValue, container.Capacity); }
/// <summary> /// Intercepts logs from the console and provides the ability to flush them to a file in the event of a crash. /// </summary> /// <param name="logger">The logger to intercept logs from.</param> /// <param name="outputDir">The directory to which the log is output to.</param> public LogWriter(Logger logger, string outputDir) { var executableName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]); var universalDateTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH.mm.ss"); Directory.CreateDirectory(outputDir); _logItems = new List <string>(MaxBufferLength + 1); _logger = logger; _logger.OnPrintMessage += OnPrintMessage; // Add integer to file path in case there is another instance of same process launched at the same time. string GetLogFilePath() { for (int x = 0; x < short.MaxValue; x++) { var filePath = x == 0 ? Path.Combine(outputDir, $"{universalDateTime} ~ {executableName}.txt") : Path.Combine(outputDir, $"{universalDateTime} ~ {executableName} [{x}].txt"); if (!File.Exists(filePath)) { return(filePath); } } return(default);
private static void PopulateCommandLineArgs() { string[] args = Environment.GetCommandLineArgs(); for (int index = 1; index < args.Length; index += 2) { _commandLineArguments.Add(args[index], args[index + 1]); } }
/// <summary> /// Sets the Reloaded Mod Loader DLL paths for a launcher config. /// </summary> private static void SetLoaderPaths(LoaderConfig config, string launcherDirectory) { if (String.IsNullOrEmpty(launcherDirectory)) { throw new DllNotFoundException("The provided launcher directory is null or empty. This is a bug. Report this to the developer."); } config.UpdatePaths(launcherDirectory, Resources.ErrorLoaderNotFound.Get()); // Update Environment Variables Task.Run(() => Environment.SetEnvironmentVariable("RELOADEDIIMODS", config.GetModConfigDirectory(), EnvironmentVariableTarget.User)); }
public static string getGameDataPath() { string gameDataPath; #if UNITY_STANDALONE_WIN gameDataPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).Replace("\\", "/"); gameDataPath += "/My Games/Mindys/Saves"; #else savedGamesPath = Application.persistentDataPath + "/"; #endif return(gameDataPath); }
/// <inheritdoc /> public void Execute(object?parameter) { var loaderConfig = IoC.Get <LoaderConfig>(); var shell = (IShellLink) new ShellLink(); var appLocation = ApplicationConfig.GetAbsoluteAppLocation(_config); shell.SetDescription($"Launch {_config?.Config.AppName} via Reloaded II"); shell.SetPath($"\"{loaderConfig.LauncherPath}\""); shell.SetArguments($"{Constants.ParameterLaunch} \"{appLocation}\""); shell.SetWorkingDirectory(Path.GetDirectoryName(loaderConfig.LauncherPath) !); if (_config != null) { var hasIcon = _config.Config.TryGetApplicationIcon(_config.Path, out var logoPath); if (hasIcon) { // Make path for icon. string newPath = Path.ChangeExtension(logoPath, ".ico"); // Convert to ICO. _iconConverter.TryConvertToIcon(logoPath, newPath); shell.SetIconLocation(newPath, 0); } else { shell.SetIconLocation(appLocation, 0); } } // Save the shortcut. var file = (IPersistFile)shell; var link = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), $"{_config?.Config.AppName} (Reloaded).lnk"); file.Save(link, false); Actions.DisplayMessagebox?.Invoke(Resources.AddAppShortcutCreatedTitle.Get(), $"{Resources.AddAppShortcutCreatedMessage.Get()} {link}", new Actions.DisplayMessageBoxParams() { StartupLocation = Actions.WindowStartupLocation.CenterScreen }); }
private static string ResolveRelativePathToProgramFiles(string relativeX86Path, string relativeX64Path, string errorMessge) { string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); string path = Path.Combine(programFiles, relativeX86Path); if (!File.Exists(path)) { programFiles = SystemEnvironment.GetEnvironmentVariable(ProgramFiles64bitKey) ?? SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFiles); path = Path.Combine(programFiles, relativeX64Path); } if (!File.Exists(path)) { throw new InvalidOperationException(errorMessge); } return(path); }
/// <summary/> public static string GetEnvironmentVariable(string variable) { return(TrustedEnvironment.GetEnvironmentVariable(variable)); }
private PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript) { // since we control output in the host, always set these true Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true"); var result = new PowerShellExecutionResults(); string commandToRun = wrap_script_with_module(chocoPowerShellScript, config); var host = new PoshHost(config); this.Log().Debug(() => "Calling built-in PowerShell host with ['{0}']".format_with(commandToRun.escape_curly_braces())); var initialSessionState = InitialSessionState.CreateDefault(); // override system execution policy without accidentally setting it initialSessionState.AuthorizationManager = new AuthorizationManager("choco"); using (var runspace = RunspaceFactory.CreateRunspace(host, initialSessionState)) { runspace.Open(); // this will affect actual execution policy //RunspaceInvoke invoker = new RunspaceInvoke(runspace); //invoker.Invoke("Set-ExecutionPolicy ByPass"); using (var pipeline = runspace.CreatePipeline()) { // The powershell host itself handles the following items: // * Write-Debug // * Write-Host // * Write-Verbose // * Write-Warning // // the two methods below will pick up Write-Output and Write-Error // Write-Output pipeline.Output.DataReady += (sender, args) => { PipelineReader <PSObject> reader = sender as PipelineReader <PSObject>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteLine(reader.Read().to_string().escape_curly_braces()); } } }; // Write-Error pipeline.Error.DataReady += (sender, args) => { PipelineReader <object> reader = sender as PipelineReader <object>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteErrorLine(reader.Read().to_string().escape_curly_braces()); } } }; var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify); var currentUserCurrentHostProfile = _fileSystem.combine_paths(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1"); var recreateProfileScript = @" if ((Test-Path(""{0}"")) -and ($profile -eq $null -or $profile -eq '')) {{ $global:profile = ""{1}"" }} ".format_with(documentsFolder, currentUserCurrentHostProfile); pipeline.Commands.Add(new Command(recreateProfileScript, isScript: true, useLocalScope: false)); // The PowerShell Output Redirection bug affects System.Management.Automation // it appears with v3 more than others. It is already known to affect v2 // this implements the redirection fix from the post below, fixed up with some comments // http://www.leeholmes.com/blog/2008/07/30/workaround-the-os-handles-position-is-not-what-filestream-expected/ const string outputRedirectionFixScript = @" try { $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $objectRef = $host.GetType().GetField(""externalHostRef"", $bindingFlags).GetValue($host) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetProperty"" $consoleHost = $objectRef.GetType().GetProperty(""Value"", $bindingFlags).GetValue($objectRef, @()) [void] $consoleHost.GetType().GetProperty(""IsStandardOutputRedirected"", $bindingFlags).GetValue($consoleHost, @()) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $field = $consoleHost.GetType().GetField(""standardOutputWriter"", $bindingFlags) $field.SetValue($consoleHost, [Console]::Out) [void] $consoleHost.GetType().GetProperty(""IsStandardErrorRedirected"", $bindingFlags).GetValue($consoleHost, @()) $field2 = $consoleHost.GetType().GetField(""standardErrorWriter"", $bindingFlags) $field2.SetValue($consoleHost, [Console]::Error) } catch { Write-Output ""Unable to apply redirection fix"" } "; pipeline.Commands.Add(new Command(outputRedirectionFixScript, isScript: true, useLocalScope: false)); pipeline.Commands.Add(new Command(commandToRun, isScript: true, useLocalScope: false)); try { pipeline.Invoke(); } catch (RuntimeException ex) { var errorStackTrace = ex.StackTrace; var record = ex.ErrorRecord; if (record != null) { // not available in v1 //errorStackTrace = record.ScriptStackTrace; var scriptStackTrace = record.GetType().GetProperty("ScriptStackTrace"); if (scriptStackTrace != null) { var scriptError = scriptStackTrace.GetValue(record, null).to_string(); if (!string.IsNullOrWhiteSpace(scriptError)) { errorStackTrace = scriptError; } } } this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, errorStackTrace.escape_curly_braces()))); } catch (Exception ex) { // Unfortunately this doesn't print line number and character. It might be nice to get back to those items unless it involves tons of work. this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, ex.StackTrace.escape_curly_braces()))); } if (pipeline.PipelineStateInfo != null) { switch (pipeline.PipelineStateInfo.State) { // disconnected is not available unless the assembly version is at least v3 //case PipelineState.Disconnected: case PipelineState.Running: case PipelineState.NotStarted: case PipelineState.Failed: case PipelineState.Stopping: case PipelineState.Stopped: if (host.ExitCode == 0) { host.SetShouldExit(1); } host.HostException = pipeline.PipelineStateInfo.Reason; break; case PipelineState.Completed: if (host.ExitCode == -1) { host.SetShouldExit(0); } break; } } } } this.Log().Debug("Built-in PowerShell host called with ['{0}'] exited with '{1}'.".format_with(commandToRun.escape_curly_braces(), host.ExitCode)); result.ExitCode = host.ExitCode; result.StandardErrorWritten = host.StandardErrorWritten; return(result); }
internal static string ResolveFSharpCPath() { string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); return(Path.Combine(programFiles, @"Microsoft SDKs", "F#", "3.1", "Framework", "v4.0", "Fsc.exe")); }
public string GetLocalFilePath(string filename) { string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); return(Path.Combine(path, filename)); }
public bool run_action(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command) { var installerRun = false; var packageDirectory = packageResult.InstallLocation; if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) { packageResult.Messages.Add( new ResultMessage( ResultType.Error, "Install location is not specific enough, cannot run PowerShell script:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation) ) ); return(false); } if (!_fileSystem.directory_exists(packageDirectory)) { packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Package install not found:'{0}'".format_with(packageDirectory))); return(installerRun); } var chocoPowerShellScript = get_script_for_action(packageResult, command); if (!string.IsNullOrEmpty(chocoPowerShellScript)) { var failure = false; ConfigurationBuilder.set_environment_variables(configuration); var package = packageResult.Package; Environment.SetEnvironmentVariable("chocolateyPackageName", package.Id); Environment.SetEnvironmentVariable("packageName", package.Id); Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Version.to_string()); Environment.SetEnvironmentVariable("packageVersion", package.Version.to_string()); Environment.SetEnvironmentVariable("chocolateyPackageFolder", packageDirectory); Environment.SetEnvironmentVariable("packageFolder", packageDirectory); // unset variables that may not be updated so they don't get passed again Environment.SetEnvironmentVariable("installArguments", null); Environment.SetEnvironmentVariable("installerArguments", null); Environment.SetEnvironmentVariable("chocolateyInstallArguments", null); Environment.SetEnvironmentVariable("packageParameters", null); Environment.SetEnvironmentVariable("chocolateyPackageParameters", null); Environment.SetEnvironmentVariable("chocolateyInstallOverride", null); // we only want to pass the following args to packages that would apply. // like choco install git -params '' should pass those params to git.install, // but not another package if (!package_is_a_dependency_not_a_virtual(configuration, package.Id)) { this.Log().Debug(ChocolateyLoggers.Verbose, "Setting installer args and package parameters for {0}".format_with(package.Id)); Environment.SetEnvironmentVariable("installArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("installerArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("chocolateyInstallArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("packageParameters", configuration.PackageParameters); Environment.SetEnvironmentVariable("chocolateyPackageParameters", configuration.PackageParameters); if (configuration.OverrideArguments) { Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true"); } } if (configuration.ForceX86) { Environment.SetEnvironmentVariable("chocolateyForceX86", "true"); } if (configuration.NotSilent) { Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true"); } //todo:if (configuration.NoOutput) //{ // Environment.SetEnvironmentVariable("ChocolateyEnvironmentQuiet","true"); //} if (package.IsDownloadCacheAvailable) { foreach (var downloadCache in package.DownloadCache.or_empty_list_if_null()) { var urlKey = CryptoHashProvider.hash_value(downloadCache.OriginalUrl, CryptoHashProviderType.Sha256).Replace("=", string.Empty); Environment.SetEnvironmentVariable("CacheFile_{0}".format_with(urlKey), downloadCache.FileName); Environment.SetEnvironmentVariable("CacheChecksum_{0}".format_with(urlKey), downloadCache.Checksum); Environment.SetEnvironmentVariable("CacheChecksumType_{0}".format_with(urlKey), "sha512"); } } this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".format_with(chocoPowerShellScript)); string chocoPowerShellScriptContents = _fileSystem.read_file(chocoPowerShellScript); this.Log().Debug(chocoPowerShellScriptContents.escape_curly_braces()); bool shouldRun = !configuration.PromptForConfirmation; if (!shouldRun) { this.Log().Info(ChocolateyLoggers.Important, () => "The package {0} wants to run '{1}'.".format_with(package.Id, _fileSystem.get_file_name(chocoPowerShellScript))); this.Log().Info(ChocolateyLoggers.Important, () => "Note: If you don't run this script, the installation will fail."); this.Log().Info(ChocolateyLoggers.Important, () => @"Note: To confirm automatically next time, use '-y' or consider setting 'allowGlobalConfirmation'. Run 'choco feature -h' for more details."); var selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run the script?", new[] { "yes", "no", "print" }, defaultChoice: null, requireAnswer: true, allowShortAnswer: true, shortPrompt: true ); if (selection.is_equal_to("print")) { this.Log().Info(ChocolateyLoggers.Important, "------ BEGIN SCRIPT ------"); this.Log().Info(() => "{0}{1}{0}".format_with(Environment.NewLine, chocoPowerShellScriptContents.escape_curly_braces())); this.Log().Info(ChocolateyLoggers.Important, "------- END SCRIPT -------"); selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run this script?", new[] { "yes", "no" }, defaultChoice: null, requireAnswer: true, allowShortAnswer: true, shortPrompt: true ); } if (selection.is_equal_to("yes")) { shouldRun = true; } if (selection.is_equal_to("no")) { Environment.ExitCode = 1; packageResult.Messages.Add(new ResultMessage(ResultType.Error, "User cancelled powershell portion of installation for '{0}'.{1} Specify -n to skip automated script actions.".format_with(chocoPowerShellScript, Environment.NewLine))); } } if (shouldRun) { installerRun = true; if (configuration.Features.UsePowerShellHost) { add_assembly_resolver(); } var result = new PowerShellExecutionResults { ExitCode = -1 }; try { result = configuration.Features.UsePowerShellHost ? Execute.with_timeout(configuration.CommandExecutionTimeoutSeconds).command(() => run_host(configuration, chocoPowerShellScript), result) : run_external_powershell(configuration, chocoPowerShellScript); } catch (Exception ex) { this.Log().Error(ex.Message.escape_curly_braces()); result.ExitCode = -1; } if (configuration.Features.UsePowerShellHost) { remove_assembly_resolver(); } if (result.StandardErrorWritten && configuration.Features.FailOnStandardError) { failure = true; } else if (result.StandardErrorWritten && result.ExitCode == 0) { this.Log().Warn( () => @"Only an exit code of non-zero will fail the package by default. Set `--failonstderr` if you want error messages to also fail a script. See `choco -h` for details."); } if (result.ExitCode != 0) { Environment.ExitCode = result.ExitCode; packageResult.ExitCode = result.ExitCode; } // 0 - most widely used success exit code // MSI valid exit codes // 1605 - (uninstall) - the product is not found, could have already been uninstalled // 1614 (uninstall) - the product is uninstalled // 1641 - restart initiated // 3010 - restart required var validExitCodes = new List <int> { 0, 1605, 1614, 1641, 3010 }; if (!validExitCodes.Contains(result.ExitCode)) { failure = true; } if (failure) { packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Error while running '{0}'.{1} See log for details.".format_with(chocoPowerShellScript, Environment.NewLine))); } packageResult.Messages.Add(new ResultMessage(ResultType.Note, "Ran '{0}'".format_with(chocoPowerShellScript))); } } return(installerRun); }
// ReSharper disable InconsistentNaming private static void Main(string[] args) // ReSharper restore InconsistentNaming { try { add_assembly_resolver(); string loggingLocation = ApplicationParameters.LoggingLocation; //no file system at this point if (!Directory.Exists(loggingLocation)) { Directory.CreateDirectory(loggingLocation); } Log4NetAppenderConfiguration.configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.to_string()); Bootstrap.initialize(); Bootstrap.startup(); var license = License.validate_license(); var container = SimpleInjectorContainer.Container; "LogFileOnly".Log().Info(() => "".PadRight(60, '=')); var config = Config.get_configuration_settings(); var fileSystem = container.GetInstance <IFileSystem>(); var warnings = new List <string>(); ConfigurationBuilder.set_up_configuration( args, config, container, license, warning => { warnings.Add(warning); } ); if (config.Features.LogWithoutColor) { ApplicationParameters.Log4NetConfigurationResource = @"chocolatey.infrastructure.logging.log4net.nocolor.config.xml"; Log4NetAppenderConfiguration.configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.to_string()); } if (!string.IsNullOrWhiteSpace(config.AdditionalLogFileLocation)) { Log4NetAppenderConfiguration.configure_additional_log_file(fileSystem.get_full_path(config.AdditionalLogFileLocation)); } report_version_and_exit_if_requested(args, config); trap_exit_scenarios(config); warn_on_nuspec_or_nupkg_usage(args, config); if (config.RegularOutput) { #if DEBUG "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty)); #else "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty)); #endif if (args.Length == 0) { "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "Please run 'choco -?' or 'choco <command> -?' for help menu."); } } if (warnings.Count != 0 && config.RegularOutput) { foreach (var warning in warnings.or_empty_list_if_null()) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning); } } if (config.HelpRequested || config.UnsuccessfulParsing) { pause_execution_if_debug(); Environment.Exit(config.UnsuccessfulParsing ? 1 : 0); } var verboseAppenderName = "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string()); var traceAppenderName = "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Trace.to_string()); Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug, verboseAppenderName, traceAppenderName); Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, config.Debug, verboseAppenderName); Log4NetAppenderConfiguration.set_trace_logger_when_trace(config.Trace, traceAppenderName); "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string())); //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine)); remove_old_chocolatey_exe(fileSystem); AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(Program)), ApplicationParameters.InstallLocation, new List <string>(), "chocolatey.console", throwError: false); //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList <string> folders = new List <string> { "helpers", "functions", "redirects", "tools" }; #if !NoResources AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources, throwError: false); #endif var application = new ConsoleApplication(); application.run(args, config, container); } catch (Exception ex) { if (ApplicationParameters.is_debug_mode_cli_primitive()) { "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with( ApplicationParameters.Name, Environment.NewLine, ex.ToString())); } else { "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message)); "chocolatey".Log().Error(ChocolateyLoggers.LogFileOnly, () => "More Details: {0}".format_with(ex.ToString())); } if (Environment.ExitCode == 0) { Environment.ExitCode = 1; } } finally { "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode)); #if DEBUG "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode)); #endif pause_execution_if_debug(); Bootstrap.shutdown(); Environment.Exit(Environment.ExitCode); } }
internal override string ResolveMSBuild15Dir() { string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); return(Path.Combine(programFiles, "MSBuild-15.3.409.57025", "MSBuild", "15.0", "Bin")); }
internal override string ResolveNpmGlobalPrefix() { string appDataDirectory = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ApplicationData); return(Path.Combine(appDataDirectory, "npm")); }
internal override string ResolveVsTestPath() { string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); return(Path.Combine(programFiles, "Microsoft Visual Studio 11.0", "Common7", "IDE", "CommonExtensions", "Microsoft", "TestWindow", "vstest.console.exe")); }
internal override string ResolveSQLCmdPath() { string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); return(Path.Combine(programFiles, "Microsoft SQL Server", "110", "Tools", "Binn", "sqlcmd.exe")); }
/// <summary/> public static string ExpandEnvironmentVariables(String name) { return(TrustedEnvironment.ExpandEnvironmentVariables(name)); }
internal override string ResolveMSBuildPath() { string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); return(Path.Combine(programFiles, "MSBuild", "14.0", "Bin", "MSBuild.exe")); }
public static bool IsCI() { return(!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("BUILD_NUMBER"))); }
static void Main(string[] args) { var options = new Options(); var modifed = new List <string>(); if (args != null) { if (args.Length == 1 && !args[0].StartsWith("-")) { modifed.Add("-f"); modifed.Add(args[0]); } else { modifed.AddRange(args); } } if (!CommandLine.Parser.Default.ParseArguments(modifed.ToArray(), options)) { Environment.ExitCode = Error; return; } var request = new Request(options.File) { Configuration = options.Configuration ?? "default.xml", Types = options.Types, View = options.Table, Provider = options.Provider, Server = options.Server, Database = options.Database, Schema = options.Schema, User = options.User, Password = options.Password, Port = options.Port }; if (!request.IsValid()) { Console.Error.WriteLine(request.Message); Environment.Exit(Error); } try { using (var bootstrapper = new Bootstrapper(request)) { var cfg = bootstrapper.Resolve <Cfg>(); if (cfg.Errors().Any()) { foreach (var error in cfg.Errors()) { Console.Error.WriteLine(error); Environment.ExitCode = Error; } } else { var response = bootstrapper.Resolve <Importer>().Import(); if (response.Records != 0) { return; } Console.Error.WriteLine("Did not import any records!"); Environment.ExitCode = Error; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); Environment.ExitCode = Error; } Environment.ExitCode = 0; }
public static void Exit(int exitCode) { BeforeClose(); Environment.Exit(exitCode); }
// ReSharper disable InconsistentNaming private static void Main(string[] args) // ReSharper restore InconsistentNaming { try { string loggingLocation = ApplicationParameters.LoggingLocation; //no file system at this point if (!Directory.Exists(loggingLocation)) { Directory.CreateDirectory(loggingLocation); } Log4NetAppenderConfiguration.configure(loggingLocation); Bootstrap.initialize(); Bootstrap.startup(); var container = SimpleInjectorContainer.Container; var config = container.GetInstance <ChocolateyConfiguration>(); var fileSystem = container.GetInstance <IFileSystem>(); var warnings = new List <string>(); ConfigurationBuilder.set_up_configuration( args, config, fileSystem, container.GetInstance <IXmlService>(), warning => { warnings.Add(warning); } ); Config.initialize_with(config); report_version_and_exit_if_requested(args, config); trap_exit_scenarios(config); if (config.RegularOuptut) { "logfile".Log().Info(() => "".PadRight(60, '=')); #if DEBUG "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion)); #else "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion)); #endif } if (warnings.Count != 0 && config.RegularOuptut) { foreach (var warning in warnings.or_empty_list_if_null()) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning); } } if (config.HelpRequested) { pause_execution_if_debug(); Environment.Exit(-1); } Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, ChocolateyLoggers.Verbose.to_string()); Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug); "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string())); //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine)); warn_when_admin_needs_elevation(config); remove_old_chocolatey_exe(fileSystem); LicenseValidation.validate(fileSystem); //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList <string> folders = new List <string> { "helpers", "functions", "redirects", "tools" }; AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources); var application = new ConsoleApplication(); application.run(args, config, container); } catch (Exception ex) { var debug = false; // no access to the good stuff here, need to go a bit primitive in parsing args foreach (var arg in args.or_empty_list_if_null()) { if (arg.Contains("debug") || arg.is_equal_to("-d") || arg.is_equal_to("/d")) { debug = true; break; } } if (debug) { "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with( ApplicationParameters.Name, Environment.NewLine, ex.ToString())); } else { "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message)); } Environment.ExitCode = 1; } finally { "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode)); #if DEBUG "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode)); #endif pause_execution_if_debug(); Bootstrap.shutdown(); Environment.Exit(Environment.ExitCode); } }
static void StartUp() { RunningOnCI = !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CI_SERVER")); RunningOnLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); if (RunningOnLinux) { ConsoleWrapper.WriteLine("Linux Environment detected!"); } Directory.SetCurrentDirectory(Path.GetDirectoryName(ExePath)); if (RunningOnCI) { ConsoleWrapper.WriteLine("CI Environment detected!"); } else { if (runConfig == "Debug") { Console.Title = "MEE7 - DEBUG"; } else { Console.Title = "MEE7"; } //if (!RunningOnLinux) // ShowWindow(GetConsoleWindow(), 2); Thread.CurrentThread.Name = "Main"; Console.ForegroundColor = ConsoleColor.White; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal; handler = new ConsoleEventDelegate(ConsoleEventCallback); if (!RunningOnLinux) { SetConsoleCtrlHandler(handler, true); } } LoadBuildDate(); //UpdateYTDL(); var config = new DiscordSocketConfig() { GatewayIntents = GatewayIntents.All, AlwaysDownloadUsers = true, }; client = new DiscordSocketClient(config); SetClientEvents(); Login(); CreateCommandInstances(); while (!ClientReady || client.ConnectionState != ConnectionState.Connected) { Thread.Sleep(50); } SetState(); CurrentChannel = (ISocketMessageChannel)client.GetChannel(473991188974927884); Thread.Sleep(1000); Master = client.GetUser(300699566041202699); DiscordNETWrapper.SendText(logStartupMessage, (IMessageChannel)GetChannelFromID(logChannel)).Wait(); Config.Load(); BuildHelpMenu(); StartAutosaveLoop(); Task.Run(() => BootTwitterModule()); CallOnConnected(); }
private ICommand find_command(ChocolateyConfiguration config, Container container, bool isConsole, Action <ICommand> parseArgs) { var commands = container.GetAllInstances <ICommand>(); var command = commands.Where((c) => { var attributes = c.GetType().GetCustomAttributes(typeof(CommandForAttribute), false); return(attributes.Cast <CommandForAttribute>().Any(attribute => attribute.CommandName.is_equal_to(config.CommandName))); }).FirstOrDefault(); if (command == null) { //todo add a search among other location/extensions for the command if (!string.IsNullOrWhiteSpace(config.CommandName)) { throw new Exception(@"Could not find a command registered that meets '{0}'. Try choco -? for command reference/help.".format_with(config.CommandName)); } if (isConsole) { Environment.ExitCode = 1; } } else { if (parseArgs != null) { parseArgs.Invoke(command); } if (command.may_require_admin_access()) { warn_when_admin_needs_elevation(config); } set_source_type(config); // guaranteed that all settings are set. EnvironmentSettings.set_environment_variables(config); this.Log().Debug(() => "Configuration: {0}".format_with(config.ToString())); if (isConsole && config.HelpRequested) { #if DEBUG Console.WriteLine("Press enter to continue..."); Console.ReadKey(); #endif Environment.Exit(1); } var token = Assembly.GetExecutingAssembly().get_public_key_token(); if (string.IsNullOrWhiteSpace(token) || !token.is_equal_to(ApplicationParameters.OfficialChocolateyPublicKey)) { if (!config.AllowUnofficialBuild) { throw new Exception(@" Custom unofficial builds are not allowed by default. To override this behavior, explicitly set --allow-unofficial. See the help menu (choco -h) for options."); } else { this.Log().Warn(ChocolateyLoggers.Important, @" Chocolatey is not an official build (bypassed with --allow-unofficial). If you are seeing this message and it is not expected, your system may now be in a bad state. Only official builds are to be trusted. " ); } } } return(command); }
// Compute the site ID, for both the top level function API case and the regular nested case private FunctionEnvelope AddFunctionAppIdToEnvelope(FunctionEnvelope function) { Uri referrer = Request.Headers.Referrer; if (referrer == null) { return(function); } string armId = referrer.AbsolutePath; const string msWeb = "Microsoft.Web"; const string functionResource = msWeb + "/functions"; const string sitesResource = msWeb + "/sites"; // Input: /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/functions/{funcname} int index = armId.IndexOf(functionResource, StringComparison.OrdinalIgnoreCase); if (index > 0) { // Produce: /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{sitename} function.FunctionAppId = $"{armId.Substring(0, index)}{sitesResource}/{Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME")}"; return(function); } // Input: /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{sitename}/functions/{funcname} index = armId.IndexOf(sitesResource, StringComparison.OrdinalIgnoreCase); if (index > 0) { // Produce: /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{sitename} index = armId.IndexOf("/", index + sitesResource.Length + 1, StringComparison.OrdinalIgnoreCase); function.FunctionAppId = armId.Substring(0, index); return(function); } return(function); }
internal static string ResolveMSBuildPath() { string windir = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.Windows); return(Path.Combine(windir, @"Microsoft.NET", "Framework", "v4.0.30319", "MSBuild.exe")); }
internal static string ResolveHgPath() { string programFiles32 = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); string path = Path.Combine(programFiles32, "Mercurial", "hg.exe"); if (!File.Exists(path)) { string programFiles = SystemEnvironment.GetEnvironmentVariable(ProgramFiles64bitKey) ?? SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFiles); path = Path.Combine(programFiles, "Mercurial", "hg.exe"); if (!File.Exists(path)) { throw new InvalidOperationException(Resources.Error_FailedToLocateHg); } } return(path); }
string GetDocsPath() { return(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); }