Exemplo n.º 1
0
        protected virtual Session CreateSession(GlobalSettings settings)
        {
            using (var session = NhibernateSessionFactory.OpenSession())
            {
                var account = GetNextAccontToProcess(session, settings.MinHoursBetweenSessionsPerAccount, DateTime.Now.AddHours(settings.LastMailedSelectionHours * -1));

                if (account == null)
                {
                    return null;
                }

                var domains = LoadDomains(session);
                var engagmentSession = CreateNewEngagementSession(session, account);
                var accountFolderNames = GetAccountFolderNames(session, account.Id);

                var driver = WebDriverExtensions.CreateWithDefaultProperties();
                var context = new Context(settings, account, driver, domains, NhibernateSessionFactory, _provider, accountFolderNames, engagmentSession, _serverStatusService);

                var result = DoCreateSession(context);

                if (result != null)
                {
                    result.SetUserNotifier(_notifier);
                }

                return result;
            }
        }
Exemplo n.º 2
0
    public void toggle()
    {
        GlobalSettings gs = new GlobalSettings();

        if (Input.GetKeyDown(KeyCode.Alpha1)){
            GameObject.Find(gs.getCamera1()).camera.depth = 1;
            GameObject.Find(gs.getCamera2()).camera.depth = 0;
            GameObject.Find(gs.getCamera3()).camera.depth = 0;
            GameObject.Find(gs.getCamera4()).camera.depth = 0;
        }

        if (Input.GetKeyDown(KeyCode.Alpha2)){
            GameObject.Find(gs.getCamera1()).camera.depth = 0;
            GameObject.Find(gs.getCamera2()).camera.depth = 1;
            GameObject.Find(gs.getCamera3()).camera.depth = 0;
            GameObject.Find(gs.getCamera4()).camera.depth = 0;
        }

        if (Input.GetKeyDown(KeyCode.Alpha3)){
            GameObject.Find(gs.getCamera1()).camera.depth = 0;
            GameObject.Find(gs.getCamera2()).camera.depth = 0;
            GameObject.Find(gs.getCamera3()).camera.depth = 1;
            GameObject.Find(gs.getCamera4()).camera.depth = 0;
        }

        if (Input.GetKeyDown(KeyCode.Alpha4)){
            GameObject.Find(gs.getCamera1()).camera.depth = 0;
            GameObject.Find(gs.getCamera2()).camera.depth = 0;
            GameObject.Find(gs.getCamera3()).camera.depth = 0;
            GameObject.Find(gs.getCamera4()).camera.depth = 1;
        }
    }
Exemplo n.º 3
0
 internal AdvancedSearchSettings(GlobalSettings settings)
 {
     this.settings = settings;
     InitializeComponent();
     InitializeSettings();
     InitializeGUI();
 }
Exemplo n.º 4
0
        public static string ResolvePackagesPath(string rootDirectory, GlobalSettings settings)
        {
            // Order
            // 1. global.json { "packages": "..." }
            // 2. EnvironmentNames.PackagesStore environment variable
            // 3. NuGet.config repositoryPath (maybe)?
            // 4. {DefaultLocalRuntimeHomeDir}\packages

            if (!string.IsNullOrEmpty(settings?.PackagesPath))
            {
                return Path.Combine(rootDirectory, settings.PackagesPath);
            }

            var runtimePackages = Environment.GetEnvironmentVariable(EnvironmentNames.PackagesStore);

            if (!string.IsNullOrEmpty(runtimePackages))
            {
                return runtimePackages;
            }

            var profileDirectory = Environment.GetEnvironmentVariable("USERPROFILE");

            if (string.IsNullOrEmpty(profileDirectory))
            {
                profileDirectory = Environment.GetEnvironmentVariable("HOME");
            }

            return Path.Combine(profileDirectory, ".nuget", "packages");
        }
Exemplo n.º 5
0
    public void toggle()
    {
        GlobalSettings gs = new GlobalSettings();

        //The following if statements run if specified keys are pressed and change the current camera depth, higher shows on top
        if (Input.GetKeyDown(KeyCode.Alpha1)){
            GameObject.Find(gs.getCamera1()).camera.depth = 1;
            GameObject.Find(gs.getCamera2()).camera.depth = 0;
            GameObject.Find(gs.getCamera3()).camera.depth = 0;
            GameObject.Find(gs.getCamera4()).camera.depth = 0;
        }

        if (Input.GetKeyDown(KeyCode.Alpha2)){
            GameObject.Find(gs.getCamera1()).camera.depth = 0;
            GameObject.Find(gs.getCamera2()).camera.depth = 1;
            GameObject.Find(gs.getCamera3()).camera.depth = 0;
            GameObject.Find(gs.getCamera4()).camera.depth = 0;
        }

        if (Input.GetKeyDown(KeyCode.Alpha3)){
            GameObject.Find(gs.getCamera1()).camera.depth = 0;
            GameObject.Find(gs.getCamera2()).camera.depth = 0;
            GameObject.Find(gs.getCamera3()).camera.depth = 1;
            GameObject.Find(gs.getCamera4()).camera.depth = 0;
        }

        if (Input.GetKeyDown(KeyCode.Alpha4)){
            GameObject.Find(gs.getCamera1()).camera.depth = 0;
            GameObject.Find(gs.getCamera2()).camera.depth = 0;
            GameObject.Find(gs.getCamera3()).camera.depth = 0;
            GameObject.Find(gs.getCamera4()).camera.depth = 1;
        }
    }
Exemplo n.º 6
0
        public GlobalSettings GetSettings(Provider? provider)
        {
            var key = string.Format("GlobalSettingsFor{0}", provider);

            var global = (GlobalSettings) MemoryCache.Default.Get(key);

            if (global != null)
                return global;

            using (var session = nhibernateSessionFactory.OpenSession())
            {
                var settings = session.Query<Setting>().Where(x => x.Provider == provider || x.Provider == null).ToList();
                ProviderSettings providerSettings = null;

                if (provider.HasValue)
                {
                    providerSettings = session.Query<ProviderSettings>().FirstOrDefault(p => p.Provider == provider);
                }

                global = new GlobalSettings(settings, providerSettings);
            }

            MemoryCache.Default.Set(key, global, DateTimeOffset.Now.AddMinutes(5));

            return global;
        }
 protected SwitchSettingsAction()
 {
     _globalSettings = PlatformObsoleteStatics.Instance.GetComponent<GlobalSettings>();
     if (_globalSettings == null)
     {
         throw new ApplicationException("Could not get GlobalSettings instance!");
     }
 }
Exemplo n.º 8
0
 // ------------------------------------------------------------------
 // Desc:
 // ------------------------------------------------------------------
 public static void LoadSettings()
 {
     if ( settings == null ) {
         GameObject settingsPrefab = Resources.Load ( "prefab/settings", typeof(GameObject) ) as GameObject;
         GameObject settingsGO = GameObject.Instantiate( settingsPrefab, Vector3.zero, Quaternion.identity ) as GameObject;
         settings = settingsGO.GetComponent<GlobalSettings>();
     }
 }
Exemplo n.º 9
0
 // Use this for initialization
 void Start()
 {
     settings = GameObject.Find("GlobalObject").GetComponent<GlobalSettings>();
     player = GameObject.Find("Player").GetComponent<CamControlScript>();
     progression = 0.0f;
     nextPosition = transform.position;
     ToNextPosition();
     SetAlpha(0.0f);
 }
Exemplo n.º 10
0
 private void Awake()
 {
     if(_instance == null) {
         _instance = this;
         DontDestroyOnLoad(this);
     }
     else {
         if (this != _instance)
             Destroy(gameObject);
     }
 }
Exemplo n.º 11
0
 void Awake()
 {
     if (instance == null)
     {
         DontDestroyOnLoad(gameObject);
         instance = this;
     }
     else if (instance != this)
     {
         Destroy(gameObject);
     }
 }
Exemplo n.º 12
0
        public PushSharpPushService(
            IDeviceRepository deviceRepository,
            ILogger<IPushService> logger,
            CurrentContext currentContext,
            IHostingEnvironment hostingEnvironment,
            GlobalSettings globalSettings)
        {
            _deviceRepository = deviceRepository;
            _logger = logger;
            _currentContext = currentContext;

            InitGcmBroker(globalSettings);
            InitApnsBroker(globalSettings, hostingEnvironment);
        }
        public EditorToSettingSynchronizerTest()
        {
            _synchronizer = new EditorToSettingSynchronizer();

            var textView = CreateTextView();
            var globalSettings = new GlobalSettings();
            _localSettings = new LocalSettings(globalSettings);
            _windowSettings = new WindowSettings(globalSettings);
            _editorOptions = textView.Options;
            _vimBuffer = new Mock<IVimBuffer>(MockBehavior.Strict);
            _vimBuffer.SetupGet(x => x.LocalSettings).Returns(_localSettings);
            _vimBuffer.SetupGet(x => x.WindowSettings).Returns(_windowSettings);
            _vimBuffer.SetupGet(x => x.TextView).Returns(textView);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Settings"/> class.
        /// </summary>
        public InstanceSettings(GlobalSettings globalSettings)
        {
            Global = globalSettings;

            Away = new AwaySettings();
            BadNickname = new BadNicknameSettings();
            Control = new ControlSettings();
            Event = new EventSettings();
            Idle = new IdleSettings();
            Message = new MessageSettings();
            Record = new RecordSettings();
            Sticky = new StickySettings();
            TeamSpeak = new TeamSpeakServerSettings();
            Vote = new VoteSettings();
        }
Exemplo n.º 15
0
        public void RunConverter()
        {
            var objectSettings = new ObjectSettings() { _pageUri = "https://www.google.com/" }.GetObjectConfig();
            var globalSettings = new GlobalSettings().GetGlobalConfig();
            using (var converter = new WkHtmlToPdfConverter(globalSettings, objectSettings))
            {
                try
                {
                    var file = converter.Convert();
                    File.WriteAllBytes("C:\\temp\\" + Guid.NewGuid() + ".pdf", file);
                }
                catch { };

            }
        }
Exemplo n.º 16
0
 public GlobalData()
 {
     if (File.Exists(path))
     {
         using (FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read))
         {
             BinaryFormatter bFormatter = new BinaryFormatter();
             settings = (GlobalSettings)bFormatter.Deserialize(fStream);
         }
     }
     else
     {
         settings = new GlobalSettings(SystemColors.ButtonFace, SystemColors.ControlText, false, false, false, "Ctrl+F");
     }
 }
        /// <summary>
        ///     Registers the framework dependencies into the inversion of control container.
        /// </summary>
        /// <param name="container">Inversion of control container.</param>
        /// <param name="compositionSettings">Composition settings.</param>
        /// <param name="globalSettings">Global settings.</param>
        public static void RegisterAbstractor(this IContainer container, Action<CompositionRootSettings> compositionSettings, Action<GlobalSettings> globalSettings = null)
        {
            Guard.ArgumentIsNotNull(container, nameof(container));
            Guard.ArgumentIsNotNull(compositionSettings, nameof(compositionSettings));

            var crs = new CompositionRootSettings();
            compositionSettings.Invoke(crs);

            container.AllowResolvingFuncFactories();
            container.RegisterSingleton(() => crs);
            container.RegisterAbstractorInstallers(crs);

            if (globalSettings == null)
                globalSettings = gs => { };

            var gsInstance = new GlobalSettings();

            globalSettings.Invoke(gsInstance);
            container.RegisterSingleton(() => gsInstance);
        }
Exemplo n.º 18
0
        public Context(GlobalSettings globalSettings, Account account, IWebDriver driver, IList<Domain> domains, ISessionFactory nhibernateSessionFactory, Provider provider, IList<string> accountFolderNames, EngagementSession engagementSession, IServerStatusService serverStatusService)
        {
            GlobalSettings = globalSettings;
            Account = account;
            Driver = driver;
            NhibernateSessionFactory = nhibernateSessionFactory;
            this.provider = provider;
            ManualReset = new ManualResetEvent(false);
            AccountFolderNames = accountFolderNames;
            InboxEngageCounts = new Dictionary<string, int>();
            JunkEngageCounts = new Dictionary<string, int>();
            EngagementSession = engagementSession;
            _serverStatusService = serverStatusService;

            foreach (var domain in domains)
            {
                domain.GenerateBernoullis();
            }
            Domains = domains;
        }
        public TemplatesLoader(Lifetime lifetime, GlobalSettings globalSettings, UserInjectedSettingsLayers userInjectedSettingsLayers,
            IThreading threading, IFileSystemTracker filetracker, FileSettingsStorageBehavior behavior)
        {
            var path = GetSettingsFile();

            var persistentId = new UserInjectedSettingsLayers.InjectedLayerPersistentIdentity(AngularJsInjectedLayerId);

            var pathAsProperty = new Property<FileSystemPath>(lifetime, "InjectedFileStoragePath", path);
            var serialization = new XmlFileSettingsStorage(lifetime, "angularjs-templates::" + path.FullPath.QuoteIfNeeded(), pathAsProperty,
                SettingsStoreSerializationToXmlDiskFile.SavingEmptyContent.DeleteFile, threading, filetracker, behavior);

            var descriptor = new UserInjectedSettingsLayers.UserInjectedLayerDescriptor(lifetime, globalSettings.ProductGlobalLayerId,
                persistentId, serialization.Storage, SettingsStorageMountPoint.MountPath.Default, () => { });
            descriptor.InitialMetadata.Set(UserFriendlySettingsLayers.DisplayName, "angularjs-templates");
            descriptor.InitialMetadata.Set(UserFriendlySettingsLayers.Origin, "AngularJS plugin");
            descriptor.InitialMetadata.Set(PreventDeletion, true);
            descriptor.InitialMetadata.Set(PreventReset, true);

            userInjectedSettingsLayers.RegisterUserInjectedLayer(lifetime, descriptor);
        }
Exemplo n.º 20
0
        public static IEnumerable<string> ResolveSearchPaths(this Project project, out GlobalSettings globalSettings)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            var searchPaths = new HashSet<string> { Directory.GetParent(project.ProjectDirectory).FullName };

            globalSettings = project.ResolveGlobalSettings();
            if (globalSettings != null)
            {
                foreach (var searchPath in globalSettings.ProjectSearchPaths)
                {
                    var path = Path.Combine(globalSettings.DirectoryPath, searchPath);
                    searchPaths.Add(Path.GetFullPath(path));
                }
            }

            return searchPaths;
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            try
            {
                var globals = new GlobalSettings();

                var parser = new GlobalParser();
                parser.AddGlobalOptions(globals);

                if (parser.Parse(args))
                {
                    if (!globals.NoLogo)
                    {
                        PrintLogo();
                    }

                    // TODO - need to handle positional parameters at the group (global) level!
                    Console.WriteLine("** Inject Snippets **");
                    globals.Dump();
                }
            }
            catch (CommandLineParserException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled exception in main:");
                Console.WriteLine(ex);
            }

            if (Debugger.IsAttached)
            {
                Console.Write("<press ENTER to continue>");
                Console.ReadLine();
            }
        }
Exemplo n.º 22
0
        public static IServiceCollection AddDistributedIdentityServices(this IServiceCollection services, GlobalSettings globalSettings)
        {
            if (string.IsNullOrWhiteSpace(globalSettings.IdentityServer?.RedisConnectionString))
            {
                services.AddDistributedMemoryCache();
            }
            else
            {
                services.AddDistributedRedisCache(options =>
                                                  options.Configuration = globalSettings.IdentityServer.RedisConnectionString);
            }

            services.AddOidcStateDataFormatterCache();
            services.AddSession();
            services.ConfigureApplicationCookie(configure => configure.CookieManager = new DistributedCacheCookieManager());
            services.ConfigureExternalCookie(configure => configure.CookieManager    = new DistributedCacheCookieManager());
            services.AddSingleton <IPostConfigureOptions <CookieAuthenticationOptions> >(
                svcs => new ConfigureOpenIdConnectDistributedOptions(
                    svcs.GetRequiredService <IHttpContextAccessor>(),
                    globalSettings,
                    svcs.GetRequiredService <IdentityServerOptions>())
                );

            return(services);
        }
Exemplo n.º 23
0
 void Start()
 {
     Instance = this;
 }
 public Set_Game_EnableTutorial(GlobalSettings settings) : base(settings)
 {
 }
 public OrganizationDuoWebTokenProvider(GlobalSettings globalSettings)
 {
     _globalSettings = globalSettings;
 }
Exemplo n.º 26
0
        public static IIdentityServerBuilder AddCustomIdentityServerServices(IServiceCollection services,
                                                                             IWebHostEnvironment env, GlobalSettings globalSettings)
        {
            services.AddTransient <IAuthorizationCodeStore, AuthorizationCodeStore>();

            var issuerUri             = new Uri(globalSettings.BaseServiceUri.InternalIdentity);
            var identityServerBuilder = services
                                        .AddIdentityServer(options =>
            {
                options.Endpoints.EnableIntrospectionEndpoint   = false;
                options.Endpoints.EnableEndSessionEndpoint      = false;
                options.Endpoints.EnableUserInfoEndpoint        = false;
                options.Endpoints.EnableCheckSessionEndpoint    = false;
                options.Endpoints.EnableTokenRevocationEndpoint = false;
                options.IssuerUri = $"{issuerUri.Scheme}://{issuerUri.Host}";
                options.Caching.ClientStoreExpiration = new TimeSpan(0, 5, 0);
            })
                                        .AddInMemoryCaching()
                                        .AddInMemoryApiResources(ApiResources.GetApiResources())
                                        .AddClientStoreCache <ClientStore>()
                                        .AddCustomTokenRequestValidator <CustomTokenRequestValidator>()
                                        .AddProfileService <ProfileService>()
                                        .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
                                        .AddPersistedGrantStore <PersistedGrantStore>()
                                        .AddClientStore <ClientStore>()
                                        .AddIdentityServerCertificate(env, globalSettings);

            services.AddTransient <ICorsPolicyService, CustomCorsPolicyService>();
            return(identityServerBuilder);
        }
Exemplo n.º 27
0
        public static void AddSqlServerRepositories(this IServiceCollection services, GlobalSettings globalSettings)
        {
            if (!string.IsNullOrWhiteSpace(globalSettings.PostgreSql?.ConnectionString))
            {
                services.AddAutoMapper(typeof(EntityFrameworkRepos.UserRepository));
                services.AddDbContext <EntityFrameworkRepos.DatabaseContext>();
                services.AddSingleton <IUserRepository, EntityFrameworkRepos.UserRepository>();
            }
            else
            {
                services.AddSingleton <IUserRepository, SqlServerRepos.UserRepository>();
                services.AddSingleton <ICipherRepository, SqlServerRepos.CipherRepository>();
                services.AddSingleton <IDeviceRepository, SqlServerRepos.DeviceRepository>();
                services.AddSingleton <IGrantRepository, SqlServerRepos.GrantRepository>();
                services.AddSingleton <IOrganizationRepository, SqlServerRepos.OrganizationRepository>();
                services.AddSingleton <IOrganizationUserRepository, SqlServerRepos.OrganizationUserRepository>();
                services.AddSingleton <ICollectionRepository, SqlServerRepos.CollectionRepository>();
                services.AddSingleton <IFolderRepository, SqlServerRepos.FolderRepository>();
                services.AddSingleton <ICollectionCipherRepository, SqlServerRepos.CollectionCipherRepository>();
                services.AddSingleton <IGroupRepository, SqlServerRepos.GroupRepository>();
                services.AddSingleton <IU2fRepository, SqlServerRepos.U2fRepository>();
                services.AddSingleton <IInstallationRepository, SqlServerRepos.InstallationRepository>();
                services.AddSingleton <IMaintenanceRepository, SqlServerRepos.MaintenanceRepository>();
                services.AddSingleton <ITransactionRepository, SqlServerRepos.TransactionRepository>();
            }

            if (globalSettings.SelfHosted)
            {
                services.AddSingleton <IEventRepository, SqlServerRepos.EventRepository>();
                services.AddSingleton <IInstallationDeviceRepository, NoopRepos.InstallationDeviceRepository>();
                services.AddSingleton <IMetaDataRepository, NoopRepos.MetaDataRepository>();
            }
            else
            {
                services.AddSingleton <IEventRepository, TableStorageRepos.EventRepository>();
                services.AddSingleton <IInstallationDeviceRepository, TableStorageRepos.InstallationDeviceRepository>();
                services.AddSingleton <IMetaDataRepository, TableStorageRepos.MetaDataRepository>();
            }
        }
Exemplo n.º 28
0
 public LogicSettings(GlobalSettings settings)
 {
     _settings = settings;
 }
Exemplo n.º 29
0
 protected override IVimSettings Create()
 {
     var global = new GlobalSettings();
     return new LocalSettings(global);
 }
Exemplo n.º 30
0
        public static IIdentityServerBuilder AddIdentityServerCertificate(
            this IIdentityServerBuilder identityServerBuilder, IWebHostEnvironment env, GlobalSettings globalSettings)
        {
            var certificate = CoreHelpers.GetIdentityServerCertificate(globalSettings);

            if (certificate != null)
            {
                identityServerBuilder.AddSigningCredential(certificate);
            }
            else if (env.IsDevelopment())
            {
                identityServerBuilder.AddDeveloperSigningCredential(false);
            }
            else
            {
                throw new Exception("No identity certificate to use.");
            }
            return(identityServerBuilder);
        }
Exemplo n.º 31
0
 public ClientSettings(GlobalSettings settings)
 {
     _settings = settings;
 }
Exemplo n.º 32
0
 void Awake()
 {
     Players.Add(AreaPosition.Top, TopPlayer);
     Players.Add(AreaPosition.Low, LowPlayer);
     Instance = this;
 }
Exemplo n.º 33
0
        private static void Run(string[] args, ThreadExecuter threadExecuter)
        {
            var factory = new SessionFactory();

            // Settings should be upgraded early, it contains the language pack etc and some services depends on settings.
            IPlayerItemDao playerItemDao = new PlayerItemRepo(threadExecuter, factory);

            UpgradeSettings(playerItemDao);

            // X
            IDatabaseItemDao databaseItemDao = new DatabaseItemRepo(threadExecuter, factory);

            GlobalSettings.InitializeLanguage(Properties.Settings.Default.LocalizationFile, databaseItemDao.GetTagDictionary());

            // Prohibited for now
            Properties.Settings.Default.InstaTransfer = false;
            Properties.Settings.Default.Save();
            threadExecuter.Execute(() => new MigrationHandler(factory).Migrate());

            IDatabaseSettingDao databaseSettingDao = new DatabaseSettingRepo(threadExecuter, factory);

            LoadUuid(databaseSettingDao);
            var azurePartitionDao = new AzurePartitionRepo(threadExecuter, factory);
            IDatabaseItemStatDao databaseItemStatDao = new DatabaseItemStatRepo(threadExecuter, factory);
            IItemTagDao          itemTagDao          = new ItemTagRepo(threadExecuter, factory);



            IBuddyItemDao         buddyItemDao         = new BuddyItemRepo(threadExecuter, factory);
            IBuddySubscriptionDao buddySubscriptionDao = new BuddySubscriptionRepo(threadExecuter, factory);
            IRecipeItemDao        recipeItemDao        = new RecipeItemRepo(threadExecuter, factory);
            IItemSkillDao         itemSkillDao         = new ItemSkillRepo(threadExecuter, factory);
            ArzParser             arzParser            = new ArzParser(databaseSettingDao);
            AugmentationItemRepo  augmentationItemRepo = new AugmentationItemRepo(threadExecuter, factory, new DatabaseItemStatDaoImpl(factory));

            Logger.Debug("Updating augment state..");
            augmentationItemRepo.UpdateState();

            // TODO: GD Path has to be an input param, as does potentially mods.
            ParsingService parsingService = new ParsingService(itemTagDao, null, databaseItemDao, databaseItemStatDao, itemSkillDao, Properties.Settings.Default.LocalizationFile);

            PrintStartupInfo(factory);


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Logger.Info("Visual styles enabled..");

            if (GlobalSettings.Language is EnglishLanguage language)
            {
                foreach (var tag in itemTagDao.GetClassItemTags())
                {
                    language.SetTagIfMissing(tag.Tag, tag.Name);
                }
            }


            bool showDevtools = args != null && args.Any(m => m.Contains("-devtools"));

            // TODO: Urgent, introduce DI and have MainWindow receive premade objects, not create them itself.
            using (CefBrowserHandler browser = new CefBrowserHandler()) {
                _mw = new MainWindow(browser,
                                     databaseItemDao,
                                     databaseItemStatDao,
                                     playerItemDao,
                                     azurePartitionDao,
                                     databaseSettingDao,
                                     buddyItemDao,
                                     buddySubscriptionDao,
                                     arzParser,
                                     recipeItemDao,
                                     itemSkillDao,
                                     itemTagDao,
                                     parsingService,
                                     showDevtools,
                                     augmentationItemRepo
                                     );

                Logger.Info("Checking for database updates..");


                // Load the GD database (or mod, if any)
                string GDPath = databaseSettingDao.GetCurrentDatabasePath();
                if (string.IsNullOrEmpty(GDPath) || !Directory.Exists(GDPath))
                {
                    GDPath = GrimDawnDetector.GetGrimLocation();
                }

                if (!string.IsNullOrEmpty(GDPath) && Directory.Exists(GDPath))
                {
                    var numFiles = Directory.GetFiles(GlobalPaths.StorageFolder).Length;
                    if (numFiles < 2000)
                    {
                        Logger.Debug($"Only found {numFiles} in storage, expected ~3200+, parsing item icons.");
                        ThreadPool.QueueUserWorkItem((m) => ArzParser.LoadIconsOnly(GDPath));
                    }
                }
                else
                {
                    Logger.Warn("Could not find the Grim Dawn install location");
                }

                playerItemDao.UpdateHardcoreSettings();

                _mw.Visible = false;
                if (DonateNagScreen.CanNag)
                {
                    Application.Run(new DonateNagScreen());
                }

                Logger.Info("Running the main application..");


                Application.Run(_mw);
            }

            Logger.Info("Application ended.");
        }
Exemplo n.º 34
0
    //List<BoxController> activeBoxes;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        if (settings == null)
        {
            settings = Resources.Load <GlobalSettings>("Global Settings");
            if (settings == null)
            {
                settings = ScriptableObject.CreateInstance <GlobalSettings>();
                Debug.LogWarning("Easy Message Box cannot load global settings. Using default settings.");
            }
        }
        if (settings.DefaultPrefab == null)
        {
            var loaded = Resources.Load <GameObject>("Default Message Box");
            if (loaded == null)
            {
                Debug.LogError("Cannot find the Default Message Box prefab.");
            }
            else
            {
                settings.DefaultPrefab = loaded;
            }
        }

        currentCanvas = gameObject.GetComponent <Canvas>();

        BoxQueue = new Queue <MessageBoxParams>();
        boxPool  = new List <List <BoxController> >();
        //activeBoxes = new List<BoxController>();

        if (Templates == null)
        {
            Templates = new List <BoxController>();
        }
        else
        {
            Templates.RemoveAll(t => t == null);
        }

        for (int i = 0; i < Templates.Count; i++)
        {
            boxPool.Add(new List <BoxController>());
            Templates[i].gameObject.SetActive(false);
            boxPool[i].Add(Templates[i]);
        }

        if (FindObjectOfType <EventSystem>() == null)
        {
            var evt = new GameObject("EventSystem");
            evt.AddComponent <EventSystem>();
            evt.AddComponent <StandaloneInputModule>();
        }
        var canvasesInTheScene = FindObjectsOfType <Canvas>();

        for (int i = 0; i < canvasesInTheScene.Length; i++)
        {
            if (canvasesInTheScene[i].sortingOrder > maxCanvasOrderInTheScene)
            {
                maxCanvasOrderInTheScene = canvasesInTheScene[i].sortingOrder;
            }
        }

        currentCanvas.sortingOrder = maxCanvasOrderInTheScene + 1;
    }
Exemplo n.º 35
0
        public ApiClient(
            GlobalSettings globalSettings,
            string id,
            int refreshTokenSlidingDays,
            int accessTokenLifetimeHours,
            string[] scopes = null)
        {
            ClientId                         = id;
            AllowedGrantTypes                = new[] { GrantType.ResourceOwnerPassword, GrantType.AuthorizationCode };
            RefreshTokenExpiration           = TokenExpiration.Sliding;
            RefreshTokenUsage                = TokenUsage.ReUse;
            SlidingRefreshTokenLifetime      = 86400 * refreshTokenSlidingDays;
            AbsoluteRefreshTokenLifetime     = 0; // forever
            UpdateAccessTokenClaimsOnRefresh = true;
            AccessTokenLifetime              = 3600 * accessTokenLifetimeHours;
            AllowOfflineAccess               = true;

            RequireConsent      = false;
            RequirePkce         = true;
            RequireClientSecret = false;
            if (id == "web")
            {
                RedirectUris           = new[] { $"{globalSettings.BaseServiceUri.Vault}/sso-connector.html" };
                PostLogoutRedirectUris = new[] { globalSettings.BaseServiceUri.Vault };
                AllowedCorsOrigins     = new[] { globalSettings.BaseServiceUri.Vault };
            }
            else if (id == "desktop")
            {
                RedirectUris           = new[] { "bitwarden://sso-callback" };
                PostLogoutRedirectUris = new[] { "bitwarden://logged-out" };
            }
            else if (id == "connector")
            {
                var connectorUris = new List <string>();
                for (var port = 8065; port <= 8070; port++)
                {
                    connectorUris.Add(string.Format("http://localhost:{0}", port));
                }
                RedirectUris           = connectorUris.Append("bwdc://sso-callback").ToList();
                PostLogoutRedirectUris = connectorUris.Append("bwdc://logged-out").ToList();
            }
            else if (id == "browser")
            {
                RedirectUris           = new[] { $"{globalSettings.BaseServiceUri.Vault}/sso-connector.html" };
                PostLogoutRedirectUris = new[] { globalSettings.BaseServiceUri.Vault };
                AllowedCorsOrigins     = new[] { globalSettings.BaseServiceUri.Vault };
            }
            else if (id == "cli")
            {
                var cliUris = new List <string>();
                for (var port = 8065; port <= 8070; port++)
                {
                    cliUris.Add(string.Format("http://localhost:{0}", port));
                }
                RedirectUris           = cliUris;
                PostLogoutRedirectUris = cliUris;
            }
            else if (id == "mobile")
            {
                RedirectUris           = new[] { "bitwarden://sso-callback" };
                PostLogoutRedirectUris = new[] { "bitwarden://logged-out" };
            }

            if (scopes == null)
            {
                scopes = new string[] { "api" };
            }
            AllowedScopes = scopes;
        }
Exemplo n.º 36
0
        public static bool Save_Global_Settings(GlobalSettings settings)
        {
            //Systen tab 
            StringCollection aFields = new StringCollection();
            StringCollection aValues = new StringCollection();
            //System
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.WriteLogAccess }));
            aFields.Add(common.system.GetName(new { settings.PasswordMinLen }));
            aFields.Add(common.system.GetName(new { settings.UseStrongPassword }));
            
            aValues.Clear();
            aValues.Add(((byte)settings.WriteLogAccess).ToString());
            aValues.Add(settings.PasswordMinLen.ToString());
            aValues.Add(settings.UseStrongPassword.ToString());
            if (!SaveConfig(aFields, aValues)) return false;

            //Data count
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.DayScanForLastPrice }));
            aFields.Add(common.system.GetName(new { settings.AlertDataCount }));
            aFields.Add(common.system.GetName(new { settings.ChartMaxLoadCount_FIRST }));
            aFields.Add(common.system.GetName(new { settings.ChartMaxLoadCount_MORE }));

            aValues.Clear();
            aValues.Add(settings.DayScanForLastPrice.ToString());
            aValues.Add(settings.AlertDataCount.ToString());
            aValues.Add(settings.ChartMaxLoadCount_FIRST.ToString());
            aValues.Add(settings.ChartMaxLoadCount_MORE.ToString());
            if (!SaveConfig(aFields, aValues)) return false;

            //Autokey
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.DataKeyPrefix }));
            aFields.Add(common.system.GetName(new { settings.DataKeySize }));
            aFields.Add(common.system.GetName(new { settings.AutoEditKeySize }));
            aFields.Add(common.system.GetName(new { settings.TimeOut_AutoKey }));
            
            aValues.Clear();
            aValues.Add(settings.DataKeyPrefix);
            aValues.Add(settings.DataKeySize.ToString());
            aValues.Add(settings.AutoEditKeySize.ToString());
            aValues.Add(settings.TimeOut_AutoKey.ToString());
            if (!SaveConfig(aFields, aValues)) return false;

            //Mail
            aFields.Clear(); 
            aFields.Add(common.system.GetName(new { settings.smtpAddress }));
            aFields.Add(common.system.GetName(new { settings.smtpPort }));
            aFields.Add(common.system.GetName(new { settings.smtpAuthAccount }));
            aFields.Add(common.system.GetName(new { settings.smtpAuthPassword }));
            aFields.Add(common.system.GetName(new { settings.smtpSSL }));

            aValues.Clear();
            aValues.Add(settings.smtpAddress);
            aValues.Add(settings.smtpPort.ToString());
            aValues.Add(settings.smtpAuthAccount);
            aValues.Add(settings.smtpAuthPassword);
            aValues.Add(settings.smtpSSL ? Boolean.TrueString : Boolean.FalseString);
            if (!SaveConfig(aFields, aValues)) return false;

            //Default
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.DefautLanguage }));
            aFields.Add(common.system.GetName(new { settings.AlertDataCount }));
            aFields.Add(common.system.GetName(new { settings.ScreeningDataCount }));

            aFields.Add(common.system.GetName(new { settings.ScreeningTimeScaleCode }));
            aFields.Add(common.system.GetName(new { settings.DefaultTimeRange }));
            aFields.Add(common.system.GetName(new { settings.DefaultTimeScaleCode }));

            aValues.Clear();
            aValues.Add(settings.DefautLanguage.ToString());
            aValues.Add(settings.AlertDataCount.ToString());
            aValues.Add(settings.ScreeningDataCount.ToString());
            aValues.Add(settings.ScreeningTimeScaleCode);
            aValues.Add(settings.DefaultTimeRange.ToString());
            aValues.Add(settings.DefaultTimeScaleCode);
            if (!SaveConfig(aFields, aValues)) return false;

            //Timming
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.TimerIntervalInSecs }));
            aFields.Add(common.system.GetName(new { settings.RefreshDataInSecs }));
            aFields.Add(common.system.GetName(new { settings.CheckAlertInSeconds }));
            aFields.Add(common.system.GetName(new { settings.AutoCheckInSeconds }));

            aValues.Clear();
            aValues.Add(settings.TimerIntervalInSecs.ToString());
            aValues.Add(settings.RefreshDataInSecs.ToString());
            aValues.Add(settings.CheckAlertInSeconds.ToString());
            aValues.Add(settings.AutoCheckInSeconds.ToString());
            if (!SaveConfig(aFields, aValues)) return false;
            return true;
        }
Exemplo n.º 37
0
        public async Task Start(IState initialState, ISession session, string subPath, bool excelConfigAllowed = false)
        {
            var manager = TinyIoCContainer.Current.Resolve <MultiAccountManager>();

            GlobalSettings globalSettings = null;

            var state             = initialState;
            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");

            globalSettings = GlobalSettings.Load(subPath);

            FileSystemWatcher configWatcher = new FileSystemWatcher();

            configWatcher.Path                = profileConfigPath;
            configWatcher.Filter              = "config.json";
            configWatcher.NotifyFilter        = NotifyFilters.LastWrite;
            configWatcher.EnableRaisingEvents = true;

            configWatcher.Changed += (sender, e) =>
            {
                if (e.ChangeType == WatcherChangeTypes.Changed)
                {
                    globalSettings        = GlobalSettings.Load(subPath);
                    session.LogicSettings = new LogicSettings(globalSettings);
                    // BUG: duplicate boolean negation will take no effect
                    configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents;
                    configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents;
                    Logger.Write(" ##### config.json ##### ", LogLevel.Info);
                }
            };

            //watch the excel config file
            if (excelConfigAllowed)
            {
                // TODO - await is legal here! USE it or use pragma to suppress compilerwarning and write a comment why it is not used
                // TODO: Attention - do not touch (add pragma) when you do not know what you are doing ;)
                // jjskuld - Ignore CS4014 warning for now.
                #pragma warning disable 4014
                Run(async() =>
                {
                    while (true)
                    {
                        try
                        {
                            FileInfo inf = new FileInfo($"{profileConfigPath}\\config.xlsm");
                            if (inf.LastWriteTime > DateTime.Now.AddSeconds(-5))
                            {
                                globalSettings        = ExcelConfigHelper.ReadExcel(globalSettings, inf.FullName);
                                session.LogicSettings = new LogicSettings(globalSettings);
                                Logger.Write(" ##### config.xlsm ##### ", LogLevel.Info);
                            }
                            await Delay(5000).ConfigureAwait(false);
                        }
                        catch (Exception)
                        {
                            // TODO Bad practice! Wanna log this?
                        }
                    }
                });
                #pragma warning restore 4014
            }

            int apiCallFailured = 0;
            do
            {
                try
                {
                    state = await state.Execute(session, session.CancellationTokenSource.Token).ConfigureAwait(false);

                    // Exit the bot if both catching and looting has reached its limits
                    if ((UseNearbyPokestopsTask._pokestopLimitReached ||
                         UseNearbyPokestopsTask._pokestopTimerReached) &&
                        session.Stats.CatchThresholdExceeds(session))
                    {
                        session.EventDispatcher.Send(new ErrorEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.ExitDueToLimitsReached)
                        });

                        session.CancellationTokenSource.Cancel();

                        // A bit rough here; works but can be improved
                        await Delay(10000).ConfigureAwait(false);

                        state = null;
                        session.CancellationTokenSource.Dispose();
                        Environment.Exit(0);
                    }
                }
                catch (APIBadRequestException)
                {
                    session.EventDispatcher.Send(new ErrorEvent()
                    {
                        Message = "Unexpected error happen, bot will re-login"
                    });

                    if (manager.AllowMultipleBot())
                    {
                        ReInitializeSession(session, globalSettings);
                    }
                    state = new LoginState();
                }
                catch (AccountNotVerifiedException)
                {
                    if (manager.AllowMultipleBot())
                    {
                        ReInitializeSession(session, globalSettings);
                        state = new LoginState();
                    }
                    else
                    {
                        Console.Read();
                        Environment.Exit(0);
                    }
                }
                catch (ActiveSwitchAccountManualException ex)
                {
                    session.EventDispatcher.Send(new WarnEvent {
                        Message = "Switch account requested by user"
                    });
                    ReInitializeSession(session, globalSettings, ex.RequestedAccount);
                    state = new LoginState();
                }
                catch (ActiveSwitchByPokemonException rsae)
                {
                    if (rsae.Snipe && rsae.EncounterData != null)
                    {
                        session.EventDispatcher.Send(new WarnEvent {
                            Message = $"Detected a good pokemon with snipe {rsae.EncounterData.PokemonId.ToString()}   IV:{rsae.EncounterData.IV}  Move:{rsae.EncounterData.Move1}/ Move:{rsae.EncounterData.Move2}   LV: Move:{rsae.EncounterData.Level}"
                        });
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent {
                            Message = "Encountered a good pokemon, switch another bot to catch him too."
                        });
                    }

                    session.ReInitSessionWithNextBot(rsae.Bot, session.Client.CurrentLatitude, session.Client.CurrentLongitude, session.Client.CurrentAltitude);
                    state = new LoginState(rsae.LastEncounterPokemonId, rsae.EncounterData);
                }
                catch (ActiveSwitchByRuleException se)
                {
                    session.EventDispatcher.Send(new WarnEvent {
                        Message = $"Switch bot account activated by : {se.MatchedRule.ToString()}  - {se.ReachedValue} "
                    });
                    if (se.MatchedRule == SwitchRules.EmptyMap)
                    {
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(90);
                        ReInitializeSession(session, globalSettings);
                    }
                    else if (se.MatchedRule == SwitchRules.PokestopSoftban)
                    {
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot();
                        ReInitializeSession(session, globalSettings);
                    }
                    else if (se.MatchedRule == SwitchRules.CatchFlee)
                    {
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(60);
                        ReInitializeSession(session, globalSettings);
                    }
                    else
                    {
                        if (se.MatchedRule == SwitchRules.CatchLimitReached ||
                            se.MatchedRule == SwitchRules.SpinPokestopReached)
                        {
                            // TODO - await is legal here! USE it or use pragma to suppress compilerwarning and write a comment why it is not used
                            // TODO: Attention - do not touch (add pragma) when you do not know what you are doing ;)
                            // jjskuld - Ignore CS4014 warning for now.
                            #pragma warning disable 4014
                            SendNotification(session, $"{se.MatchedRule} - {session.Settings.Username}", "This bot has reach limit, it will be blocked for 60 mins for safety.", true);
                            #pragma warning restore 4014
                            session.EventDispatcher.Send(new WarnEvent()
                            {
                                Message = $"You reach limited. bot will sleep for {session.LogicSettings.MultipleBotConfig.OnLimitPauseTimes} min"
                            });

                            TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(session.LogicSettings.MultipleBotConfig.OnLimitPauseTimes);

                            ReInitializeSession(session, globalSettings);
                        }
                        else
                        {
                            ReInitializeSession(session, globalSettings);
                        }
                    }
                    //return to login state
                    state = new LoginState();
                }

                catch (InvalidResponseException e)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = $"Niantic Servers unstable, throttling API Calls. {e.Message}"
                    });
                    await Delay(1000).ConfigureAwait(false);

                    if (manager.AllowMultipleBot())
                    {
                        apiCallFailured++;
                        if (apiCallFailured > 20)
                        {
                            apiCallFailured = 0;
                            TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(30);

                            ReInitializeSession(session, globalSettings);
                        }
                    }
                    state = new LoginState();
                }
                catch (SessionInvalidatedException e)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = $"Hashing Servers errors, throttling calls. {e.Message}"
                    });
                    await Delay(1000).ConfigureAwait(false);

                    if (manager.AllowMultipleBot())
                    {
                        apiCallFailured++;
                        if (apiCallFailured > 3)
                        {
                            apiCallFailured = 0;
                            TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(30);

                            ReInitializeSession(session, globalSettings);
                        }
                    }

                    // Resetting position
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = $"Resetting position before relogging in."
                    });
                    session.Client.Player.UpdatePlayerLocation(session.Client.Settings.DefaultLatitude, session.Client.Settings.DefaultLongitude, session.Client.Settings.DefaultAltitude, 0);
                    state = new LoginState();
                }
                catch (OperationCanceledException)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = "Current Operation was canceled."
                    });
                    if (manager.AllowMultipleBot())
                    {
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(30);
                        ReInitializeSession(session, globalSettings);
                    }
                    state = new LoginState();
                }
                catch (PtcLoginException ex)
                {
                    #pragma warning disable 4014
                    SendNotification(session, $"PTC Login failed!!!! {session.Settings.Username}", session.Translation.GetTranslation(TranslationString.PtcLoginFail), true);
                    #pragma warning restore 4014

                    if (manager.AllowMultipleBot())
                    {
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(60); //need remove acc
                        ReInitializeSession(session, globalSettings);
                        state = new LoginState();
                    }
                    else
                    {
                        session.EventDispatcher.Send(new ErrorEvent {
                            RequireExit = true, Message = session.Translation.GetTranslation(TranslationString.ExitNowAfterEnterKey)
                        });
                        session.EventDispatcher.Send(new ErrorEvent {
                            RequireExit = true, Message = session.Translation.GetTranslation(TranslationString.PtcLoginFail) + $" ({ex.Message})"
                        });

                        Console.ReadKey();
                        Environment.Exit(1);
                    }
                }
                catch (LoginFailedException)
                {
                    // TODO - await is legal here! USE it or use pragma to suppress compilerwarning and write a comment why it is not used
                    // TODO: Attention - do not touch (add pragma) when you do not know what you are doing ;)
                    // jjskuld - Ignore CS4014 warning for now.
                    #pragma warning disable 4014
                    SendNotification(session, $"Banned!!!! {session.Settings.Username}", session.Translation.GetTranslation(TranslationString.AccountBanned), true);
                    #pragma warning restore 4014

                    if (manager.AllowMultipleBot())
                    {
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(24 * 60); //need remove acc
                        ReInitializeSession(session, globalSettings);
                        state = new LoginState();
                    }
                    else
                    {
                        session.EventDispatcher.Send(new ErrorEvent {
                            RequireExit = true, Message = session.Translation.GetTranslation(TranslationString.ExitNowAfterEnterKey)
                        });
                        Console.ReadKey();
                        Environment.Exit(1);
                    }
                }
                catch (MinimumClientVersionException ex)
                {
                    // We need to terminate the client.
                    session.EventDispatcher.Send(new ErrorEvent
                    {
                        Message = session.Translation.GetTranslation(TranslationString.MinimumClientVersionException, ex.CurrentApiVersion.ToString(), ex.MinimumClientVersion.ToString())
                    });

                    session.EventDispatcher.Send(new ErrorEvent {
                        RequireExit = true, Message = session.Translation.GetTranslation(TranslationString.ExitNowAfterEnterKey)
                    });
                    Console.ReadKey();
                    Environment.Exit(1);
                }
                catch (TokenRefreshException ex)
                {
                    session.EventDispatcher.Send(new ErrorEvent()
                    {
                        Message = ex.Message
                    });

                    if (manager.AllowMultipleBot())
                    {
                        ReInitializeSession(session, globalSettings);
                    }
                    state = new LoginState();
                }

                catch (PtcOfflineException)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = session.Translation.GetTranslation(TranslationString.PtcOffline)
                    });
                    session.EventDispatcher.Send(new NoticeEvent {
                        Message = session.Translation.GetTranslation(TranslationString.TryingAgainIn, 15)
                    });

                    await Delay(1000).ConfigureAwait(false);

                    state = _initialState;
                }
                catch (GoogleOfflineException)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = session.Translation.GetTranslation(TranslationString.GoogleOffline)
                    });
                    session.EventDispatcher.Send(new NoticeEvent {
                        Message = session.Translation.GetTranslation(TranslationString.TryingAgainIn, 15)
                    });

                    await Delay(15000).ConfigureAwait(false);

                    state = _initialState;
                }
                catch (AccessTokenExpiredException)
                {
                    session.EventDispatcher.Send(new NoticeEvent {
                        Message = "Access Token Expired. Logging in again..."
                    });
                    state = _initialState;
                }
                catch (CaptchaException captchaException)
                {
                    var resolved = await CaptchaManager.SolveCaptcha(session, captchaException.Url).ConfigureAwait(false);

                    if (!resolved)
                    {
                        await SendNotification(session, $"Captcha required {session.Settings.Username}", session.Translation.GetTranslation(TranslationString.CaptchaShown), true).ConfigureAwait(false);

                        session.EventDispatcher.Send(new WarnEvent {
                            Message = session.Translation.GetTranslation(TranslationString.CaptchaShown)
                        });
                        Logger.Debug("Captcha not resolved");
                        if (manager.AllowMultipleBot())
                        {
                            Logger.Debug("Change account");
                            TinyIoCContainer.Current.Resolve <MultiAccountManager>().BlockCurrentBot(15);
                            ReInitializeSession(session, globalSettings);
                            state = new LoginState();
                        }
                        else
                        {
                            session.EventDispatcher.Send(new ErrorEvent {
                                Message = session.Translation.GetTranslation(TranslationString.ExitNowAfterEnterKey)
                            });
                            Console.ReadKey();
                            Environment.Exit(0);
                        }
                    }
                    else
                    {
                        //resolve captcha
                        state = new LoginState();
                    }
                }
                catch (HasherException ex)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = ex.Message
                    });
                    //  session.EventDispatcher.Send(new ErrorEvent { Message = session.Translation.GetTranslation(TranslationString.ExitNowAfterEnterKey) });
                    state = new IdleState();
                    //Console.ReadKey();
                    //System.Environment.Exit(1);
                }
                catch (Exception ex)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = "Pokemon Servers might be offline / unstable. Trying again..."
                    });
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = "Error: " + ex
                    });
                    if (state is LoginState)
                    {
                    }
                    else
                    {
                        state = _initialState;
                    }
                }
            } while (state != null);
            configWatcher.EnableRaisingEvents = false;
            configWatcher.Dispose();
        }
Exemplo n.º 38
0
        public static void AddDefaultServices(this IServiceCollection services, GlobalSettings globalSettings)
        {
            // Required for UserService
            services.AddWebAuthn(globalSettings);

            services.AddSingleton <IPaymentService, StripePaymentService>();
            services.AddSingleton <IMailService, HandlebarsMailService>();
            services.AddSingleton <ILicensingService, LicensingService>();

            if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) &&
                CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName))
            {
                services.AddSingleton <IApplicationCacheService, InMemoryServiceBusApplicationCacheService>();
            }
            else
            {
                services.AddSingleton <IApplicationCacheService, InMemoryApplicationCacheService>();
            }

            if (CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret))
            {
                services.AddSingleton <IMailDeliveryService, AmazonSesMailDeliveryService>();
            }
            else if (CoreHelpers.SettingHasValue(globalSettings.Mail?.Smtp?.Host))
            {
                services.AddSingleton <IMailDeliveryService, MailKitSmtpMailDeliveryService>();
            }
            else
            {
                services.AddSingleton <IMailDeliveryService, NoopMailDeliveryService>();
            }

            services.AddSingleton <IPushNotificationService, MultiServicePushNotificationService>();
            if (globalSettings.SelfHosted &&
                CoreHelpers.SettingHasValue(globalSettings.PushRelayBaseUri) &&
                globalSettings.Installation?.Id != null &&
                CoreHelpers.SettingHasValue(globalSettings.Installation?.Key))
            {
                services.AddSingleton <IPushRegistrationService, RelayPushRegistrationService>();
            }
            else if (!globalSettings.SelfHosted)
            {
                services.AddSingleton <IPushRegistrationService, NotificationHubPushRegistrationService>();
            }
            else
            {
                services.AddSingleton <IPushRegistrationService, NoopPushRegistrationService>();
            }

            if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString))
            {
                services.AddSingleton <IBlockIpService, AzureQueueBlockIpService>();
            }
            else if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret))
            {
                services.AddSingleton <IBlockIpService, AmazonSqsBlockIpService>();
            }
            else
            {
                services.AddSingleton <IBlockIpService, NoopBlockIpService>();
            }

            if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString))
            {
                services.AddSingleton <IEventWriteService, AzureQueueEventWriteService>();
            }
            else if (globalSettings.SelfHosted)
            {
                services.AddSingleton <IEventWriteService, RepositoryEventWriteService>();
            }
            else
            {
                services.AddSingleton <IEventWriteService, NoopEventWriteService>();
            }

            if (CoreHelpers.SettingHasValue(globalSettings.Attachment.ConnectionString))
            {
                services.AddSingleton <IAttachmentStorageService, AzureAttachmentStorageService>();
            }
            else if (CoreHelpers.SettingHasValue(globalSettings.Attachment.BaseDirectory))
            {
                services.AddSingleton <IAttachmentStorageService, LocalAttachmentStorageService>();
            }
            else
            {
                services.AddSingleton <IAttachmentStorageService, NoopAttachmentStorageService>();
            }

            if (CoreHelpers.SettingHasValue(globalSettings.Send.ConnectionString))
            {
                services.AddSingleton <ISendFileStorageService, AzureSendFileStorageService>();
            }
            else if (CoreHelpers.SettingHasValue(globalSettings.Send.BaseDirectory))
            {
                services.AddSingleton <ISendFileStorageService, LocalSendStorageService>();
            }
            else
            {
                services.AddSingleton <ISendFileStorageService, NoopSendFileStorageService>();
            }

            if (globalSettings.SelfHosted)
            {
                services.AddSingleton <IReferenceEventService, NoopReferenceEventService>();
            }
            else
            {
                services.AddSingleton <IReferenceEventService, AzureQueueReferenceEventService>();
            }
        }
Exemplo n.º 39
0
 public RandomElevationService(GlobalSettings settings, LRUCache <string, double> cache) : base(settings, cache)
 {
 }
Exemplo n.º 40
0
 public AuditoriaData()
 {
     conexion = GlobalSettings.GetBDCadenaConexion("cnxCROMSystemaSEG");
 }
Exemplo n.º 41
0
 private void Awake()
 {
     i = this;
 }
Exemplo n.º 42
0
 public PageRepository(GlobalSettings settings)
     : this(settings.Sql.ConnectionString)
 {
 }
Exemplo n.º 43
0
    static void Build()
    {
        var globalSettings = GetGlobalSettings();

        // Use this for real release builds - more compression, but much slower build
        // var mainBundle = BuildOptions.None;
        // var assetBundle = BuildAssetBundleOptions.None;
        var mainBundle  = BuildOptions.CompressWithLz4;
        var assetBundle = BuildAssetBundleOptions.ChunkBasedCompression;

        int count  = UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings;
        var scenes = new string[]
        {
            // only main scene
            UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(0),
            UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(1)
        };

        var target   = EditorUserBuildSettings.activeBuildTarget;
        var location = GetBuildDestination();

        //Back up initial graphics settings
        var graphicsSettingsPath = Path.Combine(Path.Combine(Directory.GetParent(Application.dataPath).ToString(), "ProjectSettings"), "GraphicsSettings.asset");
        var backup = File.ReadAllText(graphicsSettingsPath);

        //Change shader inclusion settings for specific target
        ChangeShaderInclusionSettings(globalSettings.shaderInclusionSettings, GlobalSettings.BundleBuildTarget(target));

        string oldText = "";

        try
        {
            if (!SkipAssetBundles())
            {
                BuildScript.BuildAssetBundles(
                    globalSettings.assetBundleSettings,
                    assetBundle,
                    Path.Combine(Directory.GetParent(location).ToString(), "AssetBundles"),
                    target
                    );
            }

            UpdateBuildInfo(out oldText);

            BuildPipeline.BuildPlayer(scenes, location, target, mainBundle);
        }
        finally
        {
            if (oldText != "")
            {
                ResetBuildInfo(oldText);
            }

            //Reset graphics settings to initial status
            File.WriteAllText(graphicsSettingsPath, backup);
        }

        var files       = new string[] { "Map.txt" };
        var source      = Application.dataPath + "/../";
        var destination = Directory.GetParent(location) + "/";

        foreach (var f in files)
        {
            string srcFilePath    = source + f;
            string destFolderPath = destination + f;
            if (File.Exists(srcFilePath) && Directory.Exists(destFolderPath))
            {
                FileUtil.CopyFileOrDirectory(srcFilePath, destFolderPath);
            }
        }
    }
Exemplo n.º 44
0
        private void Init()
        {
            Current.Reset();

            var factory = Mock.Of <IFactory>();

            Current.Factory = factory;

            var configs = new Configs();

            Mock.Get(factory).Setup(x => x.GetInstance(typeof(Configs))).Returns(configs);
            var globalSettings = new GlobalSettings();

            configs.Add(SettingsForTests.GenerateMockUmbracoSettings);
            configs.Add <IGlobalSettings>(() => globalSettings);

            var publishedModelFactory = new NoopPublishedModelFactory();

            Mock.Get(factory).Setup(x => x.GetInstance(typeof(IPublishedModelFactory))).Returns(publishedModelFactory);

            // create a content node kit
            var kit = new ContentNodeKit
            {
                ContentTypeId = 2,
                Node          = new ContentNode(1, Guid.NewGuid(), 0, "-1,1", 0, -1, DateTime.Now, 0),
                DraftData     = new ContentData
                {
                    Name        = "It Works2!",
                    Published   = false,
                    TemplateId  = 0,
                    VersionId   = 2,
                    VersionDate = DateTime.Now,
                    WriterId    = 0,
                    Properties  = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val2"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr2"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk2"
                              },
                              new PropertyData {
                                  Culture = "dk-DA", Segment = "", Value = "val-da2"
                              },
                              new PropertyData {
                                  Culture = "de-DE", Segment = "", Value = "val-de2"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        // draft data = everything, and IsDraft indicates what's edited
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr2", IsDraft = true, Date = new DateTime(2018, 01, 03, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk2", IsDraft = true, Date = new DateTime(2018, 01, 04, 01, 00, 00)
                          } },
                        { "dk-DA", new CultureVariation {
                              Name = "name-da2", IsDraft = true, Date = new DateTime(2018, 01, 05, 01, 00, 00)
                          } },
                        { "de-DE", new CultureVariation {
                              Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } }
                    }
                },
                PublishedData = new ContentData
                {
                    Name        = "It Works1!",
                    Published   = true,
                    TemplateId  = 0,
                    VersionId   = 1,
                    VersionDate = DateTime.Now,
                    WriterId    = 0,
                    Properties  = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val1"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr1"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk1"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        // published data = only what's actually published, and IsDraft has to be false
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr1", IsDraft = false, Date = new DateTime(2018, 01, 01, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } },
                        { "de-DE", new CultureVariation {
                              Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } }
                    }
                }
            };

            // create a data source for NuCache
            var dataSource = new TestDataSource(kit);

            var runtime = Mock.Of <IRuntimeState>();

            Mock.Get(runtime).Setup(x => x.Level).Returns(RuntimeLevel.Run);

            // create data types, property types and content types
            var dataType = new DataType(new VoidEditor("Editor", Mock.Of <ILogger>()))
            {
                Id = 3
            };

            var dataTypes = new[]
            {
                dataType
            };

            _propertyType = new PropertyType("Umbraco.Void.Editor", ValueStorageType.Nvarchar)
            {
                Alias = "prop", DataTypeId = 3, Variations = ContentVariation.Culture
            };
            _contentType = new ContentType(-1)
            {
                Id = 2, Alias = "alias-ct", Variations = ContentVariation.Culture
            };
            _contentType.AddPropertyType(_propertyType);

            var contentTypes = new[]
            {
                _contentType
            };

            var contentTypeService = new Mock <IContentTypeService>();

            contentTypeService.Setup(x => x.GetAll()).Returns(contentTypes);
            contentTypeService.Setup(x => x.GetAll(It.IsAny <int[]>())).Returns(contentTypes);

            var mediaTypeService = new Mock <IMediaTypeService>();

            mediaTypeService.Setup(x => x.GetAll()).Returns(Enumerable.Empty <IMediaType>());
            mediaTypeService.Setup(x => x.GetAll(It.IsAny <int[]>())).Returns(Enumerable.Empty <IMediaType>());

            var contentTypeServiceBaseFactory = new Mock <IContentTypeBaseServiceProvider>();

            contentTypeServiceBaseFactory.Setup(x => x.For(It.IsAny <IContentBase>())).Returns(contentTypeService.Object);

            var dataTypeService = Mock.Of <IDataTypeService>();

            Mock.Get(dataTypeService).Setup(x => x.GetAll()).Returns(dataTypes);

            // create a service context
            var serviceContext = ServiceContext.CreatePartial(
                dataTypeService: dataTypeService,
                memberTypeService: Mock.Of <IMemberTypeService>(),
                memberService: Mock.Of <IMemberService>(),
                contentTypeService: contentTypeService.Object,
                mediaTypeService: mediaTypeService.Object,
                localizationService: Mock.Of <ILocalizationService>(),
                domainService: Mock.Of <IDomainService>()
                );

            // create a scope provider
            var scopeProvider = Mock.Of <IScopeProvider>();

            Mock.Get(scopeProvider)
            .Setup(x => x.CreateScope(
                       It.IsAny <IsolationLevel>(),
                       It.IsAny <RepositoryCacheMode>(),
                       It.IsAny <IEventDispatcher>(),
                       It.IsAny <bool?>(),
                       It.IsAny <bool>(),
                       It.IsAny <bool>()))
            .Returns(Mock.Of <IScope>);

            // create a published content type factory
            var contentTypeFactory = new PublishedContentTypeFactory(
                Mock.Of <IPublishedModelFactory>(),
                new PropertyValueConverterCollection(Array.Empty <IPropertyValueConverter>()),
                dataTypeService);

            // create a variation accessor
            _variationAccesor = new TestVariationContextAccessor();

            // at last, create the complete NuCache snapshot service!
            var options = new PublishedSnapshotServiceOptions {
                IgnoreLocalDb = true
            };

            _snapshotService = new PublishedSnapshotService(options,
                                                            null,
                                                            runtime,
                                                            serviceContext,
                                                            contentTypeFactory,
                                                            null,
                                                            new TestPublishedSnapshotAccessor(),
                                                            _variationAccesor,
                                                            Mock.Of <IProfilingLogger>(),
                                                            scopeProvider,
                                                            Mock.Of <IDocumentRepository>(),
                                                            Mock.Of <IMediaRepository>(),
                                                            Mock.Of <IMemberRepository>(),
                                                            new TestDefaultCultureAccessor(),
                                                            dataSource,
                                                            globalSettings,
                                                            Mock.Of <IEntityXmlSerializer>(),
                                                            Mock.Of <IPublishedModelFactory>(),
                                                            new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider() }));

            // invariant is the current default
            _variationAccesor.VariationContext = new VariationContext();

            Mock.Get(factory).Setup(x => x.GetInstance(typeof(IVariationContextAccessor))).Returns(_variationAccesor);
        }
Exemplo n.º 45
0
 public CIWriterHttpSender(IApiRequestFactory apiRequestFactory)
 {
     _apiRequestFactory = apiRequestFactory;
     _globalSettings    = GlobalSettings.FromDefaultSources();
     Log.Information("CIWriterHttpSender Initialized.");
 }
Exemplo n.º 46
0
 public EventRepository(GlobalSettings globalSettings)
     : this(globalSettings.Events.ConnectionString)
 {
 }
 private float getBackfireDamage()
 {
     return(GlobalSettings.GetRetaliationDamage());
 }
        public static CIVisibilitySettings FromDefaultSources()
        {
            var source = GlobalSettings.CreateDefaultConfigurationSource();

            return(new CIVisibilitySettings(source));
        }
Exemplo n.º 49
0
        private static void UpdateCampaignSettings(InitializationEngine context)
        {
            var authService = context.Locate.Advanced.GetInstance <IAuthenticationService>();
            var manager     = context.Locate.Advanced.GetInstance <IMarketingConnectorManager>();
            var settings    = manager.GetConnectorCredentials(EPiServer.ConnectForCampaign.Core.Helpers.Constants.ConnectorId.ToString(),
                                                              EPiServer.ConnectForCampaign.Core.Helpers.Constants.DefaultConnectorInstanceId.ToString());

            if (settings == null || CampaignSettingsFactory.Current.Password == null)
            {
                // Look for config in the settings
                if (ConfigurationManager.AppSettings[ConfigUsername] != null &&
                    ConfigurationManager.AppSettings[ConfigPassword] != null &&
                    ConfigurationManager.AppSettings[ConfigClientid] != null)
                {
                    var campaignSettings = CampaignSettingsFactory.Current;
                    campaignSettings.UserName     = ConfigurationManager.AppSettings[ConfigUsername];
                    campaignSettings.Password     = ConfigurationManager.AppSettings[ConfigPassword];
                    campaignSettings.MandatorId   = ConfigurationManager.AppSettings[ConfigClientid];
                    campaignSettings.CacheTimeout = 10;

                    if (settings == null)
                    {
                        settings = new ConnectorCredentials()
                        {
                            ConnectorName       = EPiServer.ConnectForCampaign.Core.Helpers.Constants.DefaultConnectorName,
                            ConnectorId         = EPiServer.ConnectForCampaign.Core.Helpers.Constants.ConnectorId,
                            ConnectorInstanceId = EPiServer.ConnectForCampaign.Core.Helpers.Constants.DefaultConnectorInstanceId,
                            CredentialFields    = new Dictionary <string, object>()
                        };
                    }
                    settings.CredentialFields.Add(EPiServer.ConnectForCampaign.Implementation.Helpers.Constants.UsernameFieldKey, campaignSettings.UserName);
                    settings.CredentialFields.Add(EPiServer.ConnectForCampaign.Implementation.Helpers.Constants.PasswordFieldKey, campaignSettings.Password);
                    settings.CredentialFields.Add(EPiServer.ConnectForCampaign.Implementation.Helpers.Constants.MandatorIdFieldKey, campaignSettings.MandatorId);
                    settings.CredentialFields.Add(EPiServer.ConnectForCampaign.Implementation.Helpers.Constants.CacheTimeoutFieldKey, 10);

                    // Test the credentials before saving to database
                    var token = authService.GetToken(
                        settings.CredentialFields[EPiServer.ConnectForCampaign.Implementation.Helpers.Constants.MandatorIdFieldKey] as string,
                        settings.CredentialFields[EPiServer.ConnectForCampaign.Implementation.Helpers.Constants.UsernameFieldKey] as string,
                        settings.CredentialFields[EPiServer.ConnectForCampaign.Implementation.Helpers.Constants.PasswordFieldKey] as string,
                        false);

                    if (string.IsNullOrEmpty(token))
                    {
                        throw new AuthenticationException("Authentication failed");
                    }

                    manager.SaveConnectorCredentials(settings);
                }
            }

            var            store = DynamicDataStoreFactory.Instance.GetStore("Marketing_Automation_Settings");
            var            globalSettingsList = store.LoadAll <GlobalSettings>().ToList();
            GlobalSettings globalSettings     = null;

            if (globalSettingsList.Any() && globalSettingsList.Count > 1)
            {
                globalSettings = globalSettingsList.OrderBy(x => x.LastUpdated).FirstOrDefault();
            }
            else if (globalSettingsList.Any())
            {
                globalSettings = globalSettingsList.FirstOrDefault();
            }
            if (globalSettings == null)
            {
                store.Save(new GlobalSettings
                {
                    EnableFormAutoFill = true,
                    LastUpdated        = DateTime.UtcNow
                });
            }
        }
Exemplo n.º 50
0
        public static void AddSqlServerRepositories(this IServiceCollection services, GlobalSettings globalSettings)
        {
            var usePostgreSql = CoreHelpers.SettingHasValue(globalSettings.PostgreSql?.ConnectionString);
            var useEf         = usePostgreSql;

            if (useEf)
            {
                services.AddAutoMapper(typeof(EntityFrameworkRepos.UserRepository));
                services.AddDbContext <EntityFrameworkRepos.DatabaseContext>(options =>
                {
                    if (usePostgreSql)
                    {
                        options.UseNpgsql(globalSettings.PostgreSql.ConnectionString);
                    }
                });
                services.AddSingleton <IUserRepository, EntityFrameworkRepos.UserRepository>();
                //services.AddSingleton<ICipherRepository, EntityFrameworkRepos.CipherRepository>();
                //services.AddSingleton<IOrganizationRepository, EntityFrameworkRepos.OrganizationRepository>();
            }
            else
            {
                services.AddSingleton <IUserRepository, SqlServerRepos.UserRepository>();
                services.AddSingleton <ICipherRepository, SqlServerRepos.CipherRepository>();
                services.AddSingleton <IDeviceRepository, SqlServerRepos.DeviceRepository>();
                services.AddSingleton <IGrantRepository, SqlServerRepos.GrantRepository>();
                services.AddSingleton <IOrganizationRepository, SqlServerRepos.OrganizationRepository>();
                services.AddSingleton <IOrganizationUserRepository, SqlServerRepos.OrganizationUserRepository>();
                services.AddSingleton <ICollectionRepository, SqlServerRepos.CollectionRepository>();
                services.AddSingleton <IFolderRepository, SqlServerRepos.FolderRepository>();
                services.AddSingleton <ICollectionCipherRepository, SqlServerRepos.CollectionCipherRepository>();
                services.AddSingleton <IGroupRepository, SqlServerRepos.GroupRepository>();
                services.AddSingleton <IU2fRepository, SqlServerRepos.U2fRepository>();
                services.AddSingleton <IInstallationRepository, SqlServerRepos.InstallationRepository>();
                services.AddSingleton <IMaintenanceRepository, SqlServerRepos.MaintenanceRepository>();
                services.AddSingleton <ITransactionRepository, SqlServerRepos.TransactionRepository>();
                services.AddSingleton <IPolicyRepository, SqlServerRepos.PolicyRepository>();
                services.AddSingleton <ISsoConfigRepository, SqlServerRepos.SsoConfigRepository>();
                services.AddSingleton <ISsoUserRepository, SqlServerRepos.SsoUserRepository>();
                services.AddSingleton <ISendRepository, SqlServerRepos.SendRepository>();
                services.AddSingleton <ITaxRateRepository, SqlServerRepos.TaxRateRepository>();
                services.AddSingleton <IEmergencyAccessRepository, SqlServerRepos.EmergencyAccessRepository>();
            }

            if (globalSettings.SelfHosted)
            {
                if (useEf)
                {
                    // TODO
                }
                else
                {
                    services.AddSingleton <IEventRepository, SqlServerRepos.EventRepository>();
                }
                services.AddSingleton <IInstallationDeviceRepository, NoopRepos.InstallationDeviceRepository>();
                services.AddSingleton <IMetaDataRepository, NoopRepos.MetaDataRepository>();
            }
            else
            {
                services.AddSingleton <IEventRepository, TableStorageRepos.EventRepository>();
                services.AddSingleton <IInstallationDeviceRepository, TableStorageRepos.InstallationDeviceRepository>();
                services.AddSingleton <IMetaDataRepository, TableStorageRepos.MetaDataRepository>();
            }
        }
Exemplo n.º 51
0
        public static GlobalSettings Load(string path)
        {
            GlobalSettings settings;
            var profilePath = Path.Combine(Directory.GetCurrentDirectory(), path);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile = Path.Combine(profileConfigPath, "config.json");

            if (File.Exists(configFile))
            {
                //if the file exists, load the settings
                var input = File.ReadAllText(configFile);

                var jsonSettings = new JsonSerializerSettings();
                jsonSettings.Converters.Add(new StringEnumConverter {CamelCaseText = true});
                jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace;
                jsonSettings.DefaultValueHandling = DefaultValueHandling.Populate;

                settings = JsonConvert.DeserializeObject<GlobalSettings>(input, jsonSettings);
            }
            else
            {
                settings = new GlobalSettings();
            }

            if (settings.WebSocketPort == 0)
            {
                settings.WebSocketPort = 14251;
            }

            settings.ProfilePath = profilePath;
            settings.ProfileConfigPath = profileConfigPath;
            settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config");

            var firstRun = !File.Exists(configFile);

            settings.Save(configFile);

            if (firstRun) return null;

            settings.Auth.Load(Path.Combine(profileConfigPath, "auth.json"));

            return settings;
        }
Exemplo n.º 52
0
 public BaseConnector(GlobalSettings globalSettings, Account account)
 {
     this.globalSettings = globalSettings;
     this.account        = account;
 }
Exemplo n.º 53
0
        public static GlobalSettings Load(string path)
        {
            GlobalSettings settings;
            var profilePath = Path.Combine(Directory.GetCurrentDirectory(), path);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile = Path.Combine(profileConfigPath, "config.json");

            if (File.Exists(configFile))
            {
                try
                {
                    //if the file exists, load the settings
                    var input = File.ReadAllText(configFile);

                    var jsonSettings = new JsonSerializerSettings();
                    jsonSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
                    jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace;
                    jsonSettings.DefaultValueHandling = DefaultValueHandling.Populate;

                    settings = JsonConvert.DeserializeObject<GlobalSettings>(input, jsonSettings);
                }
                catch (Newtonsoft.Json.JsonReaderException exception)
                {
                    Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error);
                    return null;
                }
            }
            else
            {
                settings = new GlobalSettings();
            }

            if (settings.WebSocketPort == 0)
            {
                settings.WebSocketPort = 14251;
            }

            if (settings.PokemonToSnipe == null)
            {
                settings.PokemonToSnipe = Default.PokemonToSnipe;
            }

            if (settings.RenameTemplate == null)
            {
                settings.RenameTemplate = Default.RenameTemplate;
            }

            if(settings.SnipeLocationServer == null)
            {
                settings.SnipeLocationServer = Default.SnipeLocationServer;
            }

            settings.ProfilePath = profilePath;
            settings.ProfileConfigPath = profileConfigPath;
            settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config");

            var firstRun = !File.Exists(configFile);

            settings.Save(configFile);
            settings.Auth.Load(Path.Combine(profileConfigPath, "auth.json"));

            if (firstRun)
            {
                return null;
            }

            return settings;
        }
Exemplo n.º 54
0
 public CollectionUserRepository(GlobalSettings globalSettings)
     : this(globalSettings.SqlServer.ConnectionString)
 {
 }
Exemplo n.º 55
0
    // Use this for initialization
    void Start()
    {
        Active = this;

        Screen.lockCursor = true;
    }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);


            if (!GlobalSettings.RequestIsInUmbracoApplication(HttpContext.Current) && umbraco.presentation.UmbracoContext.Current.LiveEditingContext.Enabled)
            {
                if (ViewState[ID + "init"] == null)
                {
                    if (DataValues["macroalias"] != null)
                    {
                        //Data is available from the database, initialize the form with the data
                        string alias = DataValues["macroalias"].ToString();

                        //Set Pulldown selected value based on the macro alias
                        _macroSelectDropdown.SelectedValue = alias;

                        //Create from with values based on the alias
                        InitializeForm(alias);
                    }
                    else
                    {
                        this.Visible = false;
                    }

                    ViewState[ID + "init"] = "ok";
                }
                else
                {
                    //Render form if properties are in the viewstate
                    if (SelectedProperties.Count > 0)
                    {
                        RendeFormControls();
                    }
                }
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    //Handle Initial Request
                    if (DataValues["macroalias"] != null)
                    {
                        //Data is available from the database, initialize the form with the data
                        string alias = DataValues["macroalias"].ToString();

                        //Set Pulldown selected value based on the macro alias
                        _macroSelectDropdown.SelectedValue = alias;

                        //Create from with values based on the alias
                        InitializeForm(alias);
                    }
                    else
                    {
                        this.Visible = false;
                    }
                }
                else
                {
                    //Render form if properties are in the viewstate
                    if (SelectedProperties.Count > 0)
                    {
                        RendeFormControls();
                    }
                }
            }
            //Make sure child controls get rendered
            EnsureChildControls();
        }
 public SimpleExtensionManager(GlobalSettings globalSettings)
 {
     this.globalSettings = globalSettings;
 }
        public static IIdentityServerBuilder AddSsoIdentityServerServices(this IServiceCollection services,
                                                                          IWebHostEnvironment env, GlobalSettings globalSettings)
        {
            services.AddTransient <IDiscoveryResponseGenerator, DiscoveryResponseGenerator>();

            var issuerUri             = new Uri(globalSettings.BaseServiceUri.InternalSso);
            var identityServerBuilder = services
                                        .AddIdentityServer(options =>
            {
                options.IssuerUri = $"{issuerUri.Scheme}://{issuerUri.Host}";
                if (env.IsDevelopment())
                {
                    options.Authentication.CookieSameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode.Unspecified;
                }
                else
                {
                    options.UserInteraction.ErrorUrl         = "/Error";
                    options.UserInteraction.ErrorIdParameter = "errorId";
                }
            })
                                        .AddInMemoryCaching()
                                        .AddInMemoryClients(new List <Client>
            {
                new OidcIdentityClient(globalSettings)
            })
                                        .AddInMemoryIdentityResources(new List <IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()
            })
                                        .AddIdentityServerCertificate(env, globalSettings);

            return(identityServerBuilder);
        }
Exemplo n.º 59
0
        //From database
        public static bool Load_Global_Settings(ref GlobalSettings settings)
        {
            int num;
            StringCollection aFields = new StringCollection();
            // System
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.WriteLogAccess }));
            aFields.Add(common.system.GetName(new { settings.PasswordMinLen }));
            aFields.Add(common.system.GetName(new { settings.UseStrongPassword }));
            if (!GetConfig(ref aFields)) return false;

            if (int.TryParse(aFields[0], out num)) settings.WriteLogAccess = (AppTypes.SyslogMedia)num;
            if (int.TryParse(aFields[1], out num)) settings.PasswordMinLen = (byte)num;
            if (aFields[2].Trim() != "") settings.UseStrongPassword = (aFields[2] == Boolean.TrueString);

            // Data count
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.DayScanForLastPrice }));
            aFields.Add(common.system.GetName(new { settings.AlertDataCount }));
            aFields.Add(common.system.GetName(new { settings.ChartMaxLoadCount_FIRST }));
            aFields.Add(common.system.GetName(new { settings.ChartMaxLoadCount_MORE }));
            if (!GetConfig(ref aFields)) return false;
            
            if (aFields[0].Trim() != "" & int.TryParse(aFields[0], out num)) settings.DayScanForLastPrice = (short)num;
            if (aFields[1].Trim() != "" & int.TryParse(aFields[1], out num)) settings.AlertDataCount = (short)num;
            if (aFields[2].Trim() != "" & int.TryParse(aFields[2], out num)) settings.ChartMaxLoadCount_FIRST = (short)num;
            if (aFields[3].Trim() != "" & int.TryParse(aFields[3], out num)) settings.ChartMaxLoadCount_MORE = (short)num;


            //Auto key
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.DataKeyPrefix }));
            aFields.Add(common.system.GetName(new { settings.DataKeySize }));
            aFields.Add(common.system.GetName(new { settings.AutoEditKeySize }));
            aFields.Add(common.system.GetName(new { settings.TimeOut_AutoKey }));
            if(!GetConfig(ref aFields)) return false;
            if (aFields[0].Trim() != "") settings.DataKeyPrefix = aFields[0].Trim();
            if (int.TryParse(aFields[1], out num)) settings.DataKeySize = num;
            if (int.TryParse(aFields[2], out num)) settings.AutoEditKeySize = num;
            if (int.TryParse(aFields[3], out num)) settings.TimeOut_AutoKey = num;

            //Email
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.smtpAddress }));
            aFields.Add(common.system.GetName(new { settings.smtpPort }));
            aFields.Add(common.system.GetName(new { settings.smtpAuthAccount }));
            aFields.Add(common.system.GetName(new { settings.smtpAuthPassword }));
            aFields.Add(common.system.GetName(new { settings.smtpSSL}));
            if (!GetConfig(ref aFields)) return false;

            if (aFields[0].Trim() != "") settings.smtpAddress = aFields[0];
            if (aFields[1].Trim() != "" & int.TryParse(aFields[1], out num)) settings.smtpPort = num;
            settings.smtpAuthAccount = aFields[2].Trim();
            settings.smtpAuthPassword = aFields[3].Trim();
            settings.smtpSSL = (aFields[4].Trim() == Boolean.TrueString);

            //Default
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.DefautLanguage }));
            aFields.Add(common.system.GetName(new { settings.DefaultTimeRange }));
            aFields.Add(common.system.GetName(new { settings.DefaultTimeScaleCode }));
            aFields.Add(common.system.GetName(new { settings.ScreeningTimeScaleCode }));

            aFields.Add(common.system.GetName(new { settings.AlertDataCount}));
            aFields.Add(common.system.GetName(new { settings.ScreeningDataCount}));

            if (!GetConfig(ref aFields)) return false;

            if (aFields[0].Trim() != "") settings.DefautLanguage = AppTypes.Code2Language(aFields[0].Trim());
            if (aFields[1].Trim() != "") settings.DefaultTimeRange = AppTypes.TimeRangeFromCode(aFields[1]);
            if (aFields[2].Trim() != "") settings.DefaultTimeScaleCode = aFields[2];
            if (aFields[3].Trim() != "") settings.ScreeningTimeScaleCode = aFields[3];

            if (aFields[4].Trim() != "" & int.TryParse(aFields[4], out num)) settings.AlertDataCount = (short)num;
            if (aFields[5].Trim() != "" & int.TryParse(aFields[5], out num)) settings.ScreeningDataCount = (short)num;

            //Timming 
            aFields.Clear();
            aFields.Add(common.system.GetName(new { settings.TimerIntervalInSecs }));
            aFields.Add(common.system.GetName(new { settings.RefreshDataInSecs }));
            aFields.Add(common.system.GetName(new { settings.CheckAlertInSeconds }));
            aFields.Add(common.system.GetName(new { settings.AutoCheckInSeconds }));
            if (!GetConfig(ref aFields)) return false;

            if (aFields[0].Trim() != "" & int.TryParse(aFields[0], out num)) settings.TimerIntervalInSecs = (short)num;
            if (aFields[1].Trim() != "" & int.TryParse(aFields[1], out num)) settings.RefreshDataInSecs = (short)num;
            if (aFields[2].Trim() != "" & int.TryParse(aFields[2], out num)) settings.CheckAlertInSeconds = (short)num;
            if (aFields[3].Trim() != "" & int.TryParse(aFields[3], out num)) settings.AutoCheckInSeconds = (short)num;
            return true;
        }
Exemplo n.º 60
0
 public CipherRepository(GlobalSettings globalSettings)
     : this(globalSettings.SqlServer.ConnectionString, globalSettings.SqlServer.ReadOnlyConnectionString)
 {
 }