public ExecuteResult Update() { try { if (_taskActuator == null) { return(ExecuteResult.Cancel("task actuator is null.")); } if (_taskManager == null) { return(ExecuteResult.Cancel("task manager is null.")); } if (ModuleId == Guid.Empty) { return(ExecuteResult.Cancel("module is is empty, return.")); } if (!_taskManager.ContainsModuleId(ModuleId)) { return(ExecuteResult.Fail($"module with id {ModuleId} not found.")); } // 注释可能出现出错 // _taskActuator.ExecuteTaskAndUpdateResults(ModuleId, Parameter); return(ExecuteResult.Success()); } catch (Exception e) { return(ExecuteResult.Error(e)); } }
public ExecuteResult Update() { if (ChangeAmount == 0) { return(ExecuteResult.Success()); } try { var findAccount = Ioc.Resolve <IAccountService>().GetAccount(AccountId); if (findAccount == null) { return(ExecuteResult.Fail($"not found account when UserId={UserId} and AccountId={AccountId}")); } findAccount.Amount += ChangeAmount; if (ChangeAmount > 0) { findAccount.HistoryAmount += ChangeAmount; } Ioc.Resolve <IAccountService>().Update(findAccount); //decimal historyChangeAmount = ChangeAmount > 0 ? ChangeAmount : 0; //string sql = $"update [Asset_Account] set [Amount]=[Amount]+{ChangeAmount}, [HistoryAmount]=[HistoryAmount]+{historyChangeAmount} where [UserId]={UserId} and [Id]={AccountId}"; //Alabo.Helpers.Ioc.Resolve<IUserRepository>().RepositoryContext.ExecuteNonQuery(sql); return(ExecuteResult.Success()); } catch (Exception e) { return(ExecuteResult.Error(e)); } }
public ExecuteResult Update() { try { if (typeof(T) == typeof(TaskQueueParameter)) { if (QueueId < 1) { return(ExecuteResult.Cancel("QueueId is empty.")); } Ioc.Resolve <ITaskQueueService>().Handle(QueueId); return(ExecuteResult.Success()); } if (Parameter == null) { return(ExecuteResult.Cancel("parameter is null.")); } Ioc.Resolve <ITaskQueueService>() .Add(UserId, ModuleId, Type, ExecutionTime, MaxExecutionTimes, Parameter); return(ExecuteResult.Success()); } catch (Exception e) { return(ExecuteResult.Error(e)); } }
public Task OnExceptionAsync(ExceptionContext context) { if (context.Exception is NpsException exception) { var warnResponse = ExecuteResult.Error("", exception.GetErrorCode(), exception.Message); _logger.LogWarning(warnResponse.ToJson()); HandlerException(context, warnResponse, exception.GetCode()); return(Task.CompletedTask); } string error = "异常信息:"; void ReadException(Exception ex) { error += $"{ex.Message} | {ex.StackTrace} | {ex.InnerException}"; if (ex.InnerException != null) { ReadException(ex.InnerException); } } ReadException(context.Exception); _logger.LogError(error); var apiResponse = ExecuteResult.Error(_environment.IsDevelopment() ? error : "服务器正忙,请稍后再试.", StatusCode.UnknownError); HandlerException(context, apiResponse, StatusCodes.Status500InternalServerError); return(Task.CompletedTask); }
public async Task <IExecuteResult> GetAsync(string serverIPAddress) { serverIPAddress.CheckNotNullOrEmpty("服务器IP不能为空"); if (!RegexHelper.IsIpAddress(serverIPAddress)) { return(ExecuteResult.Error("请输入正确的IP地址格式", Infrastructure.StatusCode.ParameterError)); } return(ExecuteResult.Ok(await _npsServerService.GetAsync(serverIPAddress))); }
public ExecuteResult Update() { try { Ioc.Resolve <ITaskQueueService>().Handle(QueueId); return(ExecuteResult.Success()); } catch (Exception e) { return(ExecuteResult.Error(e)); } }
/// <summary> /// 注入MvcControllers、FluentValidation /// </summary> /// <param name="services">IServiceCollection</param> public static void AddDefineControllers(this IServiceCollection services) { Log.Logger.Information("Initialize MvcControllers Start;"); Check.NotNull(services, nameof(services)); services.AddControllers(options => { options.Filters.Add <GlobalExceptionFilter>(); options.Filters.Add <ActionTrackFilterAttribute>(); //禁止去除ActionAsync后缀 options.SuppressAsyncSuffixInActionNames = false; }) //添加FluentValidation模型验证组件 .AddFluentValidation(config => { //只使用FluentValidation模型参数验证规则 config.RunDefaultMvcValidationAfterFluentValidationExecutes = false; //从dll文件中,注入所有模型验证实现类 var validationAssembly = Assembly.Load("Nps.Application"); config.RegisterValidatorsFromAssembly(validationAssembly); }) .AddNewtonsoftJson(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //使用驼峰 首字母小写 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }) .ConfigureApiBehaviorOptions(options => { //统一返回模型验证的信息 ExecuteResult为全局统一Api返回结果 options.InvalidModelStateResponseFactory = context => { //自定义 BadRequest 响应 var problemDetails = new ValidationProblemDetails(context.ModelState); var executeResult = ExecuteResult.Error("参数错误", StatusCode.ParameterError, problemDetails.Errors); return(new BadRequestObjectResult(executeResult) { ContentTypes = { "application/json" } }); }; }) //在Controller中使用属性注入 .AddControllersAsServices(); Log.Logger.Information("Initialize MvcControllers End;"); }
public ExecuteResult Update() { var moneyType = Ioc.Resolve <IAutoConfigService>() .GetList <MoneyTypeConfig>() .FirstOrDefault(e => e.Id == Parameter.MoneyTypeId); var repositoryContext = Ioc.Resolve <IUserRepository>().RepositoryContext; var transaction = repositoryContext.BeginNativeDbTransaction(); try { var sql = $"update Asset_Account set Amount=Amount-{Amount}, ModifiedTime=GetDate() where MoneyTypeId='{SourceMoneyTypeId}' and UserId={UserId} and Amount>={Amount}"; //判断更新语句是否影响了数据库 if (repositoryContext.ExecuteNonQuery(transaction, sql) > 0) { foreach (var item in RuleItems) { var addAmount = item.Ratio * Amount; sql = $"declare @amount decimal(18, 2);update Asset_Account set Amount=Amount+{addAmount}, @amount=Amount+{addAmount}, HistoryAmount=HistoryAmount+{addAmount}, ModifiedTime=GetDate() where MoneyTypeId='{item.MoneyTypeId}' and UserId={UserId};select @amount"; var result = repositoryContext.ExecuteScalar(transaction, sql); if (result == null || result == DBNull.Value) { return(ExecuteResult.Fail($"sql script:\"{sql}\" execute with 0 line update.")); } var afterAmount = Convert.ToDecimal(result); //此处继续加入Share_Reward与Asset_Bill表的记录 sql = @"insert into Share_Reward(AfterAcount, ConfirmTime, CreateTime, ExtraDate, Fee, FenRunDate, Intro, IsAccount, [Level], ModifiedTime, ModuleId, ModuleName, MoneyTypeId, MoneyTypeName, OrderId,OrderPrice, OrderSerial, OrderUserId, OrderUserNick, Price, Remark, Serial, SortOrder, State, Status, UserId, UserNikeName, TriggerType, ModuleConfigId, BonusId) values(@afteracount, GETDATE(), GETDATE(), '', 0, GETDATE(), @intro, 1, 0, GETDATE(), @moduleid, @modulename, @moneytypeid, @moneytypename, 0, 0, '', 0, '', 0, NULL, '', 1000, 3, 0, @userid, @usernickname, @triggertype, @moduleconfigid, @bonusid)"; IList <DbParameter> parameterList = new List <DbParameter> { repositoryContext.CreateParameter("@afteracount", afterAmount), repositoryContext.CreateParameter("@intro", Parameter.Summary), repositoryContext.CreateParameter("@moduleid", Parameter.ModuleId), repositoryContext.CreateParameter("@modulename", Parameter.ModuleName), repositoryContext.CreateParameter("@moneytypeid", Parameter.MoneyTypeId), repositoryContext.CreateParameter("@moneytypename", moneyType.Name), repositoryContext.CreateParameter("@userid", Parameter.ReceiveUserId), repositoryContext.CreateParameter("@triggertype", Parameter.TriggerType), repositoryContext.CreateParameter("@moduleconfigid", Parameter.ModuleConfigId), repositoryContext.CreateParameter("@bonusid", Parameter.BonusId) }; repositoryContext.ExecuteNonQuery(transaction, sql, parameterList.ToArray()); sql = @"insert into Asset_Bill(ActionType, AfterAmount,Amount, BillStatus, BillTypeId, BillTypeName, CheckAmount, CreateTime, Currency, ExtraDate, FailuredReason, Flow, Intro, ModifiedTime, MoneyTypeId, MoneyTypeName, OrderSerial, OtherUserId, OtherUserName, PayTime, ReceiveTime, Remark, Serial, ServiceAmount, ServiceMoneyTypeId, SortOrder, [Status], UserId, UserName, UserRemark) values(@actiontype, @afteramount, @amount, @billstatus, @billtypeid, @billtypename, @checkamount, GETDATE(), @currency, NULL, NULL, 0, @intro, GETDATE(), @moneytypeid, @moneytypename, NULL, 0, NULL,GETDATE(), GETDATE(), NULL, NULL, 0, 0, 1000, 0, @userid, @UserName, NULL)"; parameterList = new List <DbParameter> { /*epositoryContext.CreateParameter("@actiontype", fenRunBillTypeConfig.ActionType),*/ repositoryContext.CreateParameter("@afteramount", afterAmount), repositoryContext.CreateParameter("@amount", addAmount), repositoryContext.CreateParameter("@billstatus", Parameter.BillStatus), //repositoryContext.CreateParameter("@billtypeid", fenRunBillTypeConfig.Id), //repositoryContext.CreateParameter("@billtypename", fenRunBillTypeConfig.Name), repositoryContext.CreateParameter("@checkamount", addAmount), repositoryContext.CreateParameter("@currency", moneyType.Currency), repositoryContext.CreateParameter("@intro", Parameter.Summary), repositoryContext.CreateParameter("@moneytypeid", moneyType.Id), repositoryContext.CreateParameter("@moneytypename", moneyType.Name), repositoryContext.CreateParameter("@userid", Parameter.ReceiveUserId), repositoryContext.CreateParameter("@UserName", Parameter.ReceiveUserName) }; repositoryContext.ExecuteNonQuery(transaction, sql, parameterList.ToArray()); } } transaction.Commit(); return(ExecuteResult.Success()); } catch (Exception e) { transaction.Rollback(); return(ExecuteResult.Error(e)); } finally { transaction.Dispose(); } }
/// <summary> /// 注入JWT /// </summary> /// <param name="services">IServiceCollection</param> public static void AddJwtBearer(this IServiceCollection services) { Log.Logger.Information("Initialize JwtBearer Start;"); Check.NotNull(services, nameof(services)); JsonWebTokenSettings jsonWebTokenSettings = services.AddSecurity(); // 开启Bearer认证 services.AddAuthentication(opts => { opts.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) // 添加JwtBearer服务 .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { //令牌验证参数 options.TokenValidationParameters = new TokenValidationParameters { //是否验证密钥 ValidateIssuerSigningKey = true, //密钥 IssuerSigningKey = jsonWebTokenSettings.SecurityKey, //是否验证发行人 ValidateIssuer = true, ValidIssuer = jsonWebTokenSettings.Issuer, //是否验证受众人 ValidateAudience = true, ValidAudience = jsonWebTokenSettings.Audience, //验证生命周期 ValidateLifetime = true, //过期时间 RequireExpirationTime = true, // 允许服务器时间偏移量300秒,即我们配置的过期时间加上这个允许偏移的时间值,才是真正过期的时间(过期时间 +偏移值)你也可以设置为0 //ClockSkew = TimeSpan.Zero }; //使用Authorize设置为需要登录时,返回json格式数据。 options.Events = new JwtBearerEvents() { //授权失败 OnAuthenticationFailed = context => { //Token expired if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); }, //未授权 OnChallenge = async context => { //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦 context.HandleResponse(); string message; StatusCode status; int statusCode = StatusCodes.Status401Unauthorized; if (context.Error == "invalid_token" && context.ErrorDescription == "The token is expired") { message = "令牌过期"; status = StatusCode.TokenExpired; statusCode = StatusCodes.Status422UnprocessableEntity; } else if (context.Error == "invalid_token" && string.IsNullOrWhiteSpace(context.ErrorDescription)) { message = "令牌失效"; status = StatusCode.TokenInvalidation; } else { message = "请先登录 " + context.ErrorDescription; //""认证失败,请检查请求头或者重新登录"; status = StatusCode.AuthenticationFailed; } context.Response.ContentType = "application/json"; context.Response.StatusCode = statusCode; await context.Response.WriteAsync(ExecuteResult.Error(message, status).ToJson()); } }; }); Log.Logger.Information("Initialize JwtBearer End;"); }