static WebApplication()
            {
                var application = new WebApplication();

                IHttpModule module = new SimpleInjectorHttpModule();

                // This registers the EndRequest event in the HttpApplication
                module.Init(application);

                Instance = application;
            }
Esempio n. 2
0
        protected void Application_Start()
        {
            //AreaRegistration.RegisterAllAreas();

            var engine = this.Engine; // Initialize CMS engine
            engine.RegisterControllers(Assembly.GetExecutingAssembly());

            var app = new WebApplication();
            app.RegisterGlobalFilters(GlobalFilters.Filters, engine);
            app.RegisterRoutes(RouteTable.Routes);
            app.RegisterComponents(engine);

            // Register custom controller factory
            ControllerBuilder.Current.SetControllerFactory(engine.Resolve<IControllerFactory>());
        }
        private static ProcessStartInfo InitializeIisExpress(WebApplication application, string deployPath = null)
        {
            // todo: grab stdout and/or stderr for logging purposes?
            var key = Environment.Is64BitOperatingSystem ? "programfiles(x86)" : "programfiles";
            var programfiles = Environment.GetEnvironmentVariable(key);

            var startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                ErrorDialog = true,
                LoadUserProfile = true,
                CreateNoWindow = false,
                UseShellExecute = false,
                Arguments = String.Format("/path:\"{0}\" /port:{1}", deployPath ?? application.Location.FullPath, application.PortNumber),
                FileName = string.Format("{0}\\IIS Express\\iisexpress.exe", programfiles)
            };

            foreach (var variable in application.EnvironmentVariables)
                startInfo.EnvironmentVariables.Add(variable.Key, variable.Value);

            return startInfo;
        }
Esempio n. 4
0
 // Entry point for the application.
 public static void Main(string[] args) => WebApplication.Run <Startup>(args);
 private void SetConnectionString(WebApplication webApplication)
 {
     string siteMode = ConfigurationManager.AppSettings["SiteMode"];
     if(siteMode != null && siteMode.ToLower() == "true") {
         webApplication.ConnectionString = InMemoryDataStoreProvider.ConnectionString;
     }
     else {
         ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["ConnectionString"];
         if(connectionStringSettings != null) {
             webApplication.ConnectionString = connectionStringSettings.ConnectionString;
         }
         else if(string.IsNullOrEmpty(webApplication.ConnectionString) && webApplication.Connection == null) {
             connectionStringSettings = ConfigurationManager.ConnectionStrings["SqlExpressConnectionString"];
             if(connectionStringSettings != null) {
                 webApplication.ConnectionString = DbEngineDetector.PatchConnectionString(connectionStringSettings.ConnectionString);
             }
         }
     }
 }
Esempio n. 6
0
 public static void ConfigureSettingsEndpoints(this WebApplication app)
 {
     app.MapGet("/api/v1/Settings", GetSettings);
     app.MapPut("/api/v1/Settings/Prices/{price}/{balance}", UpdatePrices).RequireAuthorization();
     app.MapPut("api/v1/Settings/Loan/{balance}/{amount}", LoanInfo).RequireAuthorization();
 }
Esempio n. 7
0
 public static void SwitchToWindow(this WebApplication webApplication, string window)
 {
     webApplication.WebDriver.SwitchTo().Window(window);
 }
 /// <summary>
 /// Obsolete
 /// </summary>
 public static void Run(WebApplication app, Action <IAppConfigurator> configure)
 {
 }
Esempio n. 9
0
        public static async Task RunAsync(Application application, string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Logging for this application
            builder.Host.UseSerilog((context, configuration) => configuration
                                    .MinimumLevel.Verbose()
                                    .Filter.ByExcluding(Matching.FromSource("Microsoft"))
                                    .Enrich
                                    .FromLogContext()
                                    .WriteTo
                                    .Console()
                                    );

            builder.Services.AddRazorPages(o => o.RootDirectory = "/Dashboard/Pages");

            builder.Services.AddServerSideBlazor();

            builder.Services.AddOptions <StaticFileOptions>()
            .PostConfigure(o =>
            {
                var fileProvider = new ManifestEmbeddedFileProvider(typeof(MicronetesHost).Assembly, "wwwroot");

                // Make sure we don't remove the existing file providers (blazor needs this)
                o.FileProvider = new CompositeFileProvider(o.FileProvider, fileProvider);
            });

            builder.Services.AddSingleton(application);

            using var app = builder.Build();

            var port = app.Configuration["port"] ?? "0";

            app.Listen($"http://127.0.0.1:{port}");

            app.UseDeveloperExceptionPage();

            app.UseStaticFiles();

            app.UseRouting();

            var api = new MicronetesApi();

            api.MapRoutes(app);

            app.MapBlazorHub();
            app.MapFallbackToPage("/_Host");

            var logger = app.Logger;

            logger.LogInformation("Executing application from  {Source}", application.Source);

            var lifetime      = app.ApplicationLifetime;
            var configuration = app.Configuration;

            var diagnosticOptions    = DiagnosticOptions.FromConfiguration(configuration);
            var diagnosticsCollector = new DiagnosticsCollector(logger, diagnosticOptions);

            // Print out what providers were selected and their values
            diagnosticOptions.DumpDiagnostics(logger);

            var processor = new AggregateApplicationProcessor(new IApplicationProcessor[] {
                new EventPipeDiagnosticsRunner(logger, diagnosticsCollector),
                new ProxyService(logger),
                new DockerRunner(logger),
                new ProcessRunner(logger, ProcessRunnerOptions.FromArgs(args)),
            });

            await app.StartAsync();

            logger.LogInformation("Dashboard running on {Address}", app.Addresses.First());

            try
            {
                await processor.StartAsync(application);
            }
            catch (Exception ex)
            {
                logger.LogError(0, ex, "Failed to launch application");
            }

            var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            lifetime.ApplicationStopping.Register(obj => waitForStop.TrySetResult(null), null);

            await waitForStop.Task;

            logger.LogInformation("Shutting down...");

            try
            {
                await processor.StopAsync(application);
            }
            finally
            {
                // Stop the host after everything else has been shutdown
                await app.StopAsync();
            }
        }
Esempio n. 10
0
        public async Task <Application> RegisterClientApplicationAsync(
            Application serviceApplication,
            string clientsApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            tags ??= new List <string>();

            // Extract id of Oauth2PermissionScope for user impersonation
            var saApiOauth2PermissionScopeUserImpersonationList = serviceApplication
                                                                  .Api
                                                                  .Oauth2PermissionScopes
                                                                  .Where(scope => "User" == scope.Type &&
                                                                         "user_impersonation" == scope.Value &&
                                                                         scope.IsEnabled.GetValueOrDefault(false)
                                                                         )
                                                                  .ToList();

            if (saApiOauth2PermissionScopeUserImpersonationList.Count != 1 ||
                !saApiOauth2PermissionScopeUserImpersonationList.First().Id.HasValue)
            {
                throw new Exception("Service appplication does not expose Oauth2PermissionScope for user impersonation.");
            }

            var saApiOauth2PermissionScopeUserImpersonationId =
                saApiOauth2PermissionScopeUserImpersonationList.First().Id.Value;

            var serviceApplicationUserImpersonationRequiredResourceAccess = new RequiredResourceAccess {
                ResourceAppId  = serviceApplication.AppId, // service application
                ResourceAccess = new List <ResourceAccess> {
                    new ResourceAccess {
                        Id   = saApiOauth2PermissionScopeUserImpersonationId, // "user_impersonation"
                        Type = "Scope"
                    }
                }
            };

            var microsoftGraphUserReadRequiredResourceAccess = new RequiredResourceAccess {
                ResourceAppId  = AzureAppsConstants.MicrosoftGraph.AppId,
                ResourceAccess = new List <ResourceAccess> {
                    new ResourceAccess {
                        Id   = AzureAppsConstants.MicrosoftGraph.ResourceAccess["User.Read"],
                        Type = "Scope"
                    }
                }
            };

            var clientApplicationRequiredResourceAccess = new List <RequiredResourceAccess>()
            {
                serviceApplicationUserImpersonationRequiredResourceAccess,
                microsoftGraphUserReadRequiredResourceAccess
            };

            var clientApplicationPublicClientApplication = new Microsoft.Graph.PublicClientApplication {
                RedirectUris = new List <string> {
                    "urn:ietf:wg:oauth:2.0:oob"
                }
            };

            // Note: Oauth2AllowImplicitFlow will be enabled automatically since both
            // EnableIdTokenIssuance and EnableAccessTokenIssuance are set to true.

            var clientApplicationWebApplicatoin = new WebApplication {
                //Oauth2AllowImplicitFlow = true,
                ImplicitGrantSettings = new ImplicitGrantSettings {
                    EnableIdTokenIssuance     = true,
                    EnableAccessTokenIssuance = true
                }
            };

            var clientApplicationRequest = new Application {
                DisplayName            = clientsApplicationName,
                IsFallbackPublicClient = true,
                Tags                   = tags,
                SignInAudience         = "AzureADMyOrg",
                RequiredResourceAccess = clientApplicationRequiredResourceAccess,
                PublicClient           = clientApplicationPublicClientApplication,
                Web = clientApplicationWebApplicatoin,
                PasswordCredentials = new List <PasswordCredential> {
                }
            };

            var clientApplication = await _graphServiceClient
                                    .Applications
                                    .Request()
                                    .AddAsync(clientApplicationRequest, cancellationToken);

            // Add Client Key PasswordCredential
            var clientKeyName = "Client Key";

            var clientApplicationClientKeyPasswordCredentialDefinition = new PasswordCredential {
                StartDateTime       = DateTimeOffset.UtcNow,
                EndDateTime         = DateTimeOffset.UtcNow.AddYears(2),
                CustomKeyIdentifier = ToBase64Bytes(clientKeyName),
                DisplayName         = clientKeyName
            };

            await _graphServiceClient
            .Applications[clientApplication.Id]
            .AddPassword(clientApplicationClientKeyPasswordCredentialDefinition)
            .Request()
            .PostAsync(cancellationToken);

            // We need to create ServicePrincipal for this application.
            await CreateServicePrincipalAsync(
                clientApplication,
                tags,
                cancellationToken
                );

            return(clientApplication);
        }
Esempio n. 11
0
 bool RememberMeViewItemExists(WebApplication webApplication, object logonParameters) {
     var detailViewId = webApplication.FindDetailViewId(logonParameters.GetType());
     return ((IModelDetailView)webApplication.Model.Views[detailViewId]).Items["RememberMe"] != null;
 }
Esempio n. 12
0
        public static void Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var builder = WebApplication.CreateBuilder(args);

            builder.WebHost.ConfigureLogging((hostContext, logging) =>
            {
                logging.ClearProviders()
                .AddConsole()
                .AddFile(
                    outputTemplate: "[{Timestamp:yyyy/MM/dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
#if DEBUG
                    minimumLevel: LogLevel.Debug,
#else
                    minimumLevel: LogLevel.Information,
#endif
                    pathFormat: "D:/project-data/LottoLION/Logger/WebAPI/log-{Date}.txt"
                    );
            });

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            builder.Services.AddDbContextFactory <AppDbContext>(options =>
            {
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
            });

            builder.Services.AddSingleton <WinnerReader>();
            builder.Services.AddSingleton <PrizeReader>();
            builder.Services.AddSingleton <PipeClient>();
            builder.Services.AddSingleton <CCryption>();
            builder.Services.AddSingleton <dForcast>();

            builder.Services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder => builder
                                  //.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });


            // Make authentication compulsory across the board (i.e. shutdown EVERYTHING unless explicitly opened up).
            {
                SigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration["Tokens:Key"]));

                // Get options from app settings
                var _jwt_appsettings = builder.Configuration.GetSection(nameof(JwtIssuerOptions));

                var _jwt_useroptions = new JwtIssuerOptions
                {
                    Issuer             = _jwt_appsettings[nameof(JwtIssuerOptions.Issuer)],
                    Audience           = _jwt_appsettings[nameof(JwtIssuerOptions.Audience)],
                    ValidFor           = TimeSpan.FromMinutes(Convert.ToInt32(_jwt_appsettings[nameof(JwtIssuerOptions.ValidFor)])),
                    SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256)
                };

                builder.Services
                .Configure <JwtIssuerOptions>(options =>
                {
                    // For Injection => Configure JwtIssuerOptions
                    options.Issuer             = _jwt_useroptions.Issuer;
                    options.Audience           = _jwt_useroptions.Audience;
                    options.ValidFor           = _jwt_useroptions.ValidFor;
                    options.SigningCredentials = _jwt_useroptions.SigningCredentials;
                })
                .AddMvc(config =>
                {
                    var _policy = new AuthorizationPolicyBuilder()
                                  .RequireAuthenticatedUser()
                                  .Build();

                    config.Filters.Add(new AuthorizeFilter(_policy));
                })
                .AddJsonOptions(option =>
                {
                    option.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                });

                // For Authentication
                builder.Services
                .AddAuthorization(options =>
                {
                    // Use policy auth.
                    options.AddPolicy("LottoLionGuest",
                                      policy =>
                    {
                        policy.RequireClaim("UserType", "Guest");
                    });

                    options.AddPolicy("LottoLionMember",
                                      policy =>
                    {
                        policy.RequireClaim("UserType", "Member");
                    });

                    options.AddPolicy("LottoLionUsers",
                                      policy =>
                    {
                        policy.RequireRole("ValidUsers");
                    });
                })
                .AddAuthentication(sharedOptions =>
                {
                    sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    sharedOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken            = true;

                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidIssuer    = _jwt_useroptions.Issuer,

                        ValidateAudience = true,
                        ValidAudience    = _jwt_useroptions.Audience,

                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = SigningKey,

                        RequireExpirationTime = true,
                        ValidateLifetime      = true,

                        ClockSkew = TimeSpan.Zero
                    };
                });
            }


            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            //app.UseHttpsRedirection();
            app.UseAuthentication();

            // global policy - assign here or on each controller
            app.UseCors("CorsPolicy");

            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
Esempio n. 13
0
        protected override void InternalProcessRecord()
        {
            bool test = false;
            ShouldProcessReason reason;

            if (!base.ShouldProcess(null, null, null, out reason))
            {
                if (reason == ShouldProcessReason.WhatIf)
                {
                    test = true;
                }
            }
            if (test)
            {
                Logger.Verbose = true;
            }

            Common.WebParts.ReplaceWebPartContent.Settings settings = new Common.WebParts.ReplaceWebPartContent.Settings();
            settings.SearchString  = SearchString;
            settings.ReplaceString = ReplaceString;
            settings.WebPartName   = WebPartName;
            settings.Publish       = Publish.IsPresent;
            settings.Test          = test;
            settings.UnsafeXml     = UnsafeXml;

            switch (ParameterSetName)
            {
            case "WebApplication":
                SPWebApplication webApp1 = WebApplication.Read();
                if (webApp1 == null)
                {
                    throw new SPException("Web Application not found.");
                }
                Common.WebParts.ReplaceWebPartContent.ReplaceValues(webApp1, settings);
                break;

            case "Site":
                using (SPSite site = Site.Read())
                {
                    Common.WebParts.ReplaceWebPartContent.ReplaceValues(site, settings);
                }
                break;

            case "Web":
                using (SPWeb web = Web.Read())
                {
                    try
                    {
                        Common.WebParts.ReplaceWebPartContent.ReplaceValues(web, settings);
                    }
                    finally
                    {
                        web.Site.Dispose();
                    }
                }
                break;

            case "Page":
                SPFile file = Page.Read();
                try
                {
                    Common.WebParts.ReplaceWebPartContent.ReplaceValues(file.Web, file, settings);
                }
                finally
                {
                    file.Web.Dispose();
                    file.Web.Site.Dispose();
                }
                break;

            default:
                SPFarm farm = Farm.Read();
                foreach (SPService svc in farm.Services)
                {
                    if (!(svc is SPWebService))
                    {
                        continue;
                    }

                    foreach (SPWebApplication webApp2 in ((SPWebService)svc).WebApplications)
                    {
                        Common.WebParts.ReplaceWebPartContent.ReplaceValues(webApp2, settings);
                    }
                }
                break;
            }
        }
Esempio n. 14
0
        protected async Task <Tuple <Application, PasswordCredential> > RegisterAKSApplicationAsync(
            string aksApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new List <string>();

                Log.Information("Creating AKS application registration ...");

                // Add OAuth2Permissions for user impersonation
                var aksOauth2Permissions = new List <PermissionScope> {
                    new PermissionScope {
                        AdminConsentDescription = $"Allow the app to access {aksApplicationName} on behalf of the signed-in user.",
                        AdminConsentDisplayName = $"Access {aksApplicationName}",
                        Id        = Guid.NewGuid(),
                        IsEnabled = true,
                        Type      = "User",
                        UserConsentDescription = $"Allow the application to access {aksApplicationName} on your behalf.",
                        UserConsentDisplayName = $"Access {aksApplicationName}",
                        Value = "user_impersonation"
                    }
                };

                var aksApplicationApiApplication = new ApiApplication {
                    Oauth2PermissionScopes = aksOauth2Permissions
                };

                // ODataType = null is a workaround for a bug:
                // https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet/issues/87
                var aksApplicationWebApplication = new WebApplication {
                    ImplicitGrantSettings = new ImplicitGrantSettings {
                        ODataType             = null,
                        EnableIdTokenIssuance = true
                    }
                };

                var aksApplicationDefinition = new Application {
                    DisplayName            = aksApplicationName,
                    IsFallbackPublicClient = false,
                    IdentifierUris         = new List <string> {
                        $"https://{_tenantId.ToString()}/{aksApplicationName}"
                    },
                    Tags                   = tags,
                    SignInAudience         = "AzureADMyOrg",
                    AppRoles               = new List <AppRole>(),
                    RequiredResourceAccess = new List <RequiredResourceAccess>(),
                    Api = aksApplicationApiApplication,
                    Web = aksApplicationWebApplication,
                    PasswordCredentials = new List <PasswordCredential> {
                    }
                };

                var aksApplication = await _msGraphServiceClient
                                     .CreateApplicationAsync(
                    aksApplicationDefinition,
                    cancellationToken
                    );

                // Add RBAC Key PasswordCredential
                var aksApplicationPasswordCredential = await _msGraphServiceClient
                                                       .AddApplication2YPasswordCredentialAsync(
                    aksApplication,
                    AKS_KEY_NAME,
                    cancellationToken
                    );

                // We need to create ServicePrincipal for this application.
                await _msGraphServiceClient
                .CreateApplicationServicePrincipalAsync(
                    aksApplication,
                    tags,
                    cancellationToken
                    );

                // Get updated definition
                aksApplication = await _msGraphServiceClient
                                 .GetApplicationAsync(
                    new Guid(aksApplication.Id),
                    cancellationToken
                    );

                var result = new Tuple <Application, PasswordCredential>(
                    aksApplication,
                    aksApplicationPasswordCredential
                    );

                Log.Information("Created AKS application registration.");

                return(result);
            }
            catch (Exception) {
                Log.Error("Failed to create AKS application registration.");
                throw;
            }
        }
Esempio n. 15
0
        protected async Task <Tuple <Application, PasswordCredential> > RegisterClientApplicationAsync(
            Application serviceApplication,
            string clientApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new List <string>();

                Log.Information("Creating client application registration ...");

                // Extract id of Oauth2PermissionScope for user impersonation
                var saApiOauth2PermissionScopeUserImpersonationList = serviceApplication
                                                                      .Api
                                                                      .Oauth2PermissionScopes
                                                                      .Where(scope => "User" == scope.Type &&
                                                                             "user_impersonation" == scope.Value &&
                                                                             scope.IsEnabled.GetValueOrDefault(false)
                                                                             )
                                                                      .ToList();

                if (saApiOauth2PermissionScopeUserImpersonationList.Count != 1 ||
                    !saApiOauth2PermissionScopeUserImpersonationList.First().Id.HasValue)
                {
                    throw new Exception("Service appplication does not expose Oauth2PermissionScope for user impersonation.");
                }

                var saApiOauth2PermissionScopeUserImpersonationId =
                    saApiOauth2PermissionScopeUserImpersonationList.First().Id.Value;

                var serviceApplicationUserImpersonationRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = serviceApplication.AppId, // service application
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = saApiOauth2PermissionScopeUserImpersonationId, // "user_impersonation"
                            Type = "Scope"
                        }
                    }
                };

                var microsoftGraphUserReadRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = AzureAppsConstants.MicrosoftGraph.AppId,
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = AzureAppsConstants.MicrosoftGraph.ResourceAccess["User.Read"],
                            Type = "Scope"
                        }
                    }
                };

                var clientApplicationRequiredResourceAccess = new List <RequiredResourceAccess>()
                {
                    serviceApplicationUserImpersonationRequiredResourceAccess,
                    microsoftGraphUserReadRequiredResourceAccess
                };

                var clientApplicationPublicClientApplication = new Microsoft.Graph.PublicClientApplication {
                    RedirectUris = new List <string> {
                        "urn:ietf:wg:oauth:2.0:oob"
                    }
                };

                // Note: Oauth2AllowImplicitFlow will be enabled automatically since both
                // EnableIdTokenIssuance and EnableAccessTokenIssuance are set to true.

                // ODataType = null is a workaround for a bug:
                // https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet/issues/87
                var clientApplicationWebApplication = new WebApplication {
                    //Oauth2AllowImplicitFlow = true,
                    ImplicitGrantSettings = new ImplicitGrantSettings {
                        ODataType                 = null,
                        EnableIdTokenIssuance     = true,
                        EnableAccessTokenIssuance = true
                    }
                };

                var clientApplicationDefinition = new Application {
                    DisplayName            = clientApplicationName,
                    IsFallbackPublicClient = true,
                    IdentifierUris         = new List <string> {
                        $"https://{_tenantId.ToString()}/{clientApplicationName}"
                    },
                    Tags                   = tags,
                    SignInAudience         = "AzureADMyOrg",
                    RequiredResourceAccess = clientApplicationRequiredResourceAccess,
                    PublicClient           = clientApplicationPublicClientApplication,
                    Web = clientApplicationWebApplication,
                    PasswordCredentials = new List <PasswordCredential> {
                    }
                };

                var clientApplication = await _msGraphServiceClient
                                        .CreateApplicationAsync(
                    clientApplicationDefinition,
                    cancellationToken
                    );

                // Add Client Key PasswordCredential
                var clientApplicationPasswordCredential = await _msGraphServiceClient
                                                          .AddApplication2YPasswordCredentialAsync(
                    clientApplication,
                    CLIENT_KEY_NAME,
                    cancellationToken
                    );

                // We need to create ServicePrincipal for this application.
                await _msGraphServiceClient
                .CreateApplicationServicePrincipalAsync(
                    clientApplication,
                    tags,
                    cancellationToken
                    );

                // Get updated definition
                clientApplication = await _msGraphServiceClient
                                    .GetApplicationAsync(
                    new Guid(clientApplication.Id),
                    cancellationToken
                    );

                var result = new Tuple <Application, PasswordCredential>(
                    clientApplication,
                    clientApplicationPasswordCredential
                    );

                Log.Information("Created client application registration.");

                return(result);
            }
            catch (Exception) {
                Log.Error("Failed to created client application registration.");
                throw;
            }
        }
Esempio n. 16
0
        protected async Task <Tuple <Application, PasswordCredential> > RegisterServiceApplicationAsync(
            string serviceApplicationName,
            DirectoryObject owner,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new List <string>();

                Log.Information("Creating service application registration ...");

                // Setup AppRoles for service application
                var serviceApplicationAppRoles = new List <AppRole>();

                var serviceApplicationApproverRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Approver",
                    Value              = "Sign",
                    Description        = "Approvers have the ability to issue certificates.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationApproverRoleId
                });

                var serviceApplicationWriterRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Writer",
                    Value              = "Write",
                    Description        = "Writers Have the ability to change entities.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationWriterRoleId
                });

                var serviceApplicationAdministratorRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Administrator",
                    Value              = "Admin",
                    Description        = "Admins can access advanced features.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationAdministratorRoleId
                });

                // Setup RequiredResourceAccess for service application

                var keyVaultUserImpersonationRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = AzureAppsConstants.AzureKeyVault.AppId,
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = AzureAppsConstants.AzureKeyVault.ResourceAccess["user_impersonation"],
                            Type = "Scope"
                        }
                    }
                };

                var microsoftGraphUserReadRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = AzureAppsConstants.MicrosoftGraph.AppId,
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = AzureAppsConstants.MicrosoftGraph.ResourceAccess["User.Read"],
                            Type = "Scope"
                        }
                    }
                };

                var serviceApplicationRequiredResourceAccess = new List <RequiredResourceAccess>()
                {
                    keyVaultUserImpersonationRequiredResourceAccess,
                    microsoftGraphUserReadRequiredResourceAccess
                };

                // Add OAuth2Permissions
                var oauth2Permissions = new List <PermissionScope> {
                    new PermissionScope {
                        AdminConsentDescription = $"Allow the app to access {serviceApplicationName} on behalf of the signed-in user.",
                        AdminConsentDisplayName = $"Access {serviceApplicationName}",
                        Id        = Guid.NewGuid(),
                        IsEnabled = true,
                        Type      = "User",
                        UserConsentDescription = $"Allow the application to access {serviceApplicationName} on your behalf.",
                        UserConsentDisplayName = $"Access {serviceApplicationName}",
                        Value = "user_impersonation"
                    }
                };

                var serviceApplicationApiApplication = new ApiApplication {
                    Oauth2PermissionScopes = oauth2Permissions
                };

                // ODataType = null is a workaround for a bug:
                // https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet/issues/87
                var serviceApplicationWebApplication = new WebApplication {
                    ImplicitGrantSettings = new ImplicitGrantSettings {
                        ODataType             = null,
                        EnableIdTokenIssuance = true
                    }
                };

                var serviceApplicationDefinition = new Application {
                    DisplayName            = serviceApplicationName,
                    IsFallbackPublicClient = false,
                    IdentifierUris         = new List <string> {
                        $"https://{_tenantId.ToString()}/{serviceApplicationName}"
                    },
                    Tags                   = tags,
                    SignInAudience         = "AzureADMyOrg",
                    AppRoles               = serviceApplicationAppRoles,
                    RequiredResourceAccess = serviceApplicationRequiredResourceAccess,
                    Api = serviceApplicationApiApplication,
                    Web = serviceApplicationWebApplication,
                    PasswordCredentials = new List <PasswordCredential> {
                    }
                };

                var serviceApplication = await _msGraphServiceClient
                                         .CreateApplicationAsync(
                    serviceApplicationDefinition,
                    cancellationToken
                    );

                // Add Service Key PasswordCredential
                var serviceApplicationPasswordCredential = await _msGraphServiceClient
                                                           .AddApplication2YPasswordCredentialAsync(
                    serviceApplication,
                    SERVICE_KEY_NAME,
                    cancellationToken
                    );

                // We need to create ServicePrincipal for this application.
                var serviceApplicationSP = await _msGraphServiceClient
                                           .CreateApplicationServicePrincipalAsync(
                    serviceApplication,
                    tags,
                    cancellationToken
                    );

                // Add app role assignment to owner as Approver, Writer and Administrator.
                string PrincipalType;

                if (owner is User)
                {
                    PrincipalType = "User";
                }
                else if (owner is ServicePrincipal)
                {
                    PrincipalType = "ServicePrincipal";
                }
                else if (owner is Group)
                {
                    PrincipalType = "Group";
                }
                else
                {
                    throw new ArgumentException($"Owner is of unknown type: {owner.GetType()}", "owner");
                }

                var approverAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Approver",
                    Id        = serviceApplicationApproverRoleId.ToString(),
                    AppRoleId = serviceApplicationApproverRoleId
                };

                var writerAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Writer",
                    Id        = serviceApplicationWriterRoleId.ToString(),
                    AppRoleId = serviceApplicationWriterRoleId
                };

                var administratorAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Administrator",
                    Id        = serviceApplicationAdministratorRoleId.ToString(),
                    AppRoleId = serviceApplicationAdministratorRoleId
                };

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    approverAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    writerAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    administratorAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                // Get updated definition
                serviceApplication = await _msGraphServiceClient
                                     .GetApplicationAsync(
                    new Guid(serviceApplication.Id),
                    cancellationToken
                    );

                var result = new Tuple <Application, PasswordCredential>(
                    serviceApplication,
                    serviceApplicationPasswordCredential
                    );

                Log.Information("Created service application registration.");

                return(result);
            }
            catch (Exception) {
                Log.Error("Failed to create service application registration.");
                throw;
            }
        }
 /// <summary>
 /// Microservice configuration setup
 /// </summary>
 /// <param name="app"></param>
 public virtual void ConfigureApplication(WebApplication app)
 {
 }
Esempio n. 18
0
        public async Task <Tuple <Application, string> > RegisterAKSApplicationAsync(
            string aksApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            tags ??= new List <string>();

            // Add OAuth2Permissions for user impersonation
            var aksOauth2Permissions = new List <PermissionScope> {
                new PermissionScope {
                    AdminConsentDescription = $"Allow the app to access {aksApplicationName} on behalf of the signed-in user.",
                    AdminConsentDisplayName = $"Access {aksApplicationName}",
                    Id        = Guid.NewGuid(),
                    IsEnabled = true,
                    Type      = "User",
                    UserConsentDescription = $"Allow the application to access {aksApplicationName} on your behalf.",
                    UserConsentDisplayName = $"Access {aksApplicationName}",
                    Value = "user_impersonation"
                }
            };

            var aksApplicationApiApplication = new ApiApplication {
                Oauth2PermissionScopes = aksOauth2Permissions
            };

            var aksApplicationWebApplication = new WebApplication {
                ImplicitGrantSettings = new ImplicitGrantSettings {
                    EnableIdTokenIssuance = true
                }
            };

            var aksApplicationIdentifierUri = $"https://{_tenantGuid.ToString()}/{aksApplicationName}";

            var aksApplicationDefinition = new Application {
                DisplayName            = aksApplicationName,
                IsFallbackPublicClient = false,
                IdentifierUris         = new List <string> {
                    aksApplicationIdentifierUri
                },
                Tags                   = tags,
                SignInAudience         = "AzureADMyOrg",
                AppRoles               = new List <AppRole>(),
                RequiredResourceAccess = new List <RequiredResourceAccess>(),
                Api = aksApplicationApiApplication,
                Web = aksApplicationWebApplication,
                PasswordCredentials = new List <PasswordCredential> {
                }
            };

            var aksApplication = await _graphServiceClient
                                 .Applications
                                 .Request()
                                 .AddAsync(aksApplicationDefinition, cancellationToken);

            // Add RBAC Key PasswordCredential
            var rbacKeyName = "rbac";

            var aksApplicationRBACPasswordCredentialDefinition = new PasswordCredential {
                StartDateTime       = DateTimeOffset.UtcNow,
                EndDateTime         = DateTimeOffset.UtcNow.AddYears(2),
                CustomKeyIdentifier = ToBase64Bytes(rbacKeyName),
                DisplayName         = rbacKeyName
            };

            var aksApplicationRBACPasswordCredential = await _graphServiceClient
                                                       .Applications[aksApplication.Id]
                                                       .AddPassword(aksApplicationRBACPasswordCredentialDefinition)
                                                       .Request()
                                                       .PostAsync(cancellationToken);

            if (string.IsNullOrEmpty(aksApplicationRBACPasswordCredential.SecretText))
            {
                throw new Exception($"Failed to retrieve password credentials for AKS Application: {rbacKeyName}");
            }

            var aksApplicationRBACPasswordCredentialSecret = aksApplicationRBACPasswordCredential.SecretText;

            // We need to create ServicePrincipal for this application.
            await CreateServicePrincipalAsync(
                aksApplication,
                tags,
                cancellationToken
                );

            var result = new Tuple <Application, string>(
                aksApplication,
                aksApplicationRBACPasswordCredentialSecret
                );

            return(result);
        }
 public IisExpressWebServer(WebApplication application)
 {
     if (application == null)
         throw new ArgumentNullException("The web application must be set.");
     _application = application;
 }
Esempio n. 20
0
        public async Task <Application> RegisterServiceApplicationAsync(
            string servicesApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            tags ??= new List <string>();

            // Setup AppRoles for service application
            var serviceApplicationAppRoles = new List <AppRole>();

            var serviceApplicationApproverRoleIdGuid = Guid.NewGuid();

            serviceApplicationAppRoles.Add(new AppRole {
                DisplayName        = "Approver",
                Value              = "Sign",
                Description        = "Approvers have the ability to issue certificates.",
                AllowedMemberTypes = new List <string> {
                    "User"
                },
                Id = serviceApplicationApproverRoleIdGuid
            });

            var serviceApplicationWriterRoleIdGuid = Guid.NewGuid();

            serviceApplicationAppRoles.Add(new AppRole {
                DisplayName        = "Writer",
                Value              = "Write",
                Description        = "Writers Have the ability to change entities.",
                AllowedMemberTypes = new List <string> {
                    "User"
                },
                Id = serviceApplicationWriterRoleIdGuid
            });

            var serviceApplicationAdministratorRoleIdGuid = Guid.NewGuid();

            serviceApplicationAppRoles.Add(new AppRole {
                DisplayName        = "Administrator",
                Value              = "Admin",
                Description        = "Admins can access advanced features.",
                AllowedMemberTypes = new List <string> {
                    "User"
                },
                Id = serviceApplicationAdministratorRoleIdGuid
            });

            // Setup RequiredResourceAccess for service application

            //// This flow is not supported yet.
            //var keyVaultUserImpersonationRequiredResourceAccess =
            //    await GetRequiredResourceAccessByDisplayNameAsync(
            //        "Azure Key Vault",
            //        new List<string> { "user_impersonation" },
            //        cancellationToken
            //    );

            var keyVaultUserImpersonationRequiredResourceAccess = new RequiredResourceAccess {
                ResourceAppId  = AzureAppsConstants.AzureKeyVault.AppId,
                ResourceAccess = new List <ResourceAccess> {
                    new ResourceAccess {
                        Id   = AzureAppsConstants.AzureKeyVault.ResourceAccess["user_impersonation"],
                        Type = "Scope"
                    }
                }
            };

            //// This flow is not supported yet.
            //var microsoftGraphUserReadRequiredResourceAccess =
            //    await GetRequiredResourceAccessByDisplayNameAsync(
            //        "Microsoft Graph",
            //        new List<string> { "User.Read" },
            //        cancellationToken
            //    );

            var microsoftGraphUserReadRequiredResourceAccess = new RequiredResourceAccess {
                ResourceAppId  = AzureAppsConstants.MicrosoftGraph.AppId,
                ResourceAccess = new List <ResourceAccess> {
                    new ResourceAccess {
                        Id   = AzureAppsConstants.MicrosoftGraph.ResourceAccess["User.Read"],
                        Type = "Scope"
                    }
                }
            };

            var serviceApplicationRequiredResourceAccess = new List <RequiredResourceAccess>()
            {
                keyVaultUserImpersonationRequiredResourceAccess,
                microsoftGraphUserReadRequiredResourceAccess
            };

            // Add OAuth2Permissions
            var oauth2Permissions = new List <PermissionScope> {
                new PermissionScope {
                    AdminConsentDescription = $"Allow the app to access {servicesApplicationName} on behalf of the signed-in user.",
                    AdminConsentDisplayName = $"Access {servicesApplicationName}",
                    Id        = Guid.NewGuid(),
                    IsEnabled = true,
                    Type      = "User",
                    UserConsentDescription = $"Allow the application to access {servicesApplicationName} on your behalf.",
                    UserConsentDisplayName = $"Access {servicesApplicationName}",
                    Value = "user_impersonation"
                }
            };

            var serviceApplicationApiApplication = new ApiApplication {
                Oauth2PermissionScopes = oauth2Permissions
            };

            var serviceApplicationWebApplication = new WebApplication {
                ImplicitGrantSettings = new ImplicitGrantSettings {
                    EnableIdTokenIssuance = true
                }
            };

            var serviceApplicationIdentifierUri = $"https://{_tenantGuid.ToString()}/{servicesApplicationName}";

            var serviceApplicationRequest = new Application {
                DisplayName            = servicesApplicationName,
                IsFallbackPublicClient = false,
                IdentifierUris         = new List <string> {
                    serviceApplicationIdentifierUri
                },
                Tags                   = tags,
                SignInAudience         = "AzureADMyOrg",
                AppRoles               = serviceApplicationAppRoles,
                RequiredResourceAccess = serviceApplicationRequiredResourceAccess,
                Api = serviceApplicationApiApplication,
                Web = serviceApplicationWebApplication,
                PasswordCredentials = new List <PasswordCredential> {
                }
            };

            var serviceApplication = await _graphServiceClient
                                     .Applications
                                     .Request()
                                     .AddAsync(serviceApplicationRequest, cancellationToken);

            // Add Service Key PasswordCredential
            var serviceKeyName = "Service Key";

            var serviceApplicationServiceKeyPasswordCredentialDefinition = new PasswordCredential {
                StartDateTime       = DateTimeOffset.UtcNow,
                EndDateTime         = DateTimeOffset.UtcNow.AddYears(2),
                CustomKeyIdentifier = ToBase64Bytes(serviceKeyName),
                DisplayName         = serviceKeyName
            };

            await _graphServiceClient
            .Applications[serviceApplication.Id]
            .AddPassword(serviceApplicationServiceKeyPasswordCredentialDefinition)
            .Request()
            .PostAsync(cancellationToken);

            // We need to create ServicePrincipal for this application.
            var serviceApplicationSP = await CreateServicePrincipalAsync(
                serviceApplication,
                tags,
                cancellationToken
                );

            // Add app role assignment to me as Approver, Writer and Administrator.
            var me = Me(cancellationToken);

            var approverAppRoleAssignmentRequest = new AppRoleAssignment {
                //PrincipalDisplayName = "",
                PrincipalType       = "User",
                PrincipalId         = new Guid(me.Id),
                ResourceId          = new Guid(serviceApplicationSP.Id),
                ResourceDisplayName = "Approver",
                Id        = serviceApplicationApproverRoleIdGuid.ToString(),
                AppRoleId = serviceApplicationApproverRoleIdGuid
            };

            var writerAppRoleAssignmentRequest = new AppRoleAssignment {
                //PrincipalDisplayName = "",
                PrincipalType       = "User",
                PrincipalId         = new Guid(me.Id),
                ResourceId          = new Guid(serviceApplicationSP.Id),
                ResourceDisplayName = "Writer",
                Id        = serviceApplicationWriterRoleIdGuid.ToString(),
                AppRoleId = serviceApplicationWriterRoleIdGuid
            };

            var administratorAppRoleAssignmentRequest = new AppRoleAssignment {
                //PrincipalDisplayName = "",
                PrincipalType       = "User",
                PrincipalId         = new Guid(me.Id),
                ResourceId          = new Guid(serviceApplicationSP.Id),
                ResourceDisplayName = "Administrator",
                Id        = serviceApplicationAdministratorRoleIdGuid.ToString(),
                AppRoleId = serviceApplicationAdministratorRoleIdGuid
            };

            await _graphServiceClient
            .ServicePrincipals[serviceApplicationSP.Id]
            .AppRoleAssignments
            .Request()
            .AddAsync(
                approverAppRoleAssignmentRequest,
                cancellationToken
                );

            await _graphServiceClient
            .ServicePrincipals[serviceApplicationSP.Id]
            .AppRoleAssignments
            .Request()
            .AddAsync(
                writerAppRoleAssignmentRequest,
                cancellationToken
                );

            await _graphServiceClient
            .ServicePrincipals[serviceApplicationSP.Id]
            .AppRoleAssignments
            .Request()
            .AddAsync(
                administratorAppRoleAssignmentRequest,
                cancellationToken
                );

            return(serviceApplication);
        }
Esempio n. 21
0
 HttpCookie HttpCookie(string logonParametersAsString, WebApplication webApplication) {
     HttpCookie cookie = FormsAuthentication.GetAuthCookie("", webApplication.CanAutomaticallyLogonWithStoredLogonParameters);
     FormsAuthenticationTicket formsTicket = FormsAuthentication.Decrypt(cookie.Value);
     if (formsTicket != null) {
         var encryptedXafTicket = EncryptedXafTicket(formsTicket, logonParametersAsString);
         if (encryptedXafTicket != null && encryptedXafTicket.Length < CookieContainer.DefaultCookieLengthLimit) {
             cookie.Value = encryptedXafTicket;
         } else {
             if (encryptedXafTicket != null)
                 Tracing.Tracer.LogWarning("Cannot cache a login information into a FormsAuthentication cookie: " +
                                           "the result length is '" + encryptedXafTicket.Length +
                                           "' bytes and it exceeds the maximum cookie length '" +
                                           CookieContainer.DefaultCookieLengthLimit +
                                           "' (see the 'System.Net.CookieContainer.DefaultCookieLengthLimit' property)");
         }
     }
     return cookie;
 }
Esempio n. 22
0
        protected void Session_Start(Object sender, EventArgs e)
        {
            Tracing.Initialize();
            WebApplication.SetInstance(Session, new FT_EClaimAspNetApplication());
            DevExpress.ExpressApp.Web.Templates.DefaultVerticalTemplateContentNew.ClearSizeLimit();
            WebApplication.Instance.SwitchToNewStyle();
            #region listview column size adjustable
            WebApplication.OptimizationSettings.LockRecoverViewStateOnNavigationCallback = false;
            #endregion

            #region GeneralSettings
            string temp = "";

            temp = ConfigurationManager.AppSettings["EmailSend"].ToString();
            FT_EClaim.Module.GeneralSettings.EmailSend = false;
            if (temp.ToUpper() == "Y" || temp.ToUpper() == "YES" || temp.ToUpper() == "TRUE" || temp == "1")
            {
                FT_EClaim.Module.GeneralSettings.EmailSend = true;
            }

            FT_EClaim.Module.GeneralSettings.EmailHost       = ConfigurationManager.AppSettings["EmailHost"].ToString();
            FT_EClaim.Module.GeneralSettings.EmailHostDomain = ConfigurationManager.AppSettings["EmailHostDomain"].ToString();
            FT_EClaim.Module.GeneralSettings.EmailPort       = ConfigurationManager.AppSettings["EmailPort"].ToString();
            FT_EClaim.Module.GeneralSettings.Email           = ConfigurationManager.AppSettings["Email"].ToString();
            FT_EClaim.Module.GeneralSettings.EmailPassword   = ConfigurationManager.AppSettings["EmailPassword"].ToString();
            FT_EClaim.Module.GeneralSettings.EmailName       = ConfigurationManager.AppSettings["EmailName"].ToString();

            temp = ConfigurationManager.AppSettings["EmailSSL"].ToString();
            FT_EClaim.Module.GeneralSettings.EmailSSL = false;
            if (temp.ToUpper() == "Y" || temp.ToUpper() == "YES" || temp.ToUpper() == "TRUE" || temp == "1")
            {
                FT_EClaim.Module.GeneralSettings.EmailSSL = true;
            }

            temp = ConfigurationManager.AppSettings["EmailUseDefaultCredential"].ToString();
            FT_EClaim.Module.GeneralSettings.EmailUseDefaultCredential = false;
            if (temp.ToUpper() == "Y" || temp.ToUpper() == "YES" || temp.ToUpper() == "TRUE" || temp == "1")
            {
                FT_EClaim.Module.GeneralSettings.EmailUseDefaultCredential = true;
            }

            FT_EClaim.Module.GeneralSettings.DeliveryMethod = ConfigurationManager.AppSettings["DeliveryMethod"].ToString();

            FT_EClaim.Module.GeneralSettings.B1Post = false; // no more real time posting due to diapi error
            temp = ConfigurationManager.AppSettings["B1Post"].ToString();
            FT_EClaim.Module.GeneralSettings.B1Post = false;
            if (temp.ToUpper() == "Y" || temp.ToUpper() == "YES" || temp.ToUpper() == "TRUE" || temp == "1")
            {
                FT_EClaim.Module.GeneralSettings.B1Post = true;
            }

            FT_EClaim.Module.GeneralSettings.LocalCurrency = ConfigurationManager.AppSettings["LocalCurrency"].ToString();

            FT_EClaim.Module.GeneralSettings.B1UserName       = ConfigurationManager.AppSettings["B1UserName"].ToString();
            FT_EClaim.Module.GeneralSettings.B1Password       = ConfigurationManager.AppSettings["B1Password"].ToString();
            FT_EClaim.Module.GeneralSettings.B1Server         = ConfigurationManager.AppSettings["B1Server"].ToString();
            FT_EClaim.Module.GeneralSettings.B1CompanyDB      = ConfigurationManager.AppSettings["B1CompanyDB"].ToString();
            FT_EClaim.Module.GeneralSettings.B1License        = ConfigurationManager.AppSettings["B1License"].ToString();
            FT_EClaim.Module.GeneralSettings.B1DbServerType   = ConfigurationManager.AppSettings["B1DbServerType"].ToString();
            FT_EClaim.Module.GeneralSettings.B1Language       = ConfigurationManager.AppSettings["B1Language"].ToString();
            FT_EClaim.Module.GeneralSettings.B1DbUserName     = ConfigurationManager.AppSettings["B1DbUserName"].ToString();
            FT_EClaim.Module.GeneralSettings.B1DbPassword     = ConfigurationManager.AppSettings["B1DbPassword"].ToString();
            FT_EClaim.Module.GeneralSettings.B1AttachmentPath = ConfigurationManager.AppSettings["B1AttachmentPath"].ToString();

            //FT_EClaim.Module.GeneralSettings.B1APIVseries = int.Parse(ConfigurationManager.AppSettings["B1APIVseries"].ToString());
            //FT_EClaim.Module.GeneralSettings.B1RefCol = ConfigurationManager.AppSettings["B1RefCol"].ToString();
            FT_EClaim.Module.GeneralSettings.B1DeptDimension  = int.Parse(ConfigurationManager.AppSettings["B1DeptDimension"].ToString());
            FT_EClaim.Module.GeneralSettings.B1DivDimension   = int.Parse(ConfigurationManager.AppSettings["B1DivDimension"].ToString());
            FT_EClaim.Module.GeneralSettings.B1BrandDimension = int.Parse(ConfigurationManager.AppSettings["B1BrandDimension"].ToString());

            FT_EClaim.Module.GeneralSettings.defaulttax         = ConfigurationManager.AppSettings["DefaultTax"].ToString();
            FT_EClaim.Module.GeneralSettings.defaultmileagetax  = ConfigurationManager.AppSettings["DefaultMileageTax"].ToString();
            FT_EClaim.Module.GeneralSettings.defemptyproject    = ConfigurationManager.AppSettings["DefaultEmptyProject"].ToString();
            FT_EClaim.Module.GeneralSettings.defemptydepartment = ConfigurationManager.AppSettings["DefaultEmptyDepartment"].ToString();
            FT_EClaim.Module.GeneralSettings.defemptydivision   = ConfigurationManager.AppSettings["DefaultEmptyDivision"].ToString();
            FT_EClaim.Module.GeneralSettings.defemptybrand      = ConfigurationManager.AppSettings["DefaultEmptyBrand"].ToString();
            FT_EClaim.Module.GeneralSettings.defaultregion      = ConfigurationManager.AppSettings["DefaultRegion"].ToString();

            FT_EClaim.Module.GeneralSettings.appurl = System.Web.HttpContext.Current.Request.Url.AbsoluteUri; // + requestManager.GetQueryString(shortcut)
            #endregion
            WebApplication.Instance.CustomizeFormattingCulture += Instance_CustomizeFormattingCulture;
            WebApplication.Instance.LoggedOn += Instance_LoggedOn;

            if (ConfigurationManager.ConnectionStrings["ConnectionString"] != null)
            {
                WebApplication.Instance.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            }
#if EASYTEST
            if (ConfigurationManager.ConnectionStrings["EasyTestConnectionString"] != null)
            {
                WebApplication.Instance.ConnectionString = ConfigurationManager.ConnectionStrings["EasyTestConnectionString"].ConnectionString;
            }
#endif
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached && WebApplication.Instance.CheckCompatibilityType == CheckCompatibilityType.DatabaseSchema)
            {
                WebApplication.Instance.DatabaseUpdateMode = DatabaseUpdateMode.UpdateDatabaseAlways;
            }
#endif
            WebApplication.Instance.Setup();
            WebApplication.Instance.Start();
        }
Esempio n. 23
0
 public static void SetAppCore(this HttpContext context, WebApplication appCore)
 {
     context.Items[EXTENSIONPREFIX + "ApplicationCore"] = appCore;
 }
Esempio n. 24
0
 /// <summary>
 /// Starts the server and the <see cref="EventBroker"/> service.
 /// </summary>
 /// <param name="url">The endpoint of the service. If a value is not provided, it will be read from a configuration file.</param>
 /// <returns></returns>
 public static IDisposable Start(string url = "")
 {
     return(WebApplication.Start <Configurator>(Configuration.Server.Url ?? url));
 }
Esempio n. 25
0
        /// <summary>
        /// Starts web server for API
        /// </summary>
        private void LoadWebApi()
        {
            Log.Info("Loading Web API...");

            this.WebApp = new WebApplication();

            this.WebApp.Get("/status", new StatusController());
            this.WebApp.All("/broadcast", new BroadcastController());
            this.WebApp.All("/check-user", new CheckUserController());

            try
            {
                this.WebApp.Listen(this.Conf.Login.WebPort);

                Log.Info("Web API listening on 0.0.0.0:{0}", this.Conf.Login.WebPort);
            }
            catch (Exception)
            {
                Log.Error("Failed to load Web API, port already in use?");
            }
        }
Esempio n. 26
0
 public static void RouteTemplate(WebApplication app)
 {
     // <snippet_RouteTemplate>
     app.MapGet("/hello/{name:alpha}", (string name) => $"Hello {name}!");
     // </snippet_RouteTemplate>
 }
Esempio n. 27
0
 // Entry point for the application.
 public static void Main(string[] args) => WebApplication.Run <Startup>(args); // <<== Nuevo 2015 metodos con exp. lambda
Esempio n. 28
0
 public static void Main(string[] args)
 {
     WebApplication.Run(args);
 }
 protected void Session_End(Object sender, EventArgs e)
 {
     WebApplication.LogOff(Session);
     WebApplication.DisposeInstance(Session);
 }
Esempio n. 30
0
        /// <summary>
        /// Begin a Seleno test for a Visual Studio web project.
        /// </summary>
        /// <param name="webProjectFolder">The name of the web project to run</param>
        /// <param name="portNumber">The port number to run the project under</param>
        /// <param name="configure">Any configuration changes you would like to make</param>
        public void Run(string webProjectFolder, int portNumber, Action <IAppConfigurator> configure = null)
        {
            var webApplication = new WebApplication(ProjectLocation.FromFolder(webProjectFolder), portNumber);

            Run(webApplication, configure);
        }
 public void Setup()
 {
     app = new WebApplication(new RoutingRuleContainer());
       app.Start();
 }
 partial void IndexOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, WebApplication.Models.LoginViewModel model);
Esempio n. 33
0
 private void ConfigureCors(WebApplication app, IWebHostEnvironment env)
 {
     app.UseCors();
     app.UseRefererFiltering();
 }
Esempio n. 34
0
 public BaseControllerTests()
 {
     application = new WebApplication();
 }
 public override void Setup(IObjectSpace space, XafApplication xafApplication) {
     base.Setup(space, xafApplication);
     _application = application;
     _objectSpace = objectSpace;
     helper = new WebLookupEditorHelper(xafApplication, space, MemberInfo.MemberTypeInfo, Model);
 }
Esempio n. 36
0
    public async static Task <int> Main(string[] args)
    {
        var loggerConfiguration = new LoggerConfiguration()
#if DEBUG
                                  .MinimumLevel.Debug()
#else
                                  .MinimumLevel.Information()
#endif
                                  .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                                  .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                                  .Enrich.FromLogContext()
                                  .WriteTo.Async(c => c.File("Logs/logs.txt"))
#if DEBUG
                                  .WriteTo.Async(c => c.Console());
#endif
                                  if (IsMigrateDatabase(args))
        {
            loggerConfiguration.MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning);
            loggerConfiguration.MinimumLevel.Override("Microsoft", LogEventLevel.Warning);
            loggerConfiguration.MinimumLevel.Override("IdentityServer4.Startup", LogEventLevel.Warning);
        }

        Log.Logger = loggerConfiguration.CreateLogger();

        try
        {
            var builder = WebApplication.CreateBuilder(args);
            builder.Host.AddAppSettingsSecretsJson()
            .UseAutofac()
            .UseSerilog();
            await builder.AddApplicationAsync <MyProjectNameModule>();

            var app = builder.Build();
            await app.InitializeApplicationAsync();

            if (IsMigrateDatabase(args))
            {
                await app.Services.GetRequiredService <MyProjectNameDbMigrationService>().MigrateAsync();

                return(0);
            }

            Log.Information("Starting MyCompanyName.MyProjectName.");
            await app.RunAsync();

            return(0);
        }
        catch (Exception ex)
        {
            if (ex.GetType().Name.Equals("StopTheHostException", StringComparison.Ordinal))
            {
                throw;
            }

            Log.Fatal(ex, "MyCompanyName.MyProjectName terminated unexpectedly!");
            return(1);
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
 public override System.Web.Mvc.ActionResult Index(WebApplication.Models.LoginViewModel model)
 {
     var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Index);
     ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "model", model);
     IndexOverride(callInfo, model);
     return callInfo;
 }
Esempio n. 38
0
 public static void AddRoutes(WebApplication app)
 {
     app.MapPost("api/embed/interact", Interaction);
 }
Esempio n. 39
0
 private void ConfigureCustomHeader(WebApplication app, IWebHostEnvironment env)
 {
     app.UseCustomHeader();
 }
Esempio n. 40
0
        static void Main(string[] args)
        {
            var app = new WebApplication(new string[] { "http://localhost:54321/" });

            app.Iniciar();
        }
Esempio n. 41
0
 bool AutomaticallyLogonEnabled(WebApplication webApplication) {
     var b = _autoAthentication.Enabled || webApplication.CanAutomaticallyLogonWithStoredLogonParameters;
     if (b&&!(webApplication.Security.LogonParameters is XpandLogonParameters))
         throw new NotImplementedException("use XpandLogonParameters object in your authentication ");
     return b;
 }
Esempio n. 42
0
 void IExecuteStart <WebApplication> .ExecuteStart(WebApplication core)
 {
     core.Get <ItemsManager <WebApplication> >().RegisterModuleItemType <DB.News, ModuleMaterials>();
     core.Get <ItemsManager <WebApplication> >().RegisterModuleItemType <DB.Page, ModuleMaterials>();
 }
Esempio n. 43
0
        public IWebApplication Build()
        {
            var hostingServices = BuildHostingServices();

            var hostingContainer = hostingServices.BuildServiceProvider();

            var appEnvironment = hostingContainer.GetRequiredService<IApplicationEnvironment>();
            var startupLoader = hostingContainer.GetRequiredService<IStartupLoader>();

            // Initialize the hosting environment
            _hostingEnvironment.Initialize(appEnvironment.ApplicationBasePath, _options, _config);

            var application = new WebApplication(hostingServices, startupLoader, _options, _config);

            // Only one of these should be set, but they are used in priority
            application.ServerFactory = _serverFactory;
            application.ServerFactoryLocation = _options.ServerFactoryLocation;

            // Only one of these should be set, but they are used in priority
            application.Startup = _startup;
            application.StartupType = _startupType;
            application.StartupAssemblyName = _options.Application;

            application.Initialize();

            return application;
        }
        public async Task <string> InitiateTokenRetrieval()
        {
            var builder = WebApplication.CreateBuilder();

            builder.Host.ConfigureLogging(logging =>
            {
                logging.ClearProviders();
            });
            var app = builder.Build();

            var tcs = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously);

            app.Run(async ctx =>
            {
                Task WriteResponse(HttpContext ctx)
                {
                    ctx.Response.StatusCode  = 200;
                    ctx.Response.ContentType = "text/html";
                    return(ctx.Response.WriteAsync("<html><head><meta http-equiv='refresh' content='10;url=https://lifx.com'></head><body>Please return to the app.</body></html>", Encoding.UTF8));
                }

                switch (ctx.Request.Method)
                {
                case "GET":
                    await WriteResponse(ctx);

                    tcs.TrySetResult(ctx.Request.QueryString.Value);
                    break;

                case "POST" when !ctx.Request.HasFormContentType:
                    ctx.Response.StatusCode = 415;
                    break;

                case "POST":
                    {
                        using var sr = new StreamReader(ctx.Request.Body, Encoding.UTF8);
                        var body     = await sr.ReadToEndAsync();

                        await WriteResponse(ctx);

                        tcs.TrySetResult(body);
                        break;
                    }

                default:
                    ctx.Response.StatusCode = 405;
                    break;
                }
            });

            var browserPort = 17236;

            app.Urls.Add($"http://localhost:{browserPort}/");

            app.Start();

            var timeout = TimeSpan.FromMinutes(5);

            string redirectUri = string.Format($"http://localhost:{browserPort}/");

            string state = RandomDataBase64Url(32);

            string authorizationRequest = string.Format("{0}?response_type=code&scope=remote_control:all&client_id={1}&state={2}&redirect_uri={3}",
                                                        _lIFXAuthorizationEndpoint,
                                                        _options.LightSettings.LIFX.LIFXClientId,
                                                        state,
                                                        HttpUtility.UrlEncode(redirectUri)
                                                        );

            Helpers.OpenBrowser(authorizationRequest);

            var qs = await tcs.Task.WaitAsync(timeout);

            var          qsDict = QueryHelpers.ParseQuery(qs.Replace("?", ""));
            StringValues code;

            qsDict.TryGetValue("code", out code);
            await app.DisposeAsync();

            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("code", code.ToString()),
                new KeyValuePair <string, string>("client_id", _options.LightSettings.LIFX.LIFXClientId),
                new KeyValuePair <string, string>("client_secret", _options.LightSettings.LIFX.LIFXClientSecret),
                new KeyValuePair <string, string>("grant_type", "authorization_code")
            });


            // sends the request
            HttpClient _client = new HttpClient();

            _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var response = await _client.PostAsync(_lIFXTokenEndpoint, formContent);

            string responseText = await response.Content.ReadAsStringAsync();

            Dictionary <string, string> tokenEndpointDecoded = JsonConvert.DeserializeObject <Dictionary <string, string> >(responseText);

            string _accessToken = tokenEndpointDecoded["access_token"];


            return(_accessToken);
        }