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); }
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); }
static async Task Main() { var serviceProvider = CreateServices(); using (var scope = serviceProvider.CreateScope()) { UpdateDatabase(scope.ServiceProvider); } var endPointName = "Transactions.NSBEndpoint"; Console.Title = endPointName; var endpointConfiguration = new EndpointConfiguration(endPointName); var transport = endpointConfiguration.UseTransport <RabbitMQTransport>(); transport.UseConventionalRoutingTopology(); string rabbitmqUrl = Environment.GetEnvironmentVariable("RABBITMQ_PCF_NSB_URL"); transport.ConnectionString(rabbitmqUrl); string mysqlConnectionString = Environment.GetEnvironmentVariable("MYSQL_STRCON_CORE_TRANSACTIONS"); var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>(); persistence.UseOutboxRecord <Outbox, OutboxMap>(); var nHibernateConfig = new Configuration(); nHibernateConfig.SetProperty(NHEnvironment.ConnectionProvider, typeof(NHibernate.Connection.DriverConnectionProvider).FullName); nHibernateConfig.SetProperty(NHEnvironment.ConnectionDriver, typeof(NHibernate.Driver.MySqlDataDriver).FullName); nHibernateConfig.SetProperty(NHEnvironment.Dialect, typeof(NHibernate.Dialect.MySQLDialect).FullName); nHibernateConfig.SetProperty(NHEnvironment.ConnectionString, mysqlConnectionString); AddFluentMappings(nHibernateConfig, mysqlConnectionString); persistence.UseConfiguration(nHibernateConfig); persistence.DisableSchemaUpdate(); endpointConfiguration.EnableOutbox(); endpointConfiguration.EnableInstallers(); endpointConfiguration.AuditProcessedMessagesTo("audit"); var routing = transport.Routing(); routing.RouteToEndpoint(typeof(WithdrawMoneyCommand).Assembly, "Accounts.NSBEndpoint"); routing.RouteToEndpoint(typeof(DepositMoneyCommand).Assembly, "Accounts.NSBEndpoint"); var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false); Console.WriteLine("Press Enter to exit."); Console.ReadLine(); await endpointInstance.Stop().ConfigureAwait(false); }
static void Main(string[] args) { var rHome = "/usr/lib/R"; string path = Environment.GetEnvironmentVariable("PATH") ?? String.Empty; // Note that using /usr/lib where a libR.so symlink exists is not good enough path = string.Concat(path, ":", "/usr/lib/R/lib"); Environment.SetEnvironmentVariable("R_HOME", rHome); Environment.SetEnvironmentVariable("PATH", path); Console.WriteLine("R init: creating R engine"); REngine rEngine = REngine.CreateInstance("RDotNet"); rEngine.Initialize(); Console.WriteLine("Created rEngine: " + rEngine.ToString()); // simple arithmetic test const string arithmeticExpression = "2 + 14 * 7"; var result = rEngine.Evaluate(arithmeticExpression).AsNumeric().ToArray(); Console.WriteLine(arithmeticExpression + " = " + result[0]); // test the problematic CreateNumericVector method // Missing method RDotNet.REngineExtension::CreateNumericVector(REngine,IEnumerable`1<double>) in assembly /data/col52j/calibration-files/bin/Release/R.NET.dll // values <- 0:99 double[] values = new double[100]; for (int i = 0; i < values.Length; i++) { values[i] = i; } rEngine.SetSymbol("values", rEngine.CreateNumericVector(values)); // calculate the sum // sum(values) # 4950 string sum = "sum(values)"; #if RDN15 result = rEngine.Evaluate(sum).AsNumeric().ToArray(); #else result = rEngine.EagerEvaluate(sum).AsNumeric().ToArray(); #endif Console.WriteLine("Sum of integer range 0:99 = " + result[0]); }
internal static string ResolveGitInstallDirPath() { // look up whether x86 or x64 of git was installed. string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); string path = Path.Combine(programFiles, "Git"); if (Directory.Exists(path) && File.Exists(Path.Combine(path, "cmd", "git.exe"))) { return(path); } programFiles = SystemEnvironment.GetEnvironmentVariable(ProgramFiles64bitKey) ?? SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFiles); path = Path.Combine(programFiles, "Git"); if (Directory.Exists(path) && File.Exists(Path.Combine(path, "cmd", "git.exe"))) { return(path); } throw new InvalidOperationException(Resources.Error_FailedToLocateGit); }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseMicrosoftLogFactoryLogging() .UseNServiceBus(hostBuilderContext => { var endPointName = "Banking.API"; string rabbitmqUrl = Environment.GetEnvironmentVariable("RABBITMQ_BANKING_NSB_CORE"); var endpointConfiguration = new EndpointConfiguration(endPointName); var transport = endpointConfiguration.UseTransport <RabbitMQTransport>(); transport.ConnectionString(rabbitmqUrl); transport.UseConventionalRoutingTopology(); var routing = transport.Routing(); routing.RouteToEndpoint(typeof(StartTransfer).Assembly, "Banking.Transactions"); endpointConfiguration.SendOnly(); return(endpointConfiguration); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>(); });
private void btnSave_Click(object sender, EventArgs e) { try { Environment.SetEnvironmentVariable("TOGGL_COM_API_KEY", txtKey.Text.Trim(), EnvironmentVariableTarget.User); if (Environment.GetEnvironmentVariable("TOGGL_COM_API_KEY", EnvironmentVariableTarget.User).Length == 0) { throw new Exception("Blank key saved - fill in your key based on what your Toggl.com profile says."); } btnSave.BackColor = Color.Green; tmrSaveColorFeedback.Enabled = true; isThereAKeySaved = true; } catch (Exception exception) { btnSave.BackColor = Color.Red; tmrSaveColorFeedback.Enabled = true; } }
private static string ResolveNpmVersion(string nodeVersion) { string programFiles = SystemEnvironment.GetFolderPath(SystemEnvironment.SpecialFolder.ProgramFilesX86); string appSettingNpmVersion = SystemEnvironment.GetEnvironmentVariable("WEBSITE_NPM_DEFAULT_VERSION"); if (!string.IsNullOrEmpty(appSettingNpmVersion)) { return(appSettingNpmVersion); } else if (nodeVersion.Equals("4.1.2", StringComparison.OrdinalIgnoreCase)) { // This case is only to work around node version 4.1.2 with npm 2.x failing to publish ASP.NET 5 apps due to long path issues. return("3.3.6"); } else { string npmTxtPath = Path.Combine(programFiles, "nodejs", nodeVersion, "npm.txt"); return(FileSystemHelpers.FileExists(npmTxtPath) ? FileSystemHelpers.ReadAllTextFromFile(npmTxtPath).Trim() : DefaultNpmVersion); } }
private static void Main(string[] args) { _environment = new HostingEnvironment { EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), ApplicationName = AppDomain.CurrentDomain.FriendlyName, ContentRootPath = AppDomain.CurrentDomain.BaseDirectory, ContentRootFileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory) }; var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json", true, true) .AddJsonFile($"appsettings.{_environment.EnvironmentName}.json", true, true) .AddEnvironmentVariables(); var configuration = builder.Build(); var myConnString = configuration.GetConnectionString("SQLConn"); MainClientAsync().GetAwaiter().GetResult(); MainAsync().GetAwaiter().GetResult(); Console.ReadLine(); }
private static async Task Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration((hostContext, configuration) => { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); }) .UseServiceProviderFactory(new DryIocServiceProviderFactory <Container>()) .ConfigureContainer <Container>((hostContext, container) => { container.RegisterAllComponents(hostContext.Configuration); container.AddAutoTx(); container.AddNHibernate(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); }) .UseNLog(); var app = builder.UseConsoleLifetime().Build(); Configure(app); await app.RunAsync(); var scope = (Logger)app.Services.GetService(typeof(Logger)); scope.WriteToLog(string.Format("{0} - Stopped", DateTime.UtcNow)); foreach (var target in LogManager.Configuration.AllTargets) { target.Dispose(); } }
/// <summary> /// Gets the only profile /// </summary> /// <returns></returns> public List <ProfilePath> getProfiles() { string userProfile = SYS.GetEnvironmentVariable("USERPROFILE"); string localAppData = SYS.GetEnvironmentVariable("LOCALAPPDATA"); // list of possible paths with the temp. // added in the order of possibility List <String> paths = new List <String>() { Util.ReadRegistryKey(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\", "Cache"), Util.ReadRegistryKey(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\", "Cache"), localAppData + @"\Microsoft\Windows\Temporary Internet Files\Low\Content.IE5", userProfile + @"\Local Settings\Temp\Temporary Internet Files\Content.IE5", userProfile + @"\Local Settings\Temporary Internet Files", userProfile + @"\Local Settings\Temp\Temporary Internet Files", userProfile + @"\Local Settings\Temporary Internet Files", }; paths.RemoveAll(d => !Directory.Exists(d)); String profile = ""; if (paths.Any()) { profile = paths.First(); } else { return(new List <ProfilePath>()); } return(new List <ProfilePath>() { new ProfilePath("Internet Explorer", profile) }); }
public static void TearDown() { var environmentVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES"); var fileContent = File.ReadAllText(environmentVariable); var vcapServices = JObject.Parse(fileContent); string _endpoint = vcapServices["discovery"][0]["credentials"]["url"].Value <string>(); string _username = vcapServices["discovery"][0]["credentials"]["username"].Value <string>(); string _password = vcapServices["discovery"][0]["credentials"]["password"].Value <string>(); DiscoveryService _discovery = new DiscoveryService(_username, _password, DiscoveryService.DISCOVERY_VERSION_DATE_2017_11_07); if (!string.IsNullOrEmpty(_createdEnvironmentId) && !string.IsNullOrEmpty(_createdCollectionId) && !string.IsNullOrEmpty(_createdDocumentId)) { _discovery.DeleteDocument(_createdEnvironmentId, _createdCollectionId, _createdDocumentId); } if (!string.IsNullOrEmpty(_createdEnvironmentId) && !string.IsNullOrEmpty(_createdCollectionId)) { _discovery.DeleteCollection(_createdEnvironmentId, _createdCollectionId); } if (!string.IsNullOrEmpty(_createdEnvironmentId) && !string.IsNullOrEmpty(_createdConfigurationId)) { _discovery.DeleteConfiguration(_createdEnvironmentId, _createdConfigurationId); } if (!string.IsNullOrEmpty(_createdEnvironmentId)) { _discovery.DeleteEnvironment(_createdEnvironmentId); } }
// 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); }
public static bool IsCI() { return(!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("BUILD_NUMBER"))); }
private string GetAppPathbase() { return(SysEnvironment.GetEnvironmentVariable( "ASPNETCORE_PATHBASE" )); }
public override void Install(IDictionary stateSaver) { base.Install(stateSaver); string regValue = ""; RegistryHelper registry = new RegistryHelper(); registry.BaseRegistryKey = Registry.LocalMachine; registry.SubKey += @"System\CurrentControlSet\Control\Session Manager\Environment"; regValue = registry.ReadKey("PATH"); string installDir = Context.Parameters["myDir"]; if (regValue != null) { // BDS: 13-11-2006 // Saving the original value and restoring it during the uninstallation would // loose the PATH information set by other software installed after WSCF. // Therefore I'm saving the installation directory to our state saver and later // using it to remove it from the PATH variable. // Consequently this line will soon become obsolete. stateSaver.Add("OriginalPathRegValue", regValue); stateSaver.Add("InstallDir", installDir); string newPathValue = regValue + ";" + installDir; registry.WriteKey("PATH", newPathValue); } // What happens if this value is null is not defined. EnvironmentHelper.BroadCast(); // BDS: Write the installation directory into the registry. // Write the .addin file to the selected folder. try { RegistryKey subkey = Registry.LocalMachine.CreateSubKey( RegistrySubKey); subkey.SetValue(Path, installDir); // Write the .addin file. ResourceManager rm = new ResourceManager("Thinktecture.Tools.Web.Services.Wscf.Environment.Properties.Resources", Assembly.GetExecutingAssembly()); string settings = rm.GetString("WSCF"); string asmPath = installDir; if (!installDir.EndsWith(@"\")) { asmPath += @"\"; } asmPath += @"Thinktecture.Tools.Web.Services.ContractFirst.dll"; settings = settings.Replace(@"@@ASM@@", asmPath); string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); settings = settings.Replace(@"@@FNVER@@", version); string configDir = null; if (Context.Parameters[@"ALLUSERS"] == @"1") { configDir = FxEnvironment.GetEnvironmentVariable(@"ALLUSERSPROFILE"); if (configDir == null) { throw new InstallException("All Users directory not found."); } configDir += @"\Application Data\Microsoft\MSEnvShared\Addins"; if (!Directory.Exists(configDir)) { Directory.CreateDirectory(configDir); } } else { configDir = FxEnvironment.GetFolderPath(FxEnvironment.SpecialFolder.ApplicationData); configDir += @"\Microsoft\MSEnvShared\Addins"; if (!Directory.Exists(configDir)) { Directory.CreateDirectory(configDir); } } string addinFile = configDir + @"\WSCF.addin"; StreamWriter writer = new StreamWriter(addinFile, false, Encoding.Unicode); writer.Write(settings); writer.Flush(); writer.Close(); stateSaver.Add(@"AddinFilePath", addinFile); } catch (SecurityException) { MessageBox.Show(@"You must have write permission to the HKEY_LOCAL_MACHINE registry key in order to install this software."); throw new InstallException(@"Access denied."); } catch (Exception ex) { throw new InstallException(@"Unknown error:" + ex.Message); } }
public string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { return(Env.GetEnvironmentVariable(variable, target)); }
/// <summary/> public static string GetEnvironmentVariable(string variable) { return(TrustedEnvironment.GetEnvironmentVariable(variable)); }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { JsonProperty property = base.CreateProperty(member, memberSerialization); if (property.PropertyName.StartsWith("UserAttribute_")) { property.PropertyName = property.PropertyName.Replace("UserAttribute", $"extension_{Env.GetEnvironmentVariable("B2CGraphApiExtensionsAppId").Replace("-","")}"); } return(property); }
public string GetEnvironmentVariable(string variableName) => SysEnv.GetEnvironmentVariable(variableName);
private static string FindMsBuildToolsPathOnWindows() { if (!OS.IsWindows) { throw new PlatformNotSupportedException(); } // Try to find 15.0 with vswhere string vsWherePath = Environment.GetEnvironmentVariable(Internal.GodotIs32Bits() ? "ProgramFiles" : "ProgramFiles(x86)"); vsWherePath += "\\Microsoft Visual Studio\\Installer\\vswhere.exe"; var vsWhereArgs = new[] { "-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild" }; var outputArray = new Godot.Collections.Array <string>(); int exitCode = Godot.OS.Execute(vsWherePath, vsWhereArgs, blocking: true, output: (Godot.Collections.Array)outputArray); if (exitCode != 0) { return(string.Empty); } if (outputArray.Count == 0) { return(string.Empty); } var lines = outputArray[0].Split('\n'); foreach (string line in lines) { int sepIdx = line.IndexOf(':'); if (sepIdx <= 0) { continue; } string key = line.Substring(0, sepIdx); // No need to trim if (key != "installationPath") { continue; } string value = line.Substring(sepIdx + 1).StripEdges(); if (value.Empty()) { throw new FormatException("installationPath value is empty"); } if (!value.EndsWith("\\")) { value += "\\"; } // Since VS2019, the directory is simply named "Current" string msbuildDir = Path.Combine(value, "MSBuild\\Current\\Bin"); if (Directory.Exists(msbuildDir)) { return(msbuildDir); } // Directory name "15.0" is used in VS 2017 return(Path.Combine(value, "MSBuild\\15.0\\Bin")); } return(string.Empty); }
public async Task <IActionResult> Create([Bind("FilePath", "Name", "Filter", "LogType", "LogInputCategory")] LogInput input) { ViewBag.LogPath = input.FilePath; ViewBag.LogName = input.Name; ViewBag.Filter = input.Filter; ViewBag.LogType = input.LogType; ViewBag.LogInput = input.LogInputCategory; string lowcap = input.Name.ToLower(); string pattern = @"[^A-Za-z0-9]+"; string replacement = "-"; string replace = Regex.Replace(lowcap, pattern, replacement); var BucketName2 = "smartinsights-" + replace; var data = "{ \r\n \"Sources\":[ \r\n { \r\n \"Id\":\"" + input.Name + "\",\r\n \"SourceType\":\"WindowsEventLogSource\",\r\n \"LogName\":\"" + input.LogType + "\",\r\n \"IncludeEventData\" : true\r\n }\r\n ],\r\n \"Sinks\":[ \r\n { \r\n \"Id\":\"" + input.Name + "Firehose\",\r\n \"SinkType\":\"KinesisFirehose\",\r\n \"AccessKey\":\"" + Environment.GetEnvironmentVariable("FIREHOSE_ACCESS_KEY_ID") + "\",\r\n \"SecretKey\":\"" + Environment.GetEnvironmentVariable("FIREHOSE_SECRET_ACCESS_KEY") + "\",\r\n \"Region\":\"ap-southeast-1\",\r\n \"StreamName\":\"" + BucketName2 + "\"\r\n \"Format\": \"json\"\r\n }\r\n ],\r\n \"Pipes\":[ \r\n { \r\n \"Id\":\"WinSecurityPipe\",\r\n \"SourceRef\":\"" + input.Name + "\",\r\n \"SinkRef\":\"" + input.Name + "KinesisFirehose\"\r\n }\r\n ],\r\n \"SelfUpdate\":0\r\n}"; var data2 = "{\r\n \"cloudwatch.emitMetrics\": false,\r\n \"awsSecretAccessKey\": \"" + Environment.GetEnvironmentVariable("FIREHOSE_SECRET_ACCESS_KEY") + "\",\r\n \"firehose.endpoint\": \"firehose.ap-southeast-1.amazonaws.com\",\r\n \"awsAccessKeyId\": \"" + Environment.GetEnvironmentVariable("FIREHOSE_ACCESS_KEY_ID") + "\",\r\n \"flows\": [\r\n {\r\n \"filePattern\": \"/opt/generators/CLF/*.log\",\r\n \"deliveryStream\": \"SmartInsights-Apache-Web-Logs\",\r\n \"dataProcessingOptions\": [\r\n {\r\n \"optionName\": \"LOGTOJSON\",\r\n \"logFormat\": \"COMMONAPACHELOG\"\r\n }\r\n ]\r\n },\r\n {\r\n \"filePattern\": \"/opt/generators/ELF/*.log\",\r\n \"deliveryStream\": \"\",\r\n \"dataProcessingOptions\": [\r\n {\r\n \"optionName\": \"LOGTOJSON\",\r\n \"logFormat\": \"COMBINEDAPACHELOG\"\r\n }\r\n ] \r\n },\r\n {\r\n \"filePattern\": \"/opt/log/www1/secure.log\",\r\n \"deliveryStream\": \"SmartInsights-SSH-Login-Logs\",\r\n \"dataProcessingOptions\": [\r\n {\r\n \"optionName\": \"LOGTOJSON\",\r\n \"logFormat\": \"SYSLOG\",\r\n \"matchPattern\": \"^([\\\\w]+) ([\\\\w]+) ([\\\\d]+) ([\\\\d]+) ([\\\\w:]+) ([\\\\w]+) ([\\\\w]+)\\\\[([\\\\d]+)\\\\]\\\\: ([\\\\w\\\\s.\\\\:=]+)$\",\r\n \"customFieldNames\": [\"weekday\", \"month\", \"day\", \"year\", \"time\", \"host\", \"process\", \"identifer\",\"message\"]\r\n }\r\n ]\r\n },\r\n {\r\n \"filePattern\": \"/opt/log/cisco_router1/cisco_ironport_web.log\",\r\n \"deliveryStream\": \"SmartInsights-Cisco-Squid-Proxy-Logs\",\r\n \"dataProcessingOptions\": [\r\n {\r\n \"optionName\": \"LOGTOJSON\",\r\n \"logFormat\": \"SYSLOG\",\r\n \"matchPattern\": \"^([\\\\w.]+) (?:[\\\\d]+) ([\\\\d.]+) ([\\\\w]+)\\\\/([\\\\d]+) ([\\\\d]+) ([\\\\w.]+) ([\\\\S]+) ([\\\\S]+) (?:[\\\\w]+)\\\\/([\\\\S]+) ([\\\\S]+) (?:[\\\\S\\\\s]+)$\",\r\n \"customFieldNames\": [\"timestamp\",\"destination_ip_address\",\"action\",\"http_status_code\",\"bytes_in\",\"http_method\",\"requested_url\",\"user\",\"requested_url_domain\",\"content_type\"]\r\n }\r\n ]\r\n }\r\n ]\r\n}"; string data3 = ""; PutBucketResponse putBucketResponse = await _S3Client.PutBucketAsync(new PutBucketRequest { BucketName = "smartinsights-" + replace, UseClientRegion = true, CannedACL = S3CannedACL.Private }); PutBucketTaggingResponse putBucketTaggingResponse = await _S3Client.PutBucketTaggingAsync(new PutBucketTaggingRequest { BucketName = "smartinsights-" + replace, TagSet = new List <Amazon.S3.Model.Tag> { new Amazon.S3.Model.Tag { Key = "Project", Value = "OSPJ" } } }); PutPublicAccessBlockResponse putPublicAccessBlockResponse = await _S3Client.PutPublicAccessBlockAsync(new PutPublicAccessBlockRequest { BucketName = "smartinsights-" + replace, PublicAccessBlockConfiguration = new PublicAccessBlockConfiguration { BlockPublicAcls = true, BlockPublicPolicy = true, IgnorePublicAcls = true, RestrictPublicBuckets = true } }); CreateDeliveryStreamResponse createDeliveryStreamResponse = await _FirehoseClient.CreateDeliveryStreamAsync(new CreateDeliveryStreamRequest { DeliveryStreamName = "smartinsights-" + replace, DeliveryStreamType = DeliveryStreamType.DirectPut, ExtendedS3DestinationConfiguration = new ExtendedS3DestinationConfiguration { BucketARN = "arn:aws:s3:::" + BucketName2, BufferingHints = new BufferingHints { IntervalInSeconds = 60, SizeInMBs = 5 }, RoleARN = Environment.GetEnvironmentVariable("FIREHOSE_EXECUTION_ROLE") }, Tags = new List <Amazon.KinesisFirehose.Model.Tag> { new Amazon.KinesisFirehose.Model.Tag { Key = "Project", Value = "OSPJ" } } }); _logContext.S3Buckets.Add(new Models.S3Bucket { Name = BucketName2 }); await _logContext.SaveChangesAsync(); ClaimsIdentity claimsIdentity = HttpContext.User.Identity as ClaimsIdentity; string currentIdentity = claimsIdentity.FindFirst("preferred_username").Value; User user = await _accountContext.Users.Where(u => u.Username == currentIdentity).FirstOrDefaultAsync(); Models.S3Bucket bucket = await _logContext.S3Buckets.Where(b => b.Name.Equals(BucketName2)).FirstOrDefaultAsync(); await _logContext.SaveChangesAsync(); await _LambdaClient.AddPermissionAsync(new AddPermissionRequest { Action = "lambda:InvokeFunction", FunctionName = Environment.GetEnvironmentVariable("LAMBDA_FUNCTION_NAME"), Principal = "s3.amazonaws.com", SourceAccount = Environment.GetEnvironmentVariable("AWS_ACCOUNT_NUMBER"), SourceArn = "arn:aws:s3:::" + bucket.Name, StatementId = "ID-" + bucket.ID }); await _S3Client.PutBucketNotificationAsync(new PutBucketNotificationRequest { BucketName = BucketName2, LambdaFunctionConfigurations = new List <LambdaFunctionConfiguration> { new LambdaFunctionConfiguration { FunctionArn = Environment.GetEnvironmentVariable("LAMBDA_FUNCTION_ARN"), Events = new List <EventType> { EventType.ObjectCreatedPut } } } }); if (!input.LogInputCategory.Equals(LogInputCategory.WindowsEventLogs)) { data3 = data2; } else { data3 = data; } _logContext.LogInputs.Add(new Models.LogInput { Name = input.Name, FirehoseStreamName = BucketName2, ConfigurationJSON = data3, LogInputCategory = input.LogInputCategory, LinkedUserID = user.ID, LinkedS3BucketID = bucket.ID, FilePath = input.FilePath, Filter = input.Filter, LogType = input.LogType, }); try { await _logContext.SaveChangesAsync(); TempData["Alert"] = "Success"; TempData["Message"] = "Log Input " + input.Name + " created successfully!"; return(RedirectToAction("Manage", new { InputID = _logContext.LogInputs.Where(LI => LI.Name.Equals(input.Name)).FirstOrDefault().ID })); } catch (DbUpdateException) { TempData["Alert"] = "Danger"; TempData["Message"] = "Error Creating log input " + input.Name + "!"; return(View(input)); } }
public void Configure(IWebJobsBuilder builder) { builder.AddSwashBuckle(Assembly.GetExecutingAssembly()); builder.AddAzureFunctionsToken(new TokenAzureB2COptions() { AzureB2CSingingKeyUri = new Uri(Env.GetEnvironmentVariable("AuthSigningKey")), Audience = Env.GetEnvironmentVariable("AuthAudience"), Issuer = Env.GetEnvironmentVariable("AuthIssuer") }); builder.Services.AddHttpClient(); builder.Services.AddSingleton((s) => { GremlinServer gremlinServer = new GremlinServer(Env.GetEnvironmentVariable("CosmosGremlinHost"), int.Parse(Env.GetEnvironmentVariable("CosmosPort")), enableSsl: true, username: "******" + Env.GetEnvironmentVariable("CosmosDatabaseName") + "/colls/" + Env.GetEnvironmentVariable("CosmosGraphName"), password: Env.GetEnvironmentVariable("CosmosKey")); IGremlinClient gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); return(gremlinClient); }); builder.Services.AddSingleton((s) => { IB2CGraphClient b2CGraphClient = new B2CGraphClient(); return(b2CGraphClient); }); }
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(); }
public static void SetupMain() { Java.Lang.JavaSystem.LoadLibrary("fnadroid-ext"); // Required for OpenAL to function properly as it access the JNI env directly. Java.Lang.JavaSystem.LoadLibrary("soft_oal"); // Give the main library something to call in Mono-Land afterwards SetMain(SDL_Main); // Load stub Steamworks.NET Steamworks.SteamAPI.Init(); // FNA and FNADroid environment vars // If your game code is shipping with the APK (f.e. your game is referenced by the FNADroid project), FNADROID_GAMEPATH is useless to you. if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("FNADROID_GAMEPATH"))) { // HARDCODED FOR DEMO PURPOSES Environment.SetEnvironmentVariable("FNADROID_GAMEPATH", "/storage/sdcard1/Stardew Valley/Stardew Valley.exe"); } string storagePath = MainActivity.SDL2DCS_Instance.GetExternalFilesDir(null).AbsolutePath; string gamePath = Environment.GetEnvironmentVariable("FNADROID_GAMEPATH"); string gameDir; if (!string.IsNullOrEmpty(gamePath)) { // GAMEPATH defined: Set paths relative to game path. gameDir = Directory.GetParent(gamePath).FullName; } else { // GAMEPATH not defined: Set paths relative to storage path. gamePath = Path.Combine(storagePath, "game.exe"); // Fake! gameDir = storagePath; } Directory.SetCurrentDirectory(gameDir); Environment.SetEnvironmentVariable("FNADROID", "1"); Environment.SetEnvironmentVariable("FNADROID_LOCALDIR", storagePath); Environment.SetEnvironmentVariable("FNA_CONFDIR", storagePath); Environment.SetEnvironmentVariable("FNA_TITLEDIR", gameDir); Environment.SetEnvironmentVariable("FNA_OPENGL_FORCE_ES3", "1"); // At this point I'm just waiting for FACT... // Those were once required for old that old copy of OpenAL I found somewhere(tm). /* * Environment.SetEnvironmentVariable("FNA_AUDIO_DEVICE_NAME", "Android Legacy"); * Environment.SetEnvironmentVariable("FNA_AUDIO_DEVICES_IN", " "); */ // This is required to save RAM. Environment.SetEnvironmentVariable("FNA_AUDIO_FORCE_STREAM", "1"); // Required as SDL2 seems to take UI elements such as the action bar into account. Android.Graphics.Point size = new Android.Graphics.Point(); MainActivity.SDL2DCS_Instance.WindowManager.DefaultDisplay.GetRealSize(size); string displayMode = $"{size.X}, {size.Y}"; Environment.SetEnvironmentVariable("FNA_GRAPHICS_MODES", displayMode); Environment.SetEnvironmentVariable("FNA_GRAPHICS_MODE", displayMode); }
public string GetEnvironmentVariable(string variable) { return(Env.GetEnvironmentVariable(variable)); }
static void HandleMessage(BDictionary message, TcpClient client) { var opValue = message["op"]; var opString = opValue as BString; var autoCompletionSupportEnabled = RT.booleanCast(((IPersistentMap)configVar.invoke()).valAt(Keyword.intern("nrepl-auto-completion"))); if (opString != null) { var session = GetSession(message); switch (opString.ToString()) { case "clone": var newSession = CloneSession(session); SendMessage( new BDictionary { { "id", message["id"] }, { "status", new BList { "done" } }, { "new-session", newSession.ToString() } }, client); break; case "describe": // TODO include arcadia version var clojureVersion = (IPersistentMap)RT.var("clojure.core", "*clojure-version*").deref(); var clojureMajor = (int)clojureVersion.valAt(Keyword.intern("major")); var clojureMinor = (int)clojureVersion.valAt(Keyword.intern("minor")); var clojureIncremental = (int)clojureVersion.valAt(Keyword.intern("incremental")); var clojureQualifier = (string)clojureVersion.valAt(Keyword.intern("qualifier")); var supportedOps = new BDictionary { { "eval", 1 }, { "load-file", 1 }, { "describe", 1 }, { "clone", 1 }, { "info", 1 }, { "eldoc", 1 }, { "classpath", 1 }, }; // Debug.Log("Autocomplete support is enabled?: " + autoCompletionSupportEnabled); if (autoCompletionSupportEnabled) { supportedOps.Add("complete", 1); } SendMessage( new BDictionary { { "id", message["id"] }, { "session", session.ToString() }, { "status", new BList { "done" } }, { "ops", supportedOps }, { "versions", new BDictionary { { "clojure", new BDictionary { { "major", clojureMajor }, { "minor", clojureMinor }, { "incremental", clojureIncremental }, { "qualifier", clojureQualifier } } }, { "nrepl", new BDictionary { { "major", 0 }, { "minor", 2 }, { "incremental", 3 } } } } } }, client); break; case "eval": var fn = new EvalFn(message, client); fn.invoke(); break; case "load-file": message["code"] = new BString("(do " + message["file"].ToString() + " )"); var loadFn = new EvalFn(message, client); loadFn.invoke(); break; case "eldoc": case "info": String symbolStr = message["symbol"].ToString(); // Editors like Calva that support doc-on-hover sometimes will ask about empty strings or spaces if (symbolStr == "" || symbolStr == null || symbolStr == " ") { break; } IPersistentMap symbolMetadata = null; try { symbolMetadata = (IPersistentMap)metaVar.invoke(nsResolveVar.invoke( findNsVar.invoke(symbolVar.invoke(message["ns"].ToString())), symbolVar.invoke(symbolStr))); } catch (TypeNotFoundException) { // We'll just ignore this call if the type cannot be found. This happens sometimes. // TODO: One particular case when this happens is when querying info for a namespace. // That case should be handled separately (e.g., via `find-ns`?) } if (symbolMetadata != null) { var resultMessage = new BDictionary { { "id", message["id"] }, { "session", session.ToString() }, { "status", new BList { "done" } } }; foreach (var entry in symbolMetadata) { if (entry.val() != null) { String keyStr = entry.key().ToString().Substring(1); String keyVal = entry.val().ToString(); if (keyStr == "arglists") { keyStr = "arglists-str"; } if (keyStr == "forms") { keyStr = "forms-str"; } resultMessage[keyStr] = new BString(keyVal); } } SendMessage(resultMessage, client); } else { SendMessage( new BDictionary { { "id", message["id"] }, { "session", session.ToString() }, { "status", new BList { "done", "no-info" } } }, client); } break; case "complete": // When autoCompletionSupportEnabled is false, we don't advertise auto-completion support. // some editors seem to ignore this and request anyway, so we return an unknown op message. if (!autoCompletionSupportEnabled) { SendMessage( new BDictionary { { "id", message["id"] }, { "session", session.ToString() }, { "status", new BList { "done", "error", "unknown-op" } } }, client); break; } Namespace ns = Namespace.find(Symbol.create(message["ns"].ToString())); var sessionBindings = _sessions[session]; var completeBindings = sessionBindings; if (ns != null) { completeBindings = completeBindings.assoc(RT.CurrentNSVar, ns); } // Make sure to eval this in the right namespace Var.pushThreadBindings(completeBindings); BList completions = (BList)completeVar.invoke(message["symbol"].ToString()); Var.popThreadBindings(); SendMessage(new BDictionary { { "id", message["id"] }, { "session", session.ToString() }, { "status", new BList { "done" } }, { "completions", completions } }, client); break; case "classpath": BList classpath = new BList(); foreach (String p in Environment.GetEnvironmentVariable("CLOJURE_LOAD_PATH").Split(System.IO.Path.PathSeparator)) { if (p != "") { classpath.Add(Path.GetFullPath(p)); } } SendMessage(new BDictionary { { "id", message["id"] }, { "session", session.ToString() }, { "status", new BList { "done" } }, { "classpath", classpath }, }, client); break; default: SendMessage( new BDictionary { { "id", message["id"] }, { "session", session.ToString() }, { "status", new BList { "done", "error", "unknown-op" } } }, client); break; } } }
public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget?target = null) { return(target.HasValue ? Env.GetEnvironmentVariable(variable, target.Value) : Env.GetEnvironmentVariable(variable)); }