Exemple #1
0
 public void ProcessOrder(Order order, IEventPublisher eventPublisher)
 {
     if (Equals(order.ServiceType, ServiceType.Delivery))
     {
         eventPublisher.Publish(new OrderNeedsDelivery(this));
     }
 }
        public CommandVersioningHandlerModule(IEventPublisher publisher)
        {
            For<CommandMessage<CreateTShirtV2>>()
                .Handle((_, __) => { throw new NotSupportedException(); });

            For<CommandMessage<CreateTShirtV3>>()
                .Handle((commandMessage, ct) =>
                {
                    var command = new CreateTShirtV4
                    {
                        Name = commandMessage.Command.Name,
                        Sizes = commandMessage.Command.Sizes,
                        Colors = commandMessage.Command.Colors,
                        BlankType = "Round"
                    };
                    var upconvertedCommand = new CommandMessage<CreateTShirtV4>(
                        commandMessage.CommandId,
                        commandMessage.RequestUser, 
                        command);
                    return this.DispatchSingle(upconvertedCommand, ct);
                });

            For<CommandMessage<CreateTShirtV4>>()
                .Handle((commandMessage, ct) =>
                {
                    publisher.Publish(new TShirtCreatedV4
                    {
                        BlankType = commandMessage.Command.BlankType,
                        Name = commandMessage.Command.Name,
                        Colors = commandMessage.Command.Colors,
                        Sizes = commandMessage.Command.Sizes
                    });
                    return Task.FromResult(true);
                });
        }
        public void WhenIIssueACreateElectionCommand()
        {
            //setup the "bus" components
            m_commandDispatcher = new CommandDispatcher();
            m_eventPublisher = new EventDispatcher();

            //register the command handler
            var repository = MockRepository.GenerateStub<IRepository<Election>>();
            m_commandDispatcher.Register(new MakeAnElectionCommandHandler(repository, null));

            //register the event handler
            m_eventPublisher.RegisterHandler<ElectionMadeEvent>(@event => m_electionCreatedEvent = @event);

            //wire-up the domain event to the event publisher
            DomainEvents.Register<ElectionMadeEvent>(@event => m_eventPublisher.Publish(@event));

            //create and send the command
            var command = new MakeAnElection
                              {
                                  AdministratorCode = "AdmCode",
                                  CompanyCode = "CoCode",
                                  ParticipantId = "12345",
                                  ElectionAmount = 1000,
                                  ElectionReason = "election reason",
                              };

            m_commandDispatcher.Dispatch<MakeAnElection>(command);
            
            Assert.Pass();
        }
        public void MarkEventsAsCommitted()
        {
            // first publish commmitted events
            foreach (var @event in _changes)
            {
                _eventPublisher?.Publish(@event);
                _eventPublisher?.PublishCommitted(@event);
            }

            _changes.Clear();
        }
        /// <summary>
        /// Register customer
        /// </summary>
        /// <param name="request">Request</param>
        /// <returns>Result</returns>
        public virtual CustomerRegistrationResult RegisterCustomer(CustomerRegistrationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.Customer == null)
            {
                throw new ArgumentException("Can't load current customer");
            }

            var result = new CustomerRegistrationResult();

            if (request.Customer.IsSearchEngineAccount())
            {
                result.AddError("Search engine can't be registered");
                return(result);
            }
            if (request.Customer.IsBackgroundTaskAccount())
            {
                result.AddError("Background task account can't be registered");
                return(result);
            }
            if (request.Customer.IsRegistered())
            {
                result.AddError("Current customer is already registered");
                return(result);
            }
            if (String.IsNullOrEmpty(request.Email))
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailIsNotProvided"));
                return(result);
            }
            if (!CommonHelper.IsValidEmail(request.Email))
            {
                result.AddError(_localizationService.GetResource("Common.WrongEmail"));
                return(result);
            }
            if (String.IsNullOrWhiteSpace(request.Password))
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.PasswordIsNotProvided"));
                return(result);
            }
            if (_customerSettings.UsernamesEnabled)
            {
                if (String.IsNullOrEmpty(request.Username))
                {
                    result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameIsNotProvided"));
                    return(result);
                }
            }

            //validate unique user
            if (_customerService.GetCustomerByEmail(request.Email) != null)
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailAlreadyExists"));
                return(result);
            }
            if (_customerSettings.UsernamesEnabled)
            {
                if (_customerService.GetCustomerByUsername(request.Username) != null)
                {
                    result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameAlreadyExists"));
                    return(result);
                }
            }

            //at this point request is valid
            request.Customer.Username = request.Username;
            request.Customer.Email    = request.Email;

            var customerPassword = new CustomerPassword
            {
                Customer       = request.Customer,
                PasswordFormat = request.PasswordFormat,
                CreatedOnUtc   = DateTime.UtcNow
            };

            switch (request.PasswordFormat)
            {
            case PasswordFormat.Clear:
                customerPassword.Password = request.Password;
                break;

            case PasswordFormat.Encrypted:
                customerPassword.Password = _encryptionService.EncryptText(request.Password);
                break;

            case PasswordFormat.Hashed:
            {
                var saltKey = _encryptionService.CreateSaltKey(5);
                customerPassword.PasswordSalt = saltKey;
                customerPassword.Password     = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat);
            }
            break;
            }
            _customerService.InsertCustomerPassword(customerPassword);

            request.Customer.Active = request.IsApproved;

            //add to 'Registered' role
            var registeredRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered);

            if (registeredRole == null)
            {
                throw new NopException("'Registered' role could not be loaded");
            }
            request.Customer.CustomerRoles.Add(registeredRole);
            //remove from 'Guests' role
            var guestRole = request.Customer.CustomerRoles.FirstOrDefault(cr => cr.SystemName == SystemCustomerRoleNames.Guests);

            if (guestRole != null)
            {
                request.Customer.CustomerRoles.Remove(guestRole);
            }

            //Add reward points for customer registration (if enabled)
            if (_rewardPointsSettings.Enabled &&
                _rewardPointsSettings.PointsForRegistration > 0)
            {
                _rewardPointService.AddRewardPointsHistoryEntry(request.Customer,
                                                                _rewardPointsSettings.PointsForRegistration,
                                                                request.StoreId,
                                                                _localizationService.GetResource("RewardPoints.Message.EarnedForRegistration"));
            }

            _customerService.UpdateCustomer(request.Customer);

            //publish event
            _eventPublisher.Publish(new CustomerPasswordChangedEvent(customerPassword));

            return(result);
        }
Exemple #6
0
 /// <summary>
 /// Publishes the newsletter unsubscribe event.
 /// </summary>
 /// <param name="eventPublisher">The event publisher.</param>
 /// <param name="email">The email.</param>
 public static async Task PublishNewsletterUnsubscribe(this IEventPublisher eventPublisher, string email)
 {
     await eventPublisher.Publish(new EmailUnsubscribedEvent(email));
 }
Exemple #7
0
        /// <summary>
        /// 执行工作流
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <WorkFlowExecutionResult> ExecuteAsync(WorkFlowExecutionContext context)
        {
            var result = new WorkFlowExecutionResult();

            OnExecuting(context, result);
            _eventPublisher.Publish(new WorkFlowExecutingEvent {
                Context = context
            });
            try
            {
                _workFlowInstanceService.BeginTransaction();
                //更新当前步骤处理状态
                _workFlowProcessUpdater.Update(n => n
                                               .Set(f => f.StateCode, context.ProcessState)
                                               .Set(f => f.HandleTime, DateTime.Now)
                                               .Set(f => f.Description, context.Description)
                                               .Set(f => f.Attachments, context.Attachments)
                                               .Where(f => f.WorkFlowProcessId == context.ProcessInfo.WorkFlowProcessId)
                                               );
                //上传附件
                await _attachmentCreater.CreateManyAsync(context.EntityMetaData.EntityId, context.ProcessInfo.WorkFlowProcessId, context.AttachmentFiles).ConfigureAwait(false);

                //更新当前步骤其他处理者状态
                _workFlowProcessUpdater.Update(n => n
                                               .Set(f => f.StateCode, WorkFlowProcessState.Disabled)
                                               .Where(f => f.WorkFlowInstanceId == context.ProcessInfo.WorkFlowInstanceId && f.StepOrder == context.ProcessInfo.StepOrder && f.WorkFlowProcessId != context.ProcessInfo.WorkFlowProcessId)
                                               );
                var nextI     = context.ProcessInfo.StepOrder + 1;
                var nextSteps = _workFlowProcessFinder.Query(n => n.Where(f => f.WorkFlowInstanceId == context.ProcessInfo.WorkFlowInstanceId && f.StepOrder == nextI));
                //如果到了最后一个环节
                if (nextSteps.IsEmpty())
                {
                    //如果同意
                    if (context.ProcessState == WorkFlowProcessState.Passed)
                    {
                        //更新单据状态为审批通过
                        //_workFlowProcessUpdater.UpdateObjectProcessState(context.EntityMetaData, context.InstanceInfo.ObjectId, context.ProcessState);
                        //更新本次申请状态为完成
                        _workFlowInstanceService.Update(n => n
                                                        .Set(f => f.StateCode, context.ProcessState)
                                                        .Set(f => f.CompletedOn, DateTime.Now)
                                                        .Where(f => f.WorkFlowInstanceId == context.InstanceInfo.WorkFlowInstanceId)
                                                        );
                    }
                    //如果驳回
                    else if (context.ProcessState == WorkFlowProcessState.UnPassed)
                    {
                        //var steps = this.Query(n => n.Where(f => f.WorkFlowInstanceId == context.RunnerInfo.WorkFlowInstanceId));
                        ////第一步
                        //if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.FirstStep)
                        //{
                        //    //重新生成审批步骤
                        //    steps.ForEach((n) =>
                        //    {
                        //        n.WorkFlowProcessId = Guid.NewGuid();
                        //        n.Attachments = 0;
                        //        n.Description = string.Empty;
                        //        n.CreatedOn = DateTime.Now;
                        //        n.HandleTime = null;
                        //        n.StartTime = DateTime.Now;
                        //        n.StateCode = WorkFlowProcessState.Waiting;
                        //    });
                        //    this.CreateMany(steps);
                        //}
                        ////上一步
                        //else if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.PrevStep)
                        //{
                        //    var newSteps = new List<WorkFlowProcess>();
                        //    //重新生成上一步、当前步的审批步骤
                        //    var prevStep = steps.Find(n => n.StepOrder == context.ProcessInfo.StepOrder - 1);
                        //    prevStep.WorkFlowProcessId = Guid.NewGuid();
                        //    prevStep.Attachments = 0;
                        //    prevStep.Description = string.Empty;
                        //    prevStep.CreatedOn = DateTime.Now;
                        //    prevStep.HandleTime = null;
                        //    prevStep.StartTime = DateTime.Now;
                        //    prevStep.StateCode = WorkFlowProcessState.Waiting;
                        //    newSteps.Add(prevStep);
                        //    var currentStep = new WorkFlowProcess();
                        //    currentStep.WorkFlowProcessId = Guid.NewGuid();
                        //    currentStep.WorkFlowInstanceId = context.RunnerInfo.WorkFlowInstanceId;
                        //    currentStep.Attachments = 0;
                        //    currentStep.Description = string.Empty;
                        //    currentStep.CreatedOn = DateTime.Now;
                        //    currentStep.HandleTime = null;
                        //    currentStep.StartTime = DateTime.Now;
                        //    currentStep.StateCode = WorkFlowProcessState.Waiting;
                        //    newSteps.Add(currentStep);
                        //    this.CreateMany(newSteps);
                        //}
                        ////某一步
                        //else if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.SpecifyStep)
                        //{
                        //    var newSteps = new List<WorkFlowProcess>();
                        //    //重新生成指定步骤、及后续步骤
                        //    steps.Where(n => n.StepOrder >= context.ProcessInfo.ReturnTo).ToList().ForEach((n) =>
                        //    {
                        //        n.WorkFlowProcessId = Guid.NewGuid();
                        //        n.Attachments = 0;
                        //        n.Description = string.Empty;
                        //        n.CreatedOn = DateTime.Now;
                        //        n.HandleTime = null;
                        //        n.StartTime = DateTime.Now;
                        //        n.StateCode = WorkFlowProcessState.Waiting;
                        //        newSteps.Add(n);
                        //    });
                        //    this.CreateMany(newSteps);
                        //}
                        ////重新提交
                        //else if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.ReSubmit)
                        //{
                        //    //更新单据状态为审批不通过
                        //    this.UpdateObjectProcessState(context.RunnerInfo.EntityId, context.RunnerInfo.ObjectId, context.ProcessState, context.EntityMetaData.Name);
                        //    //更新当前流程实例状态为完成
                        //    runnerService.Update(n => n
                        //        .Set(f => f.StateCode, context.ProcessState)
                        //            .Set(f => f.CompletedOn, DateTime.Now)
                        //        .Where(f => f.WorkFlowInstanceId == context.RunnerInfo.WorkFlowInstanceId)
                        //    );
                        //}
                        //更新单据状态为审批不通过
                        //_workFlowProcessUpdater.UpdateObjectProcessState(context.EntityMetaData, context.InstanceInfo.ObjectId, context.ProcessState);
                        //更新当前流程实例状态为完成
                        _workFlowInstanceService.Update(n => n
                                                        .Set(f => f.StateCode, context.ProcessState)
                                                        .Set(f => f.CompletedOn, DateTime.Now)
                                                        .Where(f => f.WorkFlowInstanceId == context.InstanceInfo.WorkFlowInstanceId)
                                                        );
                    }
                }
                //如果还有下一步
                else
                {
                    //驳回
                    if (context.ProcessState == WorkFlowProcessState.UnPassed)
                    {
                        //    //更新未处理的步骤状态为作废
                        //    this.Update(n => n.Set(f => f.StateCode, WorkFlowProcessState.Disabled).Where(f => f.WorkFlowInstanceId == context.RunnerInfo.WorkFlowInstanceId && f.StateCode == WorkFlowProcessState.Waiting));
                        //    //第一步
                        //    if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.FirstStep)
                        //    {
                        //        var steps = this.Query(n => n.Where(f => f.WorkFlowInstanceId == context.RunnerInfo.WorkFlowInstanceId));
                        //        //重新生成审批步骤
                        //        steps.ForEach((n) =>
                        //        {
                        //            n.WorkFlowProcessId = Guid.NewGuid();
                        //            n.Attachments = 0;
                        //            n.Description = string.Empty;
                        //            n.CreatedOn = DateTime.Now;
                        //            n.HandleTime = null;
                        //            n.StartTime = DateTime.Now;
                        //            n.StateCode = WorkFlowProcessState.Waiting;
                        //        });
                        //        this.CreateMany(steps);
                        //    }
                        //    //上一步
                        //    else if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.PrevStep)
                        //    {
                        //    }
                        //    //某一步
                        //    else if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.SpecifyStep)
                        //    {
                        //    }
                        //    //重新提交
                        //    else if (context.ProcessInfo.ReturnType == (int)WorkFlowStepReturnType.ReSubmit)
                        //    {
                        //        //更新单据状态为审批不通过
                        //        this.UpdateObjectProcessState(context.RunnerInfo.EntityId, context.RunnerInfo.ObjectId, context.ProcessState, context.EntityMetaData.Name);
                        //        //更新当前流程实例状态为完成
                        //        runnerService.Update(n => n
                        //            .Set(f => f.StateCode, context.ProcessState)
                        //            .Set(f => f.CompletedOn, DateTime.Now)
                        //            .Where(f => f.WorkFlowInstanceId == context.RunnerInfo.WorkFlowInstanceId)
                        //        );
                        //        //更新未处理的步骤状态为作废
                        //        this.Update(n => n.Set(f => f.StateCode, WorkFlowProcessState.Disabled).Where(f => f.WorkFlowInstanceId == context.RunnerInfo.WorkFlowInstanceId && f.StateCode == WorkFlowProcessState.Waiting));
                        //    }
                        //更新单据状态为审批不通过
                        //_workFlowProcessUpdater.UpdateObjectProcessState(context.EntityMetaData, context.InstanceInfo.ObjectId, context.ProcessState);
                        //更新当前流程实例状态为完成
                        _workFlowInstanceService.Update(n => n
                                                        .Set(f => f.StateCode, context.ProcessState)
                                                        .Set(f => f.CompletedOn, DateTime.Now)
                                                        .Where(f => f.WorkFlowInstanceId == context.InstanceInfo.WorkFlowInstanceId)
                                                        );
                        //更新未处理的步骤状态为作废
                        _workFlowProcessUpdater.Update(n => n.Set(f => f.StateCode, WorkFlowProcessState.Disabled).Where(f => f.WorkFlowInstanceId == context.InstanceInfo.WorkFlowInstanceId && f.StateCode == WorkFlowProcessState.Waiting));
                    }
                    //同意则转交到下一个处理人
                    else if (context.ProcessState == WorkFlowProcessState.Passed)
                    {
                        //更新下一步骤处理状态为处理中
                        _workFlowProcessUpdater.Update(n => n.Set(f => f.StateCode, WorkFlowProcessState.Processing).Set(f => f.StartTime, DateTime.Now)
                                                       .Where(f => f.WorkFlowInstanceId == context.InstanceInfo.WorkFlowInstanceId && f.StepOrder == nextI));

                        result.NextHandlerId = _workFlowHandlerFinder.GetCurrentHandlerId(context.InstanceInfo, context.ProcessInfo, nextSteps.First().HandlerIdType, nextSteps.First().Handlers);
                    }
                }
                _workFlowInstanceService.CompleteTransaction();
                result.IsSuccess = true;
            }
            catch (Exception e)
            {
                _workFlowInstanceService.RollBackTransaction();
                result.IsSuccess = false;
                result.Message   = e.Message;
                _logService.Error(e);
            }
            OnExecuted(context, result);
            _eventPublisher.Publish(new WorkFlowExecutedEvent {
                Context = context, Result = result
            });
            return(result);
        }
Exemple #8
0
        public virtual ActionResult NewsCommentAdd(int newsItemId, NewsItemModel model, bool captchaValid)
        {
            if (!_newsSettings.Enabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var newsItem = _newsService.GetNewsById(newsItemId);

            if (newsItem == null || !newsItem.Published || !newsItem.AllowComments)
            {
                return(RedirectToRoute("HomePage"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnNewsCommentPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_newsSettings.AllowNotRegisteredUsersToLeaveComments)
            {
                ModelState.AddModelError("", _localizationService.GetResource("News.Comments.OnlyRegisteredUsersLeaveComments"));
            }

            if (ModelState.IsValid)
            {
                var comment = new NewsComment
                {
                    NewsItemId   = newsItem.Id,
                    CustomerId   = _workContext.CurrentCustomer.Id,
                    CommentTitle = model.AddNewComment.CommentTitle,
                    CommentText  = model.AddNewComment.CommentText,
                    IsApproved   = !_newsSettings.NewsCommentsMustBeApproved,
                    StoreId      = _storeContext.CurrentStore.Id,
                    CreatedOnUtc = DateTime.UtcNow,
                };
                newsItem.NewsComments.Add(comment);
                _newsService.UpdateNews(newsItem);

                //notify a store owner;
                if (_newsSettings.NotifyAboutNewNewsComments)
                {
                    _workflowMessageService.SendNewsCommentNotificationMessage(comment, _localizationSettings.DefaultAdminLanguageId);
                }

                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddNewsComment", _localizationService.GetResource("ActivityLog.PublicStore.AddNewsComment"));

                //raise event
                if (comment.IsApproved)
                {
                    _eventPublisher.Publish(new NewsCommentApprovedEvent(comment));
                }

                //The text boxes should be cleared after a comment has been posted
                //That' why we reload the page
                TempData["nop.news.addcomment.result"] = comment.IsApproved
                    ? _localizationService.GetResource("News.Comments.SuccessfullyAdded")
                    : _localizationService.GetResource("News.Comments.SeeAfterApproving");

                return(RedirectToRoute("NewsItem", new { SeName = newsItem.GetSeName(newsItem.LanguageId, ensureTwoPublishedLanguages: false) }));
            }


            //If we got this far, something failed, redisplay form
            model = _newsModelFactory.PrepareNewsItemModel(model, newsItem, true);
            return(View(model));
        }
Exemple #9
0
 /// <inheritdoc />
 public void Publish <TEvent>(TEvent @event)
     where TEvent : IEvent
 {
     _eventPublisher.Publish(@event);
 }
Exemple #10
0
 /// <summary>
 /// Publish ModelPrepared event
 /// </summary>
 /// <typeparam name="T">Type of the model</typeparam>
 /// <param name="eventPublisher">Event publisher</param>
 /// <param name="model">Model</param>
 public static void ModelPrepared <T>(this IEventPublisher eventPublisher, T model)
 {
     eventPublisher.Publish(new ModelPrepared <T>(model));
 }
Exemple #11
0
        public ProcessImageResult ProcessImage(ProcessImageQuery query, bool disposeOutput = true)
        {
            Guard.NotNull(query, nameof(query));

            ValidateQuery(query);

            var watch = new Stopwatch();

            byte[] inBuffer = null;

            try
            {
                watch.Start();

                using (var processor = new ImageFactory(preserveExifData: false, fixGamma: false))
                {
                    var source = query.Source;

                    // Load source
                    if (source is byte[] b)
                    {
                        inBuffer = b;
                    }
                    else if (source is Stream s)
                    {
                        inBuffer = s.ToByteArray();
                    }
                    else if (source is Image img)
                    {
                        processor.Load(img);
                    }
                    else if (source is string str)
                    {
                        var path = NormalizePath(str);
                        using (var fs = File.OpenRead(path))
                        {
                            inBuffer = fs.ToByteArray();
                        }
                    }
                    else if (source is IFile file)
                    {
                        using (var fs = file.OpenRead())
                        {
                            inBuffer = fs.ToByteArray();
                        }
                    }
                    else
                    {
                        throw new ProcessImageException("Invalid source type '{0}' in query.".FormatInvariant(query.Source.GetType().FullName), query);
                    }

                    if (inBuffer != null)
                    {
                        processor.Load(inBuffer);
                    }

                    // Pre-process event
                    _eventPublisher.Publish(new ImageProcessingEvent(query, processor));

                    var result = new ProcessImageResult
                    {
                        Query               = query,
                        SourceWidth         = processor.Image.Width,
                        SourceHeight        = processor.Image.Height,
                        SourceMimeType      = processor.CurrentImageFormat.MimeType,
                        DisposeOutputStream = disposeOutput
                    };

                    // Core processing
                    ProcessImageCore(query, processor, out var fxApplied);

                    // Create & prepare result
                    var outStream = new MemoryStream();
                    processor.Save(outStream);

                    var fmt = processor.CurrentImageFormat;
                    result.FileExtension = fmt.DefaultExtension == "jpeg" ? "jpg" : fmt.DefaultExtension;
                    result.MimeType      = fmt.MimeType;

                    result.HasAppliedVisualEffects = fxApplied;
                    result.Width  = processor.Image.Width;
                    result.Height = processor.Image.Height;

                    if (inBuffer != null)
                    {
                        // Check whether it is more beneficial to return the source instead of the result.
                        // Prefer result only if its size is smaller than the source size.
                        // Result size may be larger if a high-compressed image has been uploaded.
                        // During image processing the source compression algorithm gets lost and the image may be larger in size
                        // after encoding with default encoders.
                        var compare =
                            // only when image was not altered visually...
                            !fxApplied
                            // ...size has not changed
                            && result.Width == result.SourceWidth &&
                            result.Height == result.SourceHeight
                            // ...and format has not changed
                            && result.MimeType == result.SourceMimeType;

                        if (compare && inBuffer.LongLength <= outStream.Length)
                        {
                            // Source is smaller. Throw away result and get back to source.
                            outStream.Dispose();
                            result.OutputStream = new MemoryStream(inBuffer, 0, inBuffer.Length, true, true);
                        }
                    }

                    // Set output stream
                    if (result.OutputStream == null)
                    {
                        result.OutputStream = outStream;
                    }

                    // Post-process event
                    _eventPublisher.Publish(new ImageProcessedEvent(query, processor, result));

                    result.OutputStream.Position = 0;

                    result.ProcessTimeMs = watch.ElapsedMilliseconds;

                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw new ProcessImageException(query, ex);
            }
            finally
            {
                if (query.DisposeSource && query.Source is IDisposable source)
                {
                    source.Dispose();
                }

                watch.Stop();
                _totalProcessingTime += watch.ElapsedMilliseconds;
            }
        }
 public static void MessageTokensAdded <U>(this IEventPublisher eventPublisher, MessageTemplate message, System.Collections.Generic.IList <U> tokens)
 {
     eventPublisher.Publish(new MessageTokensAddedEvent <U>(message, tokens));
 }
 /// <summary>
 /// Publishes the newsletter unsubscribe event.
 /// </summary>
 /// <param name="eventPublisher">The event publisher.</param>
 /// <param name="email">The email.</param>
 public static void PublishNewsletterUnsubscribe(this IEventPublisher eventPublisher, string email)
 {
     eventPublisher.Publish(new EmailUnsubscribedEvent(email));
 }
 /// <summary>
 /// Publishes the newsletter unsubscribe event.
 /// </summary>
 /// <param name="eventPublisher">The event publisher.</param>
 /// <param name="subscription">The newsletter subscription.</param>
 public static void PublishNewsletterUnsubscribe(this IEventPublisher eventPublisher, NewsLetterSubscription subscription)
 {
     eventPublisher.Publish(new EmailUnsubscribedEvent(subscription));
 }
        public async Task Save(T aggregate)
        {
            await eventPublisher.Publish(aggregate);

            aggregate.ClearEvents();
        }
Exemple #16
0
        /// <summary>
        /// 撤消工作流
        /// </summary>
        /// <param name="entityid"></param>
        /// <param name="objectid"></param>
        /// <returns></returns>
        public WorkFlowCancellationResult Cancel(WorkFlowCancellationContext context)
        {
            WorkFlowCancellationResult result = new WorkFlowCancellationResult();

            result.IsSuccess = true;
            var Instance = _WorkFlowInstanceService.Find(n => n.EntityId == context.EntityMetaData.EntityId && n.ObjectId == context.ObjectId && n.StateCode == WorkFlowProcessState.Processing);

            if (Instance == null)
            {
                result.IsSuccess = false;
                result.Message   = _loc["workflow_noinstance"];
            }
            else if (Instance.ApplicantId != _user.SystemUserId)
            {
                result.IsSuccess = false;
                result.Message   = _loc["workflow_nopermissioncancel"];
            }
            else if (Instance.StateCode != WorkFlowProcessState.Processing)
            {
                result.IsSuccess = false;
                result.Message   = _loc["workflow_nopermissioncancel"];
            }
            var currentStep = _workFlowProcessFinder.Find(n => n.WorkFlowInstanceId == Instance.WorkFlowInstanceId && n.StateCode == WorkFlowProcessState.Processing);

            if (result.IsSuccess)
            {
                if (currentStep != null && !currentStep.AllowCancel)
                {
                    result.IsSuccess = false;
                    result.Message   = _loc["workflow_notallowcancel"];
                }
            }
            result = OnCancelling(context, result);
            _eventPublisher.Publish(new WorkFlowCancellingEvent {
                ObjectId = context.ObjectId, EntityMetaData = context.EntityMetaData, Instance = Instance, CurrentStep = currentStep, Result = result
            });
            if (result.IsSuccess)
            {
                try
                {
                    _WorkFlowInstanceService.BeginTransaction();
                    _WorkFlowInstanceService.Update(n => n
                                                    .Set(f => f.StateCode, WorkFlowProcessState.Canceled)
                                                    .Set(f => f.CompletedOn, DateTime.Now)
                                                    .Where(f => f.WorkFlowInstanceId == Instance.WorkFlowInstanceId)
                                                    );
                    _workFlowProcessUpdater.Update(n => n.Set(f => f.StateCode, WorkFlowProcessState.Disabled).Where(f => f.WorkFlowInstanceId == Instance.WorkFlowInstanceId));
                    //_workFlowProcessUpdater.UpdateObjectProcessState(context.EntityMetaData, context.ObjectId, WorkFlowProcessState.Canceled);
                    _WorkFlowInstanceService.CompleteTransaction();
                    result.IsSuccess = true;
                }
                catch (Exception e)
                {
                    _WorkFlowInstanceService.RollBackTransaction();
                    result.IsSuccess = false;
                    result.Message   = e.Message;
                    _logService.Error(e);
                }
            }
            result = OnCancelled(context, result);
            _eventPublisher.Publish(new WorkFlowCancelledEvent {
                ObjectId = context.ObjectId, EntityMetaData = context.EntityMetaData, Instance = Instance, CurrentStep = currentStep, Result = result
            });
            return(result);
        }
Exemple #17
0
 /// <summary>
 /// Publishes (queues) an <see cref="EventData"/> instance using the specified <see cref="EventMetadata.Key"/>.
 /// </summary>
 /// <typeventPublisheraram name="T">The value <see cref="Type"/>.</typeventPublisheraram>
 /// <param name="eventPublisher">The <see cref="IEventPublisher"/>.</param>
 /// <param name="value">The event value</param>
 /// <param name="source">The event source.</param>
 /// <param name="subject">The event subject.</param>
 /// <param name="action">The event action.</param>
 /// <param name="key">The event key.</param>
 /// <returns>The <see cref="IEventPublisher"/> for fluent-style method-chaining.</returns>
 public static IEventPublisher PublishValue <T>(this IEventPublisher eventPublisher, T value, Uri source, string subject, string?action = null, params IComparable?[] key) => eventPublisher.Publish(eventPublisher.CreateValueEvent(value, source, subject, action, key));
 public static void EntityTokensAdded <T, U>(this IEventPublisher eventPublisher, T entity, System.Collections.Generic.IList <U> tokens) where T : BaseEntity
 {
     eventPublisher.Publish(new EntityTokensAddedEvent <T, U>(entity, tokens));
 }
 public static void ViewComponentEvent <T, U>(this IEventPublisher eventPublisher, T entity, U component) where U : BaseViewComponent
 {
     eventPublisher.Publish(new ViewComponentEvent <T, U>(entity, component));
 }
Exemple #20
0
 public static void EntityDeleted <T>(this IEventPublisher eventPublisher, T entity) where T : IDBTable
 {
     eventPublisher.Publish(new EntityDeleted <T>(entity));
 }
 public static void ViewComponentEvent <T, U>(this IEventPublisher eventPublisher, string viewName, U component) where U : BaseViewComponent
 {
     eventPublisher.Publish(new ViewComponentEvent <T, U>(viewName, component));
 }
 /// <summary>
 /// Produce event
 /// </summary>
 /// <typeparam name="TEvent"></typeparam>
 /// <param name="sampleEvent"></param>
 #endregion // Documentation
 public static void Publish <TEvent>(TEvent sampleEvent)
 {
     s_eventPublisher.Publish <TEvent>(sampleEvent);
 }
Exemple #23
0
        public virtual async Task <IActionResult> VendorReviewsAdd(string vendorId, VendorReviewsModel model, bool captchaValid,
                                                                   [FromServices] IOrderService orderService, [FromServices] IEventPublisher eventPublisher, [FromServices] CaptchaSettings captchaSettings)
        {
            var vendor = await _vendorService.GetVendorById(vendorId);

            if (vendor == null || !vendor.Active || !vendor.AllowCustomerReviews)
            {
                return(RedirectToRoute("HomePage"));
            }

            //validate CAPTCHA
            if (captchaSettings.Enabled && captchaSettings.ShowOnVendorReviewPage && !captchaValid)
            {
                ModelState.AddModelError("", captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_vendorSettings.AllowAnonymousUsersToReviewVendor)
            {
                ModelState.AddModelError("", _localizationService.GetResource("VendorReviews.OnlyRegisteredUsersCanWriteReviews"));
            }

            //allow reviews only by customer that bought something from this vendor
            if (_vendorSettings.VendorReviewPossibleOnlyAfterPurchasing &&
                !(await orderService.SearchOrders(customerId: _workContext.CurrentCustomer.Id, vendorId: vendorId, os: OrderStatus.Complete)).Any())
            {
                ModelState.AddModelError(string.Empty, _localizationService.GetResource("VendorReviews.VendorReviewPossibleOnlyAfterPurchasing"));
            }

            if (ModelState.IsValid)
            {
                var vendorReview = await _vendorViewModelService.InsertVendorReview(vendor, model);

                //activity log
                await _customerActivityService.InsertActivity("PublicStore.AddVendorReview", vendor.Id, _localizationService.GetResource("ActivityLog.PublicStore.AddVendorReview"), vendor.Name);

                //raise event
                if (vendorReview.IsApproved)
                {
                    await eventPublisher.Publish(new VendorReviewApprovedEvent(vendorReview));
                }

                await _vendorViewModelService.PrepareVendorReviewsModel(model, vendor);

                model.AddVendorReview.Title      = null;
                model.AddVendorReview.ReviewText = null;

                model.AddVendorReview.SuccessfullyAdded = true;
                if (!vendorReview.IsApproved)
                {
                    model.AddVendorReview.Result = _localizationService.GetResource("VendorReviews.SeeAfterApproving");
                }
                else
                {
                    model.AddVendorReview.Result = _localizationService.GetResource("VendorReviews.SuccessfullyAdded");
                }

                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            await _vendorViewModelService.PrepareVendorReviewsModel(model, vendor);

            return(View(model));
        }
Exemple #24
0
 /// <summary>
 /// Publish ModelReceived event
 /// </summary>
 /// <typeparam name="T">Type of the model</typeparam>
 /// <param name="eventPublisher">Event publisher</param>
 /// <param name="model">Model</param>
 /// <param name="modelState">Model state</param>
 public static void ModelReceived <T>(this IEventPublisher eventPublisher, T model, ModelStateDictionary modelState)
 {
     eventPublisher.Publish(new ModelReceived <T>(model, modelState));
 }
        public virtual IActionResult ProductReviewsAdd(int productId, ProductReviewsModel model, bool captchaValid)
        {
            var product = _productService.GetProductById(productId);

            if (product == null || product.Deleted || !product.Published || !product.AllowCustomerReviews)
            {
                return(RedirectToRoute("HomePage"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnProductReviewPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_catalogSettings.AllowAnonymousUsersToReviewProduct)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Reviews.OnlyRegisteredUsersCanWriteReviews"));
            }

            if (_catalogSettings.ProductReviewPossibleOnlyAfterPurchasing)
            {
                var hasCompletedOrders = _orderService.SearchOrders(customerId: _workContext.CurrentCustomer.Id,
                                                                    productId: productId,
                                                                    osIds: new List <int> {
                    (int)OrderStatus.Complete
                },
                                                                    pageSize: 1).Any();
                if (!hasCompletedOrders)
                {
                    ModelState.AddModelError(string.Empty, _localizationService.GetResource("Reviews.ProductReviewPossibleOnlyAfterPurchasing"));
                }
            }

            if (ModelState.IsValid)
            {
                //save review
                var rating = model.AddProductReview.Rating;
                if (rating < 1 || rating > 5)
                {
                    rating = _catalogSettings.DefaultProductRatingValue;
                }
                var isApproved = !_catalogSettings.ProductReviewsMustBeApproved;

                var productReview = new ProductReview
                {
                    ProductId       = product.Id,
                    CustomerId      = _workContext.CurrentCustomer.Id,
                    Title           = model.AddProductReview.Title,
                    ReviewText      = model.AddProductReview.ReviewText,
                    Rating          = rating,
                    HelpfulYesTotal = 0,
                    HelpfulNoTotal  = 0,
                    IsApproved      = isApproved,
                    CreatedOnUtc    = DateTime.UtcNow,
                    StoreId         = _storeContext.CurrentStore.Id,
                };
                product.ProductReviews.Add(productReview);
                _productService.UpdateProduct(product);

                //update product totals
                _productService.UpdateProductReviewTotals(product);

                //notify store owner
                if (_catalogSettings.NotifyStoreOwnerAboutNewProductReviews)
                {
                    _workflowMessageService.SendProductReviewNotificationMessage(productReview, _localizationSettings.DefaultAdminLanguageId);
                }

                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddProductReview",
                                                        string.Format(_localizationService.GetResource("ActivityLog.PublicStore.AddProductReview"), product.Name), product);

                //raise event
                if (productReview.IsApproved)
                {
                    _eventPublisher.Publish(new ProductReviewApprovedEvent(productReview));
                }

                model = _productModelFactory.PrepareProductReviewsModel(model, product);
                model.AddProductReview.Title      = null;
                model.AddProductReview.ReviewText = null;

                model.AddProductReview.SuccessfullyAdded = true;
                if (!isApproved)
                {
                    model.AddProductReview.Result = _localizationService.GetResource("Reviews.SeeAfterApproving");
                }
                else
                {
                    model.AddProductReview.Result = _localizationService.GetResource("Reviews.SuccessfullyAdded");
                }

                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            model = _productModelFactory.PrepareProductReviewsModel(model, product);
            return(View(model));
        }
        public ActionResult RefundNotify(FormCollection form)
        {
            if (!(_paymentPluginManager.LoadPluginBySystemName("Nop.Plugin.Payments.AliPay") is AliPayPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("插件无法加载");
            }
            var aliPayPaymentSettings = _settingService.LoadSetting <AliPayPaymentSettings>(_storeContext.CurrentStore.Id);

            var partner = aliPayPaymentSettings.Partner;

            if (string.IsNullOrEmpty(partner))
            {
                throw new Exception("合作身份者ID 不能为空");
            }

            var key = aliPayPaymentSettings.Key;

            if (string.IsNullOrEmpty(key))
            {
                throw new Exception("MD5密钥不能为空");
            }

            var sellerEmail = aliPayPaymentSettings.SellerEmail;

            if (string.IsNullOrEmpty(sellerEmail))
            {
                throw new Exception("卖家Email 不能为空");
            }

            ///↓↓↓↓↓↓↓ 获取支付宝POST过来通知消息,并以“参数名 = 参数值”的形式组成数组↓↓↓↓↓↓↓↓
            int i;
            var coll      = Request.Form;
            var sortedStr = coll.Keys.ToList();
            SortedDictionary <string, string> sPara = new SortedDictionary <string, string>();

            for (i = 0; i < sortedStr.Count; i++)
            {
                sPara.Add(sortedStr[i], Request.Form[sortedStr[i]]);
            }
            ///↑↑↑↑↑↑↑ 获取支付宝POST过来通知消息,并以“参数名 = 参数值”的形式组成数组↑↑↑↑↑↑↑↑
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                AlipayNotify aliNotify    = new AlipayNotify(partner: partner, key: key, input_charset: "utf-8", sign_type: sPara["sign_type"]);
                var          notify_type  = Request.Form["notify_type"];
                var          notify_id    = Request.Form["notify_id"];
                var          sign         = Request.Form["sign"];
                bool         verifyResult = aliNotify.Verify(sPara, notify_id, sign);

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

                    //批次号

                    string batch_no = Request.Form["batch_no"];

                    //批量退款数据中转账成功的笔数

                    string success_num = Request.Form["success_num"];

                    //批量退款数据中的详细信息
                    string result_details = Request.Form["result_details"];

                    //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓业务处理↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                    try
                    {
                        string create_time = batch_no.Substring(0, 8);
                        var    refundInfo  = _refundInfoService.GetRefundInfoByBatch_no(batch_no);
                        if (refundInfo != null && refundInfo.OrderId > 0)
                        {
                            if (refundInfo.RefundStatus == RefundStatus.refund || notify_id == refundInfo.Notify_Id)
                            {
                                return(Content("success"));
                            }

                            var result_list = result_details.Split('#');
                            var item        = result_list[0];

                            refundInfo.Notify_Id   = notify_id;
                            refundInfo.Notify_Type = notify_type;

                            var obj            = item.Split('^');
                            var out_Trade_No   = obj[0];                //交易号
                            var AmountToRefund = decimal.Parse(obj[1]); //退款金额
                            var note           = obj[2];                //退款说明

                            var order       = _orderService.GetOrderById(refundInfo.OrderId);
                            var paymentInfo = _paymentInfoService.GetByOrderId(refundInfo.OrderId);
                            if (order != null)
                            {
                                if (note.ToUpper() == "SUCCESS")
                                {
                                    if (AmountToRefund >= 0 && AmountToRefund == refundInfo.AmountToRefund)
                                    {
                                        #region 成功
                                        order.OrderNotes.Add(new OrderNote
                                        {
                                            Note = string.Format("支付宝退款成功,退款编号:{0},退款金额:{1},交易号:{2},说明:{3}", batch_no, AmountToRefund, out_Trade_No, note),
                                            DisplayToCustomer = true,
                                            CreatedOnUtc      = DateTime.UtcNow
                                        });

                                        ////总退款
                                        decimal totalAmountRefunded = Math.Abs(order.RefundedAmount) + AmountToRefund;

                                        order.RefundedAmount = totalAmountRefunded;

                                        if (paymentInfo.Total > order.RefundedAmount)
                                        {
                                            order.PaymentStatus = PaymentStatus.PartiallyRefunded;
                                        }
                                        else
                                        {
                                            order.PaymentStatus = PaymentStatus.Refunded;
                                        }

                                        _orderService.UpdateOrder(order);

                                        ///改变订单状态
                                        _orderProcessingService.CheckOrderStatus(order);

                                        //修改退款记录为退款成功
                                        refundInfo.RefundStatusId = (int)RefundStatus.refund;
                                        refundInfo.RefundOnUtc    = DateTime.Now;
                                        refundInfo.Result_Details = result_details;
                                        _refundInfoService.Update(refundInfo);

                                        ///通知
                                        var orderRefundedStoreOwnerNotificationQueuedEmailId = _workflowMessageService.SendOrderRefundedStoreOwnerNotification(order, AmountToRefund, _localizationSettings.DefaultAdminLanguageId);
                                        if (orderRefundedStoreOwnerNotificationQueuedEmailId.Count > 0 && orderRefundedStoreOwnerNotificationQueuedEmailId[0] > 0)
                                        {
                                            order.OrderNotes.Add(new OrderNote
                                            {
                                                Note = string.Format("\"订单退款\" email (to store owner) has been queued. Queued email identifier: {0}.", orderRefundedStoreOwnerNotificationQueuedEmailId),
                                                DisplayToCustomer = false,
                                                CreatedOnUtc      = DateTime.UtcNow
                                            });
                                            _orderService.UpdateOrder(order);
                                        }
                                        var orderRefundedCustomerNotificationQueuedEmailId = _workflowMessageService.SendOrderRefundedCustomerNotification(order, AmountToRefund, order.CustomerLanguageId);
                                        if (orderRefundedCustomerNotificationQueuedEmailId.Count > 0 && orderRefundedCustomerNotificationQueuedEmailId[0] > 0)
                                        {
                                            order.OrderNotes.Add(new OrderNote
                                            {
                                                Note = string.Format("\"订单退款\" email (to customer) has been queued. Queued email identifier: {0}.", orderRefundedCustomerNotificationQueuedEmailId),
                                                DisplayToCustomer = false,
                                                CreatedOnUtc      = DateTime.UtcNow
                                            });
                                            _orderService.UpdateOrder(order);
                                        }

                                        //已退款事件
                                        _eventPublisher.Publish(new OrderRefundedEvent(order, AmountToRefund));
                                        return(Content("success"));

                                        #endregion
                                    }
                                    else
                                    {
                                        #region 错误
                                        //退款异常
                                        refundInfo.RefundStatusId = (int)RefundStatus.error;
                                        _refundInfoService.Update(refundInfo);
                                        order.OrderNotes.Add(new OrderNote
                                        {
                                            Note = string.Format("支付宝退款异常,退款编号:{0},退款金额:{1},交易号:{2},说明:{3}", batch_no, AmountToRefund, out_Trade_No, "退款金额错误"),
                                            DisplayToCustomer = false,
                                            CreatedOnUtc      = DateTime.UtcNow
                                        });
                                        _orderService.UpdateOrder(order);
                                        return(Content("success"));

                                        #endregion
                                    }
                                }
                            }
                        }
                        throw new Exception(string.Format("支付宝退款通知异常,退款编号:{0},退款金额:{1},交易号:{2},说明:{3}", batch_no, refundInfo.AmountToRefund, refundInfo.Out_Trade_No, "非正常处理"));
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex.Message);
                        return(Content("fail"));
                    }
                    //↑↑↑↑↑↑↑↑↑↑↑↑↑↑业务处理↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
                    ///结束业务处理
                    return(Content("success"));//请不要修改或删除
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    return(Content("fail"));
                }
            }
            else
            {
                return(Content("无通知参数"));
            }
            return(Content(""));
        }
Exemple #27
0
        public ActionResult Create(CategoryModel model, bool continueEditing, FormCollection form)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            {
                return(AccessDeniedView());
            }

            if (ModelState.IsValid)
            {
                var category = model.ToEntity();
                category.CreatedOnUtc = DateTime.UtcNow;
                category.UpdatedOnUtc = DateTime.UtcNow;
                _categoryService.InsertCategory(category);

                //search engine name
                model.SeName = category.ValidateSeName(model.SeName, category.Name, true);
                _urlRecordService.SaveSlug(category, model.SeName, 0);

                //locales
                UpdateLocales(category, model);

                //disounts
                var allDiscounts = _discountService.GetAllDiscounts(DiscountType.AssignedToCategories, null, true);
                foreach (var discount in allDiscounts)
                {
                    if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))
                    {
                        category.AppliedDiscounts.Add(discount);
                    }
                }
                _categoryService.UpdateCategory(category);

                //update "HasDiscountsApplied" property
                _categoryService.UpdateHasDiscountsApplied(category);

                //update picture seo file name
                UpdatePictureSeoNames(category);

                //ACL (customer roles)
                SaveCategoryAcl(category, model);

                //Stores
                _storeMappingService.SaveStoreMappings <Category>(category, model.SelectedStoreIds);

                _eventPublisher.Publish(new ModelBoundEvent(model, category, form));

                //activity log
                _customerActivityService.InsertActivity("AddNewCategory", _localizationService.GetResource("ActivityLog.AddNewCategory"), category.Name);

                NotifySuccess(_localizationService.GetResource("Admin.Catalog.Categories.Added"));
                return(continueEditing ? RedirectToAction("Edit", new { id = category.Id }) : RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            //templates
            PrepareTemplatesModel(model);
            //parent categories
            if (model.ParentCategoryId.HasValue)
            {
                var parentCategory = _categoryService.GetCategoryById(model.ParentCategoryId.Value);
                if (parentCategory != null && !parentCategory.Deleted)
                {
                    model.ParentCategoryBreadcrumb = parentCategory.GetCategoryBreadCrumb(_categoryService);
                }
                else
                {
                    model.ParentCategoryId = 0;
                }
            }

            PrepareCategoryModel(model, null, true);
            //ACL
            PrepareAclModel(model, null, true);
            //Stores
            PrepareStoresMappingModel(model, null, true);
            return(View(model));
        }
 public static void EntityInserted <T>(this IEventPublisher eventPublisher, T entity) where T : BaseEntity
 {
     eventPublisher.Publish(new EntityInserted <T>(entity));
 }
        public virtual async Task <IActionResult> ProductReviewsAdd(string productId, ProductReviewsModel model, bool captchaValid,
                                                                    [FromServices] IOrderService orderService, [FromServices] IEventPublisher eventPublisher)
        {
            var product = await _productService.GetProductById(productId);

            if (product == null || !product.Published || !product.AllowCustomerReviews)
            {
                return(RedirectToRoute("HomePage"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnProductReviewPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_catalogSettings.AllowAnonymousUsersToReviewProduct)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Reviews.OnlyRegisteredUsersCanWriteReviews"));
            }

            if (_catalogSettings.ProductReviewPossibleOnlyAfterPurchasing &&
                !(await orderService.SearchOrders(customerId: _workContext.CurrentCustomer.Id, productId: productId, os: OrderStatus.Complete)).Any())
            {
                ModelState.AddModelError(string.Empty, _localizationService.GetResource("Reviews.ProductReviewPossibleOnlyAfterPurchasing"));
            }

            if (ModelState.IsValid)
            {
                var productReview = await _productViewModelService.InsertProductReview(product, model);

                //activity log
                await _customerActivityService.InsertActivity("PublicStore.AddProductReview", product.Id, _localizationService.GetResource("ActivityLog.PublicStore.AddProductReview"), product.Name);

                //raise event
                if (productReview.IsApproved)
                {
                    await eventPublisher.Publish(new ProductReviewApprovedEvent(productReview));
                }

                await _productViewModelService.PrepareProductReviewsModel(model, product);

                model.AddProductReview.Title      = null;
                model.AddProductReview.ReviewText = null;

                model.AddProductReview.SuccessfullyAdded = true;
                if (!productReview.IsApproved)
                {
                    model.AddProductReview.Result = _localizationService.GetResource("Reviews.SeeAfterApproving");
                }
                else
                {
                    model.AddProductReview.Result = _localizationService.GetResource("Reviews.SuccessfullyAdded");
                }

                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            await _productViewModelService.PrepareProductReviewsModel(model, product);

            return(View(model));
        }
 /// <summary>
 /// Publishes the order placed event.
 /// </summary>
 /// <param name="eventPublisher">The event publisher.</param>
 /// <param name="order">The order.</param>
 public static void PublishOrderPlaced(this IEventPublisher eventPublisher, Order order)
 {
     eventPublisher.Publish(new OrderPlacedEvent(order));
 }
Exemple #31
0
 private static void RegisterExceptionHandler()
 {
     AppDomain.CurrentDomain.UnhandledException +=
         (sender, args) => { EventPublisher.Publish(new OnApplicationUnexpectedlyStoppedEvent(App)); };
 }
Exemple #32
0
 public static async Task EntityTokensAdded <T>(this IEventPublisher eventPublisher, T entity, Drop liquidDrop, LiquidObject liquidObject) where T : ParentEntity
 {
     await eventPublisher.Publish(new EntityTokensAddedEvent <T>(entity, liquidDrop, liquidObject));
 }
Exemple #33
0
        public int Start()
        {
            var arrived = 0;

            while (arrived < _cargosToDeliver)
            {
                foreach (var t in _transportations)
                {
                    if (t.Destination.HasValue && t.Destination.Value == t.Location)
                    {
                        // Arrive
                        var arrive = new Event
                        {
                            EventName   = EventType.Arrive,
                            Location    = t.Location,
                            Cargo       = t.Cargo,
                            Kind        = t.Kind,
                            Time        = _time,
                            TransportId = t.Id
                        };
                        _eventPublisher.Publish(arrive);
                        t.Destination = null;
                    }

                    // Unload
                    if (t.Kind == Kind.Ship && t.Location == Location.A)
                    {
                        t.Cargo       = null;
                        t.Destination = Location.Port;
                        arrived++;
                    }
                    if (t.Kind == Kind.Truck && t.Location == Location.Port)
                    {
                        PortQueue.Enqueue(t.Cargo !.Single());
                        t.Cargo       = null;
                        t.Destination = Location.Factory;
                    }
                    if (t.Kind == Kind.Truck && t.Location == Location.B)
                    {
                        t.Cargo       = null;
                        t.Destination = Location.Factory;
                        arrived++;
                    }

                    // Load
                    if (t.Kind == Kind.Truck && t.Location == Location.Factory && FactoryQueue.TryDequeue(out var cargo))
                    {
                        t.Cargo ??= new List <Cargo>();
                        t.Cargo.Add(cargo);
                        t.Destination = cargo.Destination == Location.A ? Location.Port : Location.B;
                    }
                    if (t.Kind == Kind.Ship && t.Location == Location.Port && PortQueue.TryDequeue(out var cargoP))
                    {
                        t.Cargo ??= new List <Cargo>();
                        t.Cargo.Add(cargoP);
                        t.Destination = Location.A;
                    }

                    // Location update (move)
                    var location = Move[t.Location](t);
                    if (location != t.Location)
                    {
                        if (t.Kind == Kind.Truck && (t.Location == Location.Factory || t.Location == Location.Port || t.Location == Location.B) ||
                            t.Kind == Kind.Ship && (t.Location == Location.Port || t.Location == Location.A))
                        {
                            // Depart
                            var depart = new Event
                            {
                                EventName   = EventType.Depart,
                                Destination = t.Destination !.Value,
                                Location    = t.Location,
                                Cargo       = t.Cargo,
                                Kind        = t.Kind,
                                Time        = _time,
                                TransportId = t.Id
                            };
                            _eventPublisher.Publish(depart);
                        }

                        t.Location = location;
                    }
                }

                _time++;
            }

            return(_time - 1);
        }