Ejemplo n.º 1
0
        /// <summary>
        /// Class constructor
        /// </summary>
        public ConfigViewModel()
            : base()
        {
            // Setup default values here - real values are loaded in a specific method of this class (!)
            _WordWrapText = false;
            _ReloadOpenFilesOnAppStart = false;
            _RunSingleInstance         = true;

            this.WordWrapText = false;

            // Get default list of units from settings manager
            var unitList = new ObservableCollection <UnitComboLib.Models.ListItem>(SettingsFactory.GenerateScreenUnitList());

            this.SizeUnitLabel =
                UnitComboLib.UnitViewModeService.CreateInstance(
                    unitList,
                    new ScreenConverter(),
                    (int)ZoomUnit.Percentage, 100);

            this.EditorTextOptions = new TextEditorOptions();

            // Initialize localization settings
            Languages = new List <ILang>(SettingsFactory.GetSupportedLanguages());

            // Set default language to make sure app neutral is selected and available for sure
            // (this is a fallback if all else fails)
            try
            {
                this.LanguageSelected = this.Languages.FirstOrDefault(lang => lang.BCP47 == SettingsFactory.DefaultLocal);
            }
            catch
            {
            }
        }
Ejemplo n.º 2
0
        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {
            this.controller = new RibbonController();
            SettingsFactory factory = new SettingsFactory();

            this.settings = factory.GetSettings();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Reset the view model to those options that are going to be presented for editing.
        /// </summary>
        /// <param name="settingData"></param>
        public void LoadOptionsFromModel(IOptions settingData)
        {
            this.ReloadOpenFilesOnAppStart = settingData.ReloadOpenFilesOnAppStart;
            this.RunSingleInstance         = settingData.RunSingleInstance;

            this.WordWrapText = settingData.WordWarpText;

            this.EditorTextOptions = new TextEditorOptions(settingData.EditorTextOptions);
            this.SizeUnitLabel     = UnitComboLib.UnitViewModeService.CreateInstance(
                new ObservableCollection <UnitComboLib.Models.ListItem>(
                    SettingsFactory.GenerateScreenUnitList()),
                new ScreenConverter(),
                (int)settingData.DocumentZoomUnit, settingData.DocumentZoomView);

            try
            {
                this.LanguageSelected = this.Languages.FirstOrDefault(lang => lang.BCP47 == settingData.LanguageSelected);
            }
            catch
            {
            }

            this.TextToHTML_ShowLineNumbers         = settingData.TextToHTML_ShowLineNumbers;
            this.TextToHTML_AlternateLineBackground = settingData.TextToHTML_AlternateLineBackground;

            this.HighlightOnFileNew          = settingData.HighlightOnFileNew;
            this.FileNewDefaultFileName      = settingData.FileNewDefaultFileName;
            this.FileNewDefaultFileExtension = settingData.FileNewDefaultFileExtension;
        }
Ejemplo n.º 4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            var formContents = await FormContentsFactory.Create(req);

            var comment  = CommentFactory.Create(formContents);
            var settings = SettingsFactory.Create(formContents.Options.Origin, log);

            var reCaptcha         = new ReCaptchaService(settings.ReCaptchaSecretKey, log);
            var reCaptchaResponse = await reCaptcha.Validate(formContents.Options.Recaptcha.Token);

            var akismetService  = new AkismetService(settings, log);
            var akismetResponse = await akismetService.IsSpam(req, comment, formContents);

            var gitHubService = new GitHubService(settings.GitHubOwner, settings.GitHubRepository, settings.GitHubBranch,
                                                  settings.GitHubCommentPath, settings.GitHubToken);
            var knownCommenterResponse = await gitHubService.IsKnownCommenter(comment.Name, comment.Email);

            var analyzer       = new ModerationAnalyzer(settings, log);
            var analysisReport = analyzer.NeedsModeration(comment, reCaptchaResponse, akismetResponse, knownCommenterResponse);

            await gitHubService.AddComment(comment, analysisReport, knownCommenterResponse);

            return(new OkResult());
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Update(Guid id, [FromBody] Dictionary <string, string> data)
        {
            IActionResult result = null;
            bool          locked = default;

            try
            {
                if (result == null && data == null)
                {
                    result = BadRequest("Missing patch data");
                }
                if (result == null && (!data.ContainsKey("Locked") || string.IsNullOrEmpty(data["Locked"])))
                {
                    result = BadRequest("Missing Locked value");
                }
                if (result == null && Guid.Empty.Equals(id))
                {
                    result = BadRequest("Invalid account id");
                }
                if (result == null && !UserCanAccessAccount(id))
                {
                    result = StatusCode(StatusCodes.Status401Unauthorized);
                }
                if (result == null && !bool.TryParse(data["Locked"], out locked))
                {
                    result = BadRequest("Invalid locked value.  Expecting 'True' or 'False'");
                }
                if (result == null)
                {
                    using (ILifetimeScope scope = _container.BeginLifetimeScope())
                    {
                        SettingsFactory settingsFactory = scope.Resolve <SettingsFactory>();
                        CoreSettings    settings        = settingsFactory.CreateAccount(_settings.Value);
                        IAccountFactory accountFactory  = scope.Resolve <IAccountFactory>();
                        IAccount        innerAccount    = await accountFactory.Get(settings, id);

                        if (innerAccount == null)
                        {
                            result = NotFound();
                        }
                        else
                        {
                            IAccountSaver saver = scope.Resolve <IAccountSaver>();
                            await saver.UpdateLocked(settings, innerAccount.AccountId, locked);

                            result = Ok();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (ILifetimeScope scope = _container.BeginLifetimeScope())
                {
                    await LogException(ex, scope.Resolve <IExceptionService>(), scope.Resolve <SettingsFactory>(), _settings.Value);
                }
                result = StatusCode(StatusCodes.Status500InternalServerError);
            }
            return(result);
        }
Ejemplo n.º 6
0
        private void NewBrowserLauncherView(BrandProvider brandProvider)
        {
            brandProvider.Login    = SettingsFactory.GetLoginFromDB(brandProvider.ProviderId);
            brandProvider.Password = SettingsFactory.GetPswFromDB(brandProvider.ProviderId);

            EventNewBrowserLauncherView?.Invoke(this.time, brandProvider);
        }
Ejemplo n.º 7
0
        public ActionResult Index()
        {
            ViewBag.UpdateSuccessfull = false;
            var model = SettingsFactory.CreateViewModel(SettingsService.GetSettings());

            return(View(model));
        }
Ejemplo n.º 8
0
        public void ReturnSomething_GivenSomething()
        {
            var mock            = new Mock <IRepository>();
            var settingsFactory = new SettingsFactory(mock.Object);

            var commandSettingsEntities = new List <CommandSettingsEntity>
            {
                new CommandSettingsEntity {
                    Key = "ProtectSubscribers", Value = "false"
                },
                new CommandSettingsEntity {
                    Key = "CoinsReward", Value = "23"
                },
                new CommandSettingsEntity {
                    Key = "TimeoutDurationInSeconds", Value = "34"
                },
                new CommandSettingsEntity {
                    Key = "WinPercentageChance", Value = "45"
                },
            };

            mock.Setup(x => x.List(It.IsAny <CommandSettingsPolicy>())).Returns(commandSettingsEntities);

            var rouletteSettings = settingsFactory.GetSettings <RouletteSettings>();

            rouletteSettings.Should().NotBeNull();
            rouletteSettings.ProtectSubscribers.Should().BeFalse();
            rouletteSettings.CoinsReward.Should().Be(23);
            rouletteSettings.TimeoutDurationInSeconds.Should().Be(34);
            rouletteSettings.WinPercentageChance.Should().Be(45);
        }
Ejemplo n.º 9
0
        public ActionResult Index(SettingsViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var set = SettingsFactory.CreateModel(model);
                    if (set != null)
                    {
                        SettingsRepository.Save(set);
                        ConfigurationManager.AppSettings["Theme"] = model.SelectedTheme;
                        SettingsService.ReloadSettings();
                        ShowOperationMessage(UIResources.SettingsPageSaveSuccessfull);
                    }
                }

                model.Themes.AddRange(Directory.EnumerateDirectories(Server.MapPath("~/Views/Themes")).Select(e => Path.GetFileName(e)).ToList());
                return(View(model));
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                ShowErrorMessage(ex.Message);
                return(RedirectToAction("Index", "Error"));
            }
        }
Ejemplo n.º 10
0
        public App(string settingsFilePath, List <AlertModel> alerts)
        {
            _settingsFilePath = settingsFilePath;

            _settings = SettingsFactory.GetSettings(_settingsFilePath);

            _themeResources = new ResourceDictionary();

            _shellView = CreateView <Views.ShellView, ViewModels.ShellViewModel>(this);

            _shellView.Topmost = _settings.General.TopMost;

            Accent   accent = SettingsFactory.GetAccent(_settings.General.ThemeAccent);
            AppTheme theme  = SettingsFactory.GetTheme(_settings.General.ThemeBase);

            _themeResources.MergedDictionaries.Add(accent.Resources);
            _themeResources.MergedDictionaries.Add(theme.Resources);

            _navigationJournal = new List <string>();

            _eventAggregator = new EventAggregator();

            _eventAggregator.GetEvent <Events.SettingsChangedEvent>().Subscribe(SettingsChangedEvent_Handler);
            _eventAggregator.GetEvent <Events.GeneralSettingsChangedEvent>().Subscribe(GeneralSettingsChangedEvent_Handler);
            _eventAggregator.GetEvent <Events.AlertRemovedEvent>().Subscribe(AlertRemovedEvent_Handler);

            _alerts = alerts;
        }
Ejemplo n.º 11
0
        public async Task <CrocoHealthCheckerResult> CheckHealth(CancellationToken token = default)
        {
            var rootSettings = await SettingsFactory.GetSettingAsync <RootSettings>();

            if (string.IsNullOrWhiteSpace(rootSettings.RootEmail))
            {
                return(CrocoHealthCheckerResult.UnHealthy($"Проверьте настройку {typeof(RootSettings).FullName} ее свойство {nameof(RootSettings.RootEmail)}"));
            }

            var rootUser = await UserSearcher.GetUserByEmailAsync(rootSettings.RootEmail);

            if (rootUser == null)
            {
                return(CrocoHealthCheckerResult.UnHealthy($"Рут пользователь не создан." +
                                                          $" Воспользуйтесь методом {nameof(AccountInitiator.CreateRootUserAsync)} класса {nameof(AccountInitiator)} чтобы исправить данную ситуацию."));
            }

            if (rootUser.IsInRole(rootSettings.RootEmail))
            {
                return(CrocoHealthCheckerResult.UnHealthy($"Текущий рут пользователь не имеет рут прав." +
                                                          $" Воспользуйтесь методом {nameof(AccountInitiator.CreateRootUserAsync)} класса {nameof(AccountInitiator)} чтобы исправить данную ситуацию."));
            }

            return(CrocoHealthCheckerResult.Healthy("С пользователем рут все в порядке"));
        }
Ejemplo n.º 12
0
        private void CreateEditables()
        {
            var factory   = new SettingsFactory();
            var editables = factory.Reflect(Configuration, out var changeTrackingManager).ToList();

            var connectionEditables = new List <IEditableConfig>();
            var projectsEditables   = new List <IEditableConfig>();

            foreach (var config in editables)
            {
                if (config.PropertyInfo.Name == nameof(IConfiguration.Connections))
                {
                    connectionEditables.Add(config);
                    continue;
                }

                if (config.PropertyInfo.Name == nameof(IConfiguration.Projects))
                {
                    projectsEditables.Add(config);
                    continue;
                }

                Configs.Add(config);
            }

            ConnectionsSubSet = new SettingsSubSetViewModel(connectionEditables);
            ProjectsSubSet    = new SettingsSubSetViewModel(projectsEditables);

            changeTrackingManager.ConfigurationChanged += (sender, args) =>
            {
                _saveMethod.Invoke();
                SettingsChanged?.Invoke(this, EventArgs.Empty);
            };
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Search()
        {
            IActionResult result = null;

            try
            {
                using ILifetimeScope scope = _container.BeginLifetimeScope();
                SettingsFactory     settingsFactory = scope.Resolve <SettingsFactory>();
                CoreSettings        settings        = settingsFactory.CreateCore(_settings.Value);
                IPurgeWorkerFactory factory         = scope.Resolve <IPurgeWorkerFactory>();
                IMapper             mapper          = MapperConfigurationFactory.CreateMapper();
                result = Ok(
                    (await factory.GetAll(settings))
                    .Select <IPurgeWorker, PurgeWorker>(innerPurgeWorker => mapper.Map <PurgeWorker>(innerPurgeWorker))
                    );
            }
            catch (System.Exception ex)
            {
                using (ILifetimeScope scope = _container.BeginLifetimeScope())
                {
                    await LogException(ex, scope.Resolve <IExceptionService>(), scope.Resolve <SettingsFactory>(), _settings.Value);
                }
                result = StatusCode(StatusCodes.Status500InternalServerError);
            }
            return(result);
        }
Ejemplo n.º 14
0
        public TemplatesAction()
            : base(3600)
        {
            DateTime lastRun = DateTime.Today, today = DateTime.Today;

            using (IRepository <Settings, long> repository = PersistentFactory.GetContext().GetRepository <Settings, long>())
            {
                Settings settings = SettingsFactory.GetSettings(repository);
                lastRun = settings.LastRun.GetDate();
            }

            if (lastRun < today)
            {
                using (IRepository <Template, long> repository = PersistentFactory.GetContext().GetRepository <Template, long>())
                {
                    while (lastRun < today)
                    {
                        foreach (Template template in repository.GetAll())
                        {
                            if (template.SatisfiesCondition(lastRun))
                            {
                                Task newTask = template.CreateTask(lastRun);
                                TaskCreated?.Invoke(newTask);

                                repository.Update(template);
                                Log.Info($"Task {newTask.Name} was created from template for day {lastRun.ToShortDateString()}", this);
                            }
                        }

                        lastRun = lastRun.AddDays(1);
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private static void CreateDefaultSettingsIfNeeded(IRepository repository)
        {
            var settingsFactory = new SettingsFactory(repository);

            settingsFactory.CreateDefaultSettingsIfNeeded <RouletteSettings>();
            settingsFactory.CreateDefaultSettingsIfNeeded <CurrencySettings>();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Standard constructor. See also static <seealso cref="LoadFile"/> method
        /// for construction from file saved on disk.
        /// </summary>
        protected EdiViewModel(IMessageBoxService IMsgBox)
            : base(DocumentKey, IMsgBox)
        {
            CloseOnErrorWithoutMessage = false;

            // Copy text editor settings from settingsmanager by default
            TextOptions = new ICSharpCode.AvalonEdit.TextEditorOptions();
            WordWrap    = false;

            var items = new ObservableCollection <UnitComboLib.Models.ListItem>(SettingsFactory.GenerateScreenUnitList());

            SizeUnitLabel =
                UnitComboLib.UnitViewModeService.CreateInstance(items,
                                                                new ScreenConverter(),
                                                                0);

            TxtControl = new TextBoxController();

            FilePath = GetDefaultFileNewName();

            IsDirty = false;
            _HighlightingDefinition = null;

            _Document = null; //new TextDocument();

            TextEditorSelectionStart  = 0;
            TextEditorSelectionLength = 0;

            InsertBlocks = null;
        }
Ejemplo n.º 17
0
        private Task <string> CreateToken(IClient client)
        {
            using ILifetimeScope scope = _container.BeginLifetimeScope();
            SettingsFactory settingsFactory = scope.Resolve <SettingsFactory>();
            RSAParameters   rsaParameters   = CreateRSAParameter();
            //RSA rsa = new RSACryptoServiceProvider(2048);
            //Debug.WriteLine(Convert.ToBase64String(rsa.ExportRSAPublicKey()));
            RsaSecurityKey securityKey = new RsaSecurityKey(rsaParameters);
            JsonWebKey     jsonWebKey  = JsonWebKeyConverter.ConvertFromRSASecurityKey(securityKey);
            //Debug.WriteLine(JsonConvert.SerializeObject(jsonWebKey));
            SigningCredentials credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha512);
            List <Claim>       claims      = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N"))
            };

            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, client.ClientId.ToString("N")));
            claims.Add(new Claim("accounts", client.AccountId.ToString("N")));
            JwtSecurityToken token = new JwtSecurityToken(
                "urn:brassloon",
                "urn:brassloon",
                claims,
                expires: DateTime.Now.AddHours(6),
                signingCredentials: credentials
                );

            return(Task.FromResult <string>(new JwtSecurityTokenHandler().WriteToken(token)));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Execute closing function and persist session data to be reloaded on next restart
        /// </summary>
        /// <param name="win"></param>
        public void OnClosed(Window win)
        {
            try
            {
                EnableMainWindowActivated(false);

                // Persist window position, width and height from this session
                _SettingsManager.SessionData.MainWindowPosSz =
                    SettingsFactory.GetViewPosition(win.Left, win.Top, win.Width, win.Height,
                                                    (win.WindowState == WindowState.Maximized));

                _SettingsManager.SessionData.IsWorkspaceAreaOptimized = IsWorkspaceAreaOptimized;

                // Save/initialize program options that determine global programm behaviour
                SaveConfigOnAppClosed();

                DisposeResources();
            }
            catch (Exception exp)
            {
                Logger.Error(exp);
                _msgBox.Show(exp.ToString(),
                             Util.Local.Strings.STR_MSG_UnknownError_InShutDownProcess,
                             MsgBoxButtons.OK, MsgBoxImage.Error);
            }
        }
Ejemplo n.º 19
0
        public static void BeginProgram()
        {
            var timer = new Timer("Starting DaySim Controller...");

            Console.WriteLine("Run initial DaySim steps locally");

            var settingsFactory = new SettingsFactory(Global.Configuration);

            Global.Settings = settingsFactory.Create();

            ParallelUtility.Init(Global.Configuration);

            Engine.InitializeDaySim();
            Engine.BeginInitialize();
            Engine.BeginRunRawConversion();
            Engine.BeginImportData();
            Engine.BeginBuildIndexes();

            BeginRunRemoteProcesses();
            BeginMerge();
            BeginLoadData();

            Engine.BeginUpdateShadowPricing();
            if (Global.Configuration.RemoteCopySPFilesToRemoteMachines)
            {
                BeginCopyFilesToRemoteMachines();
            }

            timer.Stop("Total running time");
        }
Ejemplo n.º 20
0
        public async Task DeleteUnlinkedImages()
        {
            var siteRepository = new SiteRepository(SettingsFactory.GetConnectionString());
            var site           = await siteRepository.GetAsync();

            var imageRepository = new ImageRepository(SettingsFactory.GetConnectionString());

            var list = await imageRepository.GetFileNamesAsync();

            foreach (var fileName in list)
            {
                bool found = false;

                foreach (var recipe in site.Recipes)
                {
                    if (recipe.ImageUrl != null && recipe.ImageUrl.Contains(fileName))
                    {
                        found = true;
                    }
                }

                if (!found)
                {
                    await imageRepository.DeleteAsync(fileName);
                }
            }
        }
Ejemplo n.º 21
0
 private void SettingsChangedEvent_Handler(Models.SettingsModel settings)
 {
     if (!string.IsNullOrEmpty(_settingsFilePath))
     {
         SettingsFactory.SaveSettings(_settingsFilePath, Settings);
     }
 }
Ejemplo n.º 22
0
        public async Task <IActionResult> GetByEmailAddress(string emailAddress)
        {
            IActionResult result = null;

            using (ILifetimeScope scope = _container.BeginLifetimeScope())
            {
                SettingsFactory     settingsFactory = scope.Resolve <SettingsFactory>();
                CoreSettings        settings        = settingsFactory.CreateAccount(_settings.Value);
                IUserFactory        userFactory     = scope.Resolve <IUserFactory>();
                IEnumerable <IUser> users           = await userFactory.GetByEmailAddress(settings, emailAddress);

                IAccountFactory accountFactory = scope.Resolve <IAccountFactory>();
                ConcurrentBag <Task <IEnumerable <IAccount> > > accounts = new ConcurrentBag <Task <IEnumerable <IAccount> > >();
                users.AsParallel().ForAll(user => accounts.Add(accountFactory.GetByUserId(settings, user.UserId)));
                IMapper mapper = MapperConfigurationFactory.CreateMapper();
                result = Ok(
                    (await Task.WhenAll <IEnumerable <IAccount> >(accounts))
                    .SelectMany(results => results)
                    .Where(a => UserCanAccessAccount(a.AccountId))
                    .Select <IAccount, Account>(innerAccount => mapper.Map <Account>(innerAccount))
                    .ToList()
                    );
            }
            return(result);
        }
Ejemplo n.º 23
0
        public void CreateTest()
        {
            _objectsCreated = 0;

            var config = A.Fake <IConfiguration>();

            A.CallTo(() => config.GetItems <object>())
            .Returns(CreateNewObjects())
            .NumberOfTimes(1)
            .Then
            .Returns(CreateNewObjects());

            var factory = new SettingsFactory <object>(config);


            var items0 = factory.Create().ToArray();
            var items1 = factory.Create().ToArray();

            Assert.Equal(2, _objectsCreated);
            Assert.Single((IEnumerable)items0);
            Assert.Single(items1);
            Assert.Contains("c", items0);
            Assert.Contains("cc", items1);
            Assert.NotSame(items0, items1);
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> Update([FromRoute] Guid?id, [FromBody] ClientCredentialRequest client)
        {
            IActionResult result = null;

            try
            {
                if (result == null && !id.HasValue || id.Value.Equals(Guid.Empty))
                {
                    result = BadRequest("Missing client id value");
                }
                if (result == null && client == null)
                {
                    result = BadRequest("Missing client data");
                }
                if (result == null && string.IsNullOrEmpty(client.Name))
                {
                    result = BadRequest("Missing client name value");
                }
                if (result == null && !string.IsNullOrEmpty(client.Secret) && client.Secret.Trim().Length < 16)
                {
                    result = BadRequest("Client secret must be at least 16 characters in lenth");
                }
                if (result == null)
                {
                    using ILifetimeScope scope = _container.BeginLifetimeScope();
                    IClientFactory  clientFactory   = scope.Resolve <IClientFactory>();
                    SettingsFactory settingsFactory = scope.Resolve <SettingsFactory>();
                    CoreSettings    settings        = settingsFactory.CreateAccount(_settings.Value);
                    IClient         innerClient     = await clientFactory.Get(settings, id.Value);

                    if (innerClient == null)
                    {
                        result = NotFound();
                    }
                    if (result == null && !UserCanAccessAccount(innerClient.AccountId))
                    {
                        result = StatusCode(StatusCodes.Status401Unauthorized);
                    }
                    if (result == null)
                    {
                        IMapper mapper = MapperConfigurationFactory.CreateMapper();
                        mapper.Map <Client, IClient>(client, innerClient);
                        IClientSaver saver = scope.Resolve <IClientSaver>();
                        await saver.Update(settings, innerClient, client.Secret);

                        result = Ok(mapper.Map <Client>(innerClient));
                    }
                }
            }
            catch (Exception ex)
            {
                using (ILifetimeScope scope = _container.BeginLifetimeScope())
                {
                    await LogException(ex, scope.Resolve <IExceptionService>(), scope.Resolve <SettingsFactory>(), _settings.Value);
                }
                result = StatusCode(StatusCodes.Status500InternalServerError);
            }
            return(result);
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> Update(Guid id, [FromBody] Account account)
        {
            IActionResult result = null;

            try
            {
                if (result == null && account == null)
                {
                    result = BadRequest("Missing account data");
                }
                if (result == null && string.IsNullOrEmpty(account.Name))
                {
                    result = BadRequest("Missing account name");
                }
                if (result == null && Guid.Empty.Equals(id))
                {
                    result = BadRequest("Invalid account id");
                }
                if (result == null && !UserCanAccessAccount(id))
                {
                    result = StatusCode(StatusCodes.Status401Unauthorized);
                }
                if (result == null)
                {
                    using (ILifetimeScope scope = _container.BeginLifetimeScope())
                    {
                        SettingsFactory settingsFactory = scope.Resolve <SettingsFactory>();
                        CoreSettings    settings        = settingsFactory.CreateAccount(_settings.Value);
                        IAccountFactory accountFactory  = scope.Resolve <IAccountFactory>();
                        IAccount        innerAccount    = await accountFactory.Get(settings, id);

                        if (innerAccount == null)
                        {
                            result = NotFound();
                        }
                        else
                        {
                            IMapper mapper = MapperConfigurationFactory.CreateMapper();
                            mapper.Map <Account, IAccount>(account, innerAccount);
                            IAccountSaver saver = scope.Resolve <IAccountSaver>();
                            await saver.Update(settings, innerAccount);

                            result = Ok(
                                mapper.Map <Account>(innerAccount)
                                );
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (ILifetimeScope scope = _container.BeginLifetimeScope())
                {
                    await LogException(ex, scope.Resolve <IExceptionService>(), scope.Resolve <SettingsFactory>(), _settings.Value);
                }
                result = StatusCode(StatusCodes.Status500InternalServerError);
            }
            return(result);
        }
        //Returns the view for the Add City functionality
        public ActionResult AddMaintenanceGroup()
        {
            var customerModel = new MaintenangeGroupCreateModel {
                ConnectionStrings = SettingsFactory.GetMaintenanceGroupConnectionStringNames()
            };

            return(View(customerModel));
        }
Ejemplo n.º 27
0
        public DslStep(string type, string direction, object settings)
        {
            var settingsFactory = new SettingsFactory();

            Type = type;
            SetDirection(direction);
            Settings = settingsFactory.CopyJObject(type, (JObject)settings);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        siteSettings = SettingsFactory <SiteSettings> .Get();

        MetaDescription = siteSettings.SearchMetaDescription;
        MetaKeywords    = siteSettings.SearchMetaKeywords;
        SiteName        = siteSettings.SiteName;
    }
Ejemplo n.º 29
0
        public Formatter()
        {
            SettingsFactory factory = new SettingsFactory();

            this.settings          = factory.GetSettings();
            this.minPageForRegList = settings.MinPageForRegList;
            this.sheet             = ((Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet);
        }
Ejemplo n.º 30
0
 public EditableCollection(object forInstance, PropertyInfo propertyInfo, SettingsFactory factory, ChangeTrackingManager changeTrackingManager) : base(
         forInstance, propertyInfo, factory, changeTrackingManager)
 {
     Value             = Value;
     AddNewItemCommand = new DelegateCommand(AddNewItem);
     RemoveItemCommand = new DelegateCommand(RemoveItem);
     PrepareItemToAdd();
 }