Example #1
0
	public int remainingPoints = 0; //!< The current points available for the player to build units

	/**
	 * Called when the script is loaded, before the game starts
	 */
	void Awake () {
		S = this;

		generalSettings = new GeneralSettings ();

		units = new List<GameObject> ();
	}
Example #2
0
 /// <summary>
 /// load the general configuration up
 /// </summary>
 public static void LoadGeneralConfig()
 {
     try
     {
         string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
         folder = folder + Path.DirectorySeparatorChar + "firebwall";
         if (!Directory.Exists(folder))
             Directory.CreateDirectory(folder);
         string file = folder + Path.DirectorySeparatorChar + "generalconfig.cfg";
         if (File.Exists(file))
         {
             FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
             BinaryFormatter bFormatter = new BinaryFormatter();
             bFormatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
             bFormatter.Binder = new PassThru.UpdateChecker.VersionConfigToNamespaceAssemblyObjectBinder();
             gSettings = (GeneralSettings)bFormatter.Deserialize(stream);
             stream.Close();
         }
         else
         {
             gSettings = new GeneralSettings();
         }
     }
     catch
     {
         gSettings = new GeneralSettings();
     }
 }
Example #3
0
        public static void Load(GeneralSettings generalSettings, BindingList<Action> actions, string fileName)
        {
            var lines = new List<string>();
            using (var stream = new StreamReader(fileName))
            {
                string line;
                while ((line = stream.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }

            var generalSettingsSections = GetSections(Strings.GeneralSettings, lines);
            var actionSections = GetSections(Strings.Action, lines);

            if (generalSettingsSections.Count > 0)
            {
                generalSettings.LoadFromStringList(generalSettingsSections[0]);
            }

            actions.Clear();
            foreach (var actionSection in actionSections)
            {
                var action = Action.CreateFromActionName(actionSection);
                actions.Add(action);
            }
        }
Example #4
0
 public SettingsComponent(GUIController guiController, AGSEditor agsEditor)
     : base(guiController, agsEditor)
 {
     _settingsPane = new GeneralSettings();
     _document = new ContentDocument(_settingsPane, "General Settings", this);
     _guiController.RegisterIcon("SettingsIcon", Resources.ResourceManager.GetIcon("iconsett.ico"));
     _guiController.ProjectTree.AddTreeRoot(this, "GeneralSettings", "General Settings", "SettingsIcon");
 }
Example #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ShipNavigator"/> class.
 /// </summary>
 /// <param name="t">Ship Transform</param>
 /// <param name="data">Ship data.</param>
 public ShipNavigator(Transform t, ShipData data)
     : base(data) {
     _transform = t;
     _gameStatus = GameStatus.Instance;
     _generalSettings = GeneralSettings.Instance;
     _engineRoom = new EngineRoom(data, t.rigidbody);
     Subscribe();
 }
Example #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ShipNavigator"/> class.
 /// </summary>
 /// <param name="t">Ship Transform</param>
 /// <param name="data">Ship data.</param>
 public ShipNavigator(Transform t, ShipData data) {
     _transform = t;
     _data = data;
     _rigidbody = t.rigidbody;
     _rigidbody.useGravity = false;
     _eventMgr = GameEventManager.Instance;
     _gameTime = GameTime.Instance;
     _gameStatus = GameStatus.Instance;
     _generalSettings = GeneralSettings.Instance;
     Subscribe();
     _gameSpeedMultiplier = _gameTime.GameSpeed.SpeedMultiplier();   // FIXME where/when to get initial GameSpeed before first GameSpeed change?
     _thrustHelper = new ThrustHelper(0F, 0F, _data.FullStlEnginePower);
 }
Example #7
0
        public AccountController(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            IEmailSender emailSender,
            IOptions<GeneralSettings> generalSettings

            )
        {
            _emailSender = emailSender;
            _userManager = userManager;
            _signInManager = signInManager;
            _generalSettings = generalSettings.Value;
        }
Example #8
0
 public AdminController(
     UserManager<ApplicationUser> userManager,
     SignInManager<ApplicationUser> signInManager,
     IEmailSender emailSender,
     ISmsSender smsSender,
     IOptions<SampleDataSettings> options,
     IOptions<GeneralSettings> generalSettings)
 {
     _userManager = userManager;
     _signInManager = signInManager;
     _emailSender = emailSender;
     _smsSender = smsSender;
     _settings = options.Value;
     _generalSettings = generalSettings.Value;
 }
        private void Init()
        {
            if (GeneralSettings == null)
                GeneralSettings = new GeneralSettings();

            if (WindowSettings == null)
                WindowSettings = new WindowSettings();

            if (GridSettings == null)
                GridSettings = new GridSettings();

            if (BuildMessagesSettings == null)
                BuildMessagesSettings = new BuildMessagesSettings();

            if (ProjectItemSettings == null)
                ProjectItemSettings = new ProjectItemSettings();
        }
Example #10
0
        public static void Save(GeneralSettings generalSettings, IEnumerable<Action> actions, string fileName)
        {
            var result = new StringBuilder();

            result.AppendLine(string.Format("{0} {1}", SectionSeparatorString, Strings.GeneralSettings));
            result.AppendLine(generalSettings.SaveToString());

            foreach (var action in actions)
            {
                result.AppendLine(String.Format("{0} {1}", SectionSeparatorString, Strings.Action));
                result.AppendLine(action.SaveToString(action.GetActionName()));
                result.AppendLine();
            }

            using (var stream = new StreamWriter(fileName, false))
            {
                stream.Write(result);
            }
        }
 public FeedJob(GeneralSettings _settings)
 {
     Schedule<Feeder>().ToRunNow().AndEvery(_settings.refreshTime).Minutes();
 }
Example #12
0
 public AccountController(IOptions <ClientSettings> clientSettings, IOptions <GeneralSettings> generalSettings, IHttpClientFactory httpClientFactory)
 {
     _clientSettings    = clientSettings?.Value ?? throw new ArgumentNullException(nameof(clientSettings));
     _generalSettings   = generalSettings?.Value ?? throw new ArgumentNullException(nameof(generalSettings));
     _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
 }
Example #13
0
        public void SetUp()
        {
            Package package = new Package(new InstallmentType(1, "Monthly", 0, 1), OLoanTypes.Flat, true);

            package.KeepExpectedInstallment             = true;
            package.NonRepaymentPenalties.InitialAmount = 0.003;

            contractForAPerson = new Credit(package, 1000, 0.03, 6, 1, new DateTime(2006, 1, 1), User.CurrentUser, GeneralSettings.GetInstance(""), NonWorkingDateSingleton.GetInstance(""), ProvisioningTable.GetInstance(User.CurrentUser));
            contractForAPerson.NonRepaymentPenalties.InitialAmount = 0.003;

            _person           = new Person();
            _person.FirstName = "Nicolas";
            _person.LastName  = "MANGIN";
            _person.District  = new District(1, "Ile de France", new Province(1, "France"));
            _person.City      = "Paris";

            User user = User.CurrentUser;

            user.FirstName = "Nicolas";
            user.LastName  = "MANGIN";
            contractForAPerson.LoanOfficer = user;

            contractForAGroup           = new Credit(package, 1000, 0.03, 6, 1, new DateTime(2006, 1, 1), User.CurrentUser, GeneralSettings.GetInstance(""), NonWorkingDateSingleton.GetInstance(""), ProvisioningTable.GetInstance(User.CurrentUser));
            _group                      = new Group();
            _group.Name                 = "Groupe MANGIN";
            _group.District             = new District(1, "Lorraine", new Province(1, "France"));
            _group.City                 = "Nancy";
            contractForAGroup.EntryFees = 0.03;
        }
Example #14
0
        public void TestIfInterestPrincipalAndFeesInLetterCorrectlyRetrievedWhenRepayAndFeesWhenCurrencyIsUSDAndLanguageIsEnglish()
        {
            Credit contract = contractForAPerson.Copy();

            contract.Disburse(new DateTime(2006, 1, 1), true, false);

            CashReceipt cashReceipt = new CashReceipt(contract, _person, 0, "USD", "en-US", new ExchangeRate(new DateTime(2006, 3, 1), 3), new DateTime(2006, 3, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            Assert.AreEqual(0, cashReceipt.PaidPrincipalInExternalCurrency);
            Assert.AreEqual(90, cashReceipt.PaidInterestInExternalCurrency);
            Assert.AreEqual(252.00m, Math.Round(cashReceipt.PaidFeesInExternalCurrency, 2));
            Assert.AreEqual("ninety USD", cashReceipt.PaidInterestInLetter);
            Assert.AreEqual("two hundred and fifty-two USD", cashReceipt.PaidFeesInLetter);
            Assert.AreEqual("zero USD", cashReceipt.PaidPrincipalInLetter);
        }
Example #15
0
        public void TestIfLocalAccountNumberCorrectlyRetrievedWhenRepayAGoodLoan()
        {
            ChartOfAccounts chartOfAccounts = ChartOfAccounts.GetInstance(User.CurrentUser);

            Credit contract = contractForAPerson.Copy();

            contract.Disburse(new DateTime(2006, 1, 1), true, false);
            CashReceipt cashReceipt = new CashReceipt(contract, _person, 0, "USD", "en-US", new ExchangeRate(new DateTime(2006, 3, 1), 3), new DateTime(2006, 3, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            Assert.AreEqual(chartOfAccounts.GetAccountByNumber(OAccounts.INTERESTS_ON_CASH_CREDIT_INDIVIDUAL_LOAN).LocalNumber, cashReceipt.InterestLocalAccountNumber);
            Assert.AreEqual(chartOfAccounts.GetAccountByNumber(OAccounts.CASH_CREDIT_INDIVIDUAL_LOAN).LocalNumber, cashReceipt.PrincipalLocalAccountNumber);
            Assert.AreEqual(chartOfAccounts.GetAccountByTypeCode("COMMISSIONS").LocalNumber, cashReceipt.FeesLocalAccountNumber);
        }
Example #16
0
        public void TestIfInterestPrincipalAndFeesCorrectlyRetrievedWhenRepayAndFees()
        {
            Credit contract = contractForAPerson.Copy();

            contract.Disburse(new DateTime(2006, 1, 1), true, false);

            Assert.AreEqual(new DateTime(2006, 2, 1), contract.GetInstallment(0).ExpectedDate);
            CashReceipt cashReceipt = new CashReceipt(contract, _person, 0, "USD", "en-US", new ExchangeRate(new DateTime(2006, 3, 1), 3), new DateTime(2006, 3, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            Assert.AreEqual(0, cashReceipt.PaidPrincipalInExternalCurrency);
            Assert.AreEqual(90, cashReceipt.PaidInterestInExternalCurrency);
            Assert.AreEqual(252.00m, Math.Round(cashReceipt.PaidFeesInExternalCurrency, 2));
        }
Example #17
0
        public void TestIfCashReceiptOutCorrectlySaveAndRetrievedWhenNoCashReceiptOut()
        {
            contractForAPerson.Disbursed = false;
            CashReceipt cashReceipt = new CashReceipt(contractForAPerson, _person, null, "USD", "en-US", new ExchangeRate(new DateTime(2006, 2, 1), 3), new DateTime(2006, 2, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            Assert.AreEqual(1, cashReceipt.CashReceiptOut.Value);
        }
Example #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PartiesWrapper"/> class
 /// </summary>
 /// <param name="generalSettings">the general settings</param>
 /// <param name="logger">the logger</param>
 public PartiesWrapper(IOptions <GeneralSettings> generalSettings, ILogger <PartiesWrapper> logger)
 {
     _generalSettings = generalSettings.Value;
     _logger          = logger;
 }
Example #19
0
        /// <summary>
        /// Configure authorization settings for the service.
        /// </summary>
        /// <param name="services">the service configuration.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            _logger.LogInformation("Startup // ConfigureServices");

            services.AddControllers().AddXmlSerializerFormatters();
            services.AddHealthChecks().AddCheck <HealthCheck>("authorization_health_check");
            services.AddSingleton(Configuration);
            services.AddSingleton <IParties, PartiesWrapper>();
            services.AddSingleton <IRoles, RolesWrapper>();
            services.AddSingleton <IContextHandler, ContextHandler>();
            services.AddSingleton <IDelegationContextHandler, DelegationContextHandler>();
            services.AddSingleton <IPolicyRetrievalPoint, PolicyRetrievalPoint>();
            services.AddSingleton <IPolicyInformationPoint, PolicyInformationPoint>();
            services.AddSingleton <IPolicyAdministrationPoint, PolicyAdministrationPoint>();
            services.AddSingleton <IPolicyRepository, PolicyRepository>();
            services.AddSingleton <IInstanceMetadataRepository, InstanceMetadataRepository>();
            services.AddSingleton <IDelegationMetadataRepository, DelegationMetadataRepository>();
            services.AddSingleton <IDelegationChangeEventQueue, DelegationChangeEventQueue>();
            services.AddSingleton <IEventMapperService, EventMapperService>();
            services.Configure <GeneralSettings>(Configuration.GetSection("GeneralSettings"));
            services.Configure <AzureStorageConfiguration>(Configuration.GetSection("AzureStorageConfiguration"));
            services.Configure <AzureCosmosSettings>(Configuration.GetSection("AzureCosmosSettings"));
            services.Configure <PostgreSQLSettings>(Configuration.GetSection("PostgreSQLSettings"));
            services.AddHttpClient <PartyClient>();
            services.AddHttpClient <RolesClient>();
            services.AddHttpClient <SBLClient>();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            GeneralSettings generalSettings = Configuration.GetSection("GeneralSettings").Get <GeneralSettings>();

            services.AddAuthentication(JwtCookieDefaults.AuthenticationScheme)
            .AddJwtCookie(JwtCookieDefaults.AuthenticationScheme, options =>
            {
                options.JwtCookieName             = generalSettings.RuntimeCookieName;
                options.MetadataAddress           = generalSettings.OpenIdWellKnownEndpoint;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };

                if (_env.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(AuthzConstants.POLICY_STUDIO_DESIGNER, policy => policy.Requirements.Add(new ClaimAccessRequirement("urn:altinn:app", "studio.designer")));
                options.AddPolicy(AuthzConstants.ALTINNII_AUTHORIZATION, policy => policy.Requirements.Add(new ClaimAccessRequirement("urn:altinn:app", "sbl.authorization")));
            });

            services.AddTransient <IAuthorizationHandler, ClaimAccessHandler>();

            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            if (!string.IsNullOrEmpty(ApplicationInsightsKey))
            {
                services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel()
                {
                    StorageFolder = "/tmp/logtelemetry"
                });
                services.AddApplicationInsightsTelemetry(ApplicationInsightsKey);
                services.AddApplicationInsightsTelemetryProcessor <HealthTelemetryFilter>();
                services.AddApplicationInsightsTelemetryProcessor <IdentityTelemetryFilter>();
                services.AddSingleton <ITelemetryInitializer, CustomTelemetryInitializer>();

                _logger.LogInformation($"Startup // ApplicationInsightsTelemetryKey = {ApplicationInsightsKey}");
            }

            services.AddMvc(options =>
            {
                // Adding custom model binders
                options.ModelBinderProviders.Insert(0, new XacmlRequestApiModelBinderProvider());
                options.RespectBrowserAcceptHeader = true;
            });

            // Add Swagger support (Swashbuckle)
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Altinn Platform Authorization", Version = "v1"
                });
                IncludeXmlComments(c);
            });
        }
        public SettingsWindow()
        {
            Width = 500 * WindowLogic.MonitorInfo.DpiScaling;

            InitializeComponent();

            ContentRendered += delegate
            {
                // Center vertically
                Top = ((WindowLogic.MonitorInfo.WorkArea.Height * WindowLogic.MonitorInfo.DpiScaling) - ActualHeight) / 2 + WindowLogic.MonitorInfo.WorkArea.Top;

                KeyDown += KeysDown;
                AddGenericEvents();

                SetCheckedColorEvent();

                // SubDirRadio
                SubDirRadio.IsChecked = Properties.Settings.Default.IncludeSubDirectories;
                SubDirRadio.Click    += delegate
                {
                    Properties.Settings.Default.IncludeSubDirectories = !Properties.Settings.Default.IncludeSubDirectories;
                    Error_Handling.Reload();
                };

                // BorderColorRadio
                BorderRadio.Click += UpdateUIValues.SetBorderColorEnabled;
                if (Properties.Settings.Default.WindowBorderColorEnabled)
                {
                    BorderRadio.IsChecked = true;
                }

                // Fill
                Fill.Click += delegate
                {
                    SetWallpaper(WallpaperStyle.Fill);
                };

                // Fit
                Fit.Click += delegate
                {
                    SetWallpaper(WallpaperStyle.Fit);
                };

                // Center

                Center.Click += delegate
                {
                    SetWallpaper(WallpaperStyle.Center);
                };

                // Tile
                Tile.Click += delegate
                {
                    SetWallpaper(WallpaperStyle.Tile);
                };

                // Stretch
                Stretch.Click += delegate
                {
                    SetWallpaper(WallpaperStyle.Stretch);
                };

                SlideshowSlider.Value         = Properties.Settings.Default.SlideTimer / 1000;
                SlideshowSlider.ValueChanged += SlideshowSlider_ValueChanged;

                LightThemeRadio.IsChecked = !Properties.Settings.Default.DarkTheme;
                DarkThemeRadio.IsChecked  = Properties.Settings.Default.DarkTheme;

                DarkThemeRadio.Click += delegate
                {
                    ChangeToDarkTheme();
                    LightThemeRadio.IsChecked = false;
                };
                LightThemeRadio.Click += delegate
                {
                    ChangeToLightTheme();
                    DarkThemeRadio.IsChecked = false;
                };

                foreach (var language in Enum.GetValues(typeof(Languages)))
                {
                    LanguageBox.Items.Add(new ComboBoxItem
                    {
                        Content    = new CultureInfo(language.ToString()).DisplayName,
                        IsSelected = language.ToString() == Properties.Settings.Default.UserLanguage,
                    });
                }

                LanguageBox.SelectionChanged += delegate
                {
                    GeneralSettings.ChangeLanguage((LanguageBox.SelectedIndex));
                };

                RestartButton.Click += delegate
                {
                    GeneralSettings.RestartApp();
                };

                // DarkThemeRadio
                DarkThemeRadio.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(DarkThemeText); };
                DarkThemeRadio.MouseEnter += delegate { ButtonMouseOverAnim(DarkThemeText); };
                DarkThemeRadio.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(DarkThemeBrush); };
                DarkThemeRadio.MouseLeave += delegate { ButtonMouseLeaveAnim(DarkThemeText); };
                DarkThemeRadio.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(DarkThemeBrush); };

                // LightThemeRadio
                LightThemeRadio.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(LightThemeText); };
                LightThemeRadio.MouseEnter += delegate { ButtonMouseOverAnim(LightThemeText); };
                LightThemeRadio.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(LightThemeBrush); };
                LightThemeRadio.MouseLeave += delegate { ButtonMouseLeaveAnim(LightThemeText); };
                LightThemeRadio.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(LightThemeBrush); };

                // SubDirRadio
                SubDirRadio.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(SubDirText); };
                SubDirRadio.MouseEnter += delegate { ButtonMouseOverAnim(SubDirText); };
                SubDirRadio.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(SubDirBrush); };
                SubDirRadio.MouseLeave += delegate { ButtonMouseLeaveAnim(SubDirText); };
                SubDirRadio.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(SubDirBrush); };

                // BorderRadio
                BorderRadio.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(BorderBrushText); };
                BorderRadio.MouseEnter += delegate { ButtonMouseOverAnim(BorderBrushText); };
                BorderRadio.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(BorderBrushColor); };
                BorderRadio.MouseLeave += delegate { ButtonMouseLeaveAnim(BorderBrushText); };
                BorderRadio.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(BorderBrushColor); };

                // Fill
                Fill.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(FillText); };
                Fill.MouseEnter += delegate { ButtonMouseOverAnim(FillText); };
                Fill.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(FillBrush); };
                Fill.MouseLeave += delegate { ButtonMouseLeaveAnim(FillText); };
                Fill.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(FillBrush); };

                // Center
                Center.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(CenterText); };
                Center.MouseEnter += delegate { ButtonMouseOverAnim(CenterText); };
                Center.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(CenterBrush); };
                Center.MouseLeave += delegate { ButtonMouseLeaveAnim(CenterText); };
                Center.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(CenterBrush); };

                // Fit
                Fit.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(FitText); };
                Fit.MouseEnter += delegate { ButtonMouseOverAnim(FitText); };
                Fit.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(FitBrush); };
                Fit.MouseLeave += delegate { ButtonMouseLeaveAnim(FitText); };
                Fit.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(FitBrush); };

                // Tile
                Tile.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(TileText); };
                Tile.MouseEnter += delegate { ButtonMouseOverAnim(TileText); };
                Tile.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(TileBrush); };
                Tile.MouseLeave += delegate { ButtonMouseLeaveAnim(TileText); };
                Tile.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(TileBrush); };

                // Stretch
                Stretch.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(StretchText); };
                Stretch.MouseEnter += delegate { ButtonMouseOverAnim(StretchText); };
                Stretch.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(StretchBrush); };
                Stretch.MouseLeave += delegate { ButtonMouseLeaveAnim(StretchText); };
                Stretch.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(StretchBrush); };

                // Restart
                RestartButton.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(RestartText); };
                RestartButton.MouseEnter += delegate { ButtonMouseOverAnim(RestartText); };
                RestartButton.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(RestartBrush); };
                RestartButton.MouseLeave += delegate { ButtonMouseLeaveAnim(RestartText); };
                RestartButton.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(RestartBrush); };
            };
        }
Example #21
0
        public RegisterStatus CreateAdminLogin([FromBody] RegisterDTO objRegister)
        {
            // RegisterStatus to return
            RegisterStatus objRegisterStatus = new RegisterStatus();

            objRegisterStatus.status       = "Registration Failure";
            objRegisterStatus.isSuccessful = false;

            // Test for a strong password
            if (!UtilitySecurity.IsPasswordStrong(objRegister.password))
            {
                objRegisterStatus.status       = "The password is not strong enough.";
                objRegisterStatus.isSuccessful = false;
                return(objRegisterStatus);
            }

            // Do not run if we can connect to the current database
            if (CurrentVersion().isNewDatabase == false)
            {
                objRegisterStatus.isSuccessful = false;
                objRegisterStatus.status       = "Cannot create the Admin account because the database is already set-up. Reload your web browser to upgrade using the updated database connection.";
            }
            else
            {
                // Run the scripts to set-up the database
                DTOStatus objDTOStatus = RunUpdateScripts(NewDatabaseVersion, _hostEnvironment, GetConnectionString());

                if (!objDTOStatus.Success)
                {
                    // If scripts have an error return it
                    objRegisterStatus.isSuccessful = false;
                    objRegisterStatus.status       = objDTOStatus.StatusMessage;
                }
                else
                {
                    // Create the Administrator
                    string strCurrentHostLocation = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
                    objRegisterStatus = RegisterController.RegisterUser(
                        objRegister, GetConnectionString(), _hostEnvironment, _userManager, _signInManager, strCurrentHostLocation, true, true);

                    // There was an error creating the Administrator
                    if (!objRegisterStatus.isSuccessful)
                    {
                        // Delete the record in the version table
                        // So the install can be run again
                        objDTOStatus = ResetVersionTable();

                        if (!objDTOStatus.Success)
                        {
                            // If there is an error return it
                            objRegisterStatus.isSuccessful = false;
                            objRegisterStatus.status       = objDTOStatus.StatusMessage;
                        }
                        else
                        {
                            //  Delete the user in case they were partially created
                            objDTOStatus = DeleteAllUsers();

                            if (!objDTOStatus.Success)
                            {
                                // If there is an error return it
                                objRegisterStatus.isSuccessful = false;
                                objRegisterStatus.status       = objDTOStatus.StatusMessage;
                            }
                        }
                    }
                    else
                    {
                        // Update the created user to be a SuperUser
                        objDTOStatus = MakeUserASuperUser(objRegister.userName);

                        #region Set the upload file path
                        try
                        {
                            string strDefaultFilesPath = ADefHelpDeskApp.Controllers.ApplicationSettingsController.GetFilesPath(_DefaultFilesPath, GetConnectionString());

                            // Get GeneralSettings
                            GeneralSettings objGeneralSettings = new GeneralSettings(GetConnectionString());
                            objGeneralSettings.UpdateFileUploadPath(GetConnectionString(), strDefaultFilesPath);
                        }
                        catch
                        {
                            // Do nothing if this fails
                            // Admin can set the file path manually
                        }
                        #endregion

                        if (!objDTOStatus.Success)
                        {
                            // If there is an error return it
                            objRegisterStatus.isSuccessful = false;
                            objRegisterStatus.status       = objDTOStatus.StatusMessage;
                        }
                    }
                }
            }

            return(objRegisterStatus);
        }
Example #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LanguageController"/> class.
 /// </summary>
 /// <param name="generalSettings">The general settings.</param>
 /// <param name="logger">the log handler.</param>
 public LanguageController(
     IOptions <GeneralSettings> generalSettings, ILogger <LanguageController> logger)
 {
     _generalSettings = generalSettings.Value;
     _logger          = logger;
 }
Example #23
0
 public AuthorisationManager(GeneralSettings generalSettings, MainContext mainContext, IPasswordHashEngine passwordHashEngine)
 {
     _generalSettings    = generalSettings;
     _mainContext        = mainContext;
     _passwordHashEngine = passwordHashEngine;
 }
Example #24
0
        private void InitializeAddIn()
        {
            if (_isInitialized)
            {
                // The add-in is already initialized. See:
                // The strange case of the add-in initialized twice
                // http://msmvps.com/blogs/carlosq/archive/2013/02/14/the-strange-case-of-the-add-in-initialized-twice.aspx
                return;
            }

            var configLoader = new XmlPersistanceService <GeneralSettings>
            {
                FilePath =
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                 "Rubberduck", "rubberduck.config")
            };
            var configProvider = new GeneralConfigProvider(configLoader);

            _initialSettings = configProvider.Create();
            if (_initialSettings != null)
            {
                try
                {
                    var cultureInfo = CultureInfo.GetCultureInfo(_initialSettings.Language.Code);
                    Dispatcher.CurrentDispatcher.Thread.CurrentUICulture = cultureInfo;
                }
                catch (CultureNotFoundException)
                {
                }
            }
            else
            {
                Debug.Assert(false, "Settings could not be initialized.");
            }

            Splash splash = null;

            if (_initialSettings.CanShowSplash)
            {
                splash = new Splash
                {
                    // note: IVersionCheck.CurrentVersion could return this string.
                    Version = $"version {Assembly.GetExecutingAssembly().GetName().Version}"
                };
                splash.Show();
                splash.Refresh();
            }

            try
            {
                Startup();
            }
            catch (Win32Exception)
            {
                System.Windows.Forms.MessageBox.Show(Resources.RubberduckUI.RubberduckReloadFailure_Message, RubberduckUI.RubberduckReloadFailure_Title,
                                                     MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception exception)
            {
                _logger.Fatal(exception);
                System.Windows.Forms.MessageBox.Show(
#if DEBUG
                    exception.ToString(),
#else
                    exception.Message.ToString(),
#endif
                    RubberduckUI.RubberduckLoadFailure, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                splash?.Dispose();
            }
        }
Example #25
0
 internal static void LoadSettings()
 {
     Container      = Parameters.LoadProperties(new ContainerSettings());
     TaskDefenition = Parameters.LoadProperties(new TaskDefenitionSettings());
     General        = Parameters.LoadProperties(new GeneralSettings());
 }
Example #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PersonsWrapper"/> class.
 /// </summary>
 /// <param name="httpClient">HttpClient from default httpclientfactory</param>
 /// <param name="generalSettings">The GeneralSettings section of appsettings.</param>
 /// <param name="logger">The logger.</param>
 public PersonsWrapper(HttpClient httpClient, IOptions <GeneralSettings> generalSettings, ILogger <PersonsWrapper> logger)
 {
     _generalSettings = generalSettings.Value;
     _logger          = logger;
     _client          = httpClient;
 }
Example #27
0
        public void TestIfInterestPrincipalAndFeesCorrectlyRetrievedWhenDisburseAndFees()
        {
            Assert.AreEqual(new DateTime(2006, 1, 1), contractForAGroup.StartDate);
            CashReceipt cashReceipt = new CashReceipt(contractForAGroup, _person, null, "USD", "en-US", new ExchangeRate(new DateTime(2006, 1, 1), 3), new DateTime(2006, 1, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            //Negative value for principal if event is a loanDisbursmentEvent
            Assert.AreEqual(-3000, cashReceipt.PaidPrincipalInExternalCurrency);
            Assert.AreEqual(0, cashReceipt.PaidInterestInExternalCurrency);
            Assert.AreEqual(90, cashReceipt.PaidFeesInExternalCurrency);
        }
        private static void DeleteExistingFile(AdefHelpDeskAttachments objAttachment, string DefaultConnection, string strCurrentUser)
        {
            GeneralSettings objGeneralSettings = new GeneralSettings(DefaultConnection);

            if (objGeneralSettings.StorageFileType == "AzureStorage")
            {
                CloudStorageAccount storageAccount     = null;
                CloudBlobContainer  cloudBlobContainer = null;

                // Retrieve the connection string for use with the application.
                string storageConnectionString = objGeneralSettings.AzureStorageConnection;

                // Check whether the connection string can be parsed.
                if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
                {
                    // Ensure there is a AdefHelpDesk Container
                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                    cloudBlobContainer = cloudBlobClient.GetContainerReference("adefhelpdesk-files");
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(objAttachment.FileName);
                    cloudBlockBlob.DeleteIfExistsAsync();
                }
                else
                {
                    throw new Exception("AzureStorage configured but AzureStorageConnection value cannot connect.");
                }
            }
            else
            {
                // Construct path
                string FullPath = Path.Combine(objAttachment.AttachmentPath, objAttachment.FileName).Replace(@"\", @"/");

                // Delete file if it exists
                if (System.IO.File.Exists(FullPath))
                {
                    try
                    {
                        System.IO.File.Delete(FullPath);

                        // Log it
                        Log.InsertSystemLog(DefaultConnection,
                                            Constants.FileDeletion,
                                            strCurrentUser,
                                            $"({strCurrentUser}) Deleted File {objAttachment.OriginalFileName} ({FullPath}) of Task Detail # {objAttachment.DetailId}.");
                    }
                    catch (Exception ex)
                    {
                        Log.InsertSystemLog(DefaultConnection,
                                            Constants.FileDeleteError,
                                            strCurrentUser,
                                            $"({strCurrentUser}) Attempting to delete file {FullPath} resulted in error {ex.GetBaseException().ToString()}.");
                    }
                }
                else
                {
                    Log.InsertSystemLog(DefaultConnection,
                                        Constants.FileReadError,
                                        strCurrentUser,
                                        $"({strCurrentUser}) Attempting to delete file {FullPath} resulted in 'file not found' error.");
                }
            }
        }
Example #29
0
        public void TestIfLocalAccountNumberCorrectlyRetrievedWhenDisburse()
        {
            ChartOfAccounts chartOfAccounts = ChartOfAccounts.GetInstance(User.CurrentUser);

            CashReceipt cashReceipt = new CashReceipt(contractForAPerson, _person, null, "USD", "en-US", null, new DateTime(2006, 1, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            Assert.AreEqual(String.Empty, cashReceipt.InterestLocalAccountNumber);
            Assert.AreEqual(chartOfAccounts.GetAccountByTypeCode("CASH").LocalNumber, cashReceipt.PrincipalLocalAccountNumber);
            Assert.AreEqual(chartOfAccounts.GetAccountByTypeCode("COMMISSIONS").LocalNumber, cashReceipt.FeesLocalAccountNumber);
        }
        private static void SetEmailContents(string FileName, int intAttachmentId, string strFullFilePath, string ConnectionString, ref DTOTaskDetail objDTOTaskDetail)
        {
            GeneralSettings objGeneralSettings = new GeneralSettings(ConnectionString);

            if (objGeneralSettings.StorageFileType == "AzureStorage")
            {
                CloudStorageAccount storageAccount     = null;
                CloudBlobContainer  cloudBlobContainer = null;

                // Retrieve the connection string for use with the application.
                string storageConnectionString = objGeneralSettings.AzureStorageConnection;

                // Check whether the connection string can be parsed.
                if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
                {
                    // Ensure there is a AdefHelpDesk Container
                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                    cloudBlobContainer = cloudBlobClient.GetContainerReference("adefhelpdesk-files");
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(FileName);

                    // Download
                    cloudBlockBlob.FetchAttributesAsync().Wait();
                    long   fileByteLength = cloudBlockBlob.Properties.Length;
                    byte[] fileContent    = new byte[fileByteLength];
                    for (int i = 0; i < fileByteLength; i++)
                    {
                        fileContent[i] = 0x20;
                    }

                    cloudBlockBlob.DownloadToByteArrayAsync(fileContent, 0).Wait();

                    using (MemoryStream memstream = new MemoryStream(fileContent))
                    {
                        var message = MimeMessage.Load(memstream);

                        var visitor = new HtmlPreviewVisitor();
                        message.Accept(visitor);
                        objDTOTaskDetail.emailDescription = Utility.CleanOutlookFontDefinitions(visitor.HtmlBody);

                        // Add attachments (if any)
                        objDTOTaskDetail.colDTOAttachment = new List <DTOAttachment>();

                        foreach (var item in visitor.Attachments)
                        {
                            if (item.ContentDisposition.FileName != null)
                            {
                                DTOAttachment objDTOAttachment = new DTOAttachment();

                                objDTOAttachment.attachmentID     = intAttachmentId;
                                objDTOAttachment.attachmentPath   = "EML";
                                objDTOAttachment.userId           = "-1";
                                objDTOAttachment.fileName         = item.ContentDisposition.FileName;
                                objDTOAttachment.originalFileName = strFullFilePath;

                                objDTOTaskDetail.colDTOAttachment.Add(objDTOAttachment);
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("AzureStorage configured but AzureStorageConnection value cannot connect.");
                }
            }
            else
            {
                using (var fileContents = System.IO.File.OpenRead(strFullFilePath))
                {
                    var message = MimeMessage.Load(fileContents);

                    var visitor = new HtmlPreviewVisitor();
                    message.Accept(visitor);
                    objDTOTaskDetail.emailDescription = Utility.CleanOutlookFontDefinitions(visitor.HtmlBody);

                    // Add attachments (if any)
                    objDTOTaskDetail.colDTOAttachment = new List <DTOAttachment>();

                    foreach (var item in visitor.Attachments)
                    {
                        if (item.ContentDisposition.FileName != null)
                        {
                            DTOAttachment objDTOAttachment = new DTOAttachment();

                            objDTOAttachment.attachmentID     = intAttachmentId;
                            objDTOAttachment.attachmentPath   = "EML";
                            objDTOAttachment.userId           = "-1";
                            objDTOAttachment.fileName         = item.ContentDisposition.FileName;
                            objDTOAttachment.originalFileName = strFullFilePath;

                            objDTOTaskDetail.colDTOAttachment.Add(objDTOAttachment);
                        }
                    }
                }
            }
        }
Example #31
0
        public void TestIfInterestPrincipalAndFeesInLetterCorrectlyRetrievedWhenDisburseAndNoFeesWhenCurrencyIsSOMAndLanguageIsRussian()
        {
            Assert.AreEqual(new DateTime(2006, 1, 1), contractForAPerson.StartDate);
            CashReceipt cashReceipt = new CashReceipt(contractForAPerson, _person, null, "SOM", "ru-RU", new ExchangeRate(new DateTime(2006, 1, 1), 3), new DateTime(2006, 1, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            //Negative value for principal if event is a loanDisbursmentEvent

            Assert.AreEqual(-3000, cashReceipt.PaidPrincipalInExternalCurrency);
            Assert.AreEqual(0, cashReceipt.PaidInterestInExternalCurrency);
            Assert.AreEqual(0, cashReceipt.PaidFeesInExternalCurrency);
            Assert.AreEqual("ноль SOM", cashReceipt.PaidInterestInLetter);
            Assert.AreEqual("ноль SOM", cashReceipt.PaidFeesInLetter);
            Assert.AreEqual("три тысячи SOM", cashReceipt.PaidPrincipalInLetter);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UserProfilesWrapper"/> class
 /// </summary>
 /// <param name="httpClient">Httpclient from default httpclient factory</param>
 /// <param name="logger">the logger</param>
 /// <param name="generalSettings">the general settings</param>
 public UserProfilesWrapper(HttpClient httpClient, ILogger <UserProfilesWrapper> logger, IOptions <GeneralSettings> generalSettings)
 {
     _logger          = logger;
     _generalSettings = generalSettings.Value;
     _client          = httpClient;
 }
Example #33
0
        public void TestIfInterestPrincipalAndFeesInLetterCorrectlyRetrievedWhenRepayAndFeesWhenCurrencyIsUSDAndLanguageIsRussian()
        {
            Credit contract = contractForAPerson.Copy();

            contract.Disburse(new DateTime(2006, 1, 1), true, false);

            CashReceipt cashReceipt = new CashReceipt(contract, _person, 0, "USD", "ru-RU", new ExchangeRate(new DateTime(2006, 3, 1), 3), new DateTime(2006, 3, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            Assert.AreEqual(0, cashReceipt.PaidPrincipalInExternalCurrency);
            Assert.AreEqual(90, cashReceipt.PaidInterestInExternalCurrency);
            Assert.AreEqual(252.00m, Math.Round(cashReceipt.PaidFeesInExternalCurrency, 2));
            Assert.AreEqual("девяносто USD", cashReceipt.PaidInterestInLetter);
            Assert.AreEqual("двести пятьдесят два USD", cashReceipt.PaidFeesInLetter);
            Assert.AreEqual("ноль USD", cashReceipt.PaidPrincipalInLetter);
        }
Example #34
0
        /// <summary>
        /// configure database settings for the service
        /// </summary>
        /// <param name="services">the service configuration</param>
        public void ConfigureServices(IServiceCollection services)
        {
            _logger.LogInformation("Startup // ConfigureServices");

            services.AddControllers().AddNewtonsoftJson();
            services.AddMemoryCache();
            services.AddHealthChecks().AddCheck <HealthCheck>("storage_health_check");

            services.AddHttpClient <AuthorizationApiClient>();

            services.Configure <AzureCosmosSettings>(Configuration.GetSection("AzureCosmosSettings"));
            services.Configure <AzureStorageConfiguration>(Configuration.GetSection("AzureStorageConfiguration"));
            services.Configure <GeneralSettings>(Configuration.GetSection("GeneralSettings"));
            services.Configure <KeyVaultSettings>(Configuration.GetSection("kvSetting"));
            services.Configure <Common.PEP.Configuration.PepSettings>(Configuration.GetSection("PepSettings"));
            services.Configure <Common.PEP.Configuration.PlatformSettings>(Configuration.GetSection("PlatformSettings"));

            GeneralSettings generalSettings = Configuration.GetSection("GeneralSettings").Get <GeneralSettings>();

            services.AddAuthentication(JwtCookieDefaults.AuthenticationScheme)
            .AddJwtCookie(JwtCookieDefaults.AuthenticationScheme, options =>
            {
                options.JwtCookieName             = generalSettings.RuntimeCookieName;
                options.MetadataAddress           = generalSettings.OpenIdWellKnownEndpoint;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };

                if (_env.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(AuthzConstants.POLICY_INSTANCE_READ, policy => policy.Requirements.Add(new AppAccessRequirement("read")));
                options.AddPolicy(AuthzConstants.POLICY_INSTANCE_WRITE, policy => policy.Requirements.Add(new AppAccessRequirement("write")));
                options.AddPolicy(AuthzConstants.POLICY_INSTANCE_DELETE, policy => policy.Requirements.Add(new AppAccessRequirement("delete")));
                options.AddPolicy(AuthzConstants.POLICY_INSTANCE_COMPLETE, policy => policy.Requirements.Add(new AppAccessRequirement("complete")));
                options.AddPolicy(AuthzConstants.POLICY_SCOPE_APPDEPLOY, policy => policy.Requirements.Add(new ScopeAccessRequirement("altinn:appdeploy")));
                options.AddPolicy(AuthzConstants.POLICY_SCOPE_INSTANCE_READ, policy => policy.Requirements.Add(new ScopeAccessRequirement("altinn:instances.read")));
                options.AddPolicy(AuthzConstants.POLICY_STUDIO_DESIGNER, policy => policy.Requirements.Add(new ClaimAccessRequirement("urn:altinn:app", "studio.designer")));
            });

            services.AddSingleton <IDataRepository, DataRepository>();
            services.AddSingleton <IInstanceRepository, InstanceRepository>();
            services.AddSingleton <IApplicationRepository, ApplicationRepository>();
            services.AddSingleton <IInstanceEventRepository, InstanceEventRepository>();
            services.AddSingleton <ITextRepository, TextRepository>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <ISasTokenProvider, SasTokenProvider>();
            services.AddSingleton <IKeyVaultClientWrapper, KeyVaultClientWrapper>();
            services.AddSingleton <IPDP, PDPAppSI>();

            services.AddTransient <IAuthorizationHandler, StorageAccessHandler>();
            services.AddTransient <IAuthorizationHandler, ScopeAccessHandler>();
            services.AddTransient <IAuthorizationHandler, ClaimAccessHandler>();

            services.AddHttpClient <IPartiesWithInstancesClient, PartiesWithInstancesClient>();

            if (!string.IsNullOrEmpty(ApplicationInsightsKey))
            {
                services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel()
                {
                    StorageFolder = "/tmp/logtelemetry"
                });
                services.AddApplicationInsightsTelemetry(ApplicationInsightsKey);
                services.AddApplicationInsightsTelemetryProcessor <HealthTelemetryFilter>();
                services.AddSingleton <ITelemetryInitializer, CustomTelemetryInitializer>();

                _logger.LogInformation($"Startup // ApplicationInsightsTelemetryKey = {ApplicationInsightsKey}");
            }

            // Add Swagger support (Swashbuckle)
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Altinn Platform Storage", Version = "v1"
                });
                c.AddSecurityDefinition(JwtCookieDefaults.AuthenticationScheme, new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\". Remember to add \"Bearer\" to the input below before your token.",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Id   = JwtCookieDefaults.AuthenticationScheme,
                                Type = ReferenceType.SecurityScheme
                            }
                        },
                        new string[] { }
                    }
                });
                try
                {
                    c.IncludeXmlComments(GetXmlCommentsPathForControllers());

                    // hardcoded since nuget restore does not export the xml file.
                    c.IncludeXmlComments("Altinn.Platform.Storage.Interface.xml");
                }
                catch
                {
                    // catch swashbuckle exception if it doesn't find the generated xml documentation file
                }
            });
            services.AddSwaggerGenNewtonsoftSupport();
        }
Example #35
0
 void OnSettingsChanged(GeneralSettings settings)
 {
     voiceChatSpinBox.SetValue((int)settings.voiceChatAllow, false);
 }
Example #36
0
 public UsersController(IUserService userService,
                        ICommandDispatcher commandDispatcher,
                        GeneralSettings settings) : base(commandDispatcher)
 {
     _userService = userService;
 }
 public GeneralSettingsViewModel(GeneralSettings settings)
 {
     _settings = settings;
     UseStandardWindowsChrome = _settings.UseStandardWindowsChrome;
 }
Example #38
0
        /// <summary>
        /// Configure authentication settings for the service
        /// </summary>
        /// <param name="services">the service configuration</param>
        public void ConfigureServices(IServiceCollection services)
        {
            _logger.LogInformation("Startup // ConfigureServices");

            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.WriteIndented    = _env.IsDevelopment() || _env.IsStaging();
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });
            services.AddMvc().AddControllersAsServices();
            services.AddHealthChecks().AddCheck <HealthCheck>("authentication_health_check");

            services.AddSingleton(Configuration);
            services.Configure <GeneralSettings>(Configuration.GetSection("GeneralSettings"));
            services.Configure <AltinnCore.Authentication.Constants.KeyVaultSettings>(Configuration.GetSection("kvSetting"));
            services.Configure <AltinnCore.Authentication.Constants.CertificateSettings>(Configuration.GetSection("CertificateSettings"));
            services.Configure <Common.AccessToken.Configuration.KeyVaultSettings>(Configuration.GetSection("kvSetting"));
            services.Configure <AccessTokenSettings>(Configuration.GetSection("AccessTokenSettings"));

            services.AddAuthentication(JwtCookieDefaults.AuthenticationScheme)
            .AddJwtCookie(JwtCookieDefaults.AuthenticationScheme, options =>
            {
                GeneralSettings generalSettings   = Configuration.GetSection("GeneralSettings").Get <GeneralSettings>();
                options.JwtCookieName             = generalSettings.JwtCookieName;
                options.MetadataAddress           = generalSettings.OpenIdWellKnownEndpoint;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };

                if (_env.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }
            });

            services.AddSingleton(Configuration);
            services.AddHttpClient <ISblCookieDecryptionService, SblCookieDecryptionService>();
            services.AddHttpClient <IUserProfileService, UserProfileService>();
            services.AddSingleton <IJwtSigningCertificateProvider, JwtSigningCertificateProvider>();
            services.AddSingleton <ISigningKeysRetriever, SigningKeysRetriever>();
            services.AddTransient <IOrganisationRepository, OrganisationRepository>();
            services.AddSingleton <Common.AccessToken.Services.ISigningKeysResolver, Common.AccessToken.Services.SigningKeysResolver>();

            if (!string.IsNullOrEmpty(ApplicationInsightsKey))
            {
                services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel()
                {
                    StorageFolder = "/tmp/logtelemetry"
                });
                services.AddApplicationInsightsTelemetry(ApplicationInsightsKey);
                services.AddApplicationInsightsTelemetryProcessor <HealthTelemetryFilter>();
                services.AddSingleton <ITelemetryInitializer, CustomTelemetryInitializer>();

                _logger.LogInformation($"Startup // ApplicationInsightsTelemetryKey = {ApplicationInsightsKey}");
            }

            // Add Swagger support (Swashbuckle)
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Altinn Platform Authentication", Version = "v1"
                });

                try
                {
                    string filePath = GetXmlCommentsPathForControllers();
                    _logger.LogInformation($"Swagger XML document file: {filePath}");

                    c.IncludeXmlComments(filePath);
                }
                catch
                {
                    // catch swashbuckle exception if it doesn't find the generated xml documentation file
                }
            });
        }
Example #39
0
 private Configuration()
 {
     var properties = Properties.Settings.Default;
      // Read configuration section elements
      // General
      string outputDir = properties.General_OutputDirectory;
      if (string.IsNullOrEmpty(outputDir)) {
     string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
     try {
        outputDir = Path.Combine(myDocuments, outputDirInMyDocs);
     }
     catch (ArgumentException) {
        outputDir = myDocuments;
     }
      }
      GeneralSettings general = new GeneralSettings();
      general.MinimizeOnRecord = properties.General_MinimizeOnRecord;
      general.HideFromTaskbar = properties.General_HideFromTaskbarIfMinimized;
      general.OutputDirectory = outputDir;
      // Hot Keys
      HotKeySettings hotKeys = new HotKeySettings();
      hotKeys.Cancel = properties.HotKeys_Cancel;
      hotKeys.Global = properties.HotKeys_Global;
      hotKeys.Pause = properties.HotKeys_Pause;
      hotKeys.Record = properties.HotKeys_Record;
      hotKeys.Stop = properties.HotKeys_Stop;
      // Mouse
      MouseSettings mouse = new MouseSettings();
      mouse.HighlightCursor = properties.Mouse_HighlightCursor;
      mouse.HighlightCursorColor = properties.Mouse_HighlightCursorColor;
      mouse.HighlightCursorRadious = properties.Mouse_HighlightCursorRadious;
      mouse.RecordCursor = properties.Mouse_RecordCursor;
      // Sound
      SoundSettings sound = new SoundSettings();
      sound.DeviceId = properties.Sound_DeviceId;
      sound.Format = properties.Sound_Format;
      // Tracking
      TrackingSettings tracking = new TrackingSettings();
      tracking.Bounds = properties.Tracking_Bounds;
      tracking.Type = properties.Tracking_Type;
      // Video
      VideoSettings video = new VideoSettings();
      video.Compressor = properties.Video_Compressor;
      video.Fps = properties.Video_Fps;
      video.Quality = properties.Video_Quality;
      // Watermark
      WatermarkSettings waterMark = new WatermarkSettings();
      waterMark.Alignment = properties.Watermark_Alignment;
      waterMark.Color = properties.Watermark_Color;
      waterMark.Display = properties.Watermark_Display;
      waterMark.Font = properties.Watermark_Font;
      waterMark.Margin = properties.Watermark_Margin;
      waterMark.Outline = properties.Watermark_Outline;
      waterMark.OutlineColor = properties.Watermark_OutlineColor;
      waterMark.RightToLeft = properties.Watermark_RightToLeft;
      waterMark.Text = properties.Watermark_Text;
      // Set properties
      this.General = general;
      this.HotKeys = hotKeys;
      this.Mouse = mouse;
      this.Sound = sound;
      this.Tracking = tracking;
      this.Video = video;
      this.Watermark = waterMark;
 }
Example #40
0
        public void CashReceipt_CorrectlySaveAndRetrieved_GracePeriod()
        {
            contractForAPerson.Disbursed = true;
            _person.CashReceiptIn        = 1;
            CashReceipt cashReceipt = new CashReceipt(contractForAPerson, _person, 0, "USD", "en-US", new ExchangeRate(new DateTime(2006, 2, 1), 3), new DateTime(2006, 2, 1), false, User.CurrentUser, GeneralSettings.GetInstance(""), ChartOfAccounts.GetInstance(User.CurrentUser), true);

            Assert.AreEqual(1, cashReceipt.GracePeriod);
        }
Example #41
0
        public GeneralViewModel(ISettingsUtils settingsUtils, string runAsAdminText, string runAsUserText, bool isElevated, bool isAdmin, Func <string, int> updateTheme, Func <string, int> ipcMSGCallBackFunc, Func <string, int> ipcMSGRestartAsAdminMSGCallBackFunc, Func <string, int> ipcMSGCheckForUpdatesCallBackFunc, string configFileSubfolder = "")
        {
            CheckFoUpdatesEventHandler        = new ButtonClickCommand(CheckForUpdates_Click);
            RestartElevatedButtonEventHandler = new ButtonClickCommand(Restart_Elevated);
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            try
            {
                GeneralSettingsConfigs = _settingsUtils.GetSettings <GeneralSettings>(string.Empty);

                if (Helper.CompareVersions(GeneralSettingsConfigs.PowertoysVersion, Helper.GetProductVersion()) < 0)
                {
                    // Update settings
                    GeneralSettingsConfigs.PowertoysVersion = Helper.GetProductVersion();
                    _settingsUtils.SaveSettings(GeneralSettingsConfigs.ToJsonString(), string.Empty);
                }
            }
            catch (FormatException e)
            {
                // If there is an issue with the version number format, don't migrate settings.
                Debug.WriteLine(e.Message);
            }
            catch
            {
                GeneralSettingsConfigs = new GeneralSettings();
                _settingsUtils.SaveSettings(GeneralSettingsConfigs.ToJsonString(), string.Empty);
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
            SendCheckForUpdatesConfigMSG = ipcMSGCheckForUpdatesCallBackFunc;
            SendRestartAsAdminConfigMSG  = ipcMSGRestartAsAdminMSGCallBackFunc;

            // set the callback function value to update the UI theme.
            UpdateUIThemeCallBack = updateTheme;
            UpdateUIThemeCallBack(GeneralSettingsConfigs.Theme.ToLower());

            // Update Settings file folder:
            _settingsConfigFileFolder = configFileSubfolder;

            switch (GeneralSettingsConfigs.Theme.ToLower())
            {
            case "light":
                _isLightThemeRadioButtonChecked = true;
                break;

            case "dark":
                _isDarkThemeRadioButtonChecked = true;
                break;

            case "system":
                _isSystemThemeRadioButtonChecked = true;
                break;
            }

            _startup             = GeneralSettingsConfigs.Startup;
            _autoDownloadUpdates = GeneralSettingsConfigs.AutoDownloadUpdates;
            _isElevated          = isElevated;
            _runElevated         = GeneralSettingsConfigs.RunElevated;

            RunningAsUserDefaultText  = runAsUserText;
            RunningAsAdminDefaultText = runAsAdminText;

            _isAdmin = isAdmin;
        }
Example #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PolicyRetrievalPoint"/> class.
 /// </summary>
 /// <param name="policyRepository">The policy Repository..</param>
 /// <param name="memoryCache">The cache handler </param>
 /// <param name="settings">The app settings</param>
 public PolicyRetrievalPoint(IPolicyRepository policyRepository, IMemoryCache memoryCache, IOptions <GeneralSettings> settings)
 {
     _repository      = policyRepository;
     _memoryCache     = memoryCache;
     _generalSettings = settings.Value;
 }