private void Timer_Elapsed(object sender, ElapsedEventArgs e) { System.Diagnostics.Debug.WriteLine("Monitoring..."); foreach (ExtensionFeature <IPostMonitorExtension> postMonitor in PostMonitors) { IEnumerable <ShareJobResult> applicableResults = dbContext .ShareJobResults.ToList().Where(sjr => ShareJobAppliesToPostMonitor(sjr, postMonitor.Extension)) .OrderByDescending(sjr => sjr.Time).ToList(); KeyValueStorage kvs = postMonitor.KeyValueStorage; if (kvs != null) { string shareSettingsWith = postMonitor.Extension.ShareSettingsWith; if (shareSettingsWith != null) { var sharer = SettingsManager.SharerExtensionManager.Features .FirstOrDefault(f => f.Extension.Name == shareSettingsWith); kvs = sharer.KeyValueStorage; } } postMonitor.Extension.Monitor(applicableResults, kvs); } }
/// <summary> /// Determines if the given <c>World</c> is completed. /// </summary> /// <returns>If the given <c>World</c> is completed returns <c>true</c>; /// otherwise <c>false</c>.</returns> /// <param name="world"><c>World</c> to determine if completed.</param> protected virtual bool _isCompleted(World world) { string key = keyWorldCompleted(world.ID); string val = KeyValueStorage.GetValue(key); return(!string.IsNullOrEmpty(val)); }
protected void BeginListenForJobsFromSharerWindow(NewsSharerWindow nsw, KeyValueStorage kvs) { nsw.JobsCreated += delegate(object window, JobsCreatedEventArgs e) { AddJobs(e.Jobs.Cast <T>(), kvs); }; }
/** * Retrieves the balance of the given virtual item. * * @param item the required virtual item * @return the balance of the required virtual item */ public int getBalance(VirtualItem item) { SoomlaUtils.LogDebug(mTag, "fetching balance for virtual item with itemId: " + item.getItemId()); String itemId = item.getItemId(); String key = keyBalance(itemId); String val = KeyValueStorage.GetValue(key); int balance = 0; if (val != null) { try { balance = int.Parse(val); } catch (Exception e) { SoomlaUtils.LogError(mTag, "Error casting string to int value: " + val + " " + e.Message); return(0); } } SoomlaUtils.LogDebug(mTag, "the balance for " + item.getItemId() + " is " + balance); return(balance); }
public SettingsGroup(string name, IEnumerable <ISettingsGroup> children) { this.Name = name; this.SettingsPageFactory = null; this.KeyValueStorage = null; this.Children = children; }
/** * Initializes <code>StoreInfo</code> from the database. This action should be performed only * once during the lifetime of a session of the game. <code>SoomlaStore</code> automatically * initializes <code>StoreInfo</code>. Don't do it if you don't know what you're doing. * * @return success */ public static bool initializeFromDB() { checkMetadataVersion(); String key = keyMetaStoreInfo(); String val = KeyValueStorage.GetValue(key); if (val == null && String.IsNullOrEmpty(val)) { SoomlaUtils.LogDebug(TAG, "store json is not in DB yet."); return(false); } SoomlaUtils.LogDebug(TAG, "the metadata-economy json (from DB) is " + val); try { fromJObject(new JObject(val)); // everything went well... StoreInfo is initialized from the local DB. // it's ok to return now. return(true); } catch (Exception e) { SoomlaUtils.LogDebug(TAG, "Can't parse metadata json. Going to return false and make " + "StoreInfo load from static data: " + val + " " + e.Message); } return(false); }
/** * Retrieves the current upgrade for the given virtual good. * * @param good the virtual good to retrieve upgrade for * @return the current upgrade for the given virtual good */ public UpgradeVG getCurrentUpgrade(VirtualGood good) { SoomlaUtils.LogDebug(mTag, "Fetching upgrade to virtual good: " + good.getName()); String itemId = good.getItemId(); String key = keyGoodUpgrade(itemId); String upItemId = KeyValueStorage.GetValue(key); if (upItemId == null) { SoomlaUtils.LogDebug(mTag, "You tried to fetch the current upgrade of " + good.getName() + " but there's not upgrade to it."); return(null); } try { return((UpgradeVG)StoreInfo.getVirtualItem(upItemId)); } catch (VirtualItemNotFoundException e) { SoomlaUtils.LogError(mTag, "The current upgrade's itemId from the DB is not found in StoreInfo." + " " + e.Message); } catch (InvalidCastException e) { SoomlaUtils.LogError(mTag, "The current upgrade's itemId from the DB is not an UpgradeVG." + " " + e.Message); } return(null); }
public SettingsManager(KeyValueStorage globalKvs) { this.General = new SettingsGroup("General", new GeneralSettingsPageFactory(), new PrefixedKeyValueStorage(globalKvs, "General:")); SearcherExtensionManager = new ExtensionManager <INewsSearcherExtension>(globalKvs, GetNewsSearcherExtensionsFromConfig(), "News Searchers"); NewsSearchers = SearcherExtensionManager.SettingsGroup; FilterExtensionManager = new ExtensionManager <INewsFilterExtension>(globalKvs, GetNewsFilterExtensionsFromConfig(), "News Filters"); NewsFilters = FilterExtensionManager.SettingsGroup; SharerExtensionManager = new ExtensionManager <INewsSharerExtension>(globalKvs, GetNewsSharerExtensionsFromConfig(), "News Sharers"); NewsSharers = SharerExtensionManager.SettingsGroup; PostMonitorExtensionManager = new ExtensionManager <IPostMonitorExtension>(globalKvs, GetPostMonitorExtensionsFromConfig(), "Post Monitors"); PostMonitors = PostMonitorExtensionManager.SettingsGroup; }
/** * Sets the balance of the given virtual item to be the given balance, and if notify is true * posts the change in the balance to the event bus. * * @param item the required virtual item * @param balance the new balance to be set * @param notify if notify is true post balance change event * @return the balance of the required virtual item */ public int setBalance(VirtualItem item, int balance, bool notify) { SoomlaUtils.LogDebug(mTag, "setting balance " + balance + " to " + item.getName() + "."); int oldBalance = getBalance(item); if (oldBalance == balance) { return(balance); } String itemId = item.getItemId(); String balanceStr = balance.ToString(); String key = keyBalance(itemId); KeyValueStorage.SetValue(key, balanceStr); if (notify) { postBalanceChangeEvent(item, balance, 0); } return(balance); }
/// <summary> /// Sets the fastest (given) duration for the given <c>Level</c>. /// </summary> /// <param name="level"><c>Level</c> to set fastest duration.</param> /// <param name="duration">Duration to set.</param> protected virtual void _setFastestDurationMillis(Level level, long duration) { string key = keyFastestDuration(level.ID); string val = duration.ToString(); KeyValueStorage.SetValue(key, val); }
/// <summary> /// Gets the fastest duration for the given <c>Level</c>. /// </summary> /// <returns>The fastest duration of the given <c>Level</c>.</returns> /// <param name="level"><c>Level</c> to get fastest duration.</param> protected virtual long _getFastestDurationMillis(Level level) { string key = keyFastestDuration(level.ID); string val = KeyValueStorage.GetValue(key); return((string.IsNullOrEmpty(val)) ? 0 : long.Parse(val)); }
/// <summary> /// Determines if the given <c>Gate</c> is open. /// </summary> /// <returns>If the given <c>Gate</c> is open returns <c>true</c>; /// otherwise, <c>false</c>.</returns> /// <param name="gate"><c>Gate</c> to check if is open.</param> protected virtual bool _isOpen(Gate gate) { string key = keyGateOpen(gate.ID); string val = KeyValueStorage.GetValue(key); return(!string.IsNullOrEmpty(val)); }
public ChunkRepository(byte[] id, KeyValueStorage<byte[]> data, KeyValueStorage<byte[][]> dataDependencies, KeyValueStorage<byte[][]> dataTopLevels, KeyValueStorage<byte[]> meta, KeyValueStorage<byte[][]> metaDependencies, KeyValueStorage<byte[][]> metaTopLevels, KeyValueStorage<byte[][]> signatures, KeyValueStorage<byte[][]> chunkSymmetricKeys, KeyValueStorage<byte[]> index, KeyValueStorage<byte[]> internalMeta, IDictionary<byte[], KeyValueStorage<byte[]>> encryptedData ) { if (id == null) throw new ArgumentNullException ("id"); this.id = id; this.linternalMeta = internalMeta; this.lindex = index; this.ldata = data; this.ldataDependencies = dataDependencies; this.ldataTopLevels = dataTopLevels; this.lmeta = meta; this.lmetaDependencies = metaDependencies; this.lmetaTopLevels = metaTopLevels; this.lsignatures = signatures; this.lchunkSymmetricKeys = chunkSymmetricKeys; this.lencryptedData = new SortedDictionary<byte[], KeyValueStorage<byte[]>> (encryptedData); }
void InitializeRedditPoster(KeyValueStorage kvs) { if (RedditPoster == null) { RedditPoster = new RedditSharpPoster(new RedditSettings(kvs)); } }
/// <summary> /// Retrieves the most recently saved value of the given <c>Score</c>. /// </summary> /// <returns>The latest <c>Score</c>.</returns> /// <param name="score">Score whose most recent value it to be retrieved.</param> protected virtual double _getLatestScore(Score score) { string key = keyLatestScore(score.ID); string val = KeyValueStorage.GetValue(key); return((string.IsNullOrEmpty(val)) ? -1 : double.Parse(val)); }
void InitializeDomainRater(KeyValueStorage kvs) { if (_domainRater == null) { _domainRater = new DomainRater(kvs, _serializer); } }
/** Unity-Editor Functions **/ /// <summary> /// Increases the number of times the given <c>Mission</c> has been /// completed if the given <c>up</c> is <c>true</c>; otherwise decreases /// the number of times completed. /// </summary> /// <param name="mission"><c>Mission</c> to set as completed.</param> /// <param name="up">If set to <c>true</c> add 1 to the number of times /// completed, otherwise subtract 1.</param> /// <param name="notify">If set to <c>true</c> trigger the relevant /// event according to the value of <c>up</c>.</param> protected virtual void _setCompleted(Mission mission, bool up, bool notify) { int total = _getTimesCompleted(mission) + (up ? 1 : -1); if (total < 0) { total = 0; } string key = keyMissionTimesCompleted(mission.ID); KeyValueStorage.SetValue(key, total.ToString()); if (notify) { if (up) { LevelUpEvents.OnMissionCompleted(mission); } else { LevelUpEvents.OnMissionCompletionRevoked(mission); } } }
void InitializeTweeter(KeyValueStorage kvs) { if (Tweeter == null) { Tweeter = new LatestCredentialsTweeter(new TweetSharpTweeter(), kvs); } }
public void Setup() { _items = new KeyValueStorage[ItemCount]; for (var i = 0; i < ItemCount; ++i) { _items[i] = new KeyValueStorage { Name = _keyPrefix + i, Index = i }; } _dictionary = _items.ToDictionary(t => t.Name); _caseInsensitiveDictionary = new KVDictionary( _dictionary.ToArray(), StringComparer.OrdinalIgnoreCase); if (ItemCount == 0) { _key = _keyPrefix + 0; } else { if (KeyDistance == 1) { _key = _keyPrefix + (ItemCount - 1); } else { _key = _keyPrefix + (ItemCount * KeyDistance); } } }
public LocalUserStorage(DatabasePath path, UserStorageConfiguration config) { if (path == null) throw new ArgumentNullException ("path"); if (config == null) throw new ArgumentNullException ("config"); this.path = path; Log.WriteLine ("Reading KeyValueStores"); userNames = config.Users.OpenStorage<string> (path); userParents = config.UserParents.OpenStorage<byte[]> (path); userCerts = config.UserCerts.OpenStorage<byte[]> (path); userKeys = config.UserKeys.OpenStorage<byte[]> (path); userSigningCerts = config.UserSigningCerts.OpenStorage<byte[]> (path); userSigningKeys = config.UserSigningKeys.OpenStorage<byte[]> (path); userRepositories = config.UserRepositores.OpenStorage<byte[][]> (path); repositories = config.Repositores.OpenStorage<byte[]> (path); meta = config.Meta.OpenStorage<byte[]> (path); //permissions = new LevelDBKeyValueStorage<byte[]> (path.CreatePath (config.PermissionsPath)); genericRepositories = new SortedDictionary<byte[], GenericUserStorageCollection> (ByteSequenceComparer.Shared); loggedInUsers = new SortedDictionary<byte[], RSAParameters> (ByteSequenceComparer.Shared); Log.WriteLine ("Done"); var e = userNames.GetEnumerator (); while (e.MoveNext ()) { var user = e.Current; Log.WriteLine ("user: {0}:{1}", user.Key, user.Value); genericRepositories.Add (user.Key, new GenericUserStorageCollection (path.CreatePath (user.Key.ToHexadecimal ()), null)); } }
public bool AllowArticle(NewsArticle newsArticle, string searchTerm, KeyValueStorage storage) { int days = storage.GetInteger(RecencyNewsFilterSettingsPage.MaxArticleAgeDaysKey, Int32.Parse(RecencyNewsFilterSettingsPage.MaxArticleAgeDefault)); return((DateTime.Now - newsArticle.TimePublished) < TimeSpan.FromDays(days)); }
/** Protected Functions **/ /** These protected virtual functions will only run when in editor **/ virtual protected void _setStoreAssets(IStoreAssets storeAssets) { #if UNITY_EDITOR string storeJSON = IStoreAssetsToJSON(storeAssets); KeyValueStorage.SetValue(keyMetaStoreInfo(), storeJSON); #endif }
/// <summary> /// Saves the orientation preference. /// Orientation values (same as ScreenOrientation enum): /// 0 Unknown /// 1 Portrait /// 2 Portrait upside-down /// 3 Landscape left /// 4 Landscape right /// 5 Auto rotation /// </summary> private void SaveOrientationPref(int orientationIndex) { if (orientationIndex == (int)ScreenOrientation.Unknown) { return; } KeyValueStorage.SetValue(ORIENTATION_PREF_KEY, orientationIndex.ToString()); }
public override NewsSharerWindow CreateSharerWindow(NewsArticle newsArticle, KeyValueStorage kvs) { InitializeTweeter(kvs); TwitterNewsSharerWindow window = new TwitterNewsSharerWindow(newsArticle, kvs, Tweeter); base.BeginListenForJobsFromSharerWindow(window, kvs); return(window); }
protected virtual IEnumerable <T> DeserializeShareJobs(string serialized, KeyValueStorage kvs) { if (serialized != null) { XmlSerializer reader = new XmlSerializer(typeof(List <T>)); return((List <T>)reader.Deserialize(new StringReader(serialized))); } return(new List <T>()); }
static void save() { string lu_json = toJSONObject().print(); SoomlaUtils.LogDebug(TAG, "saving SoomlaLevelUp to DB. json is: " + lu_json); string key = DB_KEY_PREFIX + "model"; KeyValueStorage.SetValue(key, lu_json); }
/** Unity-Editor Functions **/ /// <summary> /// Sets the given <c>Score</c> to the given value. /// </summary> /// <param name="score"><c>Score</c> to set.</param> /// <param name="latest">The value to set for the <c>Score</c>.</param> protected virtual void _setLatestScore(Score score, double latest) { string key = keyLatestScore(score.ID); string val = latest.ToString(); KeyValueStorage.SetValue(key, val); LevelUpEvents.OnLatestScoreChanged(score); }
/// <summary> /// Sets the given record for the given <c>Score</c>. /// </summary> /// <param name="score"><c>Score</c> whose record is to change.</param> /// <param name="record">The new record.</param> protected virtual void _setRecordScore(Score score, double record) { string key = keyRecordScore(score.ID); string val = record.ToString(); KeyValueStorage.SetValue(key, val); LevelUpEvents.OnScoreRecordChanged(score); }
/** * Saves the store's metadata in the database as JSON. */ public static void save() { String store_json = toJSONObject().ToString(); SoomlaUtils.LogDebug(TAG, "saving StoreInfo to DB. json is: " + store_json); String key = keyMetaStoreInfo(); KeyValueStorage.SetValue(key, store_json); }
public IEnumerable <IShareJob> GetUnfinishedJobs(KeyValueStorage kvs) { string storedXml = kvs.GetString(UnfinishedJobsKey); List <T> rawJobs = DeserializeShareJobs(storedXml, kvs).ToList(); UnfinishedJobs = new List <T>(); AddJobs(rawJobs, kvs, false); return(rawJobs.Cast <IShareJob>()); }
public virtual void Restore() { // restore from SettingsMappings foreach (SettingsMapping mapping in SettingsMappings) { string savedVal = KeyValueStorage.GetString(mapping.StorageKey, mapping.DefaultValue); mapping.Deserialize(savedVal); Console.WriteLine($"{mapping.StorageKey} = {savedVal} (default {mapping.DefaultValue})"); } }
public BD2ServiceAgent(KeyValueStorage <byte[]> keyValueStorage, ServiceAgentMode serviceAgentMode, ObjectBusSession objectBusSession, Action flush) : base(serviceAgentMode, objectBusSession, flush, false) { if (keyValueStorage == null) { throw new ArgumentNullException("keyValueStorage"); } this.keyValueStorage = keyValueStorage; objectBusSession.RegisterType(typeof(GetAllRequestMessage), GetAllRequestMessageReceived); }
public GenericUserStorageCollection(DatabasePath path, RSAParameters? rsa) { if (path == null) throw new ArgumentNullException ("path"); this.path = path; stores = new SortedDictionary<string, KeyValueStorage<byte[]>> (); eSymmetricKeys = new SqliteKeyValueStorage (path, "SymmetricKeys"); eMeta = new SqliteKeyValueStorage (path, "Meta"); eRepositoryConfigurations = new SqliteKeyValueStorage (path, "RepositoryConfigurations"); if (rsa.HasValue) SetRSAParameters (rsa.Value); }
public DataContext(Frontend frontend, byte[] id, DatabasePath path) : base(frontend) { Log.WriteLine ("DataContext-{0}..ctor(frontend={1}, id={2}, path={3})", id.ToHexadecimal (), frontend.ToString (), id.ToHexadecimal (), path); this.id = id; this.path = path; KeyValueStorageConfiguration kvscPrecomputedQueries = new KeyValueStorageConfiguration ("PrecomputedQueries", "Sqlite"); KeyValueStorageConfiguration kvscMeta = new KeyValueStorageConfiguration ("Meta", "Sqlite"); KeyValueStorageConfiguration kvscTemporary = new KeyValueStorageConfiguration ("Temporary", "Sqlite"); precomputedQueries = kvscPrecomputedQueries.OpenStorage<byte[]> (path); meta = kvscMeta.OpenStorage<byte[]> (path); temporary = kvscTemporary.OpenStorage<byte[]> (path); try { byte[] cid = meta.Get ("ID".SHA256 ()); if (cid == null) { meta.Put ("ID".SHA256 (), id); meta.Put ("Solid".SHA256 (), new byte[] { 0 }); } else { if (ByteSequenceComparer.Shared.Compare (cid, id) != 0) throw new InvalidDataException ("Wrong ID");//should i even do this? } } catch { meta.Put ("ID".SHA256 (), id); meta.Put ("Solid".SHA256 (), new byte[] { 0 }); } foreach (var t in frontend.GetTables ()) perTableRows.Add (t, new SortedDictionary<byte[], Row> (ByteSequenceComparer.Shared)); foreach (var kvp in temporary) { byte[] objectID = kvp.Key; //BaseDataObject bdo = new BaseDataObject (this.Frontend, objectID); System.IO.MemoryStream ms = new MemoryStream (kvp.Value, 16, kvp.Value.Length - 16); byte[] GuidBytes = new byte[16]; System.Buffer.BlockCopy (kvp.Value, 0, GuidBytes, 0, 16); BaseDataObjectVersion bdov = BaseDataObjectTypeIdAttribute.GetAttribFor (new Guid (GuidBytes)).Deserialize (this.Frontend, null, ms.ToArray ()); var row = bdov as Row; if (!references.ContainsKey (bdov.ID)) { if (row != null) { perTableRows [row.Table].Add (bdov.ID, row); } objects.Add (bdov.ID, row); } foreach (var r in bdov.ReplacingIDs) { if (!references.ContainsKey (r)) { references.Add (r, new SortedSet<byte[]> (ByteSequenceComparer.Shared)); } references [r].Add (bdov.ID); } } //this.frontendInstanceBase = (FrontendInstance)frontendInstanceBase; }