Example #1
0
 /// <summary>
 /// 引发异常事件
 /// </summary>
 /// <param name="actionExecutedContext">操作的上下文</param>
 public override void OnException(HttpActionExecutedContext actionExecutedContext)
 {
     base.OnException(actionExecutedContext);
     var message = actionExecutedContext.Exception.Message;
     var statusCode = HttpStatusCode.OK;
     if ("404".Equals(message))
     {
         message = string.Format("未找到与请求 URI“{0}”匹配的 HTTP 资源。", actionExecutedContext.Request.RequestUri);
         statusCode = HttpStatusCode.NotFound;
     }
     else
     {
         string errorInfo = string.Format("请求URI: {0} 发生异常, 异常信息: {1}.", actionExecutedContext.Request.RequestUri, actionExecutedContext.Exception);
         Logger.Client.Error(System.Reflection.MethodBase.GetCurrentMethod(), LogDomain.Ui, null, string.Empty, errorInfo);
     }
     var newContent = new ApiResult<string>
     {
         Success = false,
         Error = message,
         DebugError = message
     };
     var contentType = actionExecutedContext.Request.Headers.Accept.ToString();
     ObjectContent content = contentType.ToLower().Contains("application/json") ? new ObjectContent<ApiResult<string>>(newContent, new JsonMediaTypeFormatter()) : new ObjectContent<ApiResult<string>>(newContent, new XmlMediaTypeFormatter());
     actionExecutedContext.Response = new HttpResponseMessage { Content = content, StatusCode = statusCode };
 }
Example #2
0
        public async Task<ApiResult> Details(int bookId)
		{
		    var book = await _bookService.Details(bookId);
            if (book == null)
                return new ApiResult
                {
                    StatusCode = 404,
                    Message = $"The book with ID {bookId} was not found."
                };

            var bookDetails = new BookDetailedResultDto();
		    var apiResult = new ApiResult
		    {
                Data = Mapper.Map(book, bookDetails)
            };

            foreach (var l in bookDetails.Loans)
            {
                var user = await _userService.Details(l.UserId);
                l.UserFullName = $"{user.Name} {user.Surname}";
                l.BookName = book.Name;
            }

		    return apiResult;

		}
 public ApiResult<GetServerInfoResult> Get(HttpRequestMessage message)
 {
     var data = new GetServerInfoResult
     {
         MachineName = Environment.MachineName,
         OperatingSystem = Environment.OSVersion.Platform.ToString(),
         Version = Environment.Version.ToString()
     };
     var result = new ApiResult<GetServerInfoResult>(data);
     return result;
 }
        public JsonResult Index([Deserialize]CommandContext commandContext, string cli, bool parseAsHtml = false)
        {
            _terminalApi.Username = User.Identity.IsAuthenticated ? User.Identity.Name : null;
            _terminalApi.IPAddress = Request.UserHostAddress;
            _terminalApi.CommandContext = commandContext;
            _terminalApi.ParseAsHtml = true;//parseAsHtml;
            var commandResult = _terminalApi.ExecuteCommand(cli);

            if (User.Identity.IsAuthenticated)
            {
                if (commandResult.CurrentUser == null)
                    FormsAuthentication.SignOut();
            }
            else
            {
                if (commandResult.CurrentUser != null)
                    FormsAuthentication.SetAuthCookie(commandResult.CurrentUser.Username, true);
            }

            var displayItems = new List<ApiDisplayItem>();
            commandResult.Display.ForEach(x => displayItems.Add(new ApiDisplayItem
            {
                Text = x.Text,
                Bold = (x.DisplayMode & DisplayMode.Bold) != 0,
                Dim = (x.DisplayMode & DisplayMode.Dim) != 0,
                DontType = (x.DisplayMode & DisplayMode.DontType) != 0,
                Inverted = (x.DisplayMode & DisplayMode.Inverted) != 0,
                Italics = (x.DisplayMode & DisplayMode.Italics) != 0,
                Mute = (x.DisplayMode & DisplayMode.Mute) != 0,
                Parse = (x.DisplayMode & DisplayMode.Parse) != 0
            }));

            var apiResult = new ApiResult
            {
                ClearScreen = commandResult.ClearScreen,
                Command = commandResult.Command,
                ContextStatus = commandResult.CommandContext.Status.ToString(),
                ContextText = commandResult.CommandContext.Command
                + (commandResult.CommandContext.Text.IsNullOrEmpty()
                ? null : string.Format(" {0}", _terminalApi.CommandContext.Text)),
                CurrentUser = commandResult.CurrentUser != null ? commandResult.CurrentUser.Username : null,
                DisplayItems = displayItems,
                EditText = commandResult.EditText,
                Exit = commandResult.Exit,
                PasswordField = commandResult.PasswordField,
                ScrollToBottom = commandResult.ScrollToBottom,
                SessionId = Session.SessionID,
                TerminalTitle = commandResult.TerminalTitle,
                CommandContext = commandResult.CommandContext.Serialize()
            };
            //string json = new JavaScriptSerializer().Serialize(apiResult);
            //return callback != null ? string.Format("{0}({1});", callback, json) : json;
            return Json(apiResult);
        }
            public override void OnException(HttpActionExecutedContext context)
            {
                if (context.Exception is DbEntityValidationException)
                {
                    var ex2 = context.Exception as DbEntityValidationException;
                    var result = new ApiResult(context.Request, 1000, ex2.DbEntityValidationExceptionToString(), null);
                    var ex = result.Execute();
                    context.Response = ex;
                }
                else
                {
                    var result = new ApiResult(context.Request, 1000, context.Exception.Message.ToString() + context.Exception.StackTrace, null);
                    var ex = result.Execute();
                    context.Response = ex;

                }
            }
        public void HandleExecutedContext(HttpActionExecutedContext ctx)
        {
            IApiResult result = new ApiResult();
            //如果有模型校验错误就返回
            if (!ctx.ActionContext.ModelState.IsValid && this.HandleModelStateValidationError(ctx.ActionContext.ModelState, out result))
            {
                ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, result);
                return;
            }

            AssociateFilter.OnActionExecuted(ctx);
            if (ctx.Exception != null && this.HandleException(ctx.Exception, out result))
            {
                ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, result);
            }
            else
            {
                if (ctx.Response.StatusCode == HttpStatusCode.Unauthorized && this.HandleUnauthorizedRequest(ctx.ActionContext, out result))
                {
                    return;
                }
                else if (ctx.Response.StatusCode != HttpStatusCode.OK && ctx.Response.StatusCode != HttpStatusCode.NoContent)
                {
                    result = new ApiResult((int)ctx.Response.StatusCode, ctx.Response.StatusCode.ToString());
                }
                else
                {
                    var cnt = ctx.ActionContext.Response.Content;
                    if (cnt != null)
                    {
                        var objCnt = (ObjectContent)cnt;
                        if (typeof(IPagedList).IsAssignableFrom(objCnt.ObjectType))
                        {
                            result = PagedApiResult.FromPagedList((IPagedList)objCnt.Value);
                        }
                        else
                            ((ApiResult)result).data = ctx.ActionContext.Response.Content.ReadAsAsync<object>().Result;
                    }
                }
            }
            ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, result);
        }
        public ApiResult<PostSessionResult> Post(PostSessionRequest model)
        {
            Contract.Requires<ArgumentNullException>(model != null);

            LogonCommand command = model.ToLogonCommand();
            LogonResult logonResult = mediator.Send(command);
            var apiResult = new ApiResult<PostSessionResult>();

            apiResult.IsSuccessful = logonResult.IsSuccessful;
            if (logonResult.IsSuccessful)
            {
                apiResult.Data.Id = logonResult.User.Id;
                apiResult.Data.SessionId = "";
                apiResult.Data.Username = logonResult.User.Username;
            }
            else
            {
                apiResult.AddError(new ErrorDef("Invalid credentials."));
            }

            return apiResult;
        }
Example #8
0
        public async Task<JsonResult> Quotes(ApiQuery q)
        {
            IQuotesService service;

            switch (q.Service)
            {
                case "Google":
                    service = new GoogleQuotesService();
                    break;
                case "Yahoo":
                    service = new YahooQuotesService();
                    break;
                default:
                    throw new Exception("Service not selected!");
            }

            var list = await service.GetHistoryAsync(q.Query, q.StartDate, q.EndDate);

            var result = new ApiResult { Quotes = list };

            return Json(result);
        }
Example #9
0
        public ActionResult Delete(int gameId)
        {
            var result = new ApiResult();

            try
            {
                var game = this.repo.GetAll().SingleOrDefault(g => g.GameId == gameId);
                if (null != game)
                {
                    game.IsActive = false;
                    this.repo.Save(game);
                }
                result.Description = "Game successfully deleted!";
                result.Success = true;
            }
            catch (Exception e)
            {
                result.Description = "Failed to delete game";
                result.Success = false;
            }

            return this.ToJson(result);
        }
Example #10
0
        public async Task<ApiResult> Details(int userId)
        {
            var user = await _userService.Details(userId);
            if (user == null)
                return new ApiResult
                {
                    StatusCode = 404,
                    Message = $"The User with ID {userId} was not found."
                };

            var userDetails = new UserDetailResultDto(); 
            var apiResult =  new ApiResult
            {
                Data = Mapper.Map(user, userDetails)
            };
            foreach (var u in userDetails.Loans)
            {
                var book = await _bookService.Details(u.BookId);
                u.BookName = book.Name;
                u.UserFullName = $"{user.Name} {user.Surname}";
            }
            return apiResult; 
        }
Example #11
0
        public ActionResult Delete(int seasonId)
        {
            var seasonRepo = new SeasonRepository();
            var result = new ApiResult();

            try
            {
                var season = seasonRepo.GetAll().SingleOrDefault(sr => sr.SeasonId == seasonId);
                if (null != season)
                {
                    season.IsActive = false;
                    seasonRepo.Save(season);
                }
                result.Description = "Season successfully deleted!";
                result.Success = true;
            }
            catch (Exception e)
            {
                result.Description = "Failed to delete season";
                result.Success = false;
            }

            return this.ToJson(result);
        }
 public ApiResult<PutTagResult> Put(PutTagRequest model)
 {
     var result = new ApiResult<PutTagResult>(false);
     result.AddError(new ErrorDef("This method has not yet been implemented."));
     return result;
 }
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        private bool HandleException(Exception exception, out ApiResult result)
        {

            if (this.ExceptionHandler != null)
            {
                result = this.ExceptionHandler.Handle(exception);
                return true;
            }
            result = null;
            return false;
        }
Example #14
0
        public ApiResult BoundPhoneNumber(string id, [FromBody] BoundPhoneNumberModel member)
        {
            Argument.ThrowIfNullOrEmpty(member.PhoneNumber, "手机号");
            Argument.ThrowIfNullOrEmpty(member.SmsVerifyCode, "手机验证码");
            Argument.ThrowIfNullOrEmpty(member.Password, "密码");

            if (!_smsService.VerifyCode(member.PhoneNumber, member.SmsVerifyCode, MemberCenterModule.Instance, SmsRequestType.BoundPhoneNumber.ToString()))
            {
                throw new WebApiInnerException("0001", "手机短信验证码验证失败");
            }

            var user = _userManager.Find(AuthorizedUser.UserName, Platform != Platform.Web ? _securityService.Decrypt(member.Password) : member.Password);

            if (user != null && user.UserType == UserType.Member)
            {
                if (user.LockoutEnabled)
                {
                    throw new WebApiInnerException("0002", "此用户已经禁止登录");
                }

                //判断是否已经存在此手机号
                var testUser = _userContainer.FindUser(member.PhoneNumber);
                if (testUser != null)
                {
                    throw new WebApiInnerException("0004", "手机号已经注册,无法绑定");
                }

                user.UserName    = member.PhoneNumber;
                user.PhoneNumber = member.PhoneNumber;

                if (!string.IsNullOrWhiteSpace(member.InvitationCode))
                {
                    var referrer = _memberService.FindMemberByInvitationCode(member.InvitationCode);
                    if (referrer != null)
                    {
                        var oldMember = _memberService.FindMemberById(id);
                        if (oldMember == null)
                        {
                            throw new WebApiInnerException("0005", "会员信息不存在");
                        }
                        oldMember.ReferrerId = referrer.Id;

                        var midentityResult = _memberService.UpdateMember(oldMember);
                        if (!midentityResult.Succeeded)
                        {
                            throw new WebApiInnerException("0006", "更新失败:" + midentityResult.Errors.FirstOrDefault());
                        }
                    }
                }
            }
            else
            {
                throw new WebApiInnerException("0003", "密码不正确");
            }

            var identityResult = _userManager.Update(user);

            if (identityResult.Succeeded)
            {
                //更新缓存
                _signals.Trigger(_userContainer.UserChangedSignalName);
                _signals.Trigger($"member_{AuthorizedUser.Id}_changed");
            }
            else
            {
                throw new WebApiInnerException("0007", "手机号绑定失败");
            }
            var result = new ApiResult();

            return(result);
        }
Example #15
0
        private ApiResult SendApi(string action, string method, NameValueCollection _parameters)
        {
            var _result = new ApiResult();
            var _uri = new Uri(String.Format("{0}/{1}",_apiUri, action));

            try
            {
                HttpWebRequest request = WebRequest.Create(_uri) as HttpWebRequest;
                request.Method = method;
                request.Timeout = 60 * 1000;
                request.ContentType = "application/x-www-form-urlencoded";

                WriteData(ref request, _parameters);
                var _responseText = GetData(request);

                _result = ApiResult.DeSerializeObject<ApiResult>(_responseText);
            }
            catch (Exception ex)
            {
                _result.Code = -1;
                _result.Message = ex.Message;
                _result.OperationResultString = ex.StackTrace;
            }

            return _result;
        }
Example #16
0
 public ApiResult GetVideo(int id)
 {
     return(ApiResult.Success(_videoService.GetById(id)));
 }
Example #17
0
        /// <summary>
        /// 添加一条数据
        /// </summary>
        /// <returns></returns>
        public async Task <ApiResult <string> > AddAsync(ErpGoodsSku parm)
        {
            var res = new ApiResult <string>()
            {
                data = "1", statusCode = 200
            };

            try
            {
                //判断是否存在
                var isExt = ErpGoodsSkuDb.IsAny(m => m.Code == parm.Code);
                if (isExt)
                {
                    res.statusCode = (int)ApiEnum.ParameterError;
                    res.message    = "该条形码已存在~";
                }
                else
                {
                    //构建Code
                    var codeType = SysCodeTypeDb.GetList(m => m.ParentGuid == "8d3158d6-e179-4046-99e9-53eb8c04ddb1").Select(m => m.Guid).ToList();
                    var codeList = SysCodeDb.GetList(m => codeType.Contains(m.ParentGuid));
                    parm.Code = codeList.Find(m => m.Guid == parm.YearGuid).CodeType + codeList.Find(m => m.Guid == parm.BrankGuid).CodeType
                                + codeList.Find(m => m.Guid == parm.SeasonGuid).CodeType
                                + codeList.Find(m => m.Guid == parm.StyleGuid).CodeType
                                + codeList.Find(m => m.Guid == parm.BatchGuid).CodeType
                                + codeList.Find(m => m.Guid == parm.SizeGuid).CodeType
                                + parm.SalePrice
                                + "-" + parm.DisPrice;

                    //构建商品标题
                    var brankName = codeList.Find(m => m.Guid == parm.BrankGuid).Name;
                    var styleName = codeList.Find(m => m.Guid == parm.StyleGuid).Name;
                    var goodsName = brankName + codeList.Find(m => m.Guid == parm.SeasonGuid).Name + styleName;

                    //构建商品信息
                    var goodsModel = new ErpGoods()
                    {
                        Guid  = Guid.NewGuid().ToString(),
                        Title = goodsName,
                        Brank = brankName,
                        Style = styleName
                    };

                    parm.GoodsGuid = goodsModel.Guid;
                    parm.Guid      = Guid.NewGuid().ToString();

                    //事务保证数据一致性
                    Db.Ado.BeginTran();
                    var goodsres = ErpGoodsDb.Insert(goodsModel);
                    if (goodsres)
                    {
                        var dbres = ErpGoodsSkuDb.Insert(parm);
                        if (!dbres)
                        {
                            res.statusCode = (int)ApiEnum.Error;
                            res.message    = "插入数据失败~";
                        }
                    }
                    Db.Ado.CommitTran();
                }
            }
            catch (Exception ex)
            {
                Db.Ado.RollbackTran();
                res.statusCode = (int)ApiEnum.Error;
                res.message    = ApiEnum.Error.GetEnumText() + ex.Message;
            }
            return(await Task.Run(() => res));
        }
Example #18
0
        public async Task <IActionResult> Post([FromBody] UnlockAccountModel model)
        {
            // Validate the request
            if (model == null)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(ApiResult.InvalidRequest()));
            }

            var result = new ApiResult();

            // Validate the model
            if (ModelState.IsValid == false)
            {
                result.AddModelStateErrors(ModelState);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(result));
            }

            // Validate the Captcha
            try
            {
                if (await ValidateRecaptcha(model.Recaptcha) == false)
                {
                    result.Errors.Add(new ApiErrorItem()
                    {
                        ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCaptcha
                    });
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem()
                {
                    ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message
                });
            }


            if (result.HasErrors)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(result));
            }

            // perform the user unlock
            try
            {
                using (var principalContext = AcquirePrincipalContext())
                {
                    var userPrincipal = AcquireUserPricipal(principalContext, model.Username);

                    // Check if the user principal exists
                    if (userPrincipal == null)
                    {
                        result.Errors.Add(new ApiErrorItem()
                        {
                            ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.UserNotFound
                        });
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return(Json(result));
                    }

                    // Check if password change is allowed
                    if (userPrincipal.UserCannotChangePassword)
                    {
                        throw new Exception(Settings.ClientSettings.Alerts.ErrorPasswordChangeNotAllowed);
                    }

                    // Validate user credentials
                    if (principalContext.ValidateCredentials(model.Username, model.CurrentPassword) == false)
                    {
                        throw new Exception(Settings.ClientSettings.Alerts.ErrorInvalidCredentials);
                    }

                    // Change the password via 2 different methods. Try SetPassword if ChangePassword fails.
                    try
                    {
                        // Try by regular ChangePassword method
                        userPrincipal.ChangePassword(model.CurrentPassword, model.NewPassword);
                    }
                    catch (Exception ex2)
                    {
                        // If the previous attempt failed, use the SetPassword method.
                        if (Settings.PasswordChangeOptions.UseAutomaticContext == false)
                        {
                            userPrincipal.SetPassword(model.NewPassword);
                        }
                        else
                        {
                            throw ex2;
                        }
                    }

                    userPrincipal.Save();
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem()
                {
                    ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message
                });
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(result));
            }

            if (result.HasErrors)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }

            return(Json(result));
        }
Example #19
0
        public async Task<IActionResult> Post([FromBody]ChangePasswordModel model)
        {

            // Validate the request
            if (model == null)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(ApiResult.InvalidRequest());
            }

            var result = new ApiResult();

            // Validate the model
            if (ModelState.IsValid == false)
            {
                result.AddModelStateErrors(ModelState);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(result);
            }

            // Validate the Captcha
            try
            {
                if (await ValidateRecaptcha(model.Recaptcha) == false)
                    result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCaptcha });
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message });
            }


            if (result.HasErrors)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(result);
            }

            // perform the password change
            try
            {
                using (var principalContext = AcquirePrincipalContext())
                {
                    var userPrincipal = AcquireUserPricipal(principalContext, model.Username);

                    // Check if the user principal exists
                    if (userPrincipal == null)
                    {
                        result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.UserNotFound });
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return Json(result);
                    }
                    
                    // Check if password change is allowed
                    if (userPrincipal.UserCannotChangePassword)
                    {
                        throw new Exception(Settings.ClientSettings.Alerts.ErrorPasswordChangeNotAllowed);
                    }

                    // Validate user credentials
                    if (principalContext.ValidateCredentials(model.Username, model.CurrentPassword) == false)
                    {
                        throw new Exception(Settings.ClientSettings.Alerts.ErrorInvalidCredentials);
                    }

                    // Change the password via 2 different methods. Try SetPassword if ChangePassword fails.
                    try
                    {
                        // Try by regular ChangePassword method
                        userPrincipal.ChangePassword(model.CurrentPassword, model.NewPassword);
                    }
                    catch (Exception ex2)
                    {
                        // If the previous attempt failed, use the SetPassword method.
                        if (Settings.PasswordChangeOptions.UseAutomaticContext == false)
                            userPrincipal.SetPassword(model.NewPassword);
                        else
                            throw ex2;
                    }

                    userPrincipal.Save();

                }

            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message });
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(result);
            }

            if (result.HasErrors)
                Response.StatusCode = (int)HttpStatusCode.BadRequest;

            return Json(result);

        }
Example #20
0
        public ApiResult GetTemplate(string group,
                                     string libId,
                                     string subject)
        {
            ApiResult result = new ApiResult();
            //result.info = "test";


            LibEntity lib = dp2WeiXinService.Instance.GetLibById(libId);

            if (lib == null)
            {
                result.errorCode = -1;
                result.errorInfo = "未找到id为'" + libId + "'的图书馆";
                return(result);
            }


            string file = dp2WeiXinService.Instance._weiXinDataDir
                          + "/lib/" + "template"//lib.capoUserName
                          + "/home/"
                          + subject + ".txt";

            // 文件存在,取出文件 的内容
            string text     = "";
            string strError = "";

            if (System.IO.File.Exists(file) == true)
            {
                Encoding encoding;
                // 能自动识别文件内容的编码方式的读入文本文件内容模块
                // parameters:
                //      lMaxLength  装入的最大长度。如果超过,则超过的部分不装入。如果为-1,表示不限制装入长度
                // return:
                //      -1  出错 strError中有返回值
                //      0   文件不存在 strError中有返回值
                //      1   文件存在
                //      2   读入的内容不是全部
                int nRet = FileUtil.ReadTextFileContent(file,
                                                        -1,
                                                        out text,
                                                        out encoding,
                                                        out strError);
                if (nRet == -1 || nRet == 0)
                {
                    goto ERROR1;
                }
                if (nRet == 2)
                {
                    strError = "FileUtil.ReadTextFileContent() error";
                    goto ERROR1;
                }

                result.info = text;
            }


            return(result);

ERROR1:
            result.errorInfo = strError;
            result.errorCode = -1;
            return(result);
        }
        public static HttpResponseMessage ApiResult <T>(this ApiController controller, ApiReturnCode code, T returnObject)
        {
            var result = new ApiResult <T>(code, returnObject);

            return(ApiResultT(controller, result));
        }
Example #22
0
        public string ToUser()
        {
            ApiResult result = new ApiResult();

            try
            {
                var UserNumber = ZNRequest.GetString("UserNumber");
                if (string.IsNullOrWhiteSpace(UserNumber))
                {
                    result.message = "参数异常";
                    return(JsonConvert.SerializeObject(result));
                }
                var pager       = new Pager();
                var query       = new SubSonic.Query.Select(provider).From <ArticleZan>().Where <ArticleZan>(x => x.CreateUserNumber == UserNumber);
                var recordCount = query.GetRecordCount();
                if (recordCount == 0)
                {
                    result.message = new { records = recordCount, totalpage = 1 };
                    return(JsonConvert.SerializeObject(result));
                }

                var totalPage = recordCount % pager.Size == 0 ? recordCount / pager.Size : recordCount / pager.Size + 1;
                var list      = query.Paged(pager.Index, pager.Size).OrderDesc("ID").ExecuteTypedList <ArticleZan>();

                var articles = new SubSonic.Query.Select(provider, "ID", "Number", "Cover", "ArticlePower", "CreateUserNumber", "Status", "Title").From <Article>().Where("Number").In(list.Select(x => x.ArticleNumber).ToArray()).ExecuteTypedList <Article>();
                var users    = new SubSonic.Query.Select(provider, "ID", "NickName", "Avatar", "Number", "Cover").From <User>().Where("Number").In(list.Select(x => x.ArticleUserNumber).ToArray()).ExecuteTypedList <User>();

                List <ZanJson> newlist = new List <ZanJson>();
                list.ForEach(x =>
                {
                    var article = articles.FirstOrDefault(y => y.Number == x.ArticleNumber);
                    var user    = users.FirstOrDefault(y => y.Number == x.ArticleUserNumber);
                    if (article != null && user != null)
                    {
                        ZanJson model          = new ZanJson();
                        model.ID               = x.ID;
                        model.CreateDate       = x.CreateDate.ToString("yyyy-MM-dd");
                        model.ArticleID        = article.ID;
                        model.Title            = article.Title;
                        model.Number           = article.Number;
                        model.Cover            = article.Cover;
                        model.ArticlePower     = article.ArticlePower;
                        model.CreateUserNumber = article.CreateUserNumber;
                        model.NickName         = user.NickName;
                        model.Avatar           = user.Avatar;
                        model.UserNumber       = user.Number;
                        model.UserCover        = user.Cover;
                        newlist.Add(model);
                    }
                });
                result.result  = true;
                result.message = new
                {
                    currpage  = pager.Index,
                    records   = recordCount,
                    totalpage = totalPage,
                    list      = newlist
                };
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLoger.Error("Api_Zan_ToUser:" + ex.Message);
                result.message = ex.Message;
            }
            return(JsonConvert.SerializeObject(result));
        }
Example #23
0
        public string Edit()
        {
            ApiResult result = new ApiResult();

            try
            {
                User user = GetUserInfo();
                if (user == null)
                {
                    result.message = EnumBase.GetDescription(typeof(Enum_ErrorCode), Enum_ErrorCode.UnLogin);
                    result.code    = Enum_ErrorCode.UnLogin;
                    return(JsonConvert.SerializeObject(result));
                }
                var articleID = ZNRequest.GetInt("ArticleID");
                if (articleID <= 0)
                {
                    result.message = "参数异常";
                    return(JsonConvert.SerializeObject(result));
                }
                Article article = new SubSonic.Query.Select(provider, "ID", "CreateUserNumber", "Goods", "Number").From <Article>().Where <Article>(x => x.ID == articleID).ExecuteSingle <Article>();
                if (article == null)
                {
                    result.message = "文章信息异常";
                    return(JsonConvert.SerializeObject(result));
                }

                //判断是否拉黑
                var black = db.Exists <Black>(x => x.CreateUserNumber == article.CreateUserNumber && x.ToUserNumber == user.Number);
                if (black)
                {
                    result.code    = Enum_ErrorCode.NoPower;
                    result.message = "没有权限";
                    return(JsonConvert.SerializeObject(result));
                }

                var success = 0;
                var model   = db.Single <ArticleZan>(x => x.CreateUserNumber == user.Number && x.ArticleNumber == article.Number);
                var goods   = model == null ? article.Goods + 1 : article.Goods - 1;

                //是否新增
                var isadd = model == null ? 0 : 1;
                if (model == null)
                {
                    model                   = new ArticleZan();
                    model.CreateDate        = DateTime.Now;
                    model.CreateUserNumber  = user.Number;
                    model.CreateIP          = Tools.GetClientIP;
                    model.ArticleNumber     = article.Number;
                    model.ArticleUserNumber = article.CreateUserNumber;
                    success                 = Tools.SafeInt(db.Add <ArticleZan>(model));

                    //操作记录
                    var now    = DateTime.Now.ToString("yyyy-MM-dd");
                    var action = db.Single <UserAction>(x => x.CreateUserNumber == user.Number && x.CreateTimeText == now && x.ActionType == Enum_ActionType.Like);

                    LogHelper.ErrorLoger.Error(JsonConvert.SerializeObject(action));

                    if (action == null)
                    {
                        action = new UserAction();
                        action.CreateUserNumber = user.Number;
                        action.ActionType       = Enum_ActionType.Like;
                        action.CreateTime       = DateTime.Now;
                        action.CreateTimeText   = now;
                        action.ActionInfo       = article.Number;
                        db.Add <UserAction>(action);
                    }
                    else
                    {
                        if (!action.ActionInfo.Contains(article.Number))
                        {
                            action.ActionInfo += "," + article.Number;
                            db.Update <UserAction>(action);
                        }
                    }
                }
                else
                {
                    success = db.Delete <ArticleZan>(model.ID);
                }
                if (success > 0)
                {
                    if (goods < 0)
                    {
                        goods = 0;
                    }
                    new SubSonic.Query.Update <Article>(provider).Set("Goods").EqualTo(goods).Where <Article>(x => x.ID == articleID).Execute();
                    result.result  = true;
                    result.message = isadd + "|" + goods;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLoger.Error("Api_Zan_ArticleZanEdit" + ex.Message);
                result.message = ex.Message;
            }
            return(JsonConvert.SerializeObject(result));
        }
Example #24
0
        public string CommentZanEdit()
        {
            ApiResult result = new ApiResult();

            try
            {
                User user = GetUserInfo();
                if (user == null)
                {
                    result.message = EnumBase.GetDescription(typeof(Enum_ErrorCode), Enum_ErrorCode.UnLogin);
                    result.code    = Enum_ErrorCode.UnLogin;
                    return(JsonConvert.SerializeObject(result));
                }
                var number = ZNRequest.GetString("CommentNumber");
                if (string.IsNullOrWhiteSpace(number))
                {
                    result.message = "评论信息异常";
                    return(JsonConvert.SerializeObject(result));
                }

                Comment comment = new SubSonic.Query.Select(provider, "ID", "CreateUserNumber", "Goods", "Number").From <Comment>().Where <Comment>(x => x.Number == number).ExecuteSingle <Comment>();
                if (comment == null)
                {
                    result.message = "评论信息异常";
                    return(JsonConvert.SerializeObject(result));
                }

                //判断是否拉黑
                var black = db.Exists <Black>(x => x.CreateUserNumber == comment.CreateUserNumber && x.ToUserNumber == user.Number);
                if (black)
                {
                    result.code    = Enum_ErrorCode.NoPower;
                    result.message = "没有权限";
                    return(JsonConvert.SerializeObject(result));
                }
                var success = 0;
                var model   = db.Single <CommentZan>(x => x.CreateUserNumber == user.Number && x.CommentNumber == number);
                var goods   = model == null ? comment.Goods + 1 : comment.Goods - 1;

                //是否新增
                var isadd = model == null ? 0 : 1;
                if (model == null)
                {
                    model                  = new CommentZan();
                    model.CreateDate       = DateTime.Now;
                    model.CreateUserNumber = user.Number;
                    model.CreateIP         = Tools.GetClientIP;
                    model.CommentNumber    = number;
                    success                = Tools.SafeInt(db.Add <CommentZan>(model));
                }
                else
                {
                    success = db.Delete <CommentZan>(model.ID);
                }
                if (success > 0)
                {
                    if (goods < 0)
                    {
                        goods = 0;
                    }
                    new SubSonic.Query.Update <Comment>(provider).Set("Goods").EqualTo(goods).Where <Comment>(x => x.ID == comment.ID).Execute();
                    result.result  = true;
                    result.message = isadd + "|" + goods;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLoger.Error("Api_Zan_CommentZanEdit" + ex.Message);
                result.message = ex.Message;
            }
            return(JsonConvert.SerializeObject(result));
        }
 /// <summary>
 /// 处理未登录的请求
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="result"></param>
 /// <returns></returns>
 private bool HandleUnauthorizedRequest(HttpActionContext ctx, out ApiResult result)
 {
     if (this.UnauthorizedRequestHandler != null)
     {
         result = this.UnauthorizedRequestHandler.Handle(ctx);
         return true;
     }
     result = null;
     return false;
 }
Example #26
0
        /// <summary>
        /// An example of one strategy for placing a trade.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="callback"></param>
        public void PlaceTradeAsync(NewTradeOrderRequestDTO request, TradeOrderResponseDelegate callback)
        {


            RpcClient.TradesAndOrders.BeginTrade(request, (ar) =>
                {
                    var result = new ApiResult<ApiTradeOrderResponseDTO>();

                    try
                    {
                        result.Data = RpcClient.TradesAndOrders.EndTrade(ar);

                        // resolve the magic numbers so that we have readable values for status codes
                        RpcClient.MagicNumberResolver.ResolveMagicNumbers(result.Data);

                    }
                    catch (Exception ex)
                    {
                        result.Exception = ex;
                    }


                    // to avoid deadlocks that can occur when an async call is made within the callback of another async callback
                    // we will fire the callback on a new thread.

                    new Thread(() => callback(result)).Start();

                    // NOTE: the deadlock is a result of locking on the request queue and cache in JsonClient and is the price paid
                    // for that functionality. 
                    
                    // TODO: (in JsonClient) find out how to determine if an object is being locked on and throw exception if this is so.

                    

                }, null);

        } 
Example #27
0
        public ApiResult Create([FromBody] MemberRegisterModel member)
        {
            Argument.ThrowIfNullOrEmpty(member.PhoneNumber, "手机号码");
            Argument.ThrowIfNullOrEmpty(member.Password, "密码");
            //Argument.ThrowIfNullOrEmpty(member.NickName, "昵称");
            Argument.ThrowIfNullOrEmpty(member.SmsVerifyCode, "短信验证码");

            var result = new ApiResult();

            User user = _memberService.FindUserByName(member.PhoneNumber);

            if (user != null)
            {
                throw new WebApiInnerException("0001", "此手机号已经注册");
            }

            //if (_memberService.NickNameIsExists(member.NickName)) throw new WebApiInnerException("0003", "昵称已经被占用");


            if (!_smsService.VerifyCode(member.PhoneNumber, member.SmsVerifyCode, MemberCenterModule.Instance, SmsRequestType.Register.ToString()))
            {
                throw new WebApiInnerException("0002", "短信验证码验证失败");
            }

            string referrerId = null;
            string parentIds  = null;

            if (!string.IsNullOrWhiteSpace(member.InvitationCode))
            {
                var referrer = _memberService.FindMemberByInvitationCode(member.InvitationCode);
                if (referrer != null && referrer.MemberType == MemberType.Partner)
                {
                    referrerId = referrer.Id;
                    if (string.IsNullOrWhiteSpace(referrer.ParentIds))
                    {
                        parentIds = referrer.Id;
                    }
                    else
                    {
                        var maxLevel = _configService.Get <SystemConfig>().MaxLevel;
                        var ids      = referrer.ParentIds.Split(',');
                        if (ids.Count() >= maxLevel)
                        {
                            //只取系统设置的层级数量
                            parentIds = "";
                            for (int i = maxLevel - 3; i < ids.Count(); i++)
                            {
                                if (string.IsNullOrWhiteSpace(parentIds))
                                {
                                    parentIds = ids[i];
                                }
                                else
                                {
                                    parentIds += "," + ids[i];
                                }
                            }

                            parentIds += "," + referrer.Id;
                        }
                        else
                        {
                            parentIds = referrer.ParentIds + "," + referrer.Id;
                        }
                    }
                }
            }

            var code = KeyGenerator.GenerateRandom(6);

            while (_memberService.FindMemberByInvitationCode(code) != null)
            {
                code = KeyGenerator.GenerateRandom(6);
            }

            var newMember = new Member
            {
                UserName       = member.PhoneNumber,
                PhoneNumber    = member.PhoneNumber,
                LockoutEnabled = false,
                Sex            = SexType.UnKonw,
                NickName       = member.PhoneNumber,
                Birthday       = DateTime.Parse("1949-10-1"),
                ChannelId      = member.ChannelId,
                ReferrerId     = referrerId,
                ParentIds      = parentIds,
                CreateTime     = DateTime.Now,
                InvitationCode = code
            };

            using (TransactionScope scope = new TransactionScope())
            {
                var identityResult = _memberService.CreateMember(newMember, member.Password);

                if (!identityResult.Succeeded)
                {
                    throw new WebApiInnerException("0003", identityResult.Errors.FirstOrDefault());
                    //result.msg = identityResult.Errors.FirstOrDefault();
                }
                else
                {
                    //添加推广积分
                    if (!string.IsNullOrWhiteSpace(newMember.ReferrerId))
                    {
                        var    systemConfig = _configService.Get <SystemConfig>();
                        string error;
                        _walletService.Deposit(newMember.ReferrerId, Wallet.Models.WalletType.Integral, systemConfig.RecommendIntegral, "推荐新用户奖励", out error);
                    }

                    //绑定微信
                    if (!string.IsNullOrWhiteSpace(member.OpenId))
                    {
                        _currencyService.DeleteByConditon <UserOAuth>(uo => uo.OAuthType == OAuthType.WeiXin && uo.OAuthId.Equals(member.OpenId, StringComparison.OrdinalIgnoreCase));

                        _currencyService.Create(new UserOAuth()
                        {
                            Id        = KeyGenerator.GetGuidKey(),
                            MemberId  = newMember.Id,
                            OAuthId   = member.OpenId,
                            OAuthType = OAuthType.WeiXin
                        });
                    }

#if DEBUG
                    //添加测试余额
                    string errorMessage;
                    _walletService.Deposit(newMember.Id, Wallet.Models.WalletType.Cash, 100000, "测试现金", out errorMessage);
                    _walletService.Deposit(newMember.Id, Wallet.Models.WalletType.Integral, 100000, "测试积分", out errorMessage);
#endif
                    var createdMember = _memberService.FindMemberById(newMember.Id);
                    result.SetData(createdMember.Simplified());
                    //提交
                    scope.Complete();
                }
            }

            return(result);
        }
        /// <summary>
        /// 添加一个任务
        /// </summary>
        /// <returns></returns>
        public async Task <ApiResult <string> > Add(ScheduleEntity entity)
        {
            var result = new ApiResult <string>()
            {
                statusCode = (int)ApiEnum.Error
            };

            try
            {
                //检查任务是否已存在
                var jobKey = new JobKey(entity.JobName, entity.JobGroup);
                if (await Scheduler.CheckExists(jobKey))
                {
                    result.message = "任务已存在";
                    return(result);
                }
                //http请求配置
                var httpDir = new Dictionary <string, string>()
                {
                    { "RequestUrl", entity.RequestUrl },
                    { "RequestParameters", entity.RequestParameters },
                    { "RequestType", ((int)entity.RequestType).ToString() },
                    { Constant.HEADERS, entity.Headers },
                    { Constant.MAILMESSAGE, ((int)entity.MailMessage).ToString() },
                };
                // 定义这个工作,并将其绑定到我们的IJob实现类
                IJobDetail job = JobBuilder.CreateForAsync <HttpJob>()
                                 .SetJobData(new JobDataMap(httpDir))
                                 .WithDescription(entity.Description)
                                 .WithIdentity(entity.JobName, entity.JobGroup)
                                 .Build();
                // 创建触发器
                ITrigger trigger;
                //校验是否正确的执行周期表达式
                if (entity.TriggerType == TriggerTypeEnum.Cron)//CronExpression.IsValidExpression(entity.Cron))
                {
                    trigger = CreateCronTrigger(entity);
                }
                else
                {
                    trigger = CreateSimpleTrigger(entity);
                }

                // 告诉Quartz使用我们的触发器来安排作业
                await Scheduler.ScheduleJob(job, trigger);

                //将作业增加到Redis里面
                var redisTask = RedisHelper.Get <List <ScheduleEntity> >(KeyHelper.TaskSchedulerList);
                if (redisTask == null)
                {
                    //实例数组
                    redisTask = new List <ScheduleEntity>();
                }
                if (!redisTask.Any(m => m.JobId == entity.JobId))
                {
                    entity.JobId = Utils.GetOrderNumber();
                    redisTask.Add(entity);
                    //保存到Redis中
                    RedisHelper.Set(KeyHelper.TaskSchedulerList, redisTask);
                }
                result.statusCode = (int)ApiEnum.Status;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
            }
            return(result);
        }
Example #29
0
        public ApiResult <string> Login(SysAdminLogin parm)
        {
            var apiRes = new ApiResult <string>()
            {
                statusCode = (int)ApiEnum.HttpRequestError
            };
            var token = "";

            try
            {
                //获得公钥私钥,解密
                var rsaKey = MemoryCacheService.Default.GetCache <List <string> >("LOGINKEY");
                if (rsaKey == null)
                {
                    apiRes.message = "登录失败,请刷新浏览器再次登录";
                    return(apiRes);
                }
                //Ras解密密码
                var ras = new RSACrypt(rsaKey[0], rsaKey[1]);
                parm.password = ras.Decrypt(parm.password);

                //获得用户登录限制次数
                var configLoginCount = Convert.ToInt32(ConfigExtensions.Configuration[KeyHelper.LOGINCOUNT]);
                //获得登录次数和过期时间
                var loginConfig = MemoryCacheService.Default.GetCache <SysAdminLoginConfig>(KeyHelper.LOGINCOUNT) ?? new SysAdminLoginConfig();
                if (loginConfig.Count != 0 && loginConfig.DelayMinute != null)
                {
                    //说明存在过期时间,需要判断
                    if (DateTime.Now <= loginConfig.DelayMinute)
                    {
                        apiRes.message = "您的登录以超过设定次数,请稍后再次登录~";
                        return(apiRes);
                    }
                    else
                    {
                        //已经过了登录的预设时间,重置登录配置参数
                        loginConfig.Count       = 0;
                        loginConfig.DelayMinute = null;
                    }
                }
                //查询登录结果
                var dbres = _adminService.LoginAsync(parm).Result;
                if (dbres.statusCode != 200)
                {
                    //增加登录次数
                    loginConfig.Count += 1;
                    //登录的次数大于配置的次数,则提示过期时间
                    if (loginConfig.Count == configLoginCount)
                    {
                        var configDelayMinute = Convert.ToInt32(ConfigExtensions.Configuration[KeyHelper.LOGINDELAYMINUTE]);
                        //记录过期时间
                        loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute);
                        apiRes.message          = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录";
                        return(apiRes);
                    }
                    //记录登录次数,保存到session
                    MemoryCacheService.Default.SetCache(KeyHelper.LOGINCOUNT, loginConfig);
                    //提示用户错误和登录次数信息
                    apiRes.message = dbres.message + "  您还剩余" + (configLoginCount - loginConfig.Count) + "登录次数";
                    return(apiRes);
                }

                var user     = dbres.data.admin;
                var identity = new ClaimsPrincipal(
                    new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Sid, user.Guid),
                    new Claim(ClaimTypes.Role, user.DepartmentName),
                    new Claim(ClaimTypes.Thumbprint, user.HeadPic),
                    new Claim(ClaimTypes.Name, user.LoginName),
                    new Claim(ClaimTypes.WindowsAccountName, user.LoginName),
                    new Claim(ClaimTypes.UserData, user.UpLoginDate.ToString())
                }, CookieAuthenticationDefaults.AuthenticationScheme)
                    );
                //如果保存用户类型是Session,则默认设置cookie退出浏览器 清空
                if (ConfigExtensions.Configuration[KeyHelper.LOGINSAVEUSER] == "Session")
                {
                    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties
                    {
                        AllowRefresh = false
                    });
                }
                else
                {
                    //根据配置保存浏览器用户信息,小时单位
                    var hours = int.Parse(ConfigExtensions.Configuration[KeyHelper.LOGINCOOKIEEXPIRES]);
                    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddHours(hours),
                        IsPersistent = true,
                        AllowRefresh = false
                    });
                }

                //把权限存到缓存里
                var menuSaveType = ConfigExtensions.Configuration[KeyHelper.LOGINAUTHORIZE];
                if (menuSaveType == "Redis")
                {
                    RedisHelper.Set(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu);
                    //RedisCacheService.Default.SetCache(KeyHelper.ADMINMENU, dbres.data.menu, 600);
                }
                else
                {
                    MemoryCacheService.Default.SetCache(KeyHelper.ADMINMENU, dbres.data.menu, 600);
                }
                token = JwtHelper.IssueJWT(new TokenModel()
                {
                    Uid       = user.Guid,
                    UserName  = user.LoginName,
                    Role      = "Admin",
                    Project   = "Manage",
                    TokenType = "Web"
                });
                MemoryCacheService.Default.RemoveCache("LOGINKEY");
                MemoryCacheService.Default.RemoveCache(KeyHelper.LOGINCOUNT);

                #region 保存日志
                var agent = HttpContext.Request.Headers["User-Agent"];
                var log   = new SysLog()
                {
                    Guid     = Guid.NewGuid().ToString(),
                    Logged   = DateTime.Now,
                    Logger   = LogEnum.LOGIN.GetEnumText(),
                    Level    = "Info",
                    Message  = "登录",
                    Callsite = "/fytadmin/login",
                    IP       = Utils.GetIp(),
                    User     = parm.loginname,
                    Browser  = agent.ToString()
                };
                _logService.AddAsync(log);
                #endregion
            }
            catch (Exception ex)
            {
                apiRes.message    = ex.Message;
                apiRes.statusCode = (int)ApiEnum.Error;

                #region 保存日志
                var agent = HttpContext.Request.Headers["User-Agent"];
                var log   = new SysLog()
                {
                    Guid      = Guid.NewGuid().ToString(),
                    Logged    = DateTime.Now,
                    Logger    = LogEnum.LOGIN.GetEnumText(),
                    Level     = "Error",
                    Message   = "登录失败!" + ex.Message,
                    Exception = ex.Message,
                    Callsite  = "/fytadmin/login",
                    IP        = Utils.GetIp(),
                    User      = parm.loginname,
                    Browser   = agent.ToString()
                };
                _logService.AddAsync(log);
                #endregion
            }
            apiRes.statusCode = (int)ApiEnum.Status;
            apiRes.data       = token;
            return(apiRes);
        }
Example #30
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public Task <string> Handle()
        {
            var rlt = Task.Run <string>(() => { return(""); });

            Result = new ApiResult <IResponse> {
                node = XCore.WebNode, code = "-1", success = false, message = "unkown error"
            };
            if (string.IsNullOrEmpty(ApiHost))
            {
                Result.code    = "400";
                Result.message = "request host not set";
            }
            else if (string.IsNullOrEmpty(ApiPath))
            {
                Result.code    = "400";
                Result.message = "request path not set";
            }
            else
            {
                System.Net.Http.HttpClient http = null;
                Task <System.Net.Http.HttpResponseMessage> task = null;
                if (Certificate == null)
                {
                    http = new System.Net.Http.HttpClient();
                }
                else
                {
                    var handler = new System.Net.Http.HttpClientHandler();
                    handler.ClientCertificateOptions = System.Net.Http.ClientCertificateOption.Manual;
                    handler.SslProtocols             = System.Security.Authentication.SslProtocols.Tls12;
                    handler.ClientCertificates.Add(Certificate);
                    http = new System.Net.Http.HttpClient(handler);
                }
                http.BaseAddress = new System.Uri(ApiHost);
                if (Method == "GET")
                {
                    var query = RequestBody as string;
                    if (!string.IsNullOrEmpty(query))
                    {
                        var link = ApiPath.IndexOf('?') < 0 ? '?' : '&';
                        ApiPath += query[0] == '?' || query[0] == '&' ? query : link + query;
                    }
                    if (HttpRequestHeaders != null)
                    {
                        foreach (var kv in HttpRequestHeaders)
                        {
                            http.DefaultRequestHeaders.Add(kv.Key, kv.Value);
                        }
                    }
                    task = http.GetAsync(ApiPath);
                }
                else
                {
                    System.Net.Http.HttpContent content = null;
                    var text  = RequestBody as string;
                    var bytes = RequestBody as byte[];
                    if (bytes != null)
                    {
                        content = new System.Net.Http.ByteArrayContent(bytes);
                    }
                    else if (!string.IsNullOrEmpty(text))
                    {
                        content = new System.Net.Http.StringContent(text, Encoding, ContentType);
                    }
                    else if (RequestBody != null)
                    {
                        content = new System.Net.Http.StringContent(Json.ToString(RequestBody), Encoding, ContentType);
                    }
                    else
                    {
                        content = new System.Net.Http.ByteArrayContent(new byte[0]);
                    }
                    if (HttpRequestHeaders != null)
                    {
                        foreach (var kv in HttpRequestHeaders)
                        {
                            content.Headers.Add(kv.Key, kv.Value);
                        }
                    }
                    task = http.PostAsync(ApiPath, content);
                }

                task.Result.Content.ReadAsStringAsync().ContinueWith((res) =>
                {
                    ResponseBody        = res.Result;
                    HttpResponseHeaders = new Dictionary <string, string>();
                    foreach (var item in task.Result.Headers)
                    {
                        var em = item.Value.GetEnumerator();
                        if (em.MoveNext())
                        {
                            HttpResponseHeaders.Add(item.Key.ToLower(), em.Current);
                        }
                    }
                    rlt = Task.Run <string>(() => { return(res.Result); });
                }).Wait();
            }
            return(rlt);
        }
Example #31
0
 /// <summary>
 /// 序列化到错误内容
 /// </summary>
 /// <param name="code"></param>
 /// <param name="message"></param>
 /// <param name="message2"></param>
 /// <returns></returns>
 private string ToErrorString(int code, string message, string message2 = null)
 {
     LogRecorder.MonitorTrace($"调用异常:{message}");
     return(JsonConvert.SerializeObject(ApiResult.Error(code, _url + message, message2)));
 }
        public override Task Invoke(IOwinContext context)
        {
            var req = context.Request;
            var rep = context.Response;

            var nodePath = GetNodePath(req.Path.Value);

            if (!string.IsNullOrEmpty(nodePath))
            {
                var currentNode = NodeManager.Instance.GetNode(nodePath);
                var nodeMethod  = currentNode?.GetMethod(req.Method);
                if (nodeMethod == null)
                {
                    return(Next.Invoke(context));
                }

                Object data = null;
                try
                {
                    //调用方法处理
                    if (NodeManager.Instance.MethodInvokeHandler != null)
                    {
                        nodeMethod = NodeManager.Instance.MethodInvokeHandler.Invoke(nodeMethod, context);
                    }
                    //调用
                    var invokeTime = DateTime.Now;
                    data = nodeMethod?.Invoke(context);
                    //返回值处理
                    if (NodeManager.Instance.ReturnValueHandler != null)
                    {
                        data = NodeManager.Instance.ReturnValueHandler.Invoke(nodeMethod, data, invokeTime);
                    }
                    //如果返回值不是ApiResult
                    if (!(data is ApiResult))
                    {
                        var message = $"{nodeMethod.Name}成功";
                        var ret     = ApiResult.Success(message, data);
                        ret.SetMetaInfo("usedTime", (DateTime.Now - invokeTime).ToString());
                        data = ret;
                    }
                }
                catch (NodeMethodException ex)
                {
                    data = ApiResult.Error(ex.HResult, ex.Message, ex.MethodData);
                }
                catch (AppDomainUnloadedException ex)
                    when(ex.InnerException is NodeMethodHandledException)
                    {
                        return(Task.Delay(0));
                    }
                catch (Exception ex)
                {
                    if (NodeManager.Instance.ExceptionHandler == null)
                    {
                        throw ex;
                    }
                    data = NodeManager.Instance.ExceptionHandler.Invoke(ex);
                }
                //要输出的内容
                string result = null;
                //JSON序列化的结果
                var json          = JsonConvert.SerializeObject(data, NodeManager.Instance.JsonSerializerSettings);
                var jsonpCallback = req.Query[JSONP_CALLBACK];

                if (string.IsNullOrEmpty(jsonpCallback))
                {
                    rep.ContentType = "application/json; charset=UTF-8";
                    result          = json;
                }
                else
                {
                    rep.ContentType = "application/x-javascript";
                    result          = $"{jsonpCallback}({json})";
                }
                rep.Expires = new DateTimeOffset(DateTime.Now);
                rep.Headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
                rep.Headers["Pragma"]        = "no-cache";
                //添加额外的HTTP头
                if (AddonHttpHeaders != null && AddonHttpHeaders.Count > 0)
                {
                    foreach (var header in AddonHttpHeaders)
                    {
                        context.Response.Headers[header.Key] = header.Value;
                    }
                }

                return(context.Output(encoding.GetBytes(result), true));
            }
            return(Next.Invoke(context));
        }
        public static HttpResponseMessage ApiResult(this ApiController controller, ApiReturnCode code, string message)
        {
            var result = new ApiResult(code, message);

            return(ApiResult(controller, result));
        }
Example #34
0
        /// <summary>
        /// 登陆处理
        /// </summary>
        private void btn_Login_Click(object sender, RoutedEventArgs e)
        {
            string name     = txt_UserName.Text.Trim( );
            string password = txt_Password.Password.Trim( );

            if (name.Length == 0)
            {
                MessageBox.Show("用户名不能为空");
                return;
            }
            if (password.Length == 0)
            {
                MessageBox.Show("登陆密码不能为空");
                return;
            }
            //开始登陆
            this.LoadingText = "登陆中";
            this.ProgressIndicatorIsVisible = true;
            Dictionary <string, object> parameters = new Dictionary <string, object>
            {
                { "username", name },
                { "pwd", password },
                { "keep_login", "1" },
            };
            PostClient client = Tool.SendPostClient(Config.api_login_validate, parameters);

            client.DownloadStringCompleted += (s, e1) =>
            {
                this.ProgressIndicatorIsVisible = false;
                if (e1.Error != null)
                {
                    System.Diagnostics.Debug.WriteLine("登陆时网络错误: {0}", e1.Error.Message);
                    return;
                }
                else
                {
                    MyInfo    myInfo;
                    ApiResult result = Tool.GetLoginResult(e1.Result, out myInfo);
                    if (result != null)
                    {
                        switch (result.errorCode)
                        {
                        case 1:
                            if (( bool )check_RememberMe.IsChecked == true)
                            {
                                Config.LoginName = txt_UserName.Text.Trim( );
                                Config.Password  = txt_Password.Password.Trim( );
                            }
                            else
                            {
                                Config.LoginName = Config.Password = null;
                            }
                            Config.UID    = myInfo.uid;
                            Config.MyInfo = myInfo;
                            EventSingleton.Instance.RaiseLoginOrLogout( );
                            //登陆成功后可能需要回退
                            if (this.isNeedBack && this.NavigationService.CanGoBack)
                            {
                                this.NavigationService.GoBack( );
                            }
                            break;

                        case 0:
                        case -1:
                        case -2:
                            MessageBox.Show((result.errorMessage).TrimEnd('\n', '\t'), "登陆失败", MessageBoxButton.OK);
                            break;
                        }
                    }
                }
            };
        }
 public static HttpResponseMessage ApiResultT <T>(this ApiController controller, ApiResult <T> result)
 {
     if (controller.Request != null)
     {
         return(controller.Request.CreateResponse(HttpStatusCode.OK, result));
     }
     else
     {
         StringContent content = new StringContent(JsonConvert.SerializeObject(result));//接收:response.Content.ReadAsStringAsync().Result;
         //StringContent content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "text/json");
         HttpResponseMessage response = new HttpResponseMessage()
         {
             Content = content
         };
         return(response);
     }
 }
Example #36
0
 public override void AfterHandle <TRequest>(InspectContext <TRequest> inspectCxt, ApiResult result)
 {
 }
        public ActionResult <ApiResult> GetAll(string source, string target)
        {
            ApiResult apiResult = new ApiResult();

            return(Ok(this.shareService.GetAll(source, target)));
        }
Example #38
0
        /// <summary>
        /// 调用服务
        /// </summary>
        /// <param name="service"></param>
        /// <param name="contract"></param>
        /// <param name="paras"></param>
        /// <returns></returns>
        private ApiResult Invoke(object service, ServiceContract contract, Dictionary <string, string> paras)
        {
            ApiResult result = new ApiResult();

            try
            {
                MethodInfo _method = service.GetType().GetMethod(contract.MethodName);
                if (_method.IsGenericMethod)
                {
                    _method.MakeGenericMethod(contract.GenericType);
                }
                var    _params = _method.GetParameters();
                var    _t      = _method.ReturnType;
                string _rel    = string.Empty;
                if (_params.Length > 0)
                {
                    if (!_params.Length.Equals(paras.Count))
                    {
                        string err = string.Format("传入的参数不匹配{0},请检查!", service.GetType().FullName);
                        return(InvokeError(result, err));
                    }
                    object[] _parameters = new object[_params.Length];
                    int      i           = 0;
                    foreach (var p in _params)
                    {
                        if (paras.ContainsKey(p.Name))
                        {
                            var _p = JsonHelper.Deserialize(paras[p.Name], p.ParameterType);
                            _parameters[i] = _p;
                            i++;
                        }
                        else
                        {
                            return(this.InvokeError(result, String.Format("传入的参数找不到需要的参数:{0},请检查", p.Name)));
                        }
                    }

                    object _o = _method.Invoke(service, _parameters);
                    JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    };
                    _rel = JsonHelper.SerializeWithSetting(_o, _jsonSettings);
                }
                else
                {
                    object _o = _method.Invoke(service, null);
                    _rel = JsonHelper.Serialize(_o);
                }

                result.Message   = _rel;
                result.IsSuccess = true;
                _Logger.LogInformation(string.Format("{0}:{1}/{2}调用成功", DateTime.Now, service.GetType().FullName, contract.MethodName));
                return(result);
            }
            catch (Exception ex)
            {
                string msg = ex.InnerException is null ? ex.Message : ex.InnerException.Message;
                return(this.InvokeError(result, msg));
            }
        }
        /// <summary>
        /// 查询所有任务
        /// </summary>
        /// <returns></returns>
        public async Task <ApiResult <List <JobListEntity> > > GetList()
        {
            var result = new ApiResult <List <JobListEntity> >()
            {
                statusCode = (int)ApiEnum.Error
            };

            try
            {
                List <JobKey>        jboKeyList  = new List <JobKey>();
                List <JobListEntity> jobInfoList = new List <JobListEntity>();
                //查询redis的任务
                var redisTask = RedisHelper.Get <List <ScheduleEntity> >(KeyHelper.TaskSchedulerList);
                if (redisTask == null || redisTask.Count == 0)
                {
                    result.statusCode = (int)ApiEnum.Status;
                    result.data       = jobInfoList;
                    return(result);
                }

                var groupNames = await Scheduler.GetJobGroupNames();

                if (groupNames.Count == 0)
                {
                    //说明第一次打开,增加到任务调度里面
                    foreach (var item in redisTask)
                    {
                        if (item.TriggerState == TriggerState.Normal)
                        {
                            await Add(item);
                        }
                    }
                    //阻塞下
                    System.Threading.Thread.Sleep(500);
                    //阻塞后,重新获得在任务中的组信息
                    groupNames = await Scheduler.GetJobGroupNames();
                }

                foreach (var groupName in groupNames.OrderBy(t => t))
                {
                    jboKeyList.AddRange(await Scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(groupName)));
                    jobInfoList.Add(new JobListEntity()
                    {
                        GroupName = groupName
                    });
                }
                //定义一个空数组,接受已存在任务里面的任务名字,提供下面,判断是否存在
                var jobNameArr = new List <string>();
                foreach (var jobKey in jboKeyList.OrderBy(t => t.Name))
                {
                    var jobDetail = await Scheduler.GetJobDetail(jobKey);

                    var triggersList = await Scheduler.GetTriggersOfJob(jobKey);

                    var triggers = triggersList.AsEnumerable().FirstOrDefault();
                    foreach (var jobInfo in jobInfoList)
                    {
                        if (jobInfo.GroupName == jobKey.Group)
                        {
                            //在redis里面查询任务
                            var cacheTask = redisTask.Where(m => m.JobName == jobKey.Name && m.JobGroup == jobKey.Group).FirstOrDefault();
                            if (cacheTask != null)
                            {
                                jobNameArr.Add(cacheTask.JobName);
                                cacheTask.LastErrMsg       = jobDetail.JobDataMap.GetString(Constant.EXCEPTION);
                                cacheTask.PreviousFireTime = triggers.GetPreviousFireTimeUtc()?.LocalDateTime;
                                cacheTask.NextFireTime     = triggers.GetNextFireTimeUtc()?.LocalDateTime;
                                jobInfo.jobList.Add(cacheTask);
                            }
                        }
                    }
                }
                //查询Redis中,不在运行的任务项目
                var noTaskList = redisTask.Where(m => !jobNameArr.Contains(m.JobName)).ToList();
                //将不运行的任务,增加到List中
                if (noTaskList.Any())
                {
                    //查询组
                    var noRunTaskGroup = noTaskList.GroupBy(m => m.JobGroup).Select(m => m.Key).ToList();
                    if (noRunTaskGroup != null && noRunTaskGroup.Count > 0)
                    {
                        foreach (var item in noRunTaskGroup)
                        {
                            //根据组获得任务详细信息
                            var jobList       = new List <ScheduleEntity>();
                            var noRunTaskList = noTaskList.Where(m => m.JobGroup == item).ToList();
                            foreach (var job in noRunTaskList)
                            {
                                jobList.Add(job);
                            }
                            jobInfoList.Add(new JobListEntity()
                            {
                                GroupName = item,
                                jobList   = jobList
                            });
                        }
                    }
                }
                result.data       = jobInfoList;
                result.statusCode = (int)ApiEnum.Status;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
            }
            return(result);
        }
Example #40
0
        public ActionResult SendSms()
        {
            var member = new Member();
            member.FirstName = "Joe";
            member.LastName = "Rosenblum";

            Communication.SendSmsLoginResponse(member);

            var apiResult = new ApiResult {Success = true, Description = ""};

            return this.ToXml(apiResult);
        }
Example #41
0
        public async Task<IActionResult> Post([FromBody]ChangePasswordModel model)
        {

            // Validate the request
            if (model == null)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(ApiResult.InvalidRequest());
            }

            var result = new ApiResult();

            // Validate the model
            if (ModelState.IsValid == false)
            {
                result.AddModelStateErrors(ModelState);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(result);
            }

            // Validate the Captcha
            try
            {
                if (await ValidateRecaptcha(model.Recaptcha) == false)
                    result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCaptcha });
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message });
            }


            if (result.HasErrors)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(result);
            }

            // perform the password change
            try
            {
                var principalContext = new PrincipalContext(ContextType.Domain);
                var userPrincipal = UserPrincipal.FindByIdentity(principalContext, model.Username);

                if (userPrincipal == null)
                {
                    result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.UserNotFound });
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return Json(result);
                }

                userPrincipal.ChangePassword(model.CurrentPassword, model.NewPassword);
                userPrincipal.Save();
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message });
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(result);
            }

            if (result.HasErrors)
                Response.StatusCode = (int)HttpStatusCode.BadRequest;

            return Json(result);

        }
        public async Task <IActionResult> Post([FromBody] ChangePasswordModel model)
        {
            // Validate the request
            if (model == null)
            {
                return(BadRequest(ApiResult.InvalidRequest()));
            }

            var result = new ApiResult();

            // Validate the model
            if (ModelState.IsValid == false)
            {
                result.AddModelStateErrors(ModelState);

                return(BadRequest(result));
            }

            // Validate the Captcha
            try
            {
                // Sonar-Codacy suggested ConfigureAwait
                if (await ValidateRecaptcha(model.Recaptcha).ConfigureAwait(false) == false)
                {
                    result.Errors.Add(new ApiErrorItem {
                        ErrorCode = ApiErrorCode.InvalidCaptcha
                    });
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem
                {
                    ErrorCode = ApiErrorCode.Generic,
                    Message   = ex.Message
                });
            }

            if (result.HasErrors)
            {
                return(BadRequest(result));
            }

            // Check for default domain: if none given, ensure EFLD can be used as an override.
            var parts  = model.Username.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
            var domain = parts.Length > 1 ? parts[1] : _options.ClientSettings.DefaultDomain;

            // Domain-determinance
            if (string.IsNullOrEmpty(domain))
            {
                result.Errors.Add(new ApiErrorItem {
                    ErrorCode = ApiErrorCode.InvalidDomain
                });
                return(BadRequest(result));
            }

            var currentUsername = parts.Length > 1 ? model.Username : $"{model.Username}@{domain}";

            var resultPasswordChange = _passwordChangeProvider.PerformPasswordChange(currentUsername, model.CurrentPassword, model.NewPassword);

            if (resultPasswordChange != null)
            {
                result.Errors.Add(resultPasswordChange);
            }

            if (result.HasErrors)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }

            return(Json(result));
        }
Example #43
0
        /// <summary>
        /// 上传资源
        /// </summary>
        /// <param name="base64Img"></param>
        /// <param name="type">资源类型</param>
        /// <param name="createUserId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResult <UploadFileResDto> UploadFile(string base64Img, int type, long createUserId, HttpRequestMessage request)
        {
            var result = new ApiResult <UploadFileResDto>();

            string url      = request.RequestUri.GetLeftPart(UriPartial.Authority);
            string filePath = String.Format("/File/{0}/", DateTime.Now.ToString("yyyy/MM"));

            string errorMsg = "";
            var    photo    = Tool.SaveImage(HostingEnvironment.MapPath(filePath), base64Img, ref errorMsg);

            if (photo == null)
            {
                throw new ApiException(50000, "上传资源失败");
            }


            string rpath = url + filePath + photo.ImgName + "_Min" + photo.Extension;

            string path1 = Tool.UploadFileToOss(filePath + photo.ImgName + "_Min" + photo.Extension);
            string path2 = Tool.UploadFileToOss(filePath + photo.ImgName + photo.Extension);

            if (string.IsNullOrWhiteSpace(path1) || string.IsNullOrWhiteSpace(path2))
            {
                throw new ApiException(50000, "上传资源失败OSS");
            }

            StringBuilder strSql = new StringBuilder();

            if (type == (int)ResourceTypeEnum.用户头像)
            {
                strSql.Append("delete from dbo.ResourceMapping where [Type]=@Type and FkId=@FkId;");
            }

            strSql.Append(@"insert into ResourceMapping(Extension, RPath, Title, SortCode, CreateTime, Type, FkId, RSize) 
                                   values(@Extension, @RPath, @Title, 1, getdate(), @Type, @FkId, @RSize);select @@identity");

            SqlParameter[] sp = new SqlParameter[] {
                new SqlParameter("@FkId", createUserId),
                new SqlParameter("@Type", type),
                new SqlParameter("@Extension", photo.Extension),
                new SqlParameter("@RPath", path1),
                new SqlParameter("@RSize", photo.RSize),
                new SqlParameter("@Title", photo.ImgName)
            };

            object data = SqlHelper.ExecuteScalar(strSql.ToString(), sp);

            if (data == null)
            {
                throw new ApiException(40000, "保存资源失败");
            }

            int resId = Convert.ToInt32(data);

            UploadFileResDto resDto = new UploadFileResDto()
            {
                ResouceId = resId,
                Url       = path1
            };

            result.Data = resDto;
            return(result);
        }
Example #44
0
        private ApiResult LoadandRunSteps(Kernel kernel, bool isReSample, List <ReferenceDataObject> referenceDatas, List <FunctionObject> functions)
        {
            try
            {
                bool normalizationWarning = false;
                // Load steps from blob
                XmlSerializer ser = new XmlSerializer(typeof(steps));
                using (StringReader sreader = new StringReader(_setupStepsXml))
                {
                    using (XmlReader reader = XmlReader.Create(sreader))
                    {
                        _steps = (steps)ser.Deserialize(reader);
                    }
                }

                string result = "";
                if (!isReSample)
                {
                    // Run the steps
                    for (int i = 0; i < _steps.Items.Count(); i++)
                    {
                        _logger.LogInformation($"steps.Items[{i}] ran successfully");
                        result = kernel.ExecuteCode(_steps.Items[i].Value);
                        LogErrors(result, _steps.Items[i].Value, $"InitializationStep[{i}]");
                        _steps.Items[i].Value = NormalizationSnippetHelper(ref i, ref normalizationWarning, result, _steps.Items);
                    }
                }
                else
                {
                    // Run the resample steps
                    for (int i = _steps.Items.Count() - 2; i < _steps.Items.Count(); i++)
                    {
                        _logger.LogInformation($"steps.Items[i].Value: _steps.Items[{i}]");
                        result = kernel.ExecuteCode(_steps.Items[i].Value);
                        var errors = CheckErrors(result);
                        if (!string.IsNullOrEmpty(errors))
                        {
                            _logger.LogError($"Initialization step: {_steps.Items[i].Value}. Resulting Error: {result}");
                        }
                        _steps.Items[i].Value = NormalizationSnippetHelper(ref i, ref normalizationWarning, result, _steps.Items);
                    }
                }

                // Now run the steps to load the reference data
                LoadReferenceData(kernel, referenceDatas);

                // Now load the UDFs and UDAFs
                LoadFunctions(kernel, functions);

                var error = CheckErrors(result);
                if (!string.IsNullOrEmpty(error))
                {
                    return(ApiResult.CreateError("{'Error':'" + error + "'}"));
                }
                else
                {
                    KernelResult responseObject = new KernelResult
                    {
                        Result = kernel.Id
                    };
                    if (normalizationWarning)
                    {
                        responseObject.Message = "Warning: Normalization query in the Input tab could not be applied, probably because some columns in the query are not part of the schema. Please update the schema or try auto-generating it using longer duration in the Input tab.";
                    }
                    else
                    {
                        responseObject.Message = string.Empty;
                    }

                    return(ApiResult.CreateSuccess(JObject.FromObject(responseObject)));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"ErrorMessage: {ex.Message} SetupSteps: {_setupStepsXml}");
                return(ApiResult.CreateError(ex.ToString()));
            }
        }
Example #45
0
            public override void Process()
            {
                Core.History("history.Process()");
                ApiResult Result = new ApiResult();
                string Offset;
                Offset = Page.HistoryOffset;
                if (_full)
                {
                    Program.MainForm.Log(Languages.Get("history"));
                }

                while ( (_full || FullTotal < FullLimit) && Offset != "" )
                {
                    if (GetContent)
                    {
                        BlockSize = Math.Min(50, BlockSize);
                    }

                    string query_string = "action=query&prop=revisions&titles=" + System.Web.HttpUtility.UrlEncode(Page.Name) + "&rvlimit=" + BlockSize.ToString() + "&rvprops=ids|timestamp|user|comment";

                    if (GetContent)
                    {
                        query_string = query_string + "|content";
                    }
                    if (Offset != null)
                    {
                        query_string = query_string + "&rvstartid=" + Offset;
                    }
                    Result = ApiRequest(query_string);
                    if (Result.ResultInError)
                    {
                        Fail(Languages.Get("history-fail"), Page.Name);
                    }
                    if (_full)
                    {
                        FullTotal = FullTotal + BlockSize;
                        result = new request_core.Request_Result(result.text);
                        Program.MainForm.Log(Languages.Get("history-progress"));
                    }
                    Offset = GetParameter(Result.Result_Text, "rvstartid");
                    if (Offset == null)
                    {
                        Offset = "";
                    }
                }
                Complete(Text: Result.Result_Text);
            }
Example #46
0
        /// <summary>
        /// ExecuteQueryAsync is the method that calls into the rest api for kernel for executing the code
        /// </summary>
        /// /// <param name="code">The code to be executed</param>
        /// <param name="kernelId">kernelId</param>
        /// <returns>ApiResult which contains the actual output from executing the query or the error as the case maybe</returns>
        public async Task <ApiResult> ExecuteQueryAsync(string code, string kernelId)
        {
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    return(ApiResult.CreateError("{\"Error\":\"Please select a query in the UI\"}"));
                }

                if (code.Trim().StartsWith(_QuerySeparator))
                {
                    code = code.Replace(_QuerySeparator, "");
                }

                // Attach to kernel
                Dictionary <string, string> hs = new Dictionary <string, string>();
                string token = Base64Encode($"{_username}:{_password}");
                hs.Add("Authorization", $"Basic {token}");
                Kernel kernel = new Kernel(kernelId, _baseUrl, null, null, null, hs);

                // Remove Timewindow
                Regex timeRegex = new Regex(@"TIMEWINDOW\s{0,}\(\s{0,}.*\s{0,}\)", RegexOptions.IgnoreCase);
                Match match     = timeRegex.Match(code);
                if (match.Success)
                {
                    code = code.Replace(match.Groups[0].Value, "");
                }

                // Handle WITH UPSERT
                Regex r1 = new Regex(@"\s{0,}([^;]*)WITH\s{1,}UPSERT\s{0,}([^;]*)", RegexOptions.IgnoreCase);
                Match m1 = r1.Match(code);
                if (m1.Success)
                {
                    string newQuery = m1.Groups[2].Value.Trim() + " = " + m1.Groups[1].Value.Trim() + "\r\n";
                    code = code.Replace(m1.Groups[0].Value, newQuery);
                }

                // Now check what kind of code we have, and execute
                code = code.TrimEnd(';');
                Regex  r2 = new Regex("(.*)=([^;]*)");
                Match  m2 = r2.Match(code);
                Regex  r3 = new Regex(@"(\s{1,}CREATE TABLE\s{1,}[^;]*)", RegexOptions.IgnoreCase);
                Match  m3 = r3.Match(" " + code);
                string g  = Guid.NewGuid().ToString().Replace("-", "");
                string s  = "";
                bool   isTableCreateCommand = false;
                if (m2.Success)
                {
                    // SQL query assigning results to a table. Example: T1 = SELECT ...
                    string table = m2.Groups[1].Value.Trim();
                    s = $"val {table}Table = sql(\"{m2.Groups[2].Value}\"); {table}Table.toJSON.take({_MaxCount}).foreach(println); {table}Table.createOrReplaceTempView(\"{table}\")";
                }
                else if (m3.Success)
                {
                    // CREATE State query
                    isTableCreateCommand = true;
                    s = $"val results{g} = sql(\"{m3.Groups[1].Value.Trim()}\"); println(\"done\")";
                }
                else
                {
                    // SQL query without assigning results to a table. Example: SELECT ...
                    s = $"val results{g} = sql(\"{code}\"); results{g}.toJSON.take({_MaxCount}).foreach(println)";
                }

                // Execute code
                string result = await Task.Run(() => kernel.ExecuteCode(ReplaceNewLineFeed(s)));

                // If the table already exists, then it is not an error. Mark this done.
                if (isTableCreateCommand && result != null && result.Contains("TableAlreadyExistsException"))
                {
                    result = "done";
                }

                if (!string.IsNullOrEmpty(result))
                {
                    return(ConvertToJson(_MaxCount, result));
                }
                else
                {
                    return(ApiResult.CreateError("{\"Error\":\"No Results\"}"));
                }
            }
            catch (Exception ex)
            {
                return(ApiResult.CreateError(ex.ToString()));
            }
        }
        private IActionResult CheckStatusCode(ApiResult result)
        {
            if (result.StatusCode == (int)HttpStatusCode.Unauthorized)
            {
                return ReAuthenticateUser();
            }

            if (result.StatusCode == (int)HttpStatusCode.Forbidden)
            {
                // Redirects user to Forbidden page
                return new ChallengeResult(CookieAuthenticationDefaults.AuthenticationScheme);
            }

            if (result.StatusCode == (int)HttpStatusCode.NotFound)
            {
                ModelState.AddModelError(string.Empty, "The survey can not be found");
                ViewBag.Message = "The survey can not be found";
                return View("~/Views/Shared/Error.cshtml");
            }

            return null;
        }
Example #48
0
 public async Task <IActionResult> CreateAsync(CreateTodoItemModel createTodoItemModel)
 {
     return(Ok(ApiResult <CreateTodoItemResponseModel> .Success(
                   await _todoItemService.CreateAsync(createTodoItemModel))));
 }
 ApiResult Login(Login loginCommand)
 {
     ApiResult result = null;
     var account = _QueryContext.Accounts.FirstOrDefault(a => a.UserName.Equals(loginCommand.UserName)
                                                           && a.Password.Equals(loginCommand.Password));
     if (account != null)
     {
         // 1.
         // Regard command controller as the application service
         // where is the best place to publish application events.
         // AccountLogined is a application event not a domain event,
         // so we won't use command bus to envoke domain layer.
         // 2.
         // if regard CommandHandler as a kind of application service,
         // we can use command bus to envoke domain layer and
         // no need to define the "Login" action of controller
         _EventPublisher.Publish(new MessageContext(new AccountLogined { AccountID = account.ID, LoginTime = DateTime.Now }));
         result = new ApiResult<Guid> { Result = account.ID };
     }
     else
     {
         result = new ApiResult { ErrorCode = ErrorCode.WrongUsernameOrPassword,
                                  Message = ErrorCode.WrongUsernameOrPassword.ToString() };
     }
     return result;
 }
Example #50
0
 public async Task <IActionResult> UpdateAsync(Guid id, UpdateTodoItemModel updateTodoItemModel)
 {
     return(Ok(ApiResult <UpdateTodoItemResponseModel> .Success(
                   await _todoItemService.UpdateAsync(id, updateTodoItemModel))));
 }
 /// <summary>
 /// 处理模型校验错误
 /// </summary>
 /// <param name="modelState"></param>
 /// <param name="result"></param>
 /// <returns></returns>
 private bool HandleModelStateValidationError(ModelStateDictionary modelState, out ApiResult result)
 {
     if (this.ModelStateValidationErrorHandler != null)
     {
         result = this.ModelStateValidationErrorHandler.Handle(modelState);
         return true;
     }
     result = null;
     return false;
 }
Example #52
0
 public async Task <IActionResult> DeleteAsync(Guid id)
 {
     return(Ok(ApiResult <BaseResponseModel> .Success(await _todoItemService.DeleteAsync(id))));
 }
        public void HandleExecutedContext(HttpActionExecutedContext ctx)
        {
            ApiResult resp;
            //如果有模型校验错误就返回
            if (!ctx.ActionContext.ModelState.IsValid && this.HandleModelStateValidationError(ctx.ActionContext.ModelState, out resp))
            {
                ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, (ApiResult)(IApiResult)resp);
                return;
            }

            AssociateFilter.InvokeBaseOnActionExecuted(ctx);
            if (ctx.Exception != null && this.HandleException(ctx.Exception, out resp))
            {
                ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, (ApiResult)(IApiResult)resp);
            }
            else
            {
                if (ctx.Response.StatusCode == HttpStatusCode.Unauthorized && this.HandleUnauthorizedRequest(ctx.ActionContext, out resp))
                {
                    return;
                }
                else if (ctx.Response.StatusCode != HttpStatusCode.OK && ctx.Response.StatusCode != HttpStatusCode.NoContent)
                {
                    var result = new ApiResult((int)ctx.Response.StatusCode, ctx.Response.StatusCode.ToString());
                    ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, result);
                }
                else
                {
                    var cnt = ctx.ActionContext.Response.Content;
                    if (cnt != null)
                    {
                        var objCnt = (ObjectContent)cnt;
                        if (typeof(IPagedList).IsAssignableFrom(objCnt.ObjectType))
                        {
                            var x = ((IPagedList)objCnt.Value).AsApiResponse();
                            var result = new ApiResultWithPagedDataList<object>();
                            result.hasMore = x.hasMore;
                            result.data = x.data;
                            ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, result);
                        }
                        else if (objCnt.ObjectType.Equals(typeof(ApiResult)))
                        {
                            ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, objCnt);
                        }
                        else
                        {
                            var result = new ApiResultWithData()
                            {
                                data = ctx.ActionContext.Response.Content.ReadAsAsync<object>().Result
                            };
                            ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, result);
                        }

                    }
                    else
                    {
                        ctx.Response = ctx.Request.CreateResponse(HttpStatusCode.OK, new ApiResult());
                    }
                }
            }
        }
            private static async Task <ApiResult <ApiPreapprovalResponse> > BecauseAsync()
            {
                CreatePreapprovalResponse = await PreapprovalService.CreatePreapprovalAsync(PreapprovalRequest);

                return(await PreapprovalService.GetPreapprovalAsync(CreatePreapprovalResponse.Value.Preapproval.ID.Value));
            }
 public ApiResultException(ApiResult result, Exception innerException = null)
     : base(result.msg, innerException)
 {
     this.Result = result;
 }
Example #56
0
        public string Index(string cli, string callback, bool parseAsHtml = false)
        {
            AppSettings.ConnectionString = ConfigurationManager.ConnectionStrings["EntityContainer"].ConnectionString;

            if (Session["commandContext"] != null)
                _commandContext = (CommandContext)Session["commandContext"];
            _terminalApi.Username = Session["currentUser"] != null ? Session["currentUser"].ToString() : null;
            _terminalApi.CommandContext = _commandContext;
            _terminalApi.ParseAsHtml = parseAsHtml;
            var commandResult = _terminalApi.ExecuteCommand(cli);

            Session["currentUser"] = commandResult.CurrentUser != null ? commandResult.CurrentUser.Username : null;
            Session["commandContext"] = commandResult.CommandContext;

            var displayItems = new List<ApiDisplayItem>();
            commandResult.Display.ForEach(x => displayItems.Add(new ApiDisplayItem
            {
                Text = x.Text,
                Bold = (x.DisplayMode & DisplayMode.Bold) != 0,
                Dim = (x.DisplayMode & DisplayMode.Dim) != 0,
                DontType = (x.DisplayMode & DisplayMode.DontType) != 0,
                Inverted = (x.DisplayMode & DisplayMode.Inverted) != 0,
                Italics = (x.DisplayMode & DisplayMode.Italics) != 0,
                Mute = (x.DisplayMode & DisplayMode.Mute) != 0,
                Parse = (x.DisplayMode & DisplayMode.Parse) != 0
            }));

            var apiResult = new ApiResult
            {
                ClearScreen = commandResult.ClearScreen,
                Command = commandResult.Command,
                ContextStatus = commandResult.CommandContext.Status.ToString(),
                ContextText = commandResult.CommandContext.Command
                + (commandResult.CommandContext.Text.IsNullOrEmpty()
                ? null : string.Format(" {0}", _terminalApi.CommandContext.Text)),
                CurrentUser = commandResult.CurrentUser != null ? commandResult.CurrentUser.Username : null,
                DisplayItems = displayItems,
                EditText = commandResult.EditText,
                Exit = commandResult.Exit,
                PasswordField = commandResult.PasswordField,
                ScrollToBottom = commandResult.ScrollToBottom,
                SessionId = Session.SessionID,
                TerminalTitle = commandResult.TerminalTitle
            };
            string json = new JavaScriptSerializer().Serialize(apiResult);
            return callback != null ? string.Format("{0}({1});", callback, json) : json;
        }