public IDataTable GetTable(DbTables tables) { IDataTable table = null; switch (tables) { case DbTables.Letters: table = GetLetterTable(); break; case DbTables.Words: table = GetWordTable(); break; case DbTables.Phrases: table = GetPhraseTable(); break; case DbTables.MiniGames: table = GetMiniGameTable(); break; case DbTables.Stages: table = GetStageTable(); break; case DbTables.PlaySessions: table = GetPlaySessionTable(); break; case DbTables.LearningBlocks: table = GetLearningBlockTable(); break; case DbTables.Rewards: table = GetRewardTable(); break; case DbTables.Localizations: table = GetLocalizationTable(); break; default: throw new ArgumentOutOfRangeException("tables", tables, null); } return(table); }
public async Task UpdateFieldAsync <T>(int rowId, string columnName, DbTables tableName, T newValue) { var cnn = new SqlConnection(ConnectionString); var query = $"UPDATE {tableName} SET {columnName} = @NewValue WHERE Id = @Id"; var cmd = new SqlCommand(query, cnn); cmd.Parameters.AddWithValue("@NewValue", newValue); cmd.Parameters.AddWithValue("@Id", rowId); cmd.CommandType = CommandType.Text; try { await cnn.OpenAsync(); await cmd.ExecuteNonQueryAsync(); } catch (Exception) { return; } finally { await cmd.DisposeAsync(); await cnn.CloseAsync(); } }
public List <I> GetAllInfo <D, I>(DbTables table) where I : DataInfo <D>, new() where D : IData { // Retrieve all data List <D> data_list = dbManager.GetAllData <D>(table); return(GetAllInfo <D, I>(data_list, table)); }
public List <I> GetAllInfo <D, I>(List <D> data_list, DbTables table) where I : DataInfo <D>, new() where D : IData { var info_list = new List <I>(); // Build info instances for the given data foreach (var data in data_list) { var info = new I(); info.data = data; info_list.Add(info); } // Find available scores string query = string.Format("SELECT * FROM ScoreData WHERE TableName = '" + table.ToString() + "' ORDER BY ElementId "); List <ScoreData> scoredata_list = dbManager.FindScoreDataByQuery(query); for (int i = 0; i < info_list.Count; i++) { var info = info_list[i]; var scoredata = scoredata_list.Find(x => x.ElementId == info.data.GetId()); if (scoredata != null) { info.score = scoredata.Score; info.unlocked = true; } else { info.score = 0; // 0 until unlocked info.unlocked = false; } } return(info_list); }
public ScoreData(string elementId, DbTables table, float score, int timestamp) { this.ElementId = elementId; this.TableName = table.ToString(); this.Id = TableName + "." + ElementId; this.Score = score; this.LastAccessTimestamp = timestamp; }
private UpdateData CreateUpdateDataMessage(int objectId, string columnName, DbTables tableName) { return(new UpdateData { RowId = objectId, ColumnName = columnName, TableName = tableName.ToString() }); }
public UserController(DbTables context) { this.db = context; if (!db.usr.Any()) { db.usr.Add(new User { login = "******", pass_hash = "1hher4" }); db.SaveChanges(); } }
public void TestInsertScoreData() { int rndTableValue = RND.Range(0, 7); DbTables rndTable = DbTables.Letters; string rndId = ""; switch (rndTableValue) { case 0: rndTable = DbTables.Letters; rndId = RandomHelper.GetRandom(dbManager.GetAllLetterData()).GetId(); break; case 1: rndTable = DbTables.Words; rndId = RandomHelper.GetRandom(dbManager.GetAllWordData()).GetId(); break; case 2: rndTable = DbTables.Phrases; rndId = RandomHelper.GetRandom(dbManager.GetAllPhraseData()).GetId(); break;; case 3: rndTable = DbTables.MiniGames; rndId = RandomHelper.GetRandom(dbManager.GetAllMiniGameData()).GetId(); break; case 4: rndTable = DbTables.PlaySessions; rndId = RandomHelper.GetRandom(dbManager.GetAllPlaySessionData()).GetId(); break; case 5: rndTable = DbTables.Stages; rndId = RandomHelper.GetRandom(dbManager.GetAllStageData()).GetId(); break; case 6: rndTable = DbTables.Rewards; rndId = RandomHelper.GetRandom(dbManager.GetAllRewardData()).GetId(); break; } var lastAccessTimestamp = GenericUtilities.GetRelativeTimestampFromNow(-RND.Range(0, 5)); var score = RND.Range(0f, 1f); this.dbManager.Debug_UpdateScoreData(rndTable, rndId, score, lastAccessTimestamp); PrintOutput("Inserted (or replaced) new ScoreData: " + lastAccessTimestamp.ToString()); }
private void UpdateScoreDataWithMaximum(DbTables table, string elementId, float newScore) { string query = string.Format("SELECT * FROM ScoreData WHERE TableName = '{0}' AND ElementId = '{1}'", table.ToString(), elementId); List <ScoreData> scoreDataList = db.FindScoreDataByQuery(query); float previousMaxScore = 0; if (scoreDataList.Count > 0) { previousMaxScore = scoreDataList[0].Score; } float newMaxScore = Mathf.Max(previousMaxScore, newScore); db.UpdateScoreData(table, elementId, newMaxScore); }
private void UpdateScoreDataWithMovingAverage(DbTables table, string elementId, float newScore, int movingAverageSpan) { string query = string.Format("SELECT * FROM ScoreData WHERE TableName = '{0}' AND ElementId = '{1}'", table.ToString(), elementId); List <ScoreData> scoreDataList = db.FindScoreDataByQuery(query); float previousAverageScore = 0; if (scoreDataList.Count > 0) { previousAverageScore = scoreDataList[0].Score; } // @note: for the first movingAverageSpan values, this won't be accurate float newAverageScore = previousAverageScore - previousAverageScore / movingAverageSpan + newScore / movingAverageSpan; db.UpdateScoreData(table, elementId, newAverageScore); }
protected override void Prepare() { Schema = DefaultWhereNull(Schema, () => "dbo"); DbTable = Root !.DbTables.Where(x => x.Name == Name && x.Schema == Schema).SingleOrDefault(); if (DbTable == null) { throw new CodeGenException($"Specified Schema.Table '{Schema}.{Name}' not found in database."); } Alias = DefaultWhereNull(Alias, () => new string(StringConversion.ToSentenceCase(Name) !.Split(' ').Select(x => x.Substring(0, 1).ToLower(System.Globalization.CultureInfo.InvariantCulture).ToCharArray()[0]).ToArray())); foreach (var c in DbTable.Columns) { if ((ExcludeColumns == null || !ExcludeColumns.Contains(c.Name)) && (IncludeColumns == null || IncludeColumns.Contains(c.Name))) { DbColumns.Add(c); } } }
/// <summary> /// Creates a database server with the specified name and configuration. /// </summary> /// <param name="type">The SQL server type.</param> /// <param name="key">The registry configuration key.</param> /// <param name="id">The server ID.</param> /// <param name="logFile">The log file for this database server.</param> public DbServerSql(DbType type, RegistryKey key, Guid id, string logFile) : base(DbServerClass.Sql, key, id, logFile) { // Set the server type. this.type = type; // Create the database tables and relationships. this.tables = new DbTables(this.Key); this.relationships = new DbRelationships(this.Key, this.tables); // Set the event handlers. this.tables.TableAdded += this.OnTableAdded; this.tables.TableChanged += this.OnTableChanged; this.tables.TableRemoved += this.OnTableRemoved; this.relationships.RelationshipAdded += this.OnRelationshipAdded; this.relationships.RelationshipRemoved += this.OnRelationshipRemoved; // Load the current configuration. this.LoadInternalConfiguration(); }
public static T LoadTable <T>(DbTables table) { switch (table) { case DbTables.Библиотека_продуктовDataTable: var tblAdapter1 = new DB.MakeDocDataSetTableAdapters.Библиотека_продуктовTableAdapter(); MakeDocDataSet.Библиотека_продуктовDataTable tblOut1 = new MakeDocDataSet.Библиотека_продуктовDataTable(); tblAdapter1.Fill(tblOut1); return((T)Convert.ChangeType(tblOut1, typeof(MakeDocDataSet.Библиотека_продуктовDataTable))); break; case DbTables.Заказ_на_доставкуDataTable: var tblAdapter2 = new DB.MakeDocDataSetTableAdapters.Заказ_на_доставкуTableAdapter(); var tblOut2 = tblAdapter2.GetData(); return((T)Convert.ChangeType(tblOut2, typeof(MakeDocDataSet.Заказ_на_доставкуDataTable))); break; case DbTables.МагазинDataTable: var tblAdapter3 = new DB.MakeDocDataSetTableAdapters.МагазинTableAdapter(); var tblOut3 = tblAdapter3.GetData(); return((T)Convert.ChangeType(tblOut3, typeof(MakeDocDataSet.МагазинDataTable))); break; case DbTables.Составляющие_заказаDataTable: var tblAdapter4 = new DB.MakeDocDataSetTableAdapters.Составляющие_заказаTableAdapter(); var tblOut4 = tblAdapter4.GetData(); return((T)Convert.ChangeType(tblOut4, typeof(MakeDocDataSet.Составляющие_заказаDataTable))); break; default: return((T)Convert.ChangeType(null, typeof(T))); break; } }
public List <I> GetAllJourneyDataInfo <D, I>(DbTables table, JourneyDataType dataType) where I : DataInfo <D>, new() where D : IData { List <D> data_list = dbManager.GetAllData <D>(table); var info_list = new List <I>(); // Build info instances for the given data foreach (var data in data_list) { var info = new I(); info.data = data; info_list.Add(info); } // Find available scores string query = string.Format("SELECT * FROM " + typeof(JourneyScoreData).Name + " WHERE JourneyDataType = '" + (int)dataType + "' ORDER BY ElementId "); var scoredata_list = dbManager.Query <JourneyScoreData>(query); for (int i = 0; i < info_list.Count; i++) { var info = info_list[i]; var scoredata = scoredata_list.Find(x => x.ElementId == info.data.GetId()); if (scoredata != null) { info.score = scoredata.GetScore(); info.unlocked = true; } else { info.score = 0; // 0 until unlocked info.unlocked = false; } } return(info_list); }
/*public List<I> GetAllInfo<D,I>(DbTables table) where I : DataInfo<D>, new() where D : IData * { * // Retrieve all data * List<D> data_list = dbManager.GetAllData<D>(table); * return GetAllInfo<D,I>(data_list, table); * }*/ public List <I> GetAllMiniGameDataInfo <D, I>(DbTables table) where I : DataInfo <D>, new() where D : MiniGameData { List <D> data_list = dbManager.GetAllData <D>(table); var info_list = new List <I>(); // Build info instances for the given data foreach (var data in data_list) { var info = new I(); info.data = data; info_list.Add(info); } // Find available scores string query = string.Format("SELECT * FROM " + typeof(MiniGameScoreData).Name); var scoredata_list = dbManager.Query <MiniGameScoreData>(query); for (int i = 0; i < info_list.Count; i++) { var info = info_list[i]; var scoredata = scoredata_list.Find(x => x.MiniGameCode == info.data.Code); if (scoredata != null) { info.score = scoredata.GetScore(); info.unlocked = true; } else { info.score = 0; // 0 until unlocked info.unlocked = false; } } return(info_list); }
/// <summary> /// Creates a database server with the specified parameters. /// </summary> /// <param name="type">The SQL server type.</param> /// <param name="key">The registry configuration key.</param> /// <param name="id">The server ID.</param> /// <param name="name">The server name.</param> /// <param name="dataSource">The data source.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="logFile">The log file for this database server.</param> /// <param name="dateCreated">The date when the server was created.</param> /// <param name="dateModified">The date when the server was last modified.</param> public DbServerSql( DbType type, RegistryKey key, Guid id, string name, string dataSource, string username, SecureString password, string logFile, DateTime dateCreated, DateTime dateModified ) : base(DbServerClass.Sql, key, id, name, dataSource, username, password, logFile, dateCreated, dateModified) { // Set the server type. this.type = type; // Create the database tables and relationships. this.tables = new DbTables(this.Key); this.relationships = new DbRelationships(this.Key, this.tables); // Set the event handlers. this.tables.TableAdded += this.OnTableAdded; this.tables.TableChanged += this.OnTableChanged; this.tables.TableRemoved += this.OnTableRemoved; this.relationships.RelationshipAdded += this.OnRelationshipAdded; this.relationships.RelationshipRemoved += this.OnRelationshipRemoved; // Save the configuration. this.SaveInternalConfiguration(); }
// @note: new generic-only data getter, should be used instead of all the above ones public List <T> GetAllData <T>(DbTables table) where T : IData { return(staticDb.GetAll <T>((SerializableDataTable <T>)staticDb.GetTable(table))); }
public LogLearnData(string _Session, string _PlaySession, MiniGameCode _MiniGame, DbTables _table, string _elementId, float _score) { this.Session = _Session; this.PlaySession = _PlaySession; this.MiniGame = _MiniGame; this.TableName = _table.ToString(); this.ElementId = _elementId; this.Score = _score; this.Timestamp = GenericUtilities.GetTimestampForNow(); }
public void Debug_UpdateScoreData(DbTables table, string elementId, float score, int timestamp) { ScoreData data = new ScoreData(elementId, table, score, timestamp); dynamicDb.InsertOrReplace(data); }
public void UpdateScoreData(DbTables table, string elementId, float score) { ScoreData data = new ScoreData(elementId, table, score); dynamicDb.InsertOrReplace(data); }
private async Task UpdateDbFiledAsync <T>(int personId, string columnName, DbTables tableName, T value) { Type type; bool boolValue = false; int intValue = 0; DateTime dateValue = DateTime.Now; string stringValue = string.Empty; var channel = GetChannel(); switch (value) { case bool boolean: type = typeof(bool); boolValue = boolean; break; case int number: type = typeof(int); intValue = number; break; case DateTime date: type = typeof(DateTime); dateValue = date.ToUniversalTime(); break; case PermissionsEnum permission: type = typeof(string); stringValue = permission.ToString(); break; case PriorityEnum priority: type = typeof(string); stringValue = priority.ToString(); break; case string str: type = typeof(string); stringValue = str; break; default: return; } switch (type.Name) { case "Boolean": await _dbUpdatesApi.UpdateFieldAsync(channel, personId, columnName, tableName, boolValue); break; case "DateTime": await _dbUpdatesApi.UpdateFieldAsync(channel, personId, columnName, tableName, dateValue); break; case "Int32": await _dbUpdatesApi.UpdateFieldAsync(channel, personId, columnName, tableName, intValue); break; case "String": await _dbUpdatesApi.UpdateFieldAsync(channel, personId, columnName, tableName, stringValue); break; default: return; } await channel.ShutdownAsync(); }
internal async Task UpdateFieldAsync(GrpcChannel channel, int objectId, string columnName, DbTables tableName, DateTime value) { var client = new DbUpdates.DbUpdatesClient(channel); var input = new UpdateTimestampFieldInput { Data = CreateUpdateDataMessage(objectId, columnName, tableName), NewValue = value.ToTimestamp() }; await client.UpdateTimestampFieldAsync(input); }
// @note: interface for common use using categories public IData GetData(DbTables tables, string id) { var table = GetTable(tables); return(table.GetValue(id)); }
// Public methods. /// <summary> /// Creates a new database relationshiop from the specified XML element and list of tables. /// </summary> /// <param name="element">The XML element.</param> /// <param name="tables">The set of database tables.</param> public static DbRelationship Create(XElement element, DbTables tables) { // Verify the name of the XML element. if (element.Name != DbRelationship.xmlRelationship) throw new DbException("Cannot create a database relationship because the name of XML element is \'{0}\'".FormatWith(element.Name)); // Get the names of the tables and fields. Guid tableLeft = new Guid(element.Attribute(DbRelationship.xmlLeftTable).Value); Guid tableRight = new Guid(element.Attribute(DbRelationship.xmlRightTable).Value); string fieldLeft = element.Attribute(DbRelationship.xmlLeftField).Value; string fieldRight = element.Attribute(DbRelationship.xmlRightField).Value; // Check the tables exist. if (null == tables[tableLeft]) throw new DbException("Cannot create a database relationship: the left table \'{0}\' does not exist.".FormatWith(tableLeft)); if (null == tables[tableRight]) throw new DbException("Cannot create a database relationship: the right table \'{0}\' does not exist.".FormatWith(tableRight)); // Create a new database relationship object, which is not read-only. DbRelationship relationship = new DbRelationship(tables[tableLeft], tables[tableRight], fieldLeft, fieldRight, false); // Set the XML element. relationship.xml = element; // Return the relationship. return relationship; }
private List <T> WeightedDataSelect <T>(List <T> source_data_list, HashSet <T> currentPSData, int nToSelect, DbTables table, SelectionSeverity severity) where T : IData { // Given a (filtered) list of data, select some using weights List <ScoreData> score_data_list = dbManager.FindScoreDataByQuery("SELECT * FROM ScoreData WHERE TableName = '" + table.ToString() + "'"); string debugString = "-- Teacher Selection Weights"; List <float> weights_list = new List <float>(); foreach (var sourceData in source_data_list) { float cumulativeWeight = 0; debugString += "\n" + sourceData.GetId() + " ---"; // Get score data var score_data = score_data_list.Find(x => x.ElementId == sourceData.GetId()); float currentScore = 0; int daysSinceLastScore = 0; if (score_data != null) { var timespanFromLastScoreToNow = GenericUtilities.GetTimeSpanBetween(score_data.LastAccessTimestamp, GenericUtilities.GetTimestampForNow()); daysSinceLastScore = timespanFromLastScoreToNow.Days; currentScore = score_data.Score; } //UnityEngine.Debug.Log("Data " + id + " score: " + currentScore + " days " + daysSinceLastScore); // Score Weight [0,1]: higher the lower the score [-1,1] is var scoreWeight = 0.5f * (1 - currentScore); cumulativeWeight += scoreWeight * ConfigAI.data_scoreWeight; debugString += " \tScore: " + scoreWeight * ConfigAI.data_scoreWeight + "(" + scoreWeight + ")"; // RecentPlay Weight [1,0]: higher the more in the past we saw that data const float dayLinerWeightDecrease = 1f / ConfigAI.daysForMaximumRecentPlayMalus; float weightMalus = daysSinceLastScore * dayLinerWeightDecrease; float recentPlayWeight = 1f - UnityEngine.Mathf.Min(1, weightMalus); cumulativeWeight += recentPlayWeight * ConfigAI.data_recentPlayWeight; debugString += " \tRecent: " + recentPlayWeight * ConfigAI.data_recentPlayWeight + "(" + recentPlayWeight + ")"; // Current focus weight [1,0]: higher if the data is part of the current play session float currentPlaySessionWeight = currentPSData.Contains(sourceData) ? 1 : 0f; cumulativeWeight += currentPlaySessionWeight * ConfigAI.data_currentPlaySessionWeight; debugString += " \tCurrentPS: " + currentPlaySessionWeight * ConfigAI.data_currentPlaySessionWeight + "(" + currentPlaySessionWeight + ")"; // If the cumulative weight goes to the negatives, we give it a fixed weight if (cumulativeWeight <= 0) { cumulativeWeight = ConfigAI.data_minimumTotalWeight; continue; } // Save cumulative weight weights_list.Add(cumulativeWeight); debugString += " TOTw: " + cumulativeWeight; } if (ConfigAI.verboseDataSelection) { UnityEngine.Debug.Log(debugString); } // Select data from the list List <T> selected_data_list = new List <T>(); if (source_data_list.Count > 0) { int nToSelectFromCurrentList = 0; List <T> chosenData = null; switch (severity) { case SelectionSeverity.AsManyAsPossible: case SelectionSeverity.AllRequired: nToSelectFromCurrentList = UnityEngine.Mathf.Min(source_data_list.Count, nToSelect); chosenData = RandomHelper.RouletteSelectNonRepeating(source_data_list, weights_list, nToSelectFromCurrentList); selected_data_list.AddRange(chosenData); break; case SelectionSeverity.MayRepeatIfNotEnough: int nRemainingToSelect = nToSelect; while (nRemainingToSelect > 0) { var listCopy = new List <T>(source_data_list); nToSelectFromCurrentList = UnityEngine.Mathf.Min(source_data_list.Count, nRemainingToSelect); chosenData = RandomHelper.RouletteSelectNonRepeating(listCopy, weights_list, nToSelectFromCurrentList); selected_data_list.AddRange(chosenData); nRemainingToSelect -= nToSelectFromCurrentList; } break; } } return(selected_data_list); }
public List <T> SelectData <T>(System.Func <List <T> > builderSelectionFunction, SelectionParameters selectionParams) where T : IData { // skip if we require 0 values if (selectionParams.nRequired == 0 && !selectionParams.getMaxData) { return(new List <T>()); } string debugString = ""; //debugString += "--------- TEACHER: data selection --------- "; // @note: not the best of solutions, but I do not seem to be able to get more generic than this without rewriting most stuff. System.Type typeParameterType = typeof(T); HashSet <T> journeyData = null; HashSet <T> currentPSData = null; DbTables table = DbTables.Letters; if (typeParameterType == typeof(LetterData)) { table = DbTables.Letters; journeyData = new HashSet <T>(journeyLetters.Cast <T>()); currentPSData = new HashSet <T>(currentPlaySessionLetters.Cast <T>()); } else if (typeParameterType == typeof(WordData)) { table = DbTables.Words; journeyData = new HashSet <T>(journeyWords.Cast <T>()); currentPSData = new HashSet <T>(currentPlaySessionWords.Cast <T>()); } else if (typeParameterType == typeof(PhraseData)) { table = DbTables.Phrases; journeyData = new HashSet <T>(journeyPhrases.Cast <T>()); currentPSData = new HashSet <T>(currentPlaySessionPhrases.Cast <T>()); } // Get unfiltered data based on the builder's logic var dataList = builderSelectionFunction(); int nAfterBuilder = dataList.Count; debugString += ("Builder: " + dataList.Count); // Filtering based on journey if (selectionParams.useJourney && !ConfigAI.forceJourneyIgnore) { dataList = dataList.FindAll(x => journeyData.Contains(x)); } if (selectionParams.severity == SelectionSeverity.AllRequired) { if (!CheckRequiredNumberReached(dataList, selectionParams, nAfterBuilder)) { UnityEngine.Debug.Log(debugString); throw new System.Exception("The teacher could not find " + selectionParams.nRequired + " data instances after applying the journey logic."); } } debugString += (" \tJourney: " + dataList.Count); // Filtering based on pack-list history PackListHistory sev = selectionParams.packListHistory; switch (sev) { case PackListHistory.NoFilter: // we do not care which are picked, in this case break; case PackListHistory.ForceAllDifferent: // filter only by those that have not been found already in this pack, if possible dataList = dataList.FindAll(x => !selectionParams.filteringIds.Contains(x.GetId())); if (!CheckRequiredNumberReached(dataList, selectionParams, nAfterBuilder)) { UnityEngine.Debug.Log(debugString); throw new System.Exception("The teacher could not find " + selectionParams.nRequired + " data instances after applying the pack-history logic."); } break; case PackListHistory.RepeatWhenFull: // reset the previous pack list if needed var tmpDataList = dataList.FindAll(x => !selectionParams.filteringIds.Contains(x.GetId())); if (tmpDataList.Count < selectionParams.nRequired) { // reset and re-pick selectionParams.filteringIds.Clear(); dataList = dataList.FindAll(x => !selectionParams.filteringIds.Contains(x.GetId())); } else { dataList = tmpDataList; } break; } debugString += (" \tHistory: " + dataList.Count); // Weighted selection on the remaining number List <T> selectedList = null; if (selectionParams.getMaxData) { selectedList = dataList; } else { selectedList = WeightedDataSelect(dataList, currentPSData, selectionParams.nRequired, table, selectionParams.severity); } debugString += (" \tSelection: " + selectedList.Count); if (ConfigAI.verboseDataSelection) { UnityEngine.Debug.Log(debugString); } if (selectedList.Count == 0) { throw new System.Exception("The teacher could not find any data with the current filters. The game does not seem to be playable at the selected play session."); } // Update the filtering ids if (selectionParams.packListHistory != PackListHistory.NoFilter) { selectionParams.filteringIds.AddRange(selectedList.ConvertAll <string>(x => x.GetId()).ToArray()); } return(selectedList); }
public ScoreData(string elementId, DbTables table, float score) : this(elementId, table, score, GenericUtilities.GetTimestampForNow()) { }