Esempio n. 1
0
        public bool deletePost(string appKey, string postid, string username, string password, [XmlRpcParameter(Description = "Where applicable, this specifies whether the blog should be republished after the post has been deleted.")] bool publish)
        {
            CreateServices();

            ValidateUser(username, password);
            int contentId = GetContentId(postid);

            Content content = contentRepository.GetById(contentId);

            contentRepository.DeleteOnSubmit(content);
            unitOfWorkManager.Commit();

            return(false);
        }
Esempio n. 2
0
        public async Task <AjaxResult> Login(LoginDto dto)
        {
            Check.NotNull(dto, nameof(dto));

            if (!ModelState.IsValid)
            {
                return(new AjaxResult("提交信息验证失败", AjaxResultType.Error));
            }
            //todo: 校验验证码

            dto.Ip        = HttpContext.GetClientIp();
            dto.UserAgent = Request.Headers["User-Agent"].FirstOrDefault();

            OperationResult <User> result = await _identityContract.Login(dto);

            IUnitOfWorkManager unitOfWorkManager = HttpContext.RequestServices.GetRequiredService <IUnitOfWorkManager>();

#if NET5_0
            await unitOfWorkManager.CommitAsync();
#else
            unitOfWorkManager.Commit();
#endif

            if (!result.Succeeded)
            {
                return(result.ToAjaxResult());
            }

            User user = result.Data;
            await _signInManager.SignInAsync(user, dto.Remember);

            return(new AjaxResult("登录成功"));
        }
Esempio n. 3
0
        /// <summary>执行拦截业务,并根据返回结果决定提交事务还是回滚</summary>
        /// <param name="context">切面上下文</param>
        /// <param name="next">被拦截并包装的操作</param>
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            IServiceProvider   provider          = context.ServiceProvider;
            IUnitOfWorkManager unitOfWorkManager = provider.GetService <IUnitOfWorkManager>();

            try
            {
                await next(context);

                if (!RequiredCheckReturnValue)
                {
#if NET5_0
                    await unitOfWorkManager.CommitAsync();
#else
                    unitOfWorkManager.Commit();
#endif
                    return;
                }
                Type returnType = context.ProxyMethod.ReturnType;
                ITransactionDecision decision = provider.GetServices <ITransactionDecision>()
                                                .FirstOrDefault(m => m.IsFit(returnType));
                if (decision == null)
                {
                    throw new OsharpException($"无法找到与结果类型 {returnType} 匹配的 {typeof(ITransactionDecision)} 事务裁决器,请继承接口实现一个");
                }
                if (decision.CanCommit(context.ReturnValue))
                {
#if NET5_0
                    await unitOfWorkManager.CommitAsync();
#else
                    unitOfWorkManager.Commit();
#endif
                }
            }
            catch (Exception)
            {
#if NET5_0
                await unitOfWorkManager.CommitAsync();
#else
                unitOfWorkManager.Commit();
#endif
                throw;
            }
        }
Esempio n. 4
0
        public ActionResult New(ProductViewData productViewData)
        {
            var product = productBuilder.ProductFromProductViewData(productViewData, ModelState, Request);

            if (ModelState.IsValid)
            {
                productRepository.SaveOrUpdate(product);
                uow.Commit();                 //Need explicit commit in order to get the product id.
                return(this.RedirectToAction(x => x.Edit(product.Id)));
            }
            return(View("Edit", productViewData.WithErrorMessage("There were errors, please correct them and resubmit.")));
        }
        public ActionResult Index(CheckoutViewData checkoutViewData)
        {
            var order = checkoutService.OrderFromCheckoutViewData(checkoutViewData, ModelState);

            if (ModelState.IsValid)
            {
                orderRepository.SaveOrUpdate(order);
                //we need an explicit Commit in order to obtain the db-generated Order Id
                unitOfWork.Commit();
                return(this.RedirectToAction(c => c.Confirm(order.Id)));
            }

            return(View("Index", checkoutViewData));
        }
Esempio n. 6
0
        public async Task <AjaxResult> Token(TokenDto dto)
        {
            string grantType = dto.GrantType?.UpperToLowerAndSplit("_");

            if (grantType == GrantType.Password)
            {
                Check.NotNull(dto.Account, nameof(dto.Account));
                Check.NotNull(dto.Password, nameof(dto.Password));

                LoginDto loginDto = new LoginDto()
                {
                    Account    = dto.Account,
                    Password   = dto.Password,
                    ClientType = dto.ClientType,
                    IsToken    = true,
                    Ip         = HttpContext.GetClientIp(),
                    UserAgent  = Request.Headers["User-Agent"].FirstOrDefault()
                };

                OperationResult <User> result = await _identityContract.Login(loginDto);

                IUnitOfWorkManager unitOfWorkManager = HttpContext.RequestServices.GetService <IUnitOfWorkManager>();
#if NET5_0
                await unitOfWorkManager.CommitAsync();
#else
                unitOfWorkManager.Commit();
#endif
                if (!result.Succeeded)
                {
                    return(result.ToAjaxResult());
                }

                User         user  = result.Data;
                JsonWebToken token = await CreateJwtToken(user, dto.ClientType);

                return(new AjaxResult("登录成功", AjaxResultType.Success, token));
            }

            if (grantType == GrantType.RefreshToken)
            {
                Check.NotNull(dto.RefreshToken, nameof(dto.RefreshToken));
                JsonWebToken token = await CreateJwtToken(dto.RefreshToken);

                return(new AjaxResult("刷新成功", AjaxResultType.Success, token));
            }

            return(new AjaxResult("GrantType错误", AjaxResultType.Error));
        }
Esempio n. 7
0
        public ActionResult Copy(Product product)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            var copiedProduct = productCopyService.Copy(product);

            productRepository.SaveOrUpdate(copiedProduct);

            // we need an explicit commit here to get the copiedProduct id from the db
            unitOfWork.Commit();

            return(RedirectToAction("Edit", "Product", new { Id = copiedProduct.Id }));
        }
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            IServiceProvider   provider          = context.HttpContext.RequestServices;
            IUnitOfWorkManager unitOfWorkManager = provider.GetService <IUnitOfWorkManager>();

            //if (context.Exception != null && !context.ExceptionHandled)
            //{
            //    unitOfWorkManager?.Rollback();
            //}
            //else
            //{
            //    unitOfWorkManager?.Commit();
            //}
            if (context.Exception == null && context.ExceptionHandled)
            {
                unitOfWorkManager?.Commit();
            }
        }
Esempio n. 9
0
        /// <summary>
        /// 获取事件处理器实例
        /// </summary>
        /// <returns></returns>
        public EventHandlerDisposeWrapper GetHandler()
        {
            string        token = Guid.NewGuid().ToString();
            IServiceScope scope = _serviceScopeFactory.CreateScope();

            _logger.LogDebug($"创建处理器“{_handlerType}”的执行作用域,标识:{token}");
            IServiceProvider scopeProvider = scope.ServiceProvider;
            IEventHandler    eventHandler  = (IEventHandler)scopeProvider.GetService(_handlerType);

            _logger.LogDebug($"创建处理器“{_handlerType}”的实例,标识:{token}");
            return(new EventHandlerDisposeWrapper(eventHandler,
                                                  () =>
            {
                IUnitOfWorkManager unitOfWorkManager = scopeProvider.GetService <IUnitOfWorkManager>();
                unitOfWorkManager.Commit();
                scope.Dispose();
                _logger.LogDebug($"释放处理器“{_handlerType}”的执行作用域,标识: {token}");
            }));
        }
Esempio n. 10
0
        public async Task <string> LockUser2()
        {
            List <string>      list        = new List <string>();
            UserManager <User> userManager = _provider.GetService <UserManager <User> >();
            User user2 = await userManager.FindByIdAsync("2");

            list.Add($"user2.IsLocked: {user2.IsLocked}");
            user2.IsLocked = !user2.IsLocked;
            await userManager.UpdateAsync(user2);

            IUnitOfWorkManager unitOfWorkManager = _provider.GetService <IUnitOfWorkManager>();

#if NET5_0
            await unitOfWorkManager.CommitAsync();
#else
            unitOfWorkManager.Commit();
#endif
            user2 = await userManager.FindByIdAsync("2");

            list.Add($"user2.IsLocked: {user2.IsLocked}");
            return(list.ExpandAndToString());
        }
Esempio n. 11
0
        public async Task <AjaxResult> LoginBind(UserLoginInfoEx loginInfo)
        {
            loginInfo.RegisterIp = HttpContext.GetClientIp();
            OperationResult <User> result = await _identityContract.LoginBind(loginInfo);

            IUnitOfWorkManager unitOfWorkManager = HttpContext.RequestServices.GetRequiredService <IUnitOfWorkManager>();

#if NET5_0
            await unitOfWorkManager.CommitAsync();
#else
            unitOfWorkManager.Commit();
#endif
            if (!result.Succeeded)
            {
                return(result.ToAjaxResult());
            }

            User         user  = result.Data;
            JsonWebToken token = await CreateJwtToken(user);

            return(new AjaxResult("登录成功", AjaxResultType.Success, token));
        }
Esempio n. 12
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            var currentUnitOfWorkManager = context.HttpContext.RequestServices.GetService <IUnitOfWorkManager>();

            if (currentUnitOfWorkManager != null)
            {
                var entities = new List <AuditEntity>();
                foreach (var unitOfWork in currentUnitOfWorkManager.GetUnitOfWorks())
                {
                    entities.AddRange(unitOfWork.GetAuditEntities());
                }

                _auditedOperation.AddEntities(entities);
            }

            _auditedOperation.End();

            _auditService.Save(_auditedOperation);
            _auditUnitOfWorkManager.Commit();

            _logger.LogDebug("Executed audit filter");
        }
Esempio n. 13
0
        /// <summary>
        /// 重写方法,实现事务自动提交功能
        /// </summary>
        /// <param name="context"></param>
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            ScopedDictionary dict    = context.HttpContext.RequestServices.GetService <ScopedDictionary>();
            AjaxResultType   type    = AjaxResultType.Success;
            string           message = null;

            if (context.Result is JsonResult result1)
            {
                if (result1.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Successed())
                    {
                        _unitOfWorkManager?.Commit();
                    }
                }
            }
            else if (context.Result is ObjectResult result2)
            {
                if (result2.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Successed())
                    {
                        _unitOfWorkManager?.Commit();
                    }
                }
                _unitOfWorkManager?.Commit();
            }
            //普通请求
            else if (context.HttpContext.Response.StatusCode >= 400)
            {
                switch (context.HttpContext.Response.StatusCode)
                {
                case 401:
                    type = AjaxResultType.UnAuth;
                    break;

                case 403:
                    type = AjaxResultType.UnAuth;
                    break;

                case 404:
                    type = AjaxResultType.UnAuth;
                    break;

                case 423:
                    type = AjaxResultType.UnAuth;
                    break;

                default:
                    type = AjaxResultType.Error;
                    break;
                }
            }
            else
            {
                type = AjaxResultType.Success;
                _unitOfWorkManager?.Commit();
            }
            if (dict.AuditOperation != null)
            {
                dict.AuditOperation.ResultType = type;
                dict.AuditOperation.Message    = message;
            }
        }
        /// <summary>
        /// Called after the action executes, before the action result.
        /// </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext" />.</param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            ScopedDictionary dict    = context.HttpContext.RequestServices.GetService <ScopedDictionary>();
            AjaxResultType   type    = AjaxResultType.Success;
            string           message = null;

            if (context.Exception != null && !context.ExceptionHandled)
            {
                Exception ex = context.Exception;
                _logger.LogError(new EventId(), ex, ex.Message);
                message = ex.Message;
                if (context.HttpContext.Request.IsAjaxRequest() || context.HttpContext.Request.IsJsonContextType())
                {
                    if (!context.HttpContext.Response.HasStarted)
                    {
                        context.Result = new JsonResult(new AjaxResult(ex.Message, AjaxResultType.Error));
                    }
                    context.ExceptionHandled = true;
                }
            }
            if (context.Result is JsonResult result1)
            {
                if (result1.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Succeeded())
                    {
                        _unitOfWorkManager?.Commit();
                    }
                }
            }
            else if (context.Result is ObjectResult result2)
            {
                if (result2.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Succeeded())
                    {
                        _unitOfWorkManager?.Commit();
                    }
                }
                else
                {
                    _unitOfWorkManager?.Commit();
                }
            }
            //普通请求
            else if (context.HttpContext.Response.StatusCode >= 400)
            {
                switch (context.HttpContext.Response.StatusCode)
                {
                case 401:
                    type = AjaxResultType.UnAuth;
                    break;

                case 403:
                    type = AjaxResultType.UnAuth;
                    break;

                case 404:
                    type = AjaxResultType.UnAuth;
                    break;

                case 423:
                    type = AjaxResultType.UnAuth;
                    break;

                default:
                    type = AjaxResultType.Error;
                    break;
                }
            }
            else
            {
                type = AjaxResultType.Success;
                _unitOfWorkManager?.Commit();
            }

            if (dict.AuditOperation != null)
            {
                dict.AuditOperation.ResultType = type;
                dict.AuditOperation.Message    = message;
            }
        }
Esempio n. 15
0
 /// <summary>
 /// Called after the action executes, before the action result.
 /// </summary>
 /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext" />.</param>
 public void OnActionExecuted(ActionExecutedContext context)
 {
     unitOfWorkManager?.Commit();
 }