Beispiel #1
0
        [HttpGet("hello")]//, AppTicket]
        public DResult <DemoDto> Hello(VDemoInput input)
        {
            var inputDto = Mapper.Map <DemoInputDto>(input);
            var dto      = _demoService.Hello(IdentityHelper.Guid32, inputDto);

            return(DResult.Succ(dto));
        }
Beispiel #2
0
        public override DResult <VerifyDto> Verify()
        {
            var paramDict = OnlinePayHelper.GetParams();

            Logger.Info(JsonHelper.ToJson(paramDict, indented: true));
            var sign      = paramDict.GetValue <string>("sign");
            var checkSign = paramDict.Md5Sign(Config.PrivateKey);

            if (sign != checkSign)
            {
                return(DResult.Error <VerifyDto>("验证签名失败"));
            }
            if (Config.AppId != paramDict.GetValue <string>("appid"))
            {
                return(DResult.Error <VerifyDto>("AppId异常"));
            }
            var dto = new VerifyDto
            {
                Id          = paramDict.GetValue <string>("out_trade_no"),
                TradeNo     = paramDict.GetValue <string>("transaction_id"),
                TradeStatus = paramDict.GetValue <string>("result_code"),
                Amount      = paramDict.GetValue <decimal>("total_fee"),
                BuyerId     = paramDict.GetValue <string>("openid")
            };

            return(DResult.Succ(dto));
        }
Beispiel #3
0
        public DResult <Models.Wiki> AddWiki(string name, string groupId, string creatorId, string desc)
        {
            if (Wikis.Exists(w => w.Name == name))
            {
                return(DResult.Error <Models.Wiki>("词条已存在!"));
            }
            var group = Groups.SingleOrDefault(g => g.Id == groupId);

            if (group == null)
            {
                return(DResult.Error <Models.Wiki>("分组不存在!"));
            }
            var wiki = new Models.Wiki
            {
                Id          = CombHelper.Guid16,
                Name        = name,
                CreatorId   = creatorId,
                GroupId     = groupId,
                Hots        = 0,
                Sort        = 0,
                Description = desc,
                CreateTime  = Clock.Now
            };

            wiki.Sort = Wikis.Max(w => w.Sort, w => w.GroupId == groupId) + 1;
            var result = UnitOfWork.Transaction(() =>
            {
                Wikis.Insert(wiki);
                group.WikiCount++;
                group.LastUpdateTime = Clock.Now;
                Groups.Update(group);
            });

            return(result > 0 ? DResult.Succ(wiki) : DResult.Error <Models.Wiki>("添加词条失败!"));
        }
        public static DResult ClearConsole(params CParameter[] Params)
        {
            Console.Clear();
            var mes = "Console buffer cleared.";

            return(DResult.C(CDebugResult.OK, mes, ClearConsole, ConsoleDebug.CClass, ConsoleDebug.Instance));
        }
        public async Task <DResult> AddProject([FromBody] VConfigProjectInput input)
        {
            var model  = input.MapTo <TProject>();
            var result = await _repository.InsertAsync(model);

            return(result > 0 ? DResult.Success : DResult.Error("保存项目失败"));
        }
Beispiel #6
0
        public static void LoadPlugin <T>(this IServiceCollection services, T _plugin) where T : WebApiController
        {
            Console.ForegroundColor = ConsoleColor.Green;
            var plugin = (WebApiController)_plugin;
            var type   = typeof(T);

            if (plugin.IsRegisterRpc)
            {
                var contract = type.GetInterfaces().First().FullName;
                MqRpcHelper.RegisterRpcServer(contract, (r) => {
                    var c        = r.Content;
                    MethodInfo m = type.GetMethod(c.Method);
                    if (m != null)
                    {
                        return(m.Invoke(plugin, c.Params));
                    }
                    return(DResult.Error("Rpc服务中心没有找到该方法!"));
                });

                Console.WriteLine($"【{plugin.Priority}】{plugin.Name}插件({plugin.Id})rpc注册成功!");
            }
            services.AddMvcCore().AddApplicationPart(type.Assembly);
            Console.WriteLine($"【{plugin.Priority}】{plugin.Name}插件({plugin.Id})加载成功!");
            if (plugin.IsAuth)
            {
                Console.WriteLine($"【{plugin.Priority}】{plugin.Name}插件({plugin.Id})开启token验证!");
            }
            Console.ResetColor();
        }
Beispiel #7
0
        /// <summary> 请求执行时验证模型 </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!_validation || context.ModelState.IsValid)
            {
                return;
            }
            var errordict = context.ModelState.FirstOrDefault(t => t.Value.Errors.Count > 0);

            if (errordict.Key == null)
            {
                return;
            }
            var value = errordict.Value.Errors[0].ErrorMessage;

            if (string.IsNullOrWhiteSpace(value))
            {
                var ex = errordict.Value.Errors[0].Exception;
                if (ex is BusiException exception)
                {
                    value = exception.Message;
                }
                else
                {
                    _logger.LogError(ex, ex.Message);
                    value = $"参数{errordict.Key}验证失败";
                }
            }
            context.Result = new JsonResult(DResult.Error(value, ErrorCodes.ParamaterError));
            base.OnActionExecuting(context);
        }
            public virtual bool GetCachedTables(string defaultDb, DResult handler, DRows row, DRowsetHeader rh, uint flags)
            {
                ulong index = GetCallIndex();

                lock (m_csCache)
                {
                    //don't make m_csCache locked across calling SendRequest, which may lead to cross-SendRequest dead-lock
                    //in case a client asynchronously sends lots of requests without use of client side queue.
                    m_mapRowset[index] = new KeyValuePair <DRowsetHeader, DRows>(rh, row);
                }
                if (!SendRequest(DB_CONSTS.idGetCachedTables, defaultDb, flags, index, (ar) =>
                {
                    int res, dbMS;
                    string errMsg;
                    ar.Load(out dbMS).Load(out res).Load(out errMsg);
                    lock (m_csCache)
                    {
                        m_ms = (UDB.tagManagementSystem)dbMS;
                        m_mapRowset.Remove(index);
                    }
                    if (handler != null)
                    {
                        handler(res, errMsg);
                    }
                }))
                {
                    lock (m_csCache)
                    {
                        m_mapRowset.Remove(index);
                    }
                    return(false);
                }
                return(true);
            }
Beispiel #9
0
        //public override DApiResult<string> Pay(long orderNo, decimal price, string subject)
        //{
        //    var dict = Config.BaseParams("alipay.trade.pay");
        //    //业务参数
        //    var item = new Dictionary<string, object>
        //    {
        //        {"out_trade_no", orderNo},
        //        {"product_code", "QUICK_MSECURITY_PAY"},
        //        {"auth_code", "28763443825664394"},
        //        {"subject", subject},
        //        {"total_amount", price}
        //    };
        //    dict.Add("biz_content", JsonHelper.ToJson(item));
        //    dict.Add("sign", dict.RsaSign(Config.PrivateKey, Config.Charset));

        //    var url = $"{Config.Gateway}?{dict.ParamsUrl()}";
        //    Logger.Info(JsonHelper.ToJson(dict, indented: true));
        //    using (var http = new HttpHelper(url, Encoding.GetEncoding(Config.Charset)))
        //    {
        //        var html = http.GetHtml();
        //        Logger.Info(html);
        //        var dto = JsonHelper.Json<ReturnAlipayDto>(html);
        //        if (dto?.alipay_trade_pay_response == null)
        //            return DApiResult.Error<string>("支付接口异常");
        //        var result = dto.alipay_trade_pay_response;
        //        if (result.code != "10000")
        //            return DApiResult.Error<string>($"{result.msg}:{result.sub_msg}");
        //        return DApiResult.Succ(string.Empty);
        //    }
        //}

        public override DResult <VerifyDto> Verify()
        {
            var paramDict = OnlinePayHelper.GetParams();

            Logger.Info(JsonHelper.ToJson(paramDict, indented: true));
            var signVerified = AlipaySignature.RsaCheck(paramDict, Config.PublicKey, Config.Charset);

            if (!signVerified)
            {
                return(DResult.Error <VerifyDto>("验证签名失败"));
            }
            if (paramDict.GetValue <string>("app_id") != Config.AppId)
            {
                return(DResult.Error <VerifyDto>("AppId异常"));
            }
            var dto = new VerifyDto
            {
                Id           = paramDict.GetValue <string>("out_trade_no"),
                TradeNo      = paramDict.GetValue <string>("trade_no"),
                TradeStatus  = paramDict.GetValue <string>("trade_status"),
                Amount       = paramDict.GetValue <decimal>("total_amount"),
                BuyerId      = paramDict.GetValue <string>("buyer_id"),
                BuyerAccount = paramDict.GetValue <string>("buyer_logon_id")
            };

            return(DResult.Succ(dto));
        }
Beispiel #10
0
        private DResult PreAction(string userName, string userPwd, string ip, bool shutdown = true)
        {
            //return new Random().Next(0, 10) % 3 == 0 ? DResult.Success : DResult.Error("链接失败!");
            var options = new ConnectionOptions {
                Username = userName, Password = userPwd
            };
            var scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", options);

            try
            {
                //用给定管理者用户名和口令连接远程的计算机
                scope.Connect();
                var oq              = new ObjectQuery("select * from win32_OperatingSystem");
                var query           = new ManagementObjectSearcher(scope, oq);
                var queryCollection = query.Get();
                foreach (var o in queryCollection)
                {
                    var mo = (ManagementObject)o;
                    mo.InvokeMethod(shutdown ? "Shutdown" : "Reboot", null);
                    //注销
                    //mo.InvokeMethod("Logoff", null);
                }
                return(DResult.Success);
            }
            catch (Exception er)
            {
                return(DResult.Error("连接" + ip + "出错,出错信息为:" + er.Message));
            }
        }
        public static DResult ImportPKG(params CParameter[] Params)
        {
            var filepath = ConsoleDebug.Params[0].Value.ToString();

            PackageManager.Instance.Import(filepath);
            return(DResult.C(CDebugResult.OK, "", ImportPKG, ConsoleDebug.CClass, ConsoleDebug.Instance));
        }
Beispiel #12
0
        public async Task <DResults <JobDto> > JobHots()
        {
            //:todo
            var list = await Task.FromResult(new List <JobDto>());

            return(DResult.Succ(list, -1));
        }
Beispiel #13
0
        public async Task <DResult> Save(string module, [FromBody] object config, string env = null)
        {
            var envs = Enum.GetValues(typeof(ConfigEnv)).Cast <ConfigEnv>().Select(t => t.ToString().ToLower()).ToList();

            if (!string.IsNullOrWhiteSpace(env))
            {
                env = env.ToLower();
                if (!envs.Contains(env))
                {
                    return(DResult.Error($"不支持的配置模式:{env}"));
                }
            }
            var model = new ConfigDto
            {
                ProjectId = Project.Id,
                Name      = module,
                Mode      = env,
                Status    = (byte)ConfigStatus.Normal,
                Content   = JsonConvert.SerializeObject(config)
            };
            var result = await _contract.SaveAsync(model);

            if (result <= 0)
            {
                return(DResult.Error("保存配置失败"));
            }
            NotifyConfig(module, env, config);
            return(DResult.Success);
        }
        public static DResult Exit(params CParameter[] Params)
        {
            var mes = "Exiting...";

            Environment.Exit(0);
            return(DResult.C(CDebugResult.OK, mes, Exit, ConsoleDebug.CClass, ConsoleDebug.Instance));
        }
Beispiel #15
0
        /// <summary> 路由处理 </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task RouteAsync(RouteContext context)
        {
            var requestedUrl = context.HttpContext.Request.Path.Value.Trim('/');

            if (string.IsNullOrWhiteSpace(requestedUrl))
            {
                context.Handler = async ctx => await WriteJsonAsync(ctx, Methods.Keys);

                return(Task.CompletedTask);
            }

            requestedUrl = requestedUrl.ToLower();
            //健康状态
            if (requestedUrl == "healthy")
            {
                context.Handler = async ctx => await ctx.Response.WriteAsync("ok");

                return(Task.CompletedTask);
            }

            if (!Methods.TryGetValue(requestedUrl, out var method))
            {
                context.Handler = async ctx =>
                                  await WriteJsonAsync(ctx, DResult.Error($"{requestedUrl} not found"), (int)HttpStatusCode.NotFound);

                return(Task.CompletedTask);
            }
            var instance = CurrentIocManager.Resolve(method.DeclaringType);

            context.Handler = async ctx => await Runner(ctx, instance, method);

            return(Task.CompletedTask);
        }
        public static DResult ExportPKG(params CParameter[] Params)
        {
            var folderpath = ConsoleDebug.Params[0].Value.ToString();
            var pkgname    = ConsoleDebug.Params[1].Value.ToString();

            PackageManager.Instance.Export(pkgname, folderpath);
            return(DResult.C(CDebugResult.OK, "", ExportPKG, ConsoleDebug.CClass, ConsoleDebug.Instance));
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     if (filterContext.HttpContext.Request.IsAjaxRequest())
     {
         return;
     }
     filterContext.Result = DJson.Json(DResult.Error("该方法只允许Ajax调用!"));
 }
Beispiel #18
0
 public DResult Login(string account, string password)
 {
     return(DResult.Ok(new
     {
         id = 100000,
         name = account
     }));
 }
        public static DResult PackFileInPkg(params CParameter[] Params)
        {
            var fpath   = ConsoleDebug.Params[0].Value.ToString();
            var pkgname = ConsoleDebug.Params[1].Value.ToString();
            var sp      = Source.Pack(fpath);

            PackageManager.Instance.AddToPkg(pkgname, sp);
            return(DResult.C(CDebugResult.OK, "", PackFileInPkg, ConsoleDebug.CClass, ConsoleDebug.Instance));
        }
Beispiel #20
0
 public DResult Login(string account, [Required][MinLength(15)] string password)
 {
     return(DResult.Ok(new
     {
         id = 100000,
         name = account,
         account = account
     }));
 }
        public async Task <DResult> EditProject([FromBody] VConfigProjectEditInput input)
        {
            var model = input.MapTo <TProject>();

            model.Code = ProjectCode;
            var result = await _repository.UpdateAsync(model);

            return(result > 0 ? DResult.Success : DResult.Error("保存项目失败"));
        }
Beispiel #22
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context.ActionDescriptor.EndpointMetadata.Any(t => t is AllowAnonymousAttribute))
            {
                await base.OnActionExecutionAsync(context, next);

                return;
            }

            //禁止访问
            void Forbidden()
            {
                context.Result =
                    new JsonResult(DResult.Error("Forbidden", 401))
                {
                    StatusCode = (int)HttpStatusCode.Unauthorized
                };
            }

            var httpContext = context.HttpContext;
            //方式一 参数/header
            var project = httpContext.GetProjectByCode();

            if (project != null)
            {
                if (project.Security == SecurityEnum.None)
                {
                    httpContext.SetProject(project);
                    await base.OnActionExecutionAsync(context, next);

                    return;
                }
                //获取时不需要认证
                if ((project.Security & SecurityEnum.Get) == 0)
                {
                    if (context.ActionDescriptor is ControllerActionDescriptor action &&
                        action.FilterDescriptors.Any(t => t.Filter.GetType() == typeof(AllowGetAttribute)))
                    {
                        httpContext.SetProject(project);
                        await base.OnActionExecutionAsync(context, next);

                        return;
                    }
                }
            }

            //方式二 Header
            project = httpContext.GetProjectByToken();
            if (project == null)
            {
                Forbidden();
                return;
            }
            httpContext.SetProject(project);
            await base.OnActionExecutionAsync(context, next);
        }
Beispiel #23
0
        /// <summary>
        /// 出错时结果验证。
        /// </summary>
        /// <param name="context">异常上下文。</param>
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //? 验证是否通过
            if (context.ModelState.IsValid)
            {
                return;
            }

            //? 0条错误信息
            if (context.ModelState.ErrorCount == 0)
            {
                return;
            }

            bool flag = false;

            var sb = new StringBuilder();

            foreach (ModelStateEntry entry in context.ModelState.Values)
            {
                foreach (ModelError item in entry.Errors)
                {
                    string message = item.ErrorMessage;

                    if (message.IsEmpty())
                    {
                        if (item.Exception is null)
                        {
                            continue;
                        }

                        message = item.Exception.Message;
                    }

                    if (flag)
                    {
                        sb.AppendLine();
                    }
                    else
                    {
                        flag = true;
                    }

                    sb.Append(message);
                }
            }

            int code = (int)HttpStatusCode.OK;

            context.Result = new JsonResult(DResult.Error(sb.ToString(), StatusCodes.RequestForbidden))
            {
                StatusCode = code
            };

            context.HttpContext.Response.StatusCode = code;
        }
        public static DResult UnpackFileInPkg(params CParameter[] Params)
        {
            var filename   = ConsoleDebug.Params[0].Value.ToString();
            var pkgname    = ConsoleDebug.Params[1].Value.ToString();
            var folderpath = ConsoleDebug.Params[2].Value.ToString();
            var pp         = PackageManager.Instance.GetPkg(pkgname);

            pp.Unpack(filename, folderpath);
            return(DResult.C(CDebugResult.OK, "", UnpackFileInPkg, ConsoleDebug.CClass, ConsoleDebug.Instance));
        }
 public async Task <DResult <IList <OrganizationTypeDto> > > GetRelationMasterOrganizationTypes(string TypeId)
 {
     try {
         return(DResult.Succ(businessOrganization.GetRelationMasterOrganizationTypes(TypeId)));
     }
     catch (Exception ex) {
         Logger.Error(ex.ToString());
         return(DResult.Error <IList <OrganizationTypeDto> >(ex.Message, 500));
     }
 }
Beispiel #26
0
 public DResult Register(string account, string password)
 {
     dependency.AopTest();
     return(DResult.Ok(new
     {
         id = 100000,
         name = account,
         account
     }));
 }
Beispiel #27
0
 public async Task <DResult <PagedList <UserInfoDto> > > QueryUserRelationUserByName(string UserId, string Name, int Page = 0, int Size = 0)
 {
     try
     {
         return(DResult.Succ(businessUser.QueryUserRelationUserByName(UserId, Name, Page, Size)));
     }
     catch (Exception ex) {
         Logger.Error(ex.ToString());
         return(DResult.Error <PagedList <UserInfoDto> >(ex.Message, 500));
     }
 }
        /// <summary> 执行数据库事务 </summary>
        /// <param name="action"></param>
        /// <param name="connectionName"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        protected DResult Transaction(Action <IDbConnection, IDbTransaction> action, DBConfig dBConfig = null,
                                      IsolationLevel?level = null)
        {
            var result = Transaction((conn, trans) =>
            {
                action.Invoke(conn, trans);
                return(DResult.Success);
            }, dBConfig, level);

            return(result ?? DResult.Error("事务执行失败"));
        }
Beispiel #29
0
        public DResults <TEntity> PageList(IOrderedQueryable <TEntity> ordered, DPage page)
        {
            if (ordered == null)
            {
                return(DResult.Errors <TEntity>("数据查询异常!"));
            }
            var result = ordered.Skip(page.Page * page.Size).Take(page.Size).ToList();
            var total  = ordered.Count();

            return(DResult.Succ(result, total));
        }
Beispiel #30
0
 public async Task <DResult <IList <V2UserInfoDto> > > GetV2UserInfos([FromBody] IList <string> UserIds)
 {
     try
     {
         return(DResult.Succ(businessUser.GetV2UserInfos(UserIds)));
     }
     catch (Exception ex) {
         Logger.Error(ex.ToString());
         return(DResult.Error <IList <V2UserInfoDto> >(ex.Message, 500));
     }
 }