public void TestJsonStorageLoadWrongKey()
        {
            const string key     = "tesd";
            JsonStorage  storage = new JsonStorage();

            storage.RestoreObject <string>(key);
        }
예제 #2
0
 private TvShowRepo()
 {
     _tmdbClient = new TMDbClient(Settings.TMDB_API_KEY);
     _tmdbClient.GetConfig();
     _strikeClient = new Strike();
     _jsonStorage = new JsonStorage();
 }
예제 #3
0
        public ActionResult Build(string id, bool redeploy = false, bool reset = false, string key = null)
        {
            string configPath = GetConfigPath(id);


            var model = JsonStorage.ReadFile <BuildConfig>(configPath);


            if (!string.IsNullOrWhiteSpace(key))
            {
                if (model.TriggerKey != key)
                {
                    throw new UnauthorizedAccessException();
                }
            }

            SaveConfig(id, configPath, model);

            string buildPath   = model.BuildFolder;
            string commandLine = "id=" + id + " config=\"" + configPath + "\" build=\"" + buildPath + "\"";

            if (redeploy)
            {
                commandLine += " redeploy=true";
            }


            return(new BuildActionResult(model, commandLine, reset, SettingsPath));
        }
예제 #4
0
        public WebServer()
        {
            string sessionSecret;

            if (JsonStorage.Exists("session_secret"))
            {
                Dictionary <string, object> data = JsonStorage.Load <Dictionary <string, object> >("session_secret");
                if (DateTime.FromBinary((long)data["exp"]) < DateTime.UtcNow)
                {
                    sessionSecret = GenerateNewSecret();
                }
                else
                {
                    sessionSecret = (string)data["val"];
                }
            }
            else
            {
                sessionSecret = GenerateNewSecret();
            }

            AccountManager = new AccountManager();
            Sessions       = new SessionManager(sessionSecret);
            Socket         = new WebSocketServer(25319);
            Events         = new EventHandler();
            Events.Add <WebServer>();
            Events.Add <SessionManager>();
            Events.Add <AccountManager>();
            Commands = new CommandHandler();
            //Socket.AddWebSocketService<Client>("/locgcapi");
            DiscordVerification.VerificationSuccess += OnDiscordVerified;
            DiscordVerification.Start();
        }
예제 #5
0
        public async Task UsersAddedCanThenBeRemoved()
        {
            var storage = new JsonStorage(new Mock <Serilog.ILogger>().Object);
            var state   = new OptOutState(storage);
            await state.Start();

            storage.DeleteFile("optouts");
            Assert.AreEqual(0, state.ChannelList.Count());

            await state.AddUserToOptOutOfChannel(new Models.Person()
            {
                UserId = "1", UserName = "******"
            }, "testroom");

            await state.AddUserToOptOutOfChannel(new Models.Person()
            {
                UserId = "2", UserName = "******"
            }, "testroom");

            var count = state.ChannelList["testroom"].UsersThatHaveOptedOut.Count();

            Assert.AreEqual(2, count);
            await state.RemoveUserFromOptOutOfChannel(new Models.Person()
            {
                UserId = "2", UserName = "******"
            }, "testroom");

            count = state.ChannelList["testroom"].UsersThatHaveOptedOut.Count();
            Assert.AreEqual(1, count);
        }
예제 #6
0
        public BuildSourceMap Get(string sourceKey)
        {
            if (IISStore == null)
            {
                IISStore = System.Web.Configuration.WebConfigurationManager.AppSettings["IISCI.Store"];
            }


            lock (Instance) {
                var existingList = IISStore + "\\source-map.json";

                var list = JsonStorage.ReadFileOrDefault <List <BuildSourceMap> >(existingList);
                List.Clear();
                List.AddRange(list);

                var map = List.FirstOrDefault(x => x.SourceKey == sourceKey);
                if (map == null)
                {
                    map = new BuildSourceMap {
                        Id        = "Source-" + (List.Count + 1),
                        SourceKey = sourceKey
                    };
                    List.Add(map);
                    JsonStorage.WriteFile(List, existingList);
                }
                return(map);
            }
        }
예제 #7
0
        public void Init()
        {
            ResourceStorage.DecompressMidiBundle();

            jsonStorage = new JsonStorage();
            jsonStorage.Load();

            uiState          = jsonStorage.Get(JsonStorageKeys.V1.UI_STATE, Storage.Protos.Json.V1.UiStateProto.CreateDefault());
            midiSynthConfigs = jsonStorage.Get(JsonStorageKeys.V1.MIDI_SYNTH_CONFIGS, Storage.Protos.Json.V1.MidiSynthConfigsProto.CreateDefault());
            gameplayConfig   = jsonStorage.Get(JsonStorageKeys.V1.GAMEPLAY_CONFIG, Storage.Protos.Json.V1.GameplayConfigProto.CreateDefault());
            appConfig        = jsonStorage.Get(JsonStorageKeys.V1.APP_CONFIG, Storage.Protos.Json.V1.AppConfigProto.CreateDefault());

            localDb = new LocalDb();
            localDb.Init();

            username = PlayerPrefs.GetString("TEMP_USERNAME", null);
            password = PlayerPrefs.GetString("TEMP_PASSWORD", null);

            netManager = new NetManager();
            netManager.Init(this);

            translationSevice = new TranslationService();
            translationSevice.Init(netManager);
            translationSevice.Load();
            translationSevice.lang = appConfig.displayLang;

            resourceStorage = new ResourceStorage();
            resourceStorage.Init(this);

            InitAudioConfig();
            ApplyAppAudioConfig();
        }
예제 #8
0
파일: TidyUp.cs 프로젝트: phaniav/shrink
        /// <summary>
        /// To avoid completely re-scanning the whole media library after a change, we could simply update the current JSON storage
        /// with the items that were cleaned up by our module. But take in mind that external changes are still being ignored by this module.
        /// So for an accurate rendition of the media library data usage, a re-scan is necessary once in a while.
        /// </summary>
        /// <remarks>
        /// The backlog of this module contains an idea to create a pipeline processor for the onSave handler of all items,
        /// so the JSON storage could be updated continuously, never requiring a re-scan after the initial media library scan!
        /// </remarks>
        /// <param name="itemIDs">A list of Sitecore item ID strings of the items to update in the JSON storage.</param>
        /// <param name="actionType">An ActionType enum object to indicate whether to delete the items in the list, or to remove the old versions from them.</param>
        private void UpdateStorageAfterCleanUp(List <string> itemIDs, ActionType actionType)
        {
            MediaItemReport mediaItemRoot          = null;
            JsonStorage     mediaItemReportStorage = null;

            // read the media item report object from the JSON storage
            var mediaItemPath = Settings.GetSetting("Shrink.MediaItemReportPath");

            if (!string.IsNullOrEmpty(mediaItemPath))
            {
                mediaItemReportStorage = new JsonStorage(mediaItemPath);
                mediaItemRoot          = mediaItemReportStorage.Deserialize <MediaItemReport>();
            }

            if (mediaItemRoot != null)
            {
                // remove any children as supplied in the list of Sitecore item IDs
                this.RemoveChildren(mediaItemRoot, itemIDs, actionType);

                // write the updated JSON file to disk
                mediaItemReportStorage.Serialize(mediaItemRoot);

                // update the corresponding media library report JSON storage file with the updated info
                var libraryReportPath = Settings.GetSetting("Shrink.MediaLibraryReportPath");
                if (!string.IsNullOrEmpty(libraryReportPath))
                {
                    var json = new JsonStorage(libraryReportPath);
                    json.Serialize(new MediaLibraryReport(mediaItemRoot));
                }
            }
        }
 public UserAccountRepositoryTests()
 {
     _iLogger = new Mock <Logger>();
     _logger  = new Mock <DiscordLogger>(_iLogger);
     _storage = new Mock <JsonStorage>();
     // _userRepo = new Mock<UserAccountRepository>(_logger, _storage);
 }
예제 #10
0
        private static string GetLibraries_Optifine()
        {
            VersionJson versionJson        = Global.LaunchConfiguation.MinecraftSetting.VersionJson;
            VersionJson versionJsonVanilla = JsonStorage.ParseVersionJson($"{Global.LaunchConfiguation.MinecraftSetting.MinecraftSource}\\versions\\{versionJson.inheritsFrom}");
            String      re = String.Empty;

            for (int i = 0; i < versionJson.libraries.Count; i++)
            {
                String[] split    = $"{versionJson.libraries[i].name}".Split(':');
                String   tempPath = $"{Global.LaunchConfiguation.MinecraftSetting.MinecraftSource}\\libraries\\{split[0].Replace(".", "\\")}\\{split[1]}\\{split[2]}";
                Console.WriteLine("==========================TEMP" + tempPath);
                foreach (String item in Directory.GetFiles(tempPath))
                {
                    re += $"{item};";
                }
            }
            Console.WriteLine(GetClientType(versionJsonVanilla));
            String vanilla = String.Empty;

            switch (GetClientType(versionJsonVanilla))
            {
            case 2:
                vanilla = GetLibraries_VanillaHigh();
                break;

            case 0:
                vanilla = GetLibraries_Vanilla();
                break;
            }
            return(vanilla + re);
        }
예제 #11
0
        public async Task RestartingStateWillContinueWhereLeftOff()
        {
            var count = _state.ChannelList.Count();

            Assert.AreEqual(0, count);

            var expected = Guid.NewGuid().ToString();
            await _state.AddUserToOptOutOfChannel(new Models.Person()
            {
                UserId = "1", UserName = expected
            }, "testroom");

            count = _state.ChannelList["testroom"].UsersThatHaveOptedOut.Count();
            Assert.AreEqual(1, count);


            var storage  = new JsonStorage(new Mock <Serilog.ILogger>().Object);
            var newState = new OptOutState(storage);

            await newState.Start();

            count = _state.ChannelList.Count();
            Assert.AreEqual(1, count);
            Assert.AreEqual(expected, _state.ChannelList["testroom"].UsersThatHaveOptedOut.Single(u => u.UserId == "1").UserName);
        }
예제 #12
0
        public static AppSettings GetSettings()
        {
            AppSettings result;

            try
            {
                throw new Exception("Use fake settings");
                string settings = FileTool.ReadFile(StorageDefs.AppSettings);
                result = JsonStorage.DeserializeWithType <AppSettings>(settings);
            }
            catch (Exception ex)
            {
                //throw;
                result = new AppSettings()
                {
                    WindowHeight = 500.0,
                    WindowWidth  = 650.0,
                    WinTop       = 200,
                    WinLeft      = 200,
                    WinState     = WindowState.Normal,
                    TreeWidth    = new GridLength(200.0),
                    Nodes        = new ObservableCollection <INode>(FakeTreeModel.GetNodes())
                };
            }
            return(result);
        }
예제 #13
0
        private static LastBuild Execute(BuildConfig config, bool redeploy = false)
        {
            try
            {
                string buildFolder = config.BuildFolder;

                var result = DownloadFilesAsync(config, buildFolder).Result;

                if (!redeploy)
                {
                    var lb = JsonStorage.ReadFileOrDefault <LastBuild>(config.BuildResult);
                    if (lb != null && lb.LastResult == result.LastVersion && string.IsNullOrWhiteSpace(lb.Error))
                    {
                        lb.Log      = $"{lb.LastResult} = {result.LastVersion} \r\n+++++++++++++++++++++ No changes to deploy +++++++++++++++++++++";
                        lb.ExitCode = 0;
                        lb.Error    = "";
                        return(lb);
                    }
                }

                if (config.UseMSBuild)
                {
                    var buildCommand = new MSBuildCommand()
                    {
                        Solution    = config.SolutionPath,
                        BuildFolder = buildFolder,
                        Parameters  = config.MSBuildParameters,
                        BuildConfig = config.MSBuildConfig
                    };

                    var lastBuild = buildCommand.Build();
                    if (!lastBuild.Success)
                    {
                        return(lastBuild);
                    }

                    string webConfig = XDTService.Instance.Process(config);

                    IISManager.Instance.DeployFiles(config, webConfig);

                    lastBuild.Log += "\r\n+++++++++++++++++++++ Deployment Successful !!! +++++++++++++++++++++";

                    lastBuild.LastResult = result.LastVersion;

                    return(lastBuild);
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            catch (Exception ex) {
                return(new LastBuild {
                    Error = ex.ToString(),
                    ExitCode = -1,
                    Time = DateTime.UtcNow
                });
            }
        }
예제 #14
0
        private BuildConfig GetBuildConfigModel(string id)
        {
            string      path   = GetConfigPath(id);
            BuildConfig config = JsonStorage.ReadFileOrDefault <BuildConfig>(path);

            SaveConfig(id, path, config);
            return(config);
        }
        public async Task Export(StorageFile storageFile)
        {
            var jsonSerializerSettings = JsonStorage.GetJsonSerializerSettings();

            jsonSerializerSettings.Formatting = Formatting.Indented;
            var json = JsonConvert.SerializeObject(ProfilesList, jsonSerializerSettings);
            await FileIO.WriteTextAsync(storageFile, json);
        }
예제 #16
0
        public async Task AddTranslation(string target, string translation)
        {
            translations[target] = translation;

            JsonStorage.SerializeObjectToFile(translations, "translations.json");

            RespondAsync($"I will now translate {target} to {translation}");
        }
예제 #17
0
        // Can be used in case you use multiple tokens (originally planned but not implemented yes)
        private static async void LoadToken(string channelID)
        {
            JsonStorage json = new JsonStorage("Data/Database/googleTokens.json");
            List <KeyValuePair <string, object> > list = await json.GetDataAsync(channelID);

            string token = (list.Count > 0) ? JsonConvert.SerializeObject(list[0].Value) : "{}";

            System.IO.File.WriteAllText("token.json/Google.Apis.Auth.OAuth2.Responses.TokenResponse-user", token);
        }
예제 #18
0
 public QuotesProvider(string dir)
 {
     _quotes = new List <QuotesConfiguration>();
     string[] files = System.IO.Directory.GetFiles(dir);
     foreach (string path in files)
     {
         _quotes.Add(JsonStorage.RestoreObject <QuotesConfiguration>(path));
     }
 }
예제 #19
0
 public void Import(ImportPipeline pipe)
 {
     if (!string.IsNullOrEmpty(pipe.Options.RuntimeFile))
     {
         var file = Path.Combine(pipe.Options.Workspace, pipe.Options.RuntimeFile);
         var args = new JsonStorage <RuntimeArgs>(file).Read().First();
         pipe.Runtime.With(args);
     }
 }
        public void TestJsonStorageStoreNullKey()
        {
            const string key         = null;
            const string dataToStore = "ABC";

            JsonStorage storage = new JsonStorage();

            storage.StoreObject(dataToStore, key);
        }
예제 #21
0
        public SavegameService()
        {
            _storage = new JsonStorage(FileName);
            Load();

            Observable.OnceApplicationQuit()
            .Subscribe(_ => Save())
            .AddTo(_disposer);
        }
        public void DataStorage_JsonStorage_StoreObject_InvalidKeyTest()
        {
            const string key           = "configurationFile";
            const string objectToStore = "some information";

            IDataStorage storage = new JsonStorage();

            Assert.Throws <System.ArgumentException>(() => storage.StoreObject(objectToStore, key));
        }
        public void DataStorage_JsonStorage_HasObject_Missing()
        {
            IDataStorage storage = new JsonStorage();

            const string input    = "misisng";
            const bool   expected = false;
            var          actual   = storage.HasObject(input);

            Assert.Equal(expected, actual);
        }
예제 #24
0
        /// <summary>
        /// Method to handle the first message from the Discord websocket
        /// </summary>
        /// <param name="helloResume">Gateway payload sent from the websocket</param>
        private async Task OnHelloMessageAsync(GatewayHello helloResume)
        {
            this._socketClient.StartHeartbeatTimer(helloResume.HeartbeatInterval);

            GatewayIdentify gatewayIdentify = new GatewayIdentify();

            _socketConfig         = JsonStorage.GetConfig();
            gatewayIdentify.Token = _socketConfig.Token;
            await this._socketClient.SendAsync(OpCodes.Identity, gatewayIdentify);
        }
        private IJsonStorage CreateStorage(bool clearFirst = true)
        {
            var storage = new JsonStorage(GetDirectory());

            if (clearFirst)
            {
                storage.DeleteAll();
            }
            return(storage);
        }
예제 #26
0
        public async Task Setup()
        {
            var storage = new JsonStorage(new Mock <Serilog.ILogger>().Object);

            _state = new OptOutState(storage);
            await _state.Start();

            storage.DeleteFile("optouts");
            await _state.Start();
        }
예제 #27
0
        private async void PermissionInit()
        {
            var storage = new JsonStorage(_folderMVC);

            storage.SetModel(new Permission());
            Random rnd = new Random();

            if (storage.QueryAsync <Permission>().Result.Count() == 0)
            {
                var users = db.Users;
                int num;

                foreach (var user in users)
                {
                    var id     = Guid.NewGuid();
                    var userId = user.Id;
                    if (users.First().Id == user.Id)
                    {
                        await storage.AddAsync(new Permission()
                        {
                            Id     = id,
                            UserId = userId,
                            Role   = (int)Models.Role.Admin
                        });

                        await storage.SaveChanges();
                    }
                    else
                    {
                        foreach (var auction in _auctions)
                        {
                            var permission = new Permission();
                            permission.Id     = id;
                            permission.UserId = user.Id;
                            num                     = rnd.Next(Enum.GetNames(typeof(Models.Role)).Length - 1);
                            permission.Role         = (int)(Models.Role)(num + 1);
                            permission.AuctionId    = auction.Name;
                            permission.CategoriesId = new List <Guid>();
                            if (permission.Role == (int)Models.Role.Moderator)
                            {
                                num = rnd.Next(db.Categories.Count);
                                for (var i = 0; i < num; i++)
                                {
                                    permission.CategoriesId.Add(db.Categories[i].Id);
                                }
                            }

                            await storage.AddAsync(permission);

                            await storage.SaveChanges();
                        }
                    }
                }
            }
        }
예제 #28
0
        private string GenerateNewSecret()
        {
            string secret = Cryptor.GenerateSecret();

            JsonStorage.Save("session_secret", new Dictionary <string, object>
            {
                { "exp", DateTime.UtcNow.AddDays(1).ToBinary() },
                { "val", secret }
            });
            return(secret);
        }
 static UsersPraises()
 {
     if (JsonStorage.FileExist(_filePath))
     {
         _usersPraises = JsonStorage.RestoreObject <List <UserPraises> >(_filePath);
     }
     else
     {
         _usersPraises = new List <UserPraises>();
         Save();
     }
 }
 static UsersArchievements()
 {
     if (JsonStorage.FileExist(_filePath))
     {
         _usersArchievements = JsonStorage.RestoreObject <List <UserArchievements> >(_filePath);
     }
     else
     {
         _usersArchievements = new List <UserArchievements>();
         Save();
     }
 }
예제 #31
0
        public static void retrieveCVK()
        {
            regions = RetrieveHtml.getHtmlHref();

            CVK cvk = new CVK(regions);

            JsonStorage ex = new JsonStorage();

            ex.upsert(cvk);

            Console.WriteLine("Update will in 3 minutes");
        }
 public void SetUp()
 {
     _storage = new JsonStorage();
 }