/// <summary> /// Log execute command /// </summary> /// <param name="executeCommand">Execte command</param> internal static void LogExecuteCommand(DatabaseExecuteCommand executeCommand) { if (EnableTraceLog) { LogScriptCore(executeCommand.CommandText, JsonSerializeHelper.ObjectToJson(executeCommand.Parameters)); } }
/// <summary> /// Log script /// </summary> /// <param name="script">Script</param> /// <param name="parameters">Parameters</param> internal static void LogScript(string script, object parameters) { if (EnableTraceLog) { LogScriptCore(script, JsonSerializeHelper.ObjectToJson(parameters)); } }
/// <summary> /// 存储Session对象 /// </summary> /// <param name="sessionObject">session对象</param> /// <returns></returns> public static async Task StoreSessionAsync(AuthSession sessionObject) { if (sessionObject == null) { throw new ArgumentNullException(nameof(sessionObject)); } string subjectId = sessionObject.GetSubjectId(); if (string.IsNullOrWhiteSpace(subjectId)) { throw new Exception("authentication subject is null or empty"); } string sessionId = sessionObject.SessionId; if (string.IsNullOrWhiteSpace(sessionId)) { throw new Exception("session key is null or empty"); } var sessionConfig = SessionConfiguration.GetSessionConfiguration(); var nowDate = DateTimeOffset.Now; var expiresDate = nowDate.Add(sessionConfig.Expires); sessionObject.Expires = expiresDate; var expiresSeconds = Convert.ToInt64((expiresDate - nowDate).TotalSeconds); var expiration = new CacheExpiration() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(expiresSeconds), SlidingExpiration = true }; await CacheManager.String.SetAsync(new StringSetOptions() { CacheObject = GetCacheObject(), Items = new List <CacheEntry>() { new CacheEntry() { Key = sessionId, Value = subjectId, When = CacheSetWhen.Always, Expiration = expiration }, new CacheEntry() { Key = subjectId, Value = JsonSerializeHelper.ObjectToJson(sessionObject), Expiration = expiration, When = CacheSetWhen.Always } } }).ConfigureAwait(false); }
/// <summary> /// Remote upload file /// </summary> /// <param name="remoteOption">Remote option</param> /// <param name="fileOptions">File options</param> /// <param name="files">Upload files</param> /// <param name="parameters">Parameters</param> /// <returns>Return the upload result</returns> public static async Task <UploadResult> RemoteUploadAsync(RemoteServerOptions remoteOption, List <UploadFile> fileOptions, Dictionary <string, byte[]> files, Dictionary <string, string> parameters = null) { if (remoteOption == null || string.IsNullOrWhiteSpace(remoteOption.Host)) { throw new ArgumentNullException(nameof(remoteOption)); } if (files.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(files)); } RemoteParameter uploadParameter = new RemoteParameter() { Files = fileOptions }; parameters ??= new Dictionary <string, string>(); parameters[RemoteParameter.RequestParameterName] = JsonSerializeHelper.ObjectToJson(uploadParameter); string url = remoteOption.GetUploadUrl(); return(await HttpHelper.PostUploadAsync(url, files, parameters).ConfigureAwait(false)); }
/// <summary> /// Commit work /// </summary> /// <returns>Return work commit result</returns> public async Task <WorkCommitResult> CommitAsync() { try { if (allowTraceLog) { LogManager.LogInformation <DefaultWork>($"===== Work:{WorkId} commit begin ====="); } //build commands BuildCommand(); WorkCommitResult commitResult = null; if (commandEngineGroups.IsNullOrEmpty()) { commitResult = WorkCommitResult.Empty(); } else { var executeOptions = GetCommandExecuteOptions(); if (allowTraceLog) { LogManager.LogInformation <DefaultWork>($"Work:{WorkId},Command execute options:{JsonSerializeHelper.ObjectToJson(executeOptions)}"); LogManager.LogInformation <DefaultWork>($"Work:{WorkId},Command engine keys:{string.Join(",", commandEngineGroups.Keys)},Command count:{commandCollection.Count}"); } int returnValue = await CommandExecuteManager.ExecuteAsync(executeOptions, commandEngineGroups.Values).ConfigureAwait(false); commitResult = new WorkCommitResult() { CommitCommandCount = commandCollection.Count, ExecutedDataCount = returnValue, AllowEmptyResultCommandCount = allowEmptyResultCommandCount }; } // trigger command callback event TriggerCommandCallbackEvent(commitResult.EmptyResultOrSuccess); if (commitResult.EmptyResultOrSuccess) { //Trigger commit success event TriggerCommitSuccessEvent(commitResult); //Trigger work global success event WorkManager.TriggerWorkCommitSuccessEvent(this, commitResult, commandCollection); //Execute domain event TriggerWorkCompletedDomainEvent(); //Execute data access event TriggerDataAccessEvent(); } else { //Trigger work global commit fail event WorkManager.TriggerWorkCommitFailEvent(this, commitResult, commandCollection); } if (allowTraceLog) { LogManager.LogInformation <DefaultWork>($"Work:{WorkId},Commit command count:{commitResult.CommitCommandCount},Execute data count:{commitResult.ExecutedDataCount},Allow empty result command result:{allowEmptyResultCommandCount}"); } return(commitResult); } catch (Exception ex) { Reset(); if (allowTraceLog) { LogManager.LogInformation <DefaultWork>($"Work:{WorkId},Exception message : {ex.Message}"); } throw ex; } finally { if (allowTraceLog) { LogManager.LogInformation <DefaultWork>($"===== Work:{WorkId} commit end ====="); } } }
/// <summary> /// Write json /// </summary> /// <param name="response">Response</param> /// <param name="data">Data</param> /// <returns></returns> public static async Task WriteJsonAsync(this HttpResponse response, object data) { var json = JsonSerializeHelper.ObjectToJson(data); await response.WriteJsonAsync(json).ConfigureAwait(false); }
/// <summary> /// Add datas /// </summary> /// <typeparam name="T">Data type</typeparam> /// <param name="query">Query condition</param> /// <param name="datas">Datas</param> protected virtual void AddCacheData <T>(QueryDataCallbackContext <T> queryDataCallbackContext) where T : BaseEntity <T>, new() { if (queryDataCallbackContext == null) { return; } #region Add cache data var datas = queryDataCallbackContext.Datas; List <CacheKey> dataPrimaryKeys = null; List <CacheKey> dataOtherKeys = null; List <CacheEntry> storeItems = new List <CacheEntry>(); Type entityType = typeof(T); string objectName = entityType.Name; var cacheObject = new CacheObject() { ObjectName = objectName }; int dataCount = 0; if (!datas.IsNullOrEmpty()) { dataPrimaryKeys = new List <CacheKey>(); dataOtherKeys = new List <CacheKey>(); var entityConfiguration = EntityManager.GetEntityConfiguration(entityType); if (entityConfiguration == null) { LogManager.LogError <DefaultDataCachePolicy>($"Entity :{entityType.FullName} configuration is null"); return; } //primary keys var primaryKeys = entityConfiguration.PrimaryKeys; if (primaryKeys.IsNullOrEmpty()) { LogManager.LogError <DefaultDataCachePolicy>($"Data type:{entityType.FullName} no primary key,unable to set cache data"); return; } //cache keys var cacheKeys = entityConfiguration.CacheKeys ?? new List <string>(0); cacheKeys = cacheKeys.Except(primaryKeys).ToList(); //cache prefix keys var cachePrefixKeys = entityConfiguration.CachePrefixKeys ?? new List <string>(0); foreach (var data in datas) { if (data == null) { continue; } dataCount++; bool keyValueSuccess = true; //expiration TimeSpan? dataExpirationValue = DataCacheManager.Configuration.GetExpiration(entityType); DateTimeOffset?dataExpirationTime = null; if (dataExpirationValue != null) { dataExpirationTime = DateTimeOffset.Now.Add(dataExpirationValue.Value).AddSeconds(randomSecondPrivider.TakeNextValues(1).FirstOrDefault()); } CacheExpiration dataExpiration = new CacheExpiration() { SlidingExpiration = false, AbsoluteExpiration = dataExpirationTime }; //prefix cache keys var dataPrefixKey = new CacheKey(); if (!cachePrefixKeys.IsNullOrEmpty()) { foreach (var preKey in cachePrefixKeys) { var preKeyVal = data.GetValue(preKey)?.ToString() ?? string.Empty; if (string.IsNullOrWhiteSpace(preKeyVal)) { LogManager.LogError <DefaultDataCachePolicy>($"Data type :{entityType.FullName},Identity value:{data.GetIdentityValue()},Cache prefix key:{preKey},value is null or empty,unable to set cache data"); keyValueSuccess = false; break; } dataPrefixKey.AddName(preKey, preKeyVal); } if (!keyValueSuccess) { continue; } } //primary data cache keys var dataCacheKey = new CacheKey(cacheObject, dataPrefixKey); foreach (string pk in primaryKeys) { var pkValue = data.GetValue(pk)?.ToString() ?? string.Empty; if (string.IsNullOrWhiteSpace(pkValue)) { LogManager.LogError <DefaultDataCachePolicy>($"Data type :{entityType.FullName},Identity value:{data.GetIdentityValue()},Primary key:{pk},value is null or empty,unable to set cache data"); keyValueSuccess = false; break; } dataCacheKey.AddName(pk, pkValue); } if (!keyValueSuccess) { continue; } string primaryFullCacheKey = dataCacheKey.GetActualKey(); if (primaryFullCacheKey.IsNullOrEmpty()) { continue; } dataPrimaryKeys.Add(primaryFullCacheKey); storeItems.Add(new CacheEntry() { Key = primaryFullCacheKey, Value = JsonSerializeHelper.ObjectToJson(data), Expiration = dataExpiration }); if (!cacheKeys.IsNullOrEmpty()) { foreach (string key in cacheKeys) { var otherCacheKey = new CacheKey(cacheObject, dataPrefixKey); var cacheKeyValue = data.GetValue(key)?.ToString() ?? string.Empty; if (string.IsNullOrWhiteSpace(cacheKeyValue)) { LogManager.LogError <DefaultDataCachePolicy>($"Data type :{entityType.FullName},Identity value:{data.GetIdentityValue()},Cache key:{key},value is null or empty,unable to set cache data"); keyValueSuccess = false; break; } otherCacheKey.AddName(key, cacheKeyValue?.ToString() ?? string.Empty); dataOtherKeys.Add(otherCacheKey); storeItems.Add(new CacheEntry() { Key = otherCacheKey.GetActualKey(), Value = primaryFullCacheKey, Expiration = dataExpiration }); } if (!keyValueSuccess) { continue; } } } } #endregion #region Null data int querySize = queryDataCallbackContext.Query?.QuerySize ?? 0; if (DataCacheManager.Configuration.EnableCacheNullData && (querySize < 1 || dataCount < querySize)) { IEnumerable <CacheKey> queryPrimaryKeys = queryDataCallbackContext.PrimaryCacheKeys; IEnumerable <CacheKey> queryOtherKeys = queryDataCallbackContext.OtherCacheKeys; string nullDataValue = JsonSerializeHelper.ObjectToJson <T>(null); TimeSpan? nullDataExpirationValue = DataCacheManager.Configuration.GetNullDataExpiration(entityType); DateTimeOffset?nullDataExpiration = null; if (nullDataExpirationValue != null) { nullDataExpiration = DateTimeOffset.Now.Add(nullDataExpirationValue.Value); } CacheExpiration nullDataExp = new CacheExpiration() { SlidingExpiration = false, AbsoluteExpiration = nullDataExpiration }; if (!queryPrimaryKeys.IsNullOrEmpty()) { if (!dataPrimaryKeys.IsNullOrEmpty()) { queryPrimaryKeys = queryPrimaryKeys.Except(dataPrimaryKeys); } foreach (var primaryKey in queryPrimaryKeys) { storeItems.Add(new CacheEntry() { Key = primaryKey.GetActualKey(), Value = nullDataValue, Expiration = nullDataExp }); } } if (!queryOtherKeys.IsNullOrEmpty()) { if (!dataOtherKeys.IsNullOrEmpty()) { queryOtherKeys = queryOtherKeys.Except(dataOtherKeys); } if (!queryOtherKeys.IsNullOrEmpty()) { storeItems.Add(new CacheEntry() { Key = DataCacheManager.Configuration.NullDataCacheKey, Value = nullDataValue, Expiration = nullDataExp }); foreach (var otherKey in queryOtherKeys) { storeItems.Add(new CacheEntry() { Key = otherKey, Value = DataCacheManager.Configuration.NullDataCacheKey, Expiration = nullDataExp }); } } } } #endregion StringSetOptions option = new StringSetOptions() { CacheObject = cacheObject, Items = storeItems, CommandFlags = CacheCommandFlags.FireAndForget }; var cacheResult = CacheManager.String.Set(option); if (cacheResult != null && !cacheResult.Responses.IsNullOrEmpty()) { foreach (var response in cacheResult.Responses) { if (!string.IsNullOrWhiteSpace(response?.Message)) { LogManager.LogInformation <DefaultDataCachePolicy>(response.Message); } } } }