System.Reflection.Assembly.GetEntryAssembly()

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

1560 Examples 7

19 Source : NativeTestsRunnerPluginService.cs
with Apache License 2.0
from AutomateThePlanet

private string GetRunningreplacedemblyPath() => Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);

19 Source : Startup.cs
with MIT License
from Avanade

public void ConfigureServices(IServiceCollection services)
        {
            // Add the core beef services.
            services.AddBeefExecutionContext()
                    .AddBeefSystemTime()
                    .AddBeefRequestCache()
                    .AddBeefCachePolicyManager(_config.GetSection("BeefCaching").Get<CachePolicyConfig>())
                    .AddBeefWebApiServices()
                    .AddBeefGrpcServiceServices()
                    .AddBeefBusinessServices()
                    .AddBeefTextProviderreplacedingleton();

            // Add the data sources as singletons for dependency injection requirements.
            services.AddBeefDatabaseServices(() => new Database(WebApiStartup.GetConnectionString(_config, "BeefDemo")))
                    .AddBeefEnreplacedyFrameworkServices<EfDbContext, EfDb>()
                    .AddBeefCosmosDbServices<CosmosDb>(_config.GetSection("CosmosDb"))
                    .AddSingleton<ITestOData>(_ => new TestOData(new Uri(WebApiStartup.GetConnectionString(_config, "TestOData"))))
                    .AddSingleton<ITripOData>(_ => new TripOData(new Uri(WebApiStartup.GetConnectionString(_config, "TripOData"))));

            // Add the generated reference data services for dependency injection requirements.
            services.AddGeneratedReferenceDataManagerServices()
                    .AddGeneratedReferenceDataDataSvcServices()
                    .AddGeneratedReferenceDataDataServices();

            // Add the generated enreplacedy services for dependency injection requirements.
            services.AddGeneratedManagerServices()
                    .AddGeneratedValidationServices()
                    .AddGeneratedDataSvcServices()
                    .AddGeneratedDataServices();

            // Add event publishing.
            var ehcs = _config.GetValue<string>("EventHubConnectionString");
            var sbcs = _config.GetValue<string>("ServiceBusConnectionString");
            if (!string.IsNullOrEmpty(sbcs))
                services.AddBeefEventHubEventProducer(new EventHubProducerClient(ehcs));
            else if (!string.IsNullOrEmpty(sbcs))
                services.AddBeefServiceBusSender(new ServiceBusClient(sbcs));
            else
                services.AddBeefNullEventPublisher();

            // Add identifier generator services.
            services.AddSingleton<IGuidIdentifierGenerator, GuidIdentifierGenerator>()
                    .AddSingleton<IStringIdentifierGenerator, StringIdentifierGenerator>();

            // Add event outbox services.
            services.AddGeneratedDatabaseEventOutbox();
            services.AddBeefDatabaseEventOutboxPublisherService();

            // Add custom services; in this instance to allow it to call itself for testing purposes.
            services.AddHttpClient("demo", c => c.BaseAddress = new Uri(_config.GetValue<string>("DemoServiceAgentUrl")));
            services.AddScoped<Common.Agents.IDemoWebApiAgentArgs>(sp => new Common.Agents.DemoWebApiAgentArgs(sp.GetService<System.Net.Http.IHttpClientFactory>().CreateClient("demo")));
            services.AddScoped<Common.Agents.IPersonAgent, Common.Agents.PersonAgent>();

            // Add services; note Beef requires NewtonsoftJson.
            services.AddAutoMapper(Mapper.AutoMapperProfile.replacedembly, typeof(Beef.Demo.Common.Grpc.Transformers).replacedembly, typeof(ContactData).replacedembly);
            services.AddControllers().AddNewtonsoftJson();
            services.AddGrpc();
            services.AddHealthChecks();
            services.AddHttpClient();

            // Set up services for calling http://api.zippopotam.us/.
            services.AddHttpClient("zippo", c => c.BaseAddress = new Uri(_config.GetValue<string>("ZippoAgentUrl")));
            services.AddScoped<IZippoAgentArgs>(sp => new ZippoAgentArgs(sp.GetService<System.Net.Http.IHttpClientFactory>().CreateClient("zippo")));
            services.AddScoped<IZippoAgent, ZippoAgent>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { replacedle = "Beef (Business Enreplacedy Execution Framework) Demo API", Version = "v1" });

                var xmlName = $"{replacedembly.GetEntryreplacedembly().GetName().Name}.xml";
                var xmlFile = Path.Combine(AppContext.BaseDirectory, xmlName);
                if (File.Exists(xmlFile))
                    c.IncludeXmlComments(xmlFile);
            });

            services.AddSwaggerGenNewtonsoftSupport();
        }

19 Source : Startup.cs
with MIT License
from Avanade

public void ConfigureServices(IServiceCollection services)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            // Add the core beef services.
            services.AddBeefExecutionContext()
                    .AddBeefTextProviderreplacedingleton()
                    .AddBeefSystemTime()
                    .AddBeefRequestCache()
                    .AddBeefCachePolicyManager(_config.GetSection("BeefCaching").Get<CachePolicyConfig>())
                    .AddBeefWebApiServices()
                    .AddBeefBusinessServices();

            // Add the beef database services (scoped per request/connection).
            services.AddBeefDatabaseServices(() => new HrDb(WebApiStartup.GetConnectionString(_config, "Database")));

            // Add the beef enreplacedy framework services (scoped per request/connection).
            services.AddBeefEnreplacedyFrameworkServices<HrEfDbContext, HrEfDb>();

            // Add the generated reference data services.
            services.AddGeneratedReferenceDataManagerServices()
                    .AddGeneratedReferenceDataDataSvcServices()
                    .AddGeneratedReferenceDataDataServices();

            // Add the generated enreplacedy services.
            services.AddGeneratedManagerServices()
                    .AddGeneratedValidationServices()
                    .AddGeneratedDataSvcServices()
                    .AddGeneratedDataServices();

            // Add event publishing services.
            var ehcs = _config.GetValue<string>("EventHubConnectionString");
            if (!string.IsNullOrEmpty(ehcs))
                services.AddBeefEventHubEventProducer(new EventHubProducerClient(ehcs));
            else
                services.AddBeefNullEventPublisher();

            // Add transactional event outbox services.
            services.AddGeneratedDatabaseEventOutbox();
            services.AddBeefDatabaseEventOutboxPublisherService();

            // Add AutoMapper services via replacedembly-based probing for Profiles.
            services.AddAutoMapper(Beef.Mapper.AutoMapperProfile.replacedembly, typeof(EmployeeData).replacedembly);

            // Add additional services; note Beef requires NewtonsoftJson.
            services.AddControllers().AddNewtonsoftJson();
            services.AddHealthChecks();
            services.AddHttpClient();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { replacedle = "My.Hr API", Version = "v1" });

                var xmlName = $"{replacedembly.GetEntryreplacedembly()!.GetName().Name}.xml";
                var xmlFile = Path.Combine(AppContext.BaseDirectory, xmlName);
                if (File.Exists(xmlFile))
                    c.IncludeXmlComments(xmlFile);
            });

            services.AddSwaggerGenNewtonsoftSupport();
        }

19 Source : Startup.cs
with MIT License
from Avanade

public void ConfigureServices(IServiceCollection services)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            // Add the core beef services (including the customized ExecutionContext).
            services.AddBeefExecutionContext(_ => new Business.ExecutionContext())
                    .AddBeefTextProviderreplacedingleton()
                    .AddBeefSystemTime()
                    .AddBeefRequestCache()
                    .AddBeefCachePolicyManager(_config.GetSection("BeefCaching").Get<CachePolicyConfig>())
                    .AddBeefWebApiServices()
                    .AddBeefBusinessServices();

            // Add the data sources as singletons for dependency injection requirements.
            var ccs = _config.GetSection("CosmosDb");
            services.AddSingleton<Beef.Data.Cosmos.ICosmosDb>(_ => new CosmosDb(new Cosmos.CosmosClient(ccs.GetValue<string>("EndPoint"), ccs.GetValue<string>("AuthKey")), ccs.GetValue<string>("Database")));

            // Add beef cache policy management.
            services.AddBeefCachePolicyManager(_config.GetSection("BeefCaching").Get<CachePolicyConfig>());

            // Add the generated reference data services for dependency injection requirements.
            services.AddGeneratedReferenceDataManagerServices()
                    .AddGeneratedReferenceDataDataSvcServices()
                    .AddGeneratedReferenceDataDataServices();

            // Add the generated services for dependency injection requirements.
            services.AddGeneratedManagerServices()
                    .AddGeneratedValidationServices()
                    .AddGeneratedDataSvcServices()
                    .AddGeneratedDataServices();

            // Add AutoMapper services via replacedembly-based probing for Profiles.
            services.AddAutoMapper(Beef.Mapper.AutoMapperProfile.replacedembly, typeof(AccountData).replacedembly);

            // Add services; note Beef requires NewtonsoftJson.
            services.AddControllers().AddNewtonsoftJson();
            services.AddHealthChecks();
            services.AddHttpClient();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { replacedle = "Cdr.Banking API", Version = "v1" });

                var xmlName = $"{replacedembly.GetEntryreplacedembly()!.GetName().Name}.xml";
                var xmlFile = Path.Combine(AppContext.BaseDirectory, xmlName);
                if (File.Exists(xmlFile))
                    c.IncludeXmlComments(xmlFile);
            });

            services.AddSwaggerGenNewtonsoftSupport();
        }

19 Source : Startup.cs
with MIT License
from Avanade

public void ConfigureServices(IServiceCollection services)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            // Add the core beef services.
            services.AddBeefExecutionContext()
                    .AddBeefTextProviderreplacedingleton()
                    .AddBeefSystemTime()
                    .AddBeefRequestCache()
                    .AddBeefCachePolicyManager(_config.GetSection("BeefCaching").Get<CachePolicyConfig>())
                    .AddBeefWebApiServices()
                    .AddBeefBusinessServices();

#if (implement_database || implement_enreplacedyframework)
            // Add the beef database services (scoped per request/connection).
            services.AddBeefDatabaseServices(() => new AppNameDb(WebApiStartup.GetConnectionString(_config, "Database")));

#endif
#if (implement_enreplacedyframework)
            // Add the beef enreplacedy framework services (scoped per request/connection).
            services.AddBeefEnreplacedyFrameworkServices<AppNameEfDbContext, AppNameEfDb>();

#endif
#if (implement_cosmos)
            // Add the beef cosmos services (singleton).
            services.AddBeefCosmosDbServices<AppNameCosmosDb>(_config.GetSection("CosmosDb"));

#endif
            // Add the generated reference data services.
            services.AddGeneratedReferenceDataManagerServices()
                    .AddGeneratedReferenceDataDataSvcServices()
                    .AddGeneratedReferenceDataDataServices();

            // Add the generated enreplacedy services.
            services.AddGeneratedManagerServices()
                    .AddGeneratedValidationServices()
                    .AddGeneratedDataSvcServices()
                    .AddGeneratedDataServices();

            // Add GUID identifier generator service.
            services.AddSingleton<IGuidIdentifierGenerator, GuidIdentifierGenerator>();

#if (implement_database || implement_enreplacedyframework)
            // Add transactional event outbox services.
            services.AddGeneratedDatabaseEventOutbox();
            services.AddBeefDatabaseEventOutboxPublisherService();

#endif
            // Add event publishing services.
            var sbcs = _config.GetValue<string>("ServiceBusConnectionString");
            if (!string.IsNullOrEmpty(sbcs))
                services.AddBeefServiceBusSender(new ServiceBusClient(sbcs));
            else
                services.AddBeefNullEventPublisher();

            // Add AutoMapper services via replacedembly-based probing for Profiles.
            services.AddAutoMapper(Beef.Mapper.AutoMapperProfile.replacedembly, typeof(PersonData).replacedembly);

            // Add additional services; note Beef requires NewtonsoftJson.
            services.AddControllers().AddNewtonsoftJson();
            services.AddHealthChecks();
            services.AddHttpClient();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { replacedle = "Company.AppName API", Version = "v1" });

                var xmlName = $"{replacedembly.GetEntryreplacedembly()!.GetName().Name}.xml";
                var xmlFile = Path.Combine(AppContext.BaseDirectory, xmlName);
                if (File.Exists(xmlFile))
                    c.IncludeXmlComments(xmlFile);
            });

            services.AddSwaggerGenNewtonsoftSupport();
        }

19 Source : DatabaseConsoleWrapper.cs
with MIT License
from Avanade

public async Task<int> RunAsync(string[] args)
        {
            using var app = new CommandLineApplication()
            {
                Name = "beef.database.core",
                Description = "Business Enreplacedy Execution Framework (Beef) Database Tooling."
            };

            var cmd = app.Argument<DatabaseExecutorCommand>("command", "Database command.").IsRequired();
            var sn = app.Argument("parameters", "Additional parameters used by the ScriptNew command.", multipleValues: true);
            var cs = app.Option("-cs|--connectionstring", "Override the database connection string.", CommandOptionType.SingleValue);
            var eo = app.Option("-eo|--entry-replacedembly-only", "Override replacedemblies to use the entry replacedembly only.", CommandOptionType.NoValue);
            var x2y = app.Option("-x2y|--xmlToYaml", "Convert the XML configuration into YAML equivalent (will not codegen).", CommandOptionType.NoValue);
            var evn = app.Option("-evn|--environmentVariableName", "Override the default environment variable name for the connection string.", CommandOptionType.SingleValue);
            var ps = app.Option("-p|--param", "Name=Value pair.", CommandOptionType.MultipleValue).Accepts(v => v.Use(new ParamsValidator()));
            var so = app.Option("-s|--script", "Override the script resource name.", CommandOptionType.SingleValue);

            app.OnExecuteAsync(async (_) =>
            {
                if (x2y.HasValue())
                {
                    if (cmd.ParsedValue != DatabaseExecutorCommand.CodeGen)
                        throw new CommandParsingException(app, $"Command '{cmd.ParsedValue}' is not compatible with --xmlToYaml; the command must be '{DatabaseExecutorCommand.CodeGen}'.");

                    DatabaseConsole.WriteMasthead();
                    return await CodeGenFileManager.ConvertXmlToYamlAsync(CommandType.Database, CodeGenFileManager.GetConfigFilename(_exeDir, CommandType.Database, Company, AppName)).ConfigureAwait(false);
                }

                var script = so.HasValue() ? so.Value() : _script;
                var sb = new StringBuilder();
                if (eo.HasValue())
                    sb.Append(ReplaceMoustache(CommandLinereplacedemblyTemplate, null!, null!, replacedembly.GetEntryreplacedembly()?.FullName!, script!));
                else
                    _replacedemblies.ForEach(a => sb.Append(ReplaceMoustache(CommandLinereplacedemblyTemplate, null!, null!, a.FullName!, script!)));

                var rargs = ReplaceMoustache(CommandLineTemplate, cmd.Value!, cs.Value() ?? ConnectionString, sb.ToString(), script!);

                for (int i = 0; i < sn.Values.Count; i++)
                {
                    rargs += $" -p Param{i}={sn.Values[i]}";
                }

                foreach (var p in ps.Values)
                {
                    rargs += $" -p {p}";
                }

                _schemaOrder.ForEach(so => rargs += $" -so {so}");

                return await DatabaseConsole.Create().RunAsync(rargs).ConfigureAwait(false);
            });

            try
            {
                return await app.ExecuteAsync(args).ConfigureAwait(false);
            }
            catch (CommandParsingException cpex)
            {
                Console.Error.WriteLine(cpex.Message);
                return -1;
            }
        }

19 Source : DatabaseConsoleWrapper.cs
with MIT License
from Avanade

public static DatabaseConsoleWrapper Create(string connectionString, string company, string appName, bool useBeefDbo = true)
        {
            return new DatabaseConsoleWrapper(connectionString, company, appName, useBeefDbo).replacedemblies(replacedembly.GetEntryreplacedembly()!);
        }

19 Source : RegistrationUtility.cs
with MIT License
from avarghesein

internal static void RegisterLocalServer(Type t)
        {
            GuardNullType(t, "t");  // Check the argument

            if (!ValidateActiveXServerAttribute(t)) return;

            try
            {
                // Open the CLSID key of the component.
                using (RegistryKey keyCLSID = Registry.ClreplacedesRoot.OpenSubKey(
                    @"CLSID\" + t.GUID.ToString("B"), /*writable*/true))
                {
                    // Remove the auto-generated InprocServer32 key after registration
                    // (REGASM puts it there but we are going out-of-proc).
                    keyCLSID.DeleteSubKeyTree("InprocServer32");

                    // Create "LocalServer32" under the CLSID key
                    using (RegistryKey subkey = keyCLSID.CreateSubKey("LocalServer32"))
                    {
                        subkey.SetValue("", replacedembly.GetEntryreplacedembly().Location, RegistryValueKind.String);
                    }
                }
            }
            catch (Exception eX)
            {
                System.Windows.Forms.MessageBox.Show(eX.Message);
            }
        }

19 Source : DefaultAppDataPathProvider.cs
with MIT License
from awaescher

public virtual string GetAppResourcesPath() => Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly().Location);

19 Source : MacAppDataPathProvider.cs
with MIT License
from awaescher

public override string GetAppResourcesPath() => Path.Combine(Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly().Location), "..", "Resources");

19 Source : PopupViewController.cs
with MIT License
from awaescher

private void ShowHelp()
		{
			var appName = System.Reflection.replacedembly.GetEntryreplacedembly().GetName();
			var bundleVersion = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleShortVersionString").ToString();

			var alert = new NSAlert
			{
				MessageText = appName.Name + " " + bundleVersion,
				AlertStyle = NSAlertStyle.Informational,
				InformativeText = GetHelp(TinyIoC.TinyIoCContainer.Current.Resolve<StatusCharacterMap>())
			};
			alert.AddButton(_translationService.Translate("Goreplaced"));
			alert.RunModal();
		}

19 Source : TinySoup.cs
with MIT License
from awaescher

public UpdateRequest WithNameAndVersionFromEntryreplacedembly() => WithNameAndVersionFromreplacedembly(replacedembly.GetEntryreplacedembly());

19 Source : AutoStart.cs
with MIT License
from awaescher

private static string GetAppPath() => $"\"{replacedembly.GetEntryreplacedembly().Location}\"";

19 Source : Utilities.cs
with Apache License 2.0
from aws

public static string DetermineToolVersion()
        {
            replacedemblyInformationalVersionAttribute attribute = null;
            try
            {
                var replacedembly = replacedembly.GetEntryreplacedembly();
                if (replacedembly == null)
                    return null;
                attribute = replacedembly.GetEntryreplacedembly().GetCustomAttribute<replacedemblyInformationalVersionAttribute>();
            }
            catch (Exception)
            {
                // ignored
            }

            return attribute?.InformationalVersion;
        }

19 Source : Logger.cs
with Apache License 2.0
from aws-samples

private static void ConfigureLog4Net()
        { 
        var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            IsLog4netConfigured = true;
        }

19 Source : ProgramInfo.cs
with Apache License 2.0
from awslabs

public static string GetVersionNumber()
        {
            var fileVersionAttribute = replacedembly.GetEntryreplacedembly().GetCustomAttribute<replacedemblyFileVersionAttribute>();
            return fileVersionAttribute?.Version ?? string.Empty;
        }

19 Source : SemanticReleaseEntry.cs
with MIT License
from axlj45

private static string GetVersion()
            => replacedembly.GetEntryreplacedembly().GetCustomAttribute<replacedemblyInformationalVersionAttribute>().InformationalVersion;

19 Source : DistributedCallFlow.cs
with MIT License
from azist

public static DistributedCallFlow Start(IApplication app, string description, Guid? guid = null, string directorName = null, string callerAgent = null, string callerPort = null)
    {
      app.NonNull(nameof(app));

      var current = ExecutionContext.CallFlow;

      var result = current as DistributedCallFlow;
      if (result == null)
      {
        result = new DistributedCallFlow();
        result.m_Description = description;

        if (current == null)
        {
          callerAgent = callerAgent.Default(System.Reflection.replacedembly.GetCallingreplacedembly().GetName().Name);
          callerPort = callerPort.Default(System.Reflection.replacedembly.GetEntryreplacedembly()?.GetName().Name);
          current = new CodeCallFlow(guid ?? Guid.NewGuid(), directorName, callerAgent, callerPort);
        }

        result.m_List.Add(new Step(app, ExecutionContext.Session, current));
        ExecutionContext.__SetThreadLevelCallContext(result);
      }
      else throw new AzosException("Distributed flow error: The context is already injected with DistributedCallFlow");

      return result;
    }

19 Source : DistributedCallFlow.cs
with MIT License
from azist

public static DistributedCallFlow Continue(IApplication app, JsonDataMap existing, Guid? guid = null, string directorName = null, string callerAgent = null, string callerPort = null)
    {
      app.NonNull(nameof(app));
      existing.IsTrue(v => v!=null && v.Count > 0, nameof(existing));

      var current = ExecutionContext.CallFlow;

      var result = current as DistributedCallFlow;
      if (result == null)
      {
        result = new DistributedCallFlow();

        result.ReadAsJson(existing, false, null);

        if (current == null)
        {
          callerAgent = callerAgent.Default(System.Reflection.replacedembly.GetCallingreplacedembly().GetName().Name);
          callerPort = callerPort.Default(System.Reflection.replacedembly.GetEntryreplacedembly()?.GetName().Name);
          current = new CodeCallFlow(guid ?? Guid.NewGuid(), directorName, callerAgent, callerPort);
        }
        result.m_List.Add(new Step(app, ExecutionContext.Session, current));
        ExecutionContext.__SetThreadLevelCallContext(result);
      }
      else throw new AzosException("Distributed flow error: The context is already injected with DistributedCallFlow");

      return result;
    }

19 Source : CommonApplicationLogic.cs
with MIT License
from azist

protected string GetDefaultConfigFileName()
    {
      var exeName = System.Reflection.replacedembly.GetEntryreplacedembly().Location;
      var exeNameWoExt = Path.Combine(Path.GetDirectoryName(exeName), Path.GetFileNameWithoutExtension(exeName));
      //Console.WriteLine("EXENAME:" +exeName);
      //Console.WriteLine("EXENAME wo extension:" +exeNameWoExt);
      var extensions = Configuration.AllSupportedFormats.Select(fmt => '.' + fmt);
      foreach (var ext in extensions)
      {
        var configFile = exeName + ext;
        //Console.WriteLine("Probing:" +configFile);
        if (File.Exists(configFile)) return configFile;
        configFile = exeNameWoExt + ext;
        //Console.WriteLine("Probing:" +configFile);
        if (File.Exists(configFile)) return configFile;

      }
      return string.Empty;
    }

19 Source : CoreUtils.cs
with MIT License
from azist

public static string EntryExeName(bool withPath = true)
    {
      var file = replacedembly.GetEntryreplacedembly().Location;

      if (!withPath) file = Path.GetFileName(file);

      return file;
    }

19 Source : Ver.cs
with MIT License
from azist

public override string Execute()
    {
      var result = new StringBuilder(0xff);
      result.AppendLine("Server Version/Build information:");
      result.AppendLine(" App:       [{0}] {1}".Args(App.AppId.IsZero ? "#" : App.AppId.Value,  App.Name));
      result.AppendLine(" Azos Core: " + BuildInformation.ForFramework);
      result.AppendLine(" Azos Sky:  " + new BuildInformation( typeof(Azos.Sky.SkySystem).replacedembly ));

      string host  = "n/a";
      try
      {
        host = new BuildInformation(replacedembly.GetEntryreplacedembly()).ToString();
      }
      catch{ }

      result.AppendLine(" Host:      " + host);

      return result.ToString();
    }

19 Source : ApplicationHostProgramBody.cs
with MIT License
from azist

private static int governedConsoleMainBody(BootArgs args)
    {
      Console.CancelKeyPress += (_, e) => {
        var app = s_Application;//capture
        if (app != null)
        {
          app.Stop();
          e.Cancel = true;
        }
      };

      try
      {
        try
        {
          Start(args);

          //blocks until application is running
          while(true)
          {
            var stopped = s_Application.WaitForStopOrShutdown(5000);
            if (stopped) break;
          }
        }
        finally
        {
          Stop();
        }

        return 0;
      }
      catch (Exception error)
      {
        var wrap = new WrappedExceptionData(error, true);
        var errorContent = "App Root exception, details: \n" + wrap.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
        var crashFile = "{0:yyyyMMdd-HHmmssff}-{1}-{2}.crash.log".Args(
                               DateTime.Now,
                               System.Reflection.replacedembly.GetEntryreplacedembly().GetName().Name,
                               s_AppId.Default("unset"));

        try
        {
          System.IO.File.WriteAllText(crashFile, errorContent);
          Console.WriteLine(errorContent);
        }
        catch{ }

        return -100;
      }
    }

19 Source : Utils.cs
with MIT License
from azist

public static string GetRootPath()
      {
         var exeName = System.Reflection.replacedembly.GetEntryreplacedembly().Location;
         return Path.GetDirectoryName(exeName);
      }

19 Source : FileHelpBuilder.cs
with MIT License
from Azure

public override void Write(ICommand command)
        {
            base.Write(command);

            // The main help file will be in the same directory as the replacedembly.
            var appDirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly().Location);
            var mainHelpFile = Path.Combine(appDirectory, HelpFile);

            // Find main help file to add to command line
            if (File.Exists(mainHelpFile))
            {
                var helpContent = File.ReadAllText(mainHelpFile);
                base.Console.Out.Write(helpContent);
            }

            // Find help files to add to command line
            var findPaths = _config.GetSection("AppConfig:FindPaths").Get<string[]>();
            if (findPaths != null)
            {
                foreach (var findPath in findPaths)
                {
                    var helpFiles = Directory.GetFiles(findPath, HelpFile, SearchOption.AllDirectories);
                    if (helpFiles != null && helpFiles.Any())
                    {
                        foreach (var helpFile in helpFiles)
                        {
                            if (File.Exists(helpFile))
                            {
                                var helpContent = File.ReadAllText(helpFile);
                                base.Console.Out.Write(helpContent);
                            }
                        }
                    }
                }
            }
        }

19 Source : DependencyResolution.cs
with MIT License
from Azure

private static void Autowirereplacedemblies(ContainerBuilder builder)
        {
            var replacedembly = replacedembly.GetEntryreplacedembly();
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Autowire Services.DLL
            replacedembly = typeof(IServicesConfig).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Autowire SimulationAgent.DLL
            replacedembly = typeof(ISimulationAgent).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Autowire ParreplacedioningAgent.DLL
            replacedembly = typeof(IParreplacedioningAgent).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();
        }

19 Source : DependencyResolution.cs
with MIT License
from Azure

private static void Autowirereplacedemblies(ContainerBuilder builder)
        {
            var replacedembly = replacedembly.GetEntryreplacedembly();
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire additional replacedemblies
            replacedembly = typeof(IServicesConfig).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();
        }

19 Source : Seed.cs
with MIT License
from Azure

private async Task SeedAsync(string template)
        {
            string content;

            var root = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            var file = Path.Combine(root, "Data", $"{template}.json");
            if (!File.Exists(file))
            {
                // ToDo: Check if `template` is a valid URL and try to load the content

                throw new ResourceNotFoundException($"Template {template} does not exist");
            }
            else
            {
                content = File.ReadAllText(file);
            }

            await this.SeedSingleTemplateAsync(content);
        }

19 Source : Seed.cs
with MIT License
from Azure

private Template GetSeedContent(string templateName)
        {
            Template template;
            string content;
            var root = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            var file = Path.Combine(root, "Data", $"{templateName}.json");
            if (!File.Exists(file))
            {
                // ToDo: Check if `template` is a valid URL and try to load the content

                throw new ResourceNotFoundException($"Template {templateName} does not exist");
            }
            else
            {
                content = File.ReadAllText(file);
            }

            try
            {
                template = JsonConvert.DeserializeObject<Template>(content);
            }
            catch (Exception ex)
            {
                throw new InvalidInputException("Failed to parse template", ex);
            }

            return template;
        }

19 Source : Rules.cs
with MIT License
from Azure

public async Task CreateFromTemplateAsync(string template)
        {
            string pathToTemplate = Path.Combine(
                Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location),
                @"Data\Rules\" + template + ".json");

            if (RuleTemplateValidator.IsValid(pathToTemplate))
            {
                var file = JToken.Parse(File.ReadAllText(pathToTemplate));

                foreach (var item in file["Rules"])
                {
                    Rule newRule = this.Deserialize(item.ToString());

                    await this.CreateAsync(newRule);
                }
            }
        }

19 Source : DependencyResolution.cs
with MIT License
from Azure

private static void Autowirereplacedemblies(ContainerBuilder builder)
        {
            var replacedembly = replacedembly.GetEntryreplacedembly();
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire Services.DLL
            replacedembly = typeof(IServicesConfig).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire BlobStorage.DLL
            replacedembly = typeof(IBlobStorageConfig).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire SetupAgent.DLL
            replacedembly = typeof(SetupAgent.IAgent).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire DeviceGroupsAgent.DLL
            replacedembly = typeof(DeviceGroupsAgent.IAgent).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire TelemetryRulesAgent.DLL
            replacedembly = typeof(TelemetryRulesAgent.IAgent).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();
        }

19 Source : DependencyResolution.cs
with MIT License
from Azure

private static void Autowirereplacedemblies(ContainerBuilder builder)
        {
            var replacedembly = replacedembly.GetEntryreplacedembly();
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire additional replacedemblies
            replacedembly = typeof(IServicesConfig).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            replacedembly = typeof(ActionsAgent.IAgent).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();
        }

19 Source : DependencyResolution.cs
with MIT License
from Azure

private static void Autowirereplacedemblies(ContainerBuilder builder)
        {
            var replacedembly = replacedembly.GetEntryreplacedembly();
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire additional replacedemblies
            replacedembly = typeof(IServicesConfig).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();

            // Auto-wire RecurringTasksAgent.DLL
            replacedembly = typeof(IRecurringTasksAgent).GetTypeInfo().replacedembly;
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();
        }

19 Source : DependencyResolution.cs
with MIT License
from Azure

private static void Autowirereplacedemblies(ContainerBuilder builder)
        {
            var replacedembly = replacedembly.GetEntryreplacedembly();
            builder.RegisterreplacedemblyTypes(replacedembly).AsImplementedInterfaces();
        }

19 Source : Program.cs
with Apache License 2.0
from Azure-App-Service

private static int Main(string[] args)
        {
            // Configure Logging if running on Azure
            if (System.Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID") != null)
            {
                XmlDoreplacedent log4netConfig = new XmlDoreplacedent();
                log4netConfig.Load(File.OpenRead("/opt/Kudu/KuduConsole/log4net.config"));
                var repo = log4net.LogManager.CreateRepository(replacedembly.GetEntryreplacedembly(),
                    typeof(log4net.Repository.Hierarchy.Hierarchy));
                log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
            }

            // Turn flag on in app.config to wait for debugger on launch
            if (ConfigurationManager.AppSettings["WaitForDebuggerOnStart"] == "true")
            {
                while (!Debugger.IsAttached)
                {
                    System.Threading.Thread.Sleep(100);
                }
            }

            if (System.Environment.GetEnvironmentVariable(SettingsKeys.DisableDeploymentOnPush) == "1")
            {
                return 0;
            }

            if (args.Length < 2)
            {
                System.Console.WriteLine("Usage: kudu.exe appRoot wapTargets [deployer]");
                return 1;
            }

            // The post receive hook launches the exe from sh and intereprets newline differently.
            // This fixes very wacky issues with how the output shows up in the console on push
            System.Console.Error.NewLine = "\n";
            System.Console.Out.NewLine = "\n";

            string appRoot = args[0];
            string wapTargets = args[1];
            string deployer = args.Length == 2 ? null : args[2];
            string requestId = System.Environment.GetEnvironmentVariable(Constants.RequestIdHeader);

            IEnvironment env = GetEnvironment(appRoot, requestId);
            ISettings settings = new XmlSettings.Settings(GetSettingsPath(env));
            IDeploymentSettingsManager settingsManager = new DeploymentSettingsManager(settings);

            // Setup the trace
            TraceLevel level = settingsManager.GetTraceLevel();
            ITracer tracer = GetTracer(env, level);
            ITraceFactory traceFactory = new TracerFactory(() => tracer);

            // Calculate the lock path
            string lockPath = Path.Combine(env.SiteRootPath, Constants.LockPath);
            string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);

            IOperationLock deploymentLock = DeploymentLockFile.GetInstance(deploymentLockPath, traceFactory);

            if (deploymentLock.IsHeld)
            {
                return PerformDeploy(appRoot, wapTargets, deployer, lockPath, env, settingsManager, level, tracer, traceFactory, deploymentLock);
            }

            // Cross child process lock is not working on linux via mono.
            // When we reach here, deployment lock must be HELD! To solve above issue, we lock again before continue.
            try
            {
                return deploymentLock.LockOperation(() =>
                {
                    return PerformDeploy(appRoot, wapTargets, deployer, lockPath, env, settingsManager, level, tracer, traceFactory, deploymentLock);
                }, "Performing deployment", TimeSpan.Zero);
            }
            catch (LockOperationException)
            {
                return -1;
            }
        }

19 Source : Program.cs
with Apache License 2.0
from Azure-App-Service

private static IEnvironment GetEnvironment(string siteRoot, string requestId)
        {
            string root = Path.GetFullPath(Path.Combine(siteRoot, ".."));

            // CORE TODO : test by setting SCM_REPOSITORY_PATH
            // REVIEW: this looks wrong because it ignores SCM_REPOSITORY_PATH
            string repositoryPath = Path.Combine(siteRoot, Constants.RepositoryPath);

            // SCM_BIN_PATH is introduced in Kudu apache config file
            // Provide a way to override Kudu bin path, to resolve issue where we can not find the right Kudu bin path when running on mono
            // CORE TODO I don't think this is needed anymore? This env var is not used anywhere but here.
            string binPath = System.Environment.GetEnvironmentVariable("SCM_BIN_PATH");
            if (string.IsNullOrWhiteSpace(binPath))
            {
                // CORE TODO Double check. Process.GetCurrentProcess() always gets the dotnet.exe process,
                // so changed to replacedembly.GetEntryreplacedembly().Location
                binPath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            }

            // CORE TODO Handing in a null IHttpContextAccessor (and KuduConsoleFullPath) again
            return new Kudu.Core.Environment(root,
                EnvironmentHelper.NormalizeBinPath(binPath),
                repositoryPath,
                requestId,
                Path.Combine(AppContext.BaseDirectory, "KuduConsole", "kudu.dll"),
                null,
                new FileSystemPathProvider(new NullMeshPersistentFileSystem()));
        }

19 Source : MainWindow.xaml.cs
with MIT License
from Azure-Samples

private static async Task DisplayErrorMessage(HttpResponseMessage httpResponse)
        {
            string failureDescription = await httpResponse.Content.ReadreplacedtringAsync();
            if (failureDescription.StartsWith("<!DOCTYPE html>"))
            {
                string path = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                string errorFilePath = Path.Combine(path, "error.html");
                File.WriteAllText(errorFilePath, failureDescription);
                Process.Start(errorFilePath);
            }
            else
            {
                MessageBox.Show($"{httpResponse.ReasonPhrase}\n {failureDescription}", "An error occurred while getting /api/todolist", MessageBoxButton.OK);
            }
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

static async Task DoIt()
        {
            AppCoordinates.AppCoordinates v1App = AppCoordinates.PreRegisteredApps.GetV1App(useInMsal: true);
            string resource = AppCoordinates.PreRegisteredApps.MsGraph;
            string[] scopes = new string[] { resource + "/user.read" };

            string cacheFolder = Path.GetFullPath(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location) + @"..\..\..\..");
            string adalV3cacheFileName = Path.Combine(cacheFolder, "cacheAdalV3.bin");
            string msalCacheFileName = Path.Combine(cacheFolder, "cacheMsal.bin");

            AuthenticationResult result;

            IPublicClientApplication app;
            app = PublicClientApplicationBuilder.Create(v1App.ClientId)
                                                .WithAuthority(v1App.Authority)
                                                .Build();
            FilesBasedTokenCacheHelper.EnableSerialization(app.UserTokenCache,
                                                           msalCacheFileName,
                                                           adalV3cacheFileName);
            var accounts = await app.GetAccountsAsync();
            try
            {
                result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                                  .ExecuteAsync();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"got token for '{result.Account.Username}' from the cache");
                Console.ResetColor();
            }
            catch (MsalUiRequiredException ex)
            {
                result = await app.AcquireTokenInteractive(scopes)
                                  .ExecuteAsync();
                Console.WriteLine($"got token for '{result.Account.Username}' without the cache");
            }
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

static async Task DoIt(bool disableLegacyCache)
        {
            AppCoordinates.AppCoordinates v1App = AppCoordinates.PreRegisteredApps.GetV1App(useInMsal: true);
            string resource = AppCoordinates.PreRegisteredApps.MsGraph;
            string[] scopes = new string[] { resource + "/user.read" };

            string cacheFolder = Path.GetFullPath(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location) + @"..\..\..\..");
            string adalV3cacheFileName = Path.Combine(cacheFolder, "cacheAdalV3.bin");
            string msalCacheFileName = Path.Combine(cacheFolder, "cacheMsal.bin");

            AuthenticationResult result;


            PublicClientApplicationBuilder builder = PublicClientApplicationBuilder.Create(v1App.ClientId)
                                                .WithAuthority(v1App.Authority);
             
            if (disableLegacyCache)
            {
                Console.WriteLine("Disabled legacy cache.");
                builder.WithLegacyCacheCompatibility(false);
            }
                                                
            IPublicClientApplication app = builder.Build();
            FilesBasedTokenCacheHelper.EnableSerialization(app.UserTokenCache,
                                                           msalCacheFileName,
                                                           adalV3cacheFileName);
            var accounts = await app.GetAccountsAsync();
            try
            {
                result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                                  .ExecuteAsync();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Using MSALV4.x got token for '{result.Account.Username}' from the cache");
                Console.ResetColor();
            }
            catch (MsalUiRequiredException ex)
            {
                result = await app.AcquireTokenInteractive(scopes)
                                  .ExecuteAsync();
                Console.WriteLine($"Using MSALV4.x got token for '{result.Account.Username}' without the cache");
            }
        }

19 Source : AuthenticationConfig.cs
with MIT License
from Azure-Samples

public static SampleConfiguration ReadFromJsonFile(string path)
        {
            // .NET configuration
            IConfigurationRoot Configuration;

            var builder = new ConfigurationBuilder()
             .SetBasePath(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location))
            .AddJsonFile(path);

            Configuration = builder.Build();

            // Read the auth and graph endpoint config
            SampleConfiguration config = new SampleConfiguration()
            {
                PublicClientApplicationOptions = new PublicClientApplicationOptions()
            };
            Configuration.Bind("Authentication", config.PublicClientApplicationOptions);
            config.MicrosoftGraphBaseEndpoint = Configuration.GetValue<string>("WebAPI:MicrosoftGraphBaseEndpoint");
            return config;
        }

19 Source : SampleConfiguration.cs
with MIT License
from Azure-Samples

public static SampleConfiguration ReadFromJsonFile(string path)
        {
            // .NET configuration
            IConfigurationRoot Configuration;

            var builder = new ConfigurationBuilder()
             .SetBasePath(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location))
            .AddJsonFile(path);

            Configuration = builder.Build();
            // Read the auth and graph endpoint config
            SampleConfiguration config = new SampleConfiguration()
            {
                PublicClientApplicationOptions = new PublicClientApplicationOptions()
            };
            Configuration.Bind("Authentication", config.PublicClientApplicationOptions);
            config.MicrosoftGraphBaseEndpoint = Configuration.GetValue<string>("WebAPI:MicrosoftGraphBaseEndpoint");
            return config;
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

static void Main(string[] args)
        {
            Console.WriteLine("--------------------------------------------------------------------------");
            Console.WriteLine(Path.GetFileNameWithoutExtension(replacedembly.GetEntryreplacedembly().Location));
            DoIt(args.Contains("-disable-legacy-cache")).Wait();

            // Unless ran in a batch, let the user press return to continue
            if (args.Length == 0)
            {
                Console.ReadLine();
            }
            Console.WriteLine("--------------------------------------------------------------------------");
        }

19 Source : Program.cs
with Apache License 2.0
from Azure-App-Service

public static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            CreateWebHostBuilder(args).Build().Run();
        }

19 Source : AuthenticationConfig.cs
with MIT License
from Azure-Samples

public static SampleConfiguration ReadFromJsonFile(string path)
        {
            // .NET configuration
            IConfigurationRoot Configuration;
            var builder = new ConfigurationBuilder()
            .SetBasePath(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location))
            .AddJsonFile(path);
            Configuration = builder.Build();

            // Read the auth and graph endpoint config
            SampleConfiguration config = new SampleConfiguration()
            {
                PublicClientApplicationOptions = new PublicClientApplicationOptions()
            };
            Configuration.Bind("Authentication", config.PublicClientApplicationOptions);
            config.MicrosoftGraphBaseEndpoint = Configuration.GetValue<string>("WebAPI:MicrosoftGraphBaseEndpoint");
            return config;
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

static void Main(string[] args)
        {
            Console.WriteLine("--------------------------------------------------------------------------");
            Console.WriteLine(Path.GetFileNameWithoutExtension(replacedembly.GetEntryreplacedembly().Location));
            DoIt().Wait();

            // Unless ran in a batch, let the user press return to continue
            if (args.Length == 0)
            {
                Console.ReadLine();
            }
            Console.WriteLine("--------------------------------------------------------------------------");
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

static async Task DoIt()
        {
            AppCoordinates.AppCoordinates app = AppCoordinates.PreRegisteredApps.GetV1App(useInMsal:false);

            // Multi-tenant V1 applications use the 
            if (app.Tenant == "organizations")
            {
                app.Tenant = "common";
            }
            string resource = AppCoordinates.PreRegisteredApps.MsGraph;

            string cacheFolder =  Path.GetFullPath(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location) + @"..\..\..\..");
            string cacheFileName = Path.Combine(cacheFolder, "cacheAdalV3.bin");
            FilesBasedAdalV3TokenCache tokenCache = new FilesBasedAdalV3TokenCache(cacheFileName);
            AuthenticationContext authenticationContext = new AuthenticationContext(app.Authority, tokenCache);

            AuthenticationResult result;
            try
            {
                result = await authenticationContext.AcquireTokenSilentAsync(resource, app.ClientId);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' from the cache");
                Console.ResetColor();
            }
            catch (AdalSilentTokenAcquisitionException)
            {
                result = await authenticationContext.AcquireTokenAsync(resource, app.ClientId, app.RedirectUri, new PlatformParameters(PromptBehavior.SelectAccount));
                Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' without the cache");
            }

        }

19 Source : Program.cs
with MIT License
from Azure-Samples

static async Task DoIt()
        {
            AppCoordinates.AppCoordinates app = AppCoordinates.PreRegisteredApps.GetV1App(useInMsal: false);
            string resource = AppCoordinates.PreRegisteredApps.MsGraph;

            string cacheFolder = Path.GetFullPath(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location) + @"..\..\..\..");
            string adalV3cacheFileName = Path.Combine(cacheFolder, "cacheAdalV3.bin");
            string msalCacheFileName = Path.Combine(cacheFolder, "cacheMsal.bin");
            FilesBasedTokenCache tokenCache = new FilesBasedTokenCache(adalV3cacheFileName, msalCacheFileName);
            AuthenticationContext authenticationContext = new AuthenticationContext(app.Authority, tokenCache);

            AuthenticationResult result;
            try
            {
                result = await authenticationContext.AcquireTokenSilentAsync(resource, app.ClientId);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' from the cache");
                Console.ResetColor();
            }
            catch (AdalSilentTokenAcquisitionException)
            {
                result = await authenticationContext.AcquireTokenAsync(resource, app.ClientId, app.RedirectUri, new PlatformParameters(PromptBehavior.SelectAccount));
                Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' without the cache");
            }

        }

19 Source : Program.cs
with MIT License
from Azure-Samples

private static void LoadSampleOptions()
        {
            SampleMap = new Dictionary<string, ExampleAbstraction>();

            var samples = replacedembly.GetEntryreplacedembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);

            foreach (var sample in samples)
            {
                var sampleImpl = new ExampleAbstraction(sample);
                sampleImpl.Load();

                SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
            }
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

private static void Usage(Mono.Options.OptionSet options)
        {
            // show usage
            Logger.Information("");
            Logger.Information($"{ProgramName} V{FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location).FileVersion}");
            Logger.Information($"Informational version: V{(Attribute.GetCustomAttribute(replacedembly.GetEntryreplacedembly(), typeof(replacedemblyInformationalVersionAttribute)) as replacedemblyInformationalVersionAttribute).InformationalVersion}");
            Logger.Information("");
            Logger.Information("Usage: {0}.exe [<options>]", replacedembly.GetEntryreplacedembly().GetName().Name);
            Logger.Information("");
            Logger.Information($"{ProgramName} to run actions against OPC UA servers.");
            Logger.Information("To exit the application, just press CTRL-C while it is running.");
            Logger.Information("");
            Logger.Information("To specify a list of strings, please use the following format:");
            Logger.Information("\"<string 1>,<string 2>,...,<string n>\"");
            Logger.Information("or if one string contains commas:");
            Logger.Information("\"\"<string 1>\",\"<string 2>\",...,\"<string n>\"\"");
            Logger.Information("");

            // output the options
            Logger.Information("Options:");
            StringBuilder stringBuilder = new StringBuilder();
            StringWriter stringWriter = new StringWriter(stringBuilder);
            options.WriteOptionDescriptions(stringWriter);
            string[] helpLines = stringBuilder.ToString().Split("\n");
            foreach (var line in helpLines)
            {
                Logger.Information(line);
            }
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

public async static Task MainAsync(string[] args)
        {
            try
            {
                var shouldShowHelp = false;

                // shutdown token sources
                ShutdownTokenSource = new CancellationTokenSource();

                // command line options
                Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                        { "cf|configfile=", $"the filename containing action configuration.\nDefault: '{OpcActionConfigurationFilename}'", (string p) => OpcActionConfigurationFilename = p },

                        { "tc|testconnectivity", $"tests connectivity with the default server '{TestConnectivity}'.\nDefault: {TestConnectivity}", b => TestConnectivity = b != null },
                        { "tu|testunsecureconnectivity", $"tests connectivity with the default server '{TestUnsecureConnectivity}' using an unsecured endpoint.\nDefault: {TestUnsecureConnectivity}", b => TestUnsecureConnectivity = b != null },

                        { "de|defaultendpointurl=", $"endpoint OPC UA server used as default.\nDefault: {DefaultEndpointUrl}", (string s) => DefaultEndpointUrl = s },

                        { "sw|sessionconnectwait=", $"specify the wait time in seconds we try to connect to disconnected endpoints and starts monitoring unmonitored items\nMin: 10\nDefault: {SessionConnectWait}", (int i) => {
                                if (i > 10)
                                {
                                    SessionConnectWait = i;
                                }
                                else
                                {
                                    throw new OptionException("The sessionconnectwait must be greater than 10 sec", "sessionconnectwait");
                                }
                            }
                        },
                        { "di|diagnosticsinterval=", $"shows diagnostic info at the specified interval in seconds (need log level info). 0 disables diagnostic output.\nDefault: {DiagnosticsInterval}", (uint u) => DiagnosticsInterval = u },

                        { "lf|logfile=", $"the filename of the logfile to use.\nDefault: './{_logFileName}'", (string l) => _logFileName = l },
                        { "lt|logflushtimespan=", $"the timespan in seconds when the logfile should be flushed.\nDefault: {_logFileFlushTimeSpanSec} sec", (int s) => {
                                if (s > 0)
                                {
                                    _logFileFlushTimeSpanSec = TimeSpan.FromSeconds(s);
                                }
                                else
                                {
                                    throw new Mono.Options.OptionException("The logflushtimespan must be a positive number.", "logflushtimespan");
                                }
                            }
                        },
                        { "ll|loglevel=", $"the loglevel to use (allowed: fatal, error, warn, info, debug, verbose).\nDefault: info", (string l) => {
                                List<string> logLevels = new List<string> {"fatal", "error", "warn", "info", "debug", "verbose"};
                                if (logLevels.Contains(l.ToLowerInvariant()))
                                {
                                    _logLevel = l.ToLowerInvariant();
                                }
                                else
                                {
                                    throw new Mono.Options.OptionException("The loglevel must be one of: fatal, error, warn, info, debug, verbose", "loglevel");
                                }
                            }
                        },

                        // opc configuration options
                        { "ol|opcmaxstringlen=", $"the max length of a string opc can transmit/receive.\nDefault: {OpcMaxStringLength}", (int i) => {
                                if (i > 0)
                                {
                                    OpcMaxStringLength = i;
                                }
                                else
                                {
                                    throw new OptionException("The max opc string length must be larger than 0.", "opcmaxstringlen");
                                }
                            }
                        },
                        { "ot|operationtimeout=", $"the operation timeout of the OPC UA client in ms.\nDefault: {OpcOperationTimeout}", (int i) => {
                                if (i >= 0)
                                {
                                    OpcOperationTimeout = i;
                                }
                                else
                                {
                                    throw new OptionException("The operation timeout must be larger or equal 0.", "operationtimeout");
                                }
                            }
                        },
                        { "ct|createsessiontimeout=", $"specify the timeout in seconds used when creating a session to an endpoint. On unsuccessful connection attemps a backoff up to {OpcSessionCreationBackoffMax} times the specified timeout value is used.\nMin: 1\nDefault: {OpcSessionCreationTimeout}", (uint u) => {
                                if (u > 1)
                                {
                                    OpcSessionCreationTimeout = u;
                                }
                                else
                                {
                                    throw new OptionException("The createsessiontimeout must be greater than 1 sec", "createsessiontimeout");
                                }
                            }
                        },
                        { "ki|keepaliveinterval=", $"specify the interval in seconds se send keep alive messages to the OPC servers on the endpoints it is connected to.\nMin: 2\nDefault: {OpcKeepAliveInterval}", (int i) => {
                                if (i >= 2)
                                {
                                    OpcKeepAliveInterval = i;
                                }
                                else
                                {
                                    throw new OptionException("The keepaliveinterval must be greater or equal 2", "keepalivethreshold");
                                }
                            }
                        },
                        { "kt|keepalivethreshold=", $"specify the number of keep alive packets a server can miss, before the session is disconneced\nMin: 1\nDefault: {OpcKeepAliveDisconnectThreshold}", (uint u) => {
                                if (u > 1)
                                {
                                    OpcKeepAliveDisconnectThreshold = u;
                                }
                                else
                                {
                                    throw new OptionException("The keepalivethreshold must be greater than 1", "keepalivethreshold");
                                }
                            }
                        },

                        { "aa|autoaccept", $"trusts all servers we establish a connection to.\nDefault: {AutoAcceptCerts}", b => AutoAcceptCerts = b != null },

                        { "to|trustowncert", $"our own certificate is put into the trusted certificate store automatically.\nDefault: {TrustMyself}", t => TrustMyself = t != null  },

                        // cert store options
                        { "at|appcertstoretype=", $"the own application cert store type. \n(allowed values: Directory, X509Store)\nDefault: '{OpcOwnCertStoreType}'", (string s) => {
                                if (s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) || s.Equals(CertificateStoreType.Directory, StringComparison.OrdinalIgnoreCase))
                                {
                                    OpcOwnCertStoreType = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? CertificateStoreType.X509Store : CertificateStoreType.Directory;
                                    OpcOwnCertStorePath = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? OpcOwnCertX509StorePathDefault : OpcOwnCertDirectoryStorePathDefault;
                                }
                                else
                                {
                                    throw new OptionException();
                                }
                            }
                        },
                        { "ap|appcertstorepath=", $"the path where the own application cert should be stored\nDefault (depends on store type):\n" +
                                $"X509Store: '{OpcOwnCertX509StorePathDefault}'\n" +
                                $"Directory: '{OpcOwnCertDirectoryStorePathDefault}'", (string s) => OpcOwnCertStorePath = s
                        },

                        { "tp|trustedcertstorepath=", $"the path of the trusted cert store\nDefault '{OpcTrustedCertDirectoryStorePathDefault}'", (string s) => OpcTrustedCertStorePath = s
                        },

                        { "rp|rejectedcertstorepath=", $"the path of the rejected cert store\nDefault '{OpcRejectedCertDirectoryStorePathDefault}'", (string s) => OpcRejectedCertStorePath = s
                        },

                        { "ip|issuercertstorepath=", $"the path of the trusted issuer cert store\nDefault '{OpcIssuerCertDirectoryStorePathDefault}'", (string s) => OpcIssuerCertStorePath = s
                        },

                        { "csr", $"show data to create a certificate signing request\nDefault '{ShowCreateSigningRequestInfo}'", c => ShowCreateSigningRequestInfo = c != null
                        },

                        { "ab|applicationcertbase64=", $"update/set this applications certificate with the certificate preplaceded in as bas64 string", (string s) =>
                            {
                                NewCertificateBase64String = s;
                            }
                        },
                        { "af|applicationcertfile=", $"update/set this applications certificate with the certificate file specified", (string s) =>
                            {
                                if (File.Exists(s))
                                {
                                    NewCertificateFileName = s;
                                }
                                else
                                {
                                    throw new OptionException($"The file '{s}' does not exist.", "applicationcertfile");
                                }
                            }
                        },

                        { "pb|privatekeybase64=", $"initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key preplaceded in as base64 string", (string s) =>
                            {
                                PrivateKeyBase64String = s;
                            }
                        },
                        { "pk|privatekeyfile=", $"initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key preplaceded in as file", (string s) =>
                            {
                                if (File.Exists(s))
                                {
                                    PrivateKeyFileName = s;
                                }
                                else
                                {
                                    throw new OptionException($"The file '{s}' does not exist.", "privatekeyfile");
                                }
                            }
                        },

                        { "cp|certpreplacedword=", $"the optional preplacedword for the PEM or PFX or the installed application certificate", (string s) =>
                            {
                                CertificatePreplacedword = s;
                            }
                        },

                        { "tb|addtrustedcertbase64=", $"adds the certificate to the applications trusted cert store preplaceded in as base64 string (multiple strings supported)", (string s) =>
                            {
                                TrustedCertificateBase64Strings = ParseListOfStrings(s);
                            }
                        },
                        { "tf|addtrustedcertfile=", $"adds the certificate file(s) to the applications trusted cert store preplaceded in as base64 string (multiple filenames supported)", (string s) =>
                            {
                                TrustedCertificateFileNames = ParseListOfFileNames(s, "addtrustedcertfile");
                            }
                        },

                        { "ib|addissuercertbase64=", $"adds the specified issuer certificate to the applications trusted issuer cert store preplaceded in as base64 string (multiple strings supported)", (string s) =>
                            {
                                IssuerCertificateBase64Strings = ParseListOfStrings(s);
                            }
                        },
                        { "if|addissuercertfile=", $"adds the specified issuer certificate file(s) to the applications trusted issuer cert store (multiple filenames supported)", (string s) =>
                            {
                                IssuerCertificateFileNames = ParseListOfFileNames(s, "addissuercertfile");
                            }
                        },

                        { "rb|updatecrlbase64=", $"update the CRL preplaceded in as base64 string to the corresponding cert store (trusted or trusted issuer)", (string s) =>
                            {
                                CrlBase64String = s;
                            }
                        },
                        { "uc|updatecrlfile=", $"update the CRL preplaceded in as file to the corresponding cert store (trusted or trusted issuer)", (string s) =>
                            {
                                if (File.Exists(s))
                                {
                                    CrlFileName = s;
                                }
                                else
                                {
                                    throw new OptionException($"The file '{s}' does not exist.", "updatecrlfile");
                                }
                            }
                        },

                        { "rc|removecert=", $"remove cert(s) with the given thumbprint(s) (multiple thumbprints supported)", (string s) =>
                            {
                                ThumbprintsToRemove = ParseListOfStrings(s);
                            }
                        },

                        // misc
                        { "h|help", "show this message and exit", h => shouldShowHelp = h != null },
                    };

            List<string> extraArgs = new List<string>();
            try
            {
                // parse the command line
                extraArgs = options.Parse(args);
            }
            catch (OptionException e)
            {
                // initialize logging
                InitLogging();

                    // show message
                    Logger.Fatal(e, "Error in command line options");
                    Logger.Error($"Command line arguments: {String.Join(" ", args)}");

                    // show usage
                    Usage(options);
                    return;
                }

                // initialize logging
                InitLogging();

                // show usage if requested
                if (shouldShowHelp)
                {
                    Usage(options);
                    return;
                }

                // validate and parse extra arguments
                if (extraArgs.Count > 0)
                {
                    Logger.Error("Error in command line options");
                    Logger.Error($"Command line arguments: {String.Join(" ", args)}");
                    Usage(options);
                    return;
                }

                //show version
                Logger.Information($"{ProgramName} V{FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location).FileVersion} starting up...");
                Logger.Debug($"Informational version: V{(Attribute.GetCustomAttribute(replacedembly.GetEntryreplacedembly(), typeof(replacedemblyInformationalVersionAttribute)) as replacedemblyInformationalVersionAttribute).InformationalVersion}");

                // allow canceling the application
                var quitEvent = new ManualResetEvent(false);
                try
                {
                    Console.CancelKeyPress += (sender, eArgs) =>
                    {
                        quitEvent.Set();
                        eArgs.Cancel = true;
                        ShutdownTokenSource.Cancel();
                    };
                }
                catch
                {
                }

                // init OPC configuration and tracing
                OpcApplicationConfiguration applicationStackConfiguration = new OpcApplicationConfiguration();
                await applicationStackConfiguration.ConfigureAsync();

                // read OPC action configuration
                OpcConfiguration.Init();
                if (!await ReadOpcConfigurationAsync())
                {
                    return;
                }

                // add well known actions
                if (!await CreateOpcActionDataAsync())
                {
                    return;
                }

                // kick off OPC client activities
                await SessionStartAsync();

                // initialize diagnostics
                Diagnostics.Init();

                // stop on user request
                Logger.Information("");
                Logger.Information("");
                Logger.Information($"{ProgramName} is running. Press CTRL-C to quit.");

                // wait for Ctrl-C
                quitEvent.WaitOne(Timeout.Infinite);

                Logger.Information("");
                Logger.Information("");
                ShutdownTokenSource.Cancel();
                Logger.Information($"{ProgramName} is shutting down...");

                // shutdown all OPC sessions
                await SessionShutdownAsync();

                // shutdown diagnostics
                await ShutdownAsync();

                ShutdownTokenSource = null;
            }
            catch (Exception e)
            {
                Logger.Fatal(e, e.StackTrace);
                e = e.InnerException ?? null;
                while (e != null)
                {
                    Logger.Fatal(e, e.StackTrace);
                    e = e.InnerException ?? null;
                }
                Logger.Fatal($"{ProgramName} exiting... ");
            }
        }

See More Examples