/// <summary> /// Retrieve the next value of the key into the database /// </summary> /// <param name="customerId"></param> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public int SetSequence(int customerId, string key, int value) { if (key == "Tick" || key == "Lock") { throw new ExceptionNotAuthorized("ERR_UNAUTHENTICATED"); } // Get the next value string parameterKey = $"Sequence.{key}.{customerId}"; int currentValue = 1; ParameterRecord valueRecord = _Parameter.FirstOrDefault(p => p.Key.Equals(parameterKey)); if (valueRecord == null) { valueRecord = new ParameterRecord { Key = parameterKey, Value = value.ToString() }; valueRecord = _Parameter.Add(valueRecord); } else { currentValue = int.Parse(valueRecord.Value); if (currentValue < value) { valueRecord.Value = value.ToString(); } } SaveChanges(); return(currentValue); }
/// <summary> /// Retrieve the current tick into the database for the given customer /// </summary> /// <param name="database"></param> /// <param name="customerId"></param> /// <returns></returns> public int GetTick(DatabaseContext database, int customerId) { string tickKey = $"Database.Tick.{customerId}"; ParameterRecord parameter = database._Parameter.SingleOrDefault(e => e.Key.Equals(tickKey)); if (parameter == null) { return(0); } if (!int.TryParse(parameter.Value, out int tick)) { return(0); } return(tick); }
/// <summary> /// This function is called after updating the record ... used to complete the update /// </summary> /// <param name="database"></param> /// <param name="tick"></param> /// <param name="table"></param> /// <param name="record"></param> public void OnAfterUpdateRecord(Common.Database.DatabaseContext database, int tick, string table, DSRecord record) { if (table.Equals("Language")) { if (database is Module.Administration.DatabaseContext administration && record is DSRecordWithCustomerId language) { string tickKey = $"Language.Tick.{language.CustomerId}"; ParameterRecord parameter = database._Parameter.SingleOrDefault(e => e.Key.Equals(tickKey)); if (parameter != null) { parameter.Value = tick.ToString(); } // Unable to add a line into "_Parameter" due to the lock set into the table "_Parameter"! } } }
public static void FindSoundsSTUD(STUD stud, HashSet <ulong> done, Dictionary <ulong, List <ulong> > ret, Dictionary <ulong, Record> map, CASCHandler handler, Dictionary <ulong, ulong> replace, ulong parent, ulong mykey) { foreach (ISTUDInstance instance in stud.Instances) { if (instance == null) { continue; } if (instance.Name == stud.Manager.GetName(typeof(GenericRecordReference))) { GenericRecordReference inst = (GenericRecordReference)instance; FindSoundsEx(inst.Reference.key.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(UISoundList))) { UISoundList inst = (UISoundList)instance; foreach (UISoundList.SoundListEntry[] list in inst.Entries) { foreach (UISoundList.SoundListEntry entry in list) { FindSoundsExD(entry.sound, done, ret, map, handler, replace, mykey); } } } else if (instance.Name == stud.Manager.GetName(typeof(GenericSoundReference))) { GenericSoundReference inst = (GenericSoundReference)instance; FindSoundsEx(inst.Reference.key.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(ChildGameParameterRecord))) { ChildGameParameterRecord inst = (ChildGameParameterRecord)instance; FindSoundsEx(inst.Param.binding.key, done, ret, map, handler, replace, mykey); FindSoundsEx(inst.Param.binding2.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(SoundMasterList))) { SoundMasterList smr = (SoundMasterList)instance; foreach (ulong key in smr.Sound) { FindSoundsEx(key, done, ret, map, handler, replace, mykey); } if (smr.Owner != null) { foreach (ulong key in smr.Owner) { FindSoundsEx(key, done, ret, map, handler, replace, mykey); } } } else if (instance.Name == stud.Manager.GetName(typeof(SoundOwner))) { SoundOwner owner = (SoundOwner)instance; FindSoundsEx(owner.Data.soundbank.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(SoundBank))) { SoundBank sb = (SoundBank)instance; FindSoundsEx(sb.Data.soundbank.key, done, ret, map, handler, replace, mykey); if (sb.SFX != null) { foreach (OWRecord record in sb.SFX) { FindSoundsEx(record.key, done, ret, map, handler, replace, mykey); } } if (sb.Music != null) { foreach (OWRecord record in sb.Music) { FindSoundsEx(record.key, done, ret, map, handler, replace, mykey); } } } else if (instance.Name == stud.Manager.GetName(typeof(ParameterRecord))) { ParameterRecord parameter = (ParameterRecord)instance; foreach (ParameterRecord.ParameterEntry entry in parameter.Parameters) { FindSoundsEx(entry.parameter.key, done, ret, map, handler, replace, mykey); } } else if (instance.Name == stud.Manager.GetName(typeof(SoundBindingReference))) { SoundBindingReference smr = (SoundBindingReference)instance; FindSoundsEx(smr.Reference.sound.key, done, ret, map, handler, replace, MutateKey(mykey, (ushort)smr.Reference.Typus)); } else if (instance.Name == stud.Manager.GetName(typeof(BindingRecord))) { BindingRecord record = (BindingRecord)instance; FindSoundsEx(record.Param.binding.key, done, ret, map, handler, replace, mykey); FindSoundsEx(record.Param.binding2.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(SoundFX))) { SoundFX record = (SoundFX)instance; FindSoundsEx(record.Param.binding.key, done, ret, map, handler, replace, mykey); FindSoundsEx(record.Param.binding2.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(ChildParameterRecord))) { ChildParameterRecord record = (ChildParameterRecord)instance; FindSoundsEx(record.Header.binding.key, done, ret, map, handler, replace, mykey); foreach (ChildParameterRecord.Child child in record.Children) { FindSoundsEx(child.parameter.key, done, ret, map, handler, replace, mykey); } } else if (instance.Name == stud.Manager.GetName(typeof(EffectReference))) { EffectReference reference = (EffectReference)instance; FindSoundsExD(reference.Reference.key.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(BindingEffectReference))) { BindingEffectReference reference = (BindingEffectReference)instance; // Exports a LOT of system sound effects unrelated to the origin. FindSoundsExD(reference.Reference.effect.key, done, ret, map, handler, replace, mykey); } else if (instance.Name == stud.Manager.GetName(typeof(GenericKeyReference))) { GenericKeyReference reference = (GenericKeyReference)instance; FindSoundsEx(reference.Reference.key.key, done, ret, map, handler, replace, mykey); } } }
public override void OnParameter(int num, AnimatorControllerParameter acp) { ParameterRecord record = new ParameterRecord(num, acp.name, acp.defaultBool, acp.defaultFloat, acp.defaultInt, acp.nameHash, acp.type); AconDocument.parameters.Add(record); }
/// <summary> /// Execute a list of requests from a client /// </summary> /// <param name="transaction"></param> /// <returns>RequestId, Error, Record</returns> public List <Tuple <DSRecord, InformationRecord> > ExecuteTransaction(DSTransaction transaction) { Info($"Executing the transaction [{transaction.RequestId}] containing {transaction.Requests.Count} requests ..."); List <Tuple <DSRecord, InformationRecord> > recordsTreated = new List <Tuple <DSRecord, InformationRecord> >(); List <Tuple <string, DSRecord, InformationRecord> > recordsToUpdate = new List <Tuple <string, DSRecord, InformationRecord> >(); // Retrieve the database schema DSDatabase schema = ConfigurationManager.Schemas[transaction.Area]; if (schema == null) { Error("No schema available!"); throw new ExceptionDefinitionRecord("ERR_SCHEMA"); } // Lock database during the execution of the request using (DatabaseLock lockDatabase = Database.Lock(transaction.CustomerId)) { try { if (IsVerbose()) { Verbose("Getting the first tick of the transaction ..."); } // Get the tick string tickKey = $"Database.Tick.{transaction.CustomerId}"; int tick = 0; ParameterRecord tickRecord = Database._Parameter.FirstOrDefault(p => p.Key.Equals(tickKey)); if (tickRecord == null) { tickRecord = new ParameterRecord { Key = tickKey, Value = transaction.Requests.Count.ToString() }; tickRecord = Database._Parameter.Add(tickRecord); } else { tick = int.Parse(tickRecord.Value); tickRecord.Value = (tick + transaction.Requests.Count).ToString(); } Database.SaveChanges(); if (IsDebug()) { Debug($"First tick is {tick}"); } // Execute the OnBefore trigger if (IsVerbose()) { Verbose("Executing the pre-request of the transaction ..."); } transaction.SetNewTick(tick); foreach (DSRequest request in transaction.Requests) { // Execute the request if (IsVerboseAll()) { Verbose($"Executing the pre-request[{request.Id}] with tick[{request.NewTick}]: {request} ..."); } // Execute the trigger before requesting schema.OnBeforeExecuteRequest(Database, request.NewTick, transaction.CustomerId, transaction.UserId, transaction.Area, transaction.Profile, request.Table, request.Action, request.RecordId, request.Record, request.Identity); } if (IsDebug()) { Debug($"Pre-request executed for {transaction.Requests.Count} requests"); } // Execute each request if (IsVerbose()) { Verbose("Executing the transaction ..."); } // Execution by lot List <RequestTableRecord> actions = new List <RequestTableRecord>(); int index = 0; foreach (List <DSRequest> lot in transaction.LotRequests) { // Execute the lot of requests if (IsVerbose()) { Verbose($"Executing the lot[{index}] with {lot.Count} requests ..."); } // Execute the lot of requests recordsTreated.AddRange(schema.ExecuteRequest(Database, transaction, lot)); // Saving data Database.SaveChanges(); index++; } if (IsVerbose()) { Verbose("Building the list of actions ..."); } index = 0; foreach (DSRequest request in transaction.Requests) { Tuple <DSRecord, InformationRecord> recordTreated = recordsTreated[index]; // Keep in memory all records executed recordsToUpdate.Add(Tuple.Create(request.Table, recordTreated.Item1, recordTreated.Item2)); // The request is correctly executed ... Store a new request actions.Add(new RequestTableRecord { Tick = request.NewTick, CustomerId = transaction.CustomerId, UserId = transaction.UserId, RequestId = transaction.RequestId, Table = request.Table, Action = request.Action, Id = (recordTreated == null || recordTreated.Item1 == null ? -1 : recordTreated.Item1.Id) }); Info($"The request[{request.Id}] has correctly been executed : {(recordTreated == null ? "null" : recordTreated.ToString())}"); index++; } if (IsDebug()) { Debug($"Transaction executed with {transaction.Requests.Count} requests"); } // Write actions into the RequestTable if (IsVerbose()) { Verbose($"Writing {actions.Count} actions into the RequestTable ..."); } Database._RequestTable.AddRange(actions); Database.SaveChanges(); if (IsDebug()) { Debug($"{actions.Count} actions written into the RequestTable"); } // Execute the OnAfter trigger if (IsVerbose()) { Verbose("Executing the post-request of the transaction ..."); } foreach (DSRequest request in transaction.Requests) { // Execute the request if (IsVerboseAll()) { Verbose($"Executing the post-request[{request.Id}] with tick[{request.NewTick}]: {request} ..."); } // Execute the trigger before requesting DSRecord record = recordsTreated[request.Id].Item1; if (record != null) { schema.OnAfterExecuteRequest(Database, request.NewTick, transaction.CustomerId, transaction.UserId, transaction.Area, transaction.Profile, request.Table, request.Action, record.Id, record); } } if (IsDebug()) { Debug($"Post-request executed for {transaction.Requests.Count} requests"); } // Unlock the database and commit all changes if (IsVerbose()) { Verbose("Committing changes ..."); } lockDatabase.Commit(); if (IsVerbose()) { Verbose("Changes committed"); } // Update the cache manager if (IsVerbose()) { Verbose("Updating cache ..."); } DatabaseCacheManager.Instance.UpdateCache(recordsToUpdate, transaction.CustomerId, tick + transaction.Requests.Count); if (IsVerbose()) { Verbose("Cache updated"); } } catch (System.Exception ex) { Exception("An exception occurs on executing the transaction", ex); bool saveFailed = false; do { saveFailed = false; try { Database.SaveChanges(); } catch (DbUpdateException ex2) { saveFailed = true; ex2.Entries.Single().Reload(); } }while (saveFailed); // Rollback all request already executed throw ex; } } Info("Transaction done"); return(recordsTreated); }
/// <summary> /// The client starts the initialization process and has to declare its area /// </summary> /// <param name="area"></param> /// <param name="moduleId"></param> /// <returns>the database schema correspnding to the user's profile and its area: /// Version = database version /// Schema = database schema /// DefaultLanguage = default language (user's language or default language of the application) /// User = user's profile /// LastRequestId = last request id of the user /// </returns> public JObject Initialize(string area, int moduleId) { string defaultLanguage = "EN"; int versionDatabase = 0; int lastRequestId = 0; IUser user = null; IModule module = null; Info($"Initializing connection within the area '{area}' ({moduleId}) ..."); if (_userManager == null) { Error("Unable to open the connection. UserManager is undefined!"); throw new ExceptionDefinitionRecord("ERR_CONNECTION"); } // Retrieve database information defaultLanguage = ConfigurationManager.DefaultLanguage; ParameterRecord parameterVersion = Database._Parameter.FirstOrDefault(p => p.Key.Equals("Database.Version")); if (parameterVersion != null) { versionDatabase = int.Parse(parameterVersion.Value); } // Retrieve the current user and its language user = _userManager.GetById(_userId); if (user == null) { Warn("The user doesn't exist!"); throw new ExceptionDefinitionRecord("ERR_CONNECTION"); } module = _userManager.GetModule(user, moduleId); if (module == null) { Warn("The module doesn't exist!"); throw new ExceptionDefinitionRecord("ERR_CONNECTION"); } // Retrieve the connection ConnectionRecord currentConnection = Database._Connection.FirstOrDefault(c => c.ConnectionId.Equals(_connectionId) && c.Machine.Equals(Environment.MachineName)); if (currentConnection == null) { Warn("The connection doesn't exist. Open the new connection!"); throw new ExceptionDefinitionRecord("ERR_CONNECTION"); } // Retrieve the database schema DSSchema.DSDatabase schema = ConfigurationManager.Schemas[area]; if (schema == null) { Error("No schema available!"); throw new ExceptionDefinitionRecord("ERR_SCHEMA"); } // Is this connection authorized to start the dialog ? if (!currentConnection.Allow) { Error("Not allowed!"); throw new ExceptionDefinitionRecord("ERR_UNAUTHORIZED"); } // Retrieve the last requestId of this user RequestIdRecord requestId = Database._RequestId.FirstOrDefault(r => r.UserId == _userId); if (requestId != null) { lastRequestId = requestId.RequestId; } // Set the area of the connection and notify that the connection is initialized currentConnection.Area = area; currentConnection.ModuleId = module.Id; currentConnection.Profile = module.Profile; currentConnection.Status = true; currentConnection.ConnectionLast = DateTime.Now; Database.SaveChanges(); Info($"The connection '{currentConnection}' is linked to the area '{area}'"); // define the response JObject result = new JObject { ["Version"] = versionDatabase, ["Schema"] = schema.ToJSON(area, currentConnection.Profile, Database.GetCache(schema)), ["DefaultLanguage"] = defaultLanguage, ["CurrentUserId"] = user == null ? -1 : user.Id, ["CurrentModuleId"] = moduleId, ["LastRequestId"] = lastRequestId }; JObject settings = new JObject(); foreach (KeyValuePair <string, string> setting in ConfigurationManager.Settings) { if (!setting.Key.StartsWith("Syncytium.Client.")) { continue; } settings[setting.Key.Substring("Syncytium.Client.".Length)] = setting.Value; } result["Parameters"] = settings; return(result); }
/// <summary> /// Lock the database for a customer /// </summary> /// <param name="customerId"></param> public DatabaseLock Lock(int customerId) { string lockKey = $"Database.Lock.{customerId}"; // Create Database.Lock if the line doesn't exist ParameterRecord parameterRecord = _Parameter.FirstOrDefault(p => p.Key.Equals(lockKey)); if (parameterRecord == null) { parameterRecord = new ParameterRecord() { Key = $"Database.Lock.{customerId}", Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }; parameterRecord = _Parameter.Add(parameterRecord); SaveChanges(); } // Lock the database DbContextTransaction transaction = Database.BeginTransaction(); switch (_provider.Type) { case Provider.Provider.EProvider.Oracle: if (Database.Connection.State != System.Data.ConnectionState.Open) { Database.Connection.Open(); } Database.ExecuteSqlCommand($"UPDATE \"_Parameter\" SET \"Value\" = '{DateTime.Now:yyyy-MM-dd HH:mm:ss}' where \"Key\" = 'Database.Lock.{customerId}'"); break; case Provider.Provider.EProvider.SQLServer: if (Database.Connection.State != System.Data.ConnectionState.Open) { Database.Connection.Open(); } Database.ExecuteSqlCommand($"UPDATE [{ConfigurationManager.DatabaseSchema}].[_Parameter] SET [Value] = '{DateTime.Now:yyyy-MM-dd HH:mm:ss}' where [Key] = 'Database.Lock.{customerId}'"); break; case Provider.Provider.EProvider.Firebird: if (Database.Connection.State != System.Data.ConnectionState.Open) { Database.Connection.Open(); } Database.ExecuteSqlCommand($"UPDATE \"_Parameter\" SET \"Value\" = '{DateTime.Now:yyyy-MM-dd HH:mm:ss}' where \"Key\" = 'Database.Lock.{customerId}'"); break; case Provider.Provider.EProvider.MySQL: if (Database.Connection.State != System.Data.ConnectionState.Open) { Database.Connection.Open(); } Database.ExecuteSqlCommand($"UPDATE `{ConfigurationManager.DatabaseSchema}`.`_Parameter` SET `Value` = '{DateTime.Now:yyyy-MM-dd HH:mm:ss}' where `Key` = 'Database.Lock.{customerId}'"); break; default: Warn("Unable to lock the database due to an implementation of locking database missing!"); break; } _lock = new DatabaseLock(transaction); return(_lock); }
/// <summary> /// Upgrade the current schema of the database towards the last one /// </summary> public void Upgrade() { ParameterRecord parameterVersion = null; ParameterRecord parameterUpdate = null; Info("Upgrading the database ..."); int lastUpgradingVersion = 0; string lastUpgradingDate = string.Empty; // Is the DS Model defined ? bool?existsParameter = ExistTable("_Parameter"); if (existsParameter != null && existsParameter.Value) { parameterVersion = _Parameter.SingleOrDefault(e => e.Key.Equals("Database.Version")); if (parameterVersion != null && !String.IsNullOrWhiteSpace(parameterVersion.Value) && !int.TryParse(parameterVersion.Value, out lastUpgradingVersion)) { lastUpgradingVersion = 0; } parameterUpdate = _Parameter.SingleOrDefault(e => e.Key.Equals("Database.Update")); if (parameterUpdate != null) { lastUpgradingDate = parameterUpdate.Value; } if (String.IsNullOrWhiteSpace(lastUpgradingDate)) { Info($"No database set up"); } else { Info($"The current database version '{lastUpgradingVersion:D4}' was set up at '{lastUpgradingDate}'"); } } else { Info($"No database set up"); } // Retrieve the list of script to run Regex pattern = new Regex(@"^(?<version>\d+)\-(?<year>\d+)\-(?<month>\d+)\-(?<day>\d+)-(?<label>.*)\.txt$"); Dictionary <int, string> scriptsToRun = new Dictionary <int, string>(); foreach (string sqlFilenameAndDirectory in Directory.GetFiles(Path.Combine(HttpRuntime.AppDomainAppPath, "Database", "Provider", _provider.Type.ToString(), "Script"))) { // check if the filename mathes to the pattern expected string filename = Path.GetFileName(sqlFilenameAndDirectory); Match match = pattern.Match(filename); if (!match.Success) { Warn($"The filename '{filename}' has no the correct format name ... ignore it!"); continue; } // check if the script must be run on depends on the last upgrading version int version = int.Parse(match.Groups["version"].Value); if (version <= lastUpgradingVersion) { Info($"Script '{filename}' already done ..."); continue; } if (scriptsToRun.ContainsKey(version)) { throw new ExceptionParse($"The version ('{version}') of the script '{filename}' is defined twice!"); } // load the sql file and replace all values from the settings Info($"The script '{filename}' must be applied"); scriptsToRun[version] = sqlFilenameAndDirectory; } // check if a script must be run if (scriptsToRun.Count == 0) { Info("Database already up-to-date"); return; } // Executing the list of upgrade scripts ordered by the version number Dictionary <string, string> valuesToReplace = ConfigurationManager.Settings; List <int> versions = scriptsToRun.Keys.ToList(); versions.Sort(); foreach (int version in versions) { string filename = scriptsToRun[version]; // load the sql file and replace all values from the settings Info($"Executing script '{filename}' ..."); string sqlCommand = File.ReadAllText(filename); foreach (KeyValuePair <string, string> valueToReplace in valuesToReplace) { sqlCommand = sqlCommand.Replace($"${{{valueToReplace.Key}}}", valueToReplace.Value); } if (!_provider.ExecuteScript(sqlCommand)) { throw new ExceptionParse($"Unable to execute the script '{filename}', see the log file to have more details!"); } // update parameters lastUpgradingVersion = version; if (parameterVersion == null) { _Parameter.Add(new ParameterRecord() { Key = "Database.Version", Value = lastUpgradingVersion.ToString() }); } else { parameterVersion.Value = lastUpgradingVersion.ToString(); } lastUpgradingDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); if (parameterUpdate == null) { _Parameter.Add(new ParameterRecord() { Key = "Database.Update", Value = lastUpgradingDate }); } else { parameterUpdate.Value = lastUpgradingDate; } SaveChanges(); Info($"The database is successfully upgraded in version ({lastUpgradingVersion:D4}) - '{lastUpgradingDate}'"); // retrieve the record after updating database if (parameterVersion == null) { parameterVersion = _Parameter.SingleOrDefault(e => e.Key.Equals("Database.Version")); parameterUpdate = _Parameter.SingleOrDefault(e => e.Key.Equals("Database.Update")); } } }
/// <summary> /// Check if an upgrade must be done /// </summary> /// <returns>true if the database is up to date</returns> public bool HasToUpgrade() { ParameterRecord parameter = null; Info("Checking upgrading the database schema ..."); // Is the DS Model defined ? bool?existsParameter = ExistTable("_Parameter"); if (existsParameter == null || !existsParameter.Value) { Logger.LoggerManager.Instance.Warn(Logger.LoggerManager.MODULE_NAME, "The DS Model is not defined"); return(true); } Logger.LoggerManager.Instance.Info(Logger.LoggerManager.MODULE_NAME, "The DS Model is defined"); // Retrieve the last upgrading already done int lastUpgradingVersion = 0; parameter = _Parameter.SingleOrDefault(e => e.Key.Equals("Database.Version")); if (parameter != null && !String.IsNullOrWhiteSpace(parameter.Value) && !int.TryParse(parameter.Value, out lastUpgradingVersion)) { lastUpgradingVersion = 0; } if (lastUpgradingVersion == 0) { Info("No database defined ... start the first upgrade"); return(true); } string lastUpgradingDate = string.Empty; parameter = _Parameter.SingleOrDefault(e => e.Key.Equals("Database.Update")); if (parameter != null) { lastUpgradingDate = parameter.Value; } Info($"The current database version '{lastUpgradingVersion:D4}' was set up at '{lastUpgradingDate}'"); // Check if the version of the expected database is described into the configuration file try { Debug($"The domain is '{HttpRuntime.AppDomainAppPath}'"); } catch (System.Exception) { // If an exception is raised, it means that this code is run over the web application (for example: in the job par of the application) if (lastUpgradingVersion != ConfigurationManager.DatabaseExpectedVersion) { Warn($"The expected database version must be '{ConfigurationManager.DatabaseExpectedVersion:D4}' instead of '{lastUpgradingVersion:D4}'"); return(true); } return(false); } // Check if a script must be executed ... Regex pattern = new Regex(@"^(?<version>\d+)\-(?<year>\d+)\-(?<month>\d+)\-(?<day>\d+)-(?<label>.*)\.txt$"); foreach (string sqlFilenameAndDirectory in Directory.GetFiles(Path.Combine(HttpRuntime.AppDomainAppPath, "Database", "Provider", _provider.Type.ToString(), "Script"))) { // check if the filename mathes to the pattern expected string filename = Path.GetFileName(sqlFilenameAndDirectory); Match match = pattern.Match(filename); if (!match.Success) { Warn($"The filename '{filename}' has no the correct format name ... ignore it!"); continue; } // check if the script must be run on depends on the last upgrading version int versionFile = int.Parse(match.Groups["version"].Value); if (versionFile <= lastUpgradingVersion) { Info($"Script '{filename}' already done ..."); continue; } // load the sql file and replace all values from the settings Info("A upgrade must be applied ..."); return(true); } Info("No upgrade detected"); return(false); }
/// <summary> /// Load all labels if it's necessary /// </summary> /// <param name="database"></param> /// <param name="customerId"></param> private void Load(DatabaseContext database, int?customerId) { int lastUpdate = 0; _mutex.Wait(); // lock critical section if (customerId == null) { // Load all tickId for each customer or create it if it doesn't exist foreach (CustomerRecord customer in database.Customer.ToList()) { int tick = 0; // Retrieve the tick of the database string tickKey = $"Database.Tick.{customer.Id}"; ParameterRecord parameter = database._Parameter.FirstOrDefault(e => e.Key.Equals(tickKey)); if (parameter != null) { int.TryParse(parameter.Value, out tick); } // Update or retrieve the tick of the language tickKey = $"Language.Tick.{customer.Id}"; parameter = database._Parameter.FirstOrDefault(e => e.Key.Equals(tickKey)); if (parameter == null) { database._Parameter.Add(new ParameterRecord() { Key = tickKey, Value = tick.ToString() }); } else { parameter.Value = tick.ToString(); } _lastUpdate[customer.Id] = tick; } database.SaveChanges(); } else { string tickKey = $"Language.Tick.{customerId.Value}"; ParameterRecord parameter = database._Parameter.SingleOrDefault(e => e.Key.Equals(tickKey)); if (parameter == null) { Warn($"Please, create the parameter '{tickKey}' into the database to avoid loading labels every time!"); } if (parameter != null && !String.IsNullOrWhiteSpace(parameter.Value) && !int.TryParse(parameter.Value, out lastUpdate)) { lastUpdate = 0; } if (parameter != null && _lastUpdate.ContainsKey(customerId.Value) && lastUpdate == _lastUpdate[customerId.Value] && lastUpdate >= 0) { // no changes ... _mutex.Release(); // unlock critical section return; } // Update the language tick if (parameter != null && lastUpdate < 0) { string dbTickKey = $"Database.Tick.{customerId.Value}"; ParameterRecord parameterTick = database._Parameter.FirstOrDefault(e => e.Key.Equals(dbTickKey)); if (parameterTick != null) { parameter.Value = parameterTick.Value; database.SaveChanges(); } } } if (customerId == null) { Info("Loading all labels ..."); try { int i = 0; Dictionary <int, List <LanguageRecord> > newLabels = new Dictionary <int, List <LanguageRecord> >(); foreach (LanguageRecord label in database.Language.ToList()) { if (!newLabels.ContainsKey(label.CustomerId)) { newLabels[label.CustomerId] = new List <LanguageRecord>(); } newLabels[label.CustomerId].Add(DSRecord.Copy(label) as LanguageRecord); if (IsDebug() && customerId == null && label.CustomerId == 1) { Debug($"{label.Key.Trim()} = {label}"); } i++; } Info($"{i} labels loaded"); _labels = newLabels; } catch (Exception ex) { Exception("Unable to load all labels", ex); } } else { Info($"Loading labels because they recently change ('{lastUpdate}') for the customer '{customerId.Value}' ..."); try { int i = 0; List <LanguageRecord> newLabels = new List <LanguageRecord>(); foreach (LanguageRecord label in database.Language.Where(l => l.CustomerId == customerId.Value).ToList()) { newLabels.Add(DSRecord.Copy(label) as LanguageRecord); i++; } Info($"{i} labels loaded"); _labels[customerId.Value] = newLabels; _lastUpdate[customerId.Value] = lastUpdate; } catch (Exception ex) { Exception($"Unable to load labels for the customer '{customerId.Value}'", ex); } } _mutex.Release(); // unlock critical section if (customerId != null) { DatabaseCacheManager.Instance.Reload(database, customerId.Value, "Language"); } return; }