Esempio n. 1
0
 private KeyPair(FileInfo privateKey, FileInfo publicKey, FileInfo passPhrase)
 {
     this.PrivateKey = privateKey;
     this.PublicKey  = publicKey;
     this.PassPhrase = passPhrase;
     DomainEvents.Publish(new KeyPairGeneratedEvent(this.Id));
 }
        public void TestSubscribe()
        {
            //Define a message class to send
            var msg = new Msg {
                Content = MagicString
            };

            //subscribe you handlers
            DomainEvents <Msg> .Subscribe(Handler);

            //maby ways to send
            DomainEvents <Msg> .Publish(msg);

            DomainEvents.Publish(msg);
            DomainEvents.Publish(msg, typeof(Msg));

            Assert.AreEqual(counter, 3);

            //unsubcribe when done as we are not using weakreferences internally
            DomainEvents <Msg> .Unsubscribe(Handler);

            DomainEvents.Publish(msg);

            Assert.AreEqual(counter, 3);
        }
 public void OnSuccesfullSaveSwtichesToReadMode(CmdApplicationConfigurationViewModel sut)
 {
     sut.ToggleEdit.Execute(null);
     Assert.True(sut.IsInEditMode);
     DomainEvents.Publish(new ConfigurationSavedEvent(Guid.NewGuid()));
     Assert.False(sut.IsInEditMode);
 }
Esempio n. 4
0
        /// <summary>
        /// get tocid by annotation ,and used for get TOC By TOCId;
        /// </summary>
        /// <param name="annotation"></param>
        /// <returns></returns>
        public int GetTOCIdByAnnotation(Annotation annotation)
        {
            DomainEvents.Publish(new PublicationOpeningEvent(annotation.BookId, false)).Wait();
            var tocDetail = packageAccess.GetTOCDetailByDocId(GlobalAccess.Instance.CurrentPublication.DecryptedDbFullName, annotation.DocId);

            return(tocDetail.ID);
        }
Esempio n. 5
0
 private void DoSubmitVerify(string content)
 {
     if (CanSubmitVerify())
     {
         if (content == null)
         {
             this.VerifyStatus = AccountVerifyStatus.Submited;
         }
         var verify = new AccountVerify()
         {
             AccountId  = this.ID,
             CreateTime = DateTime.Now,
             Content    = content,
             Status     = this.VerifyStatus,
         };
         this.AccountVerifies.Add(verify);
         DomainEvents.Publish(new SubmitVerifyEvent()
         {
             Account = this, AccountVerify = verify
         });
     }
     else
     {
         throw new SubmitApplyException("当前不允许提交审核");
     }
 }
Esempio n. 6
0
 private Task PublishTagDeletedEvent(Guid tagId)
 {
     return(Task.Run(async() =>
     {
         await DomainEvents.Publish(new TagDeletedEvent(tagId, GlobalAccess.Instance.Email, GlobalAccess.Instance.ServiceCode));
     }));
 }
Esempio n. 7
0
        /// <summary>
        /// Add new Annotation
        /// </summary>
        /// <param name="annotation"></param>
        /// <returns></returns>
        public async Task AddAnnotation(Annotation annotation)
        {
            await DomainEvents.Publish(new PublicationOpeningEvent(annotation.BookId, false));

            annotation.UpdatedTime = DateTime.UtcNow;
            annotation.Status      = AnnotationStatusEnum.Created;
            annotation.IsUpdated   = false;

            Annotations annotations = new Annotations();

            annotations.Email             = GlobalAccess.Instance.Email;
            annotations.ServiceCode       = GlobalAccess.Instance.ServiceCode;
            annotations.DocumentID        = annotation.DocId;
            annotations.AnnotationType    = (int)annotation.Type;
            annotations.BookID            = annotation.BookId;
            annotations.AnnotationCode    = annotation.AnnotationCode;
            annotations.AnnotationContent = annotation.ToXmlString();
            annotations.CreatedDate       = DateTime.Now;
            annotations.LastModifiedDate  = DateTime.Now;
            annotations.Status            = (int)AnnotationStatusEnum.Created;
            annotations.IsSynced          = false;
            annotations.NoteText          = annotation.NoteText;
            annotations.HighlightText     = annotation.HighlightText;
            annotationAccess.AddAnnotation(annotations);
        }
Esempio n. 8
0
        public static async Task <bool> RestFullPingServiceRequest(Uri uri, string uriTemplate, CancellationToken cancellationToken)
        {
            try
            {
                var response = await pingHclient.GetAsync(new Uri(uri + uriTemplate), cancellationToken);

                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        DomainEvents.Publish(new LastSyncedTimeChangedEvent()).WithNoWarning();
                        var status = await response.Content.ReadAsStringAsync();

                        var pingStatus = JsonConvert.DeserializeObject <PingStatus>(status);
                        return(pingStatus.Status);
                    }
                }
            }
            catch (OperationCanceledException)
            {//add cancel operation
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Unable to reach: " + uri + " Error: " + ex);
            }
            return(false);
        }
Esempio n. 9
0
        public static async Task <HttpResponse> RestFullServiceJsonRequest(Uri uri, string uriTemplate, Object serviceRequest, CancellationToken token = default(CancellationToken))
        {
            HttpResponse httpresponse = new HttpResponse {
                IsSuccess = false
            };
            JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };
            string strEncodeBody = JsonConvert.SerializeObject(serviceRequest, microsoftDateFormatSettings);
            var    response      = await hclient.PostAsync(new Uri(uri + uriTemplate), new StringContent(strEncodeBody)
            {
                Headers =
                {
                    ContentType = new MediaTypeHeaderValue(Constants.CONTENT_TYPEJSON)
                }
            }, token);

            if (response != null)
            {
                httpresponse.IsSuccess = (response.StatusCode == HttpStatusCode.OK);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Logger.Log("Response Error" + response.ReasonPhrase);
                    httpresponse.Content = response.ReasonPhrase;
                }
                else
                {
                    httpresponse.Content = await response.Content.ReadAsStringAsync();

                    DomainEvents.Publish(new LastSyncedTimeChangedEvent()).WithNoWarning();
                }
            }
            return(httpresponse);
        }
Esempio n. 10
0
 public void DispatchEvents()
 {
     foreach (IDomainEvent @event in Events)
     {
         DomainEvents.Publish(@event);
     }
     ClearEvents();
 }
Esempio n. 11
0
        public void DownVote(Guid contributorId)
        {
            var vote = new DownVote(contributorId);

            Votes.Add(vote);

            DomainEvents.Publish(new QuestionDownVoted(Id, GetVoteCount(), contributorId));
        }
Esempio n. 12
0
 public void PublishAnotherEventDoesNotInvokeHandlersOfOtherEvents(
     Mock <IEventHandler <TestEvent> > testHandler,
     TestAnotherEvent anotherEventData)
 {
     DomainEvents.Subscribe(testHandler.Object);
     DomainEvents.Publish(anotherEventData);
     testHandler.Verify(a => a.Handle(It.IsAny <TestEvent>()), Times.Never());
 }
Esempio n. 13
0
 public void PublishRaisesEventsToSubscriber(
     Mock <IEventHandler <TestEvent> > testHandler,
     TestEvent eventData)
 {
     DomainEvents.Subscribe(testHandler.Object);
     DomainEvents.Publish(eventData);
     testHandler.Verify(a => a.Handle(eventData), Times.Once());
 }
Esempio n. 14
0
 public void PublishWithNoSubscribersDoesNotCallHandler(
     Mock <IEventHandler <TestEvent> > testHandler,
     TestEvent eventData)
 {
     DomainEvents.ClearAllSubscriptions();
     DomainEvents.Publish(eventData);
     testHandler.Verify(a => a.Handle(eventData), Times.Never());
 }
Esempio n. 15
0
 public void ClearAllSubscriptionsDoesNotRaiseEventsToPreviouslySubscribedClients(
     Mock <IEventHandler <TestEvent> > testHandler,
     TestEvent eventData)
 {
     DomainEvents.Subscribe(testHandler.Object);
     DomainEvents.ClearAllSubscriptions();
     DomainEvents.Publish(eventData);
     testHandler.Verify(a => a.Handle(eventData), Times.Never());
 }
Esempio n. 16
0
 public void SubscribersRegisteredAfterClearingAllSubscriptionsGetsNotifiedOfEvents(
     Mock <IEventHandler <TestEvent> > testHandler,
     TestEvent eventData)
 {
     DomainEvents.ClearAllSubscriptions();
     DomainEvents.Subscribe(testHandler.Object);
     DomainEvents.Publish(eventData);
     testHandler.Verify(a => a.Handle(eventData), Times.Once());
 }
Esempio n. 17
0
        /// <summary>
        /// Update a existing Annotation
        /// </summary>
        /// <param name="annotation"></param>
        /// <returns></returns>
        public async Task UpdateAnnotation(Annotation annotation)
        {
            await DomainEvents.Publish(new PublicationOpeningEvent(annotation.BookId, false));

            annotation.UpdatedTime = DateTime.UtcNow;
            annotation.Status      = AnnotationStatusEnum.Updated;
            annotation.IsUpdated   = true;

            annotationAccess.UpdateAnnotation(annotation.DocId, annotation.Type, AnnotationStatusEnum.Updated, annotation.ToXmlString(), DateTime.Now, false, annotation.AnnotationCode);
        }
Esempio n. 18
0
 public int SaveToSqliteWithSynctags()
 {
     try
     {
         return(SaveToSqlite(this.Tags, GlobalAccess.Instance.Email, GlobalAccess.Instance.ServiceCode));
     }
     finally
     {
         DomainEvents.Publish(new SyncTagsEvent());
     }
 }
        private async Task UpdateCurrentPublication(DlBook dlBook)
        {
            var isSamePublication = (GlobalAccess.Instance.CurrentPublication != null &&
                                     GlobalAccess.Instance.CurrentPublication.DlBook.BookId == dlBook.BookId);

            //update currentPublication infomation when current publication is the downloaded publication
            if (isSamePublication)
            {
                await DomainEvents.Publish(new PublicationOpeningEvent(dlBook, true));
            }
        }
Esempio n. 20
0
        public async Task <List <PageItem> > GetPagesByTOCID(int bookId, int tocId)
        {
            await DomainEvents.Publish(new PublicationOpeningEvent(bookId, false));

            var currentPublication = GlobalAccess.Instance.CurrentPublication;

            if (currentPublication.HasPage)
            {
                return(currentPublication.Pages.Where(page => page.TOCID == tocId).ToList());
            }
            return(null);
        }
Esempio n. 21
0
        public async Task <PageItem> GetFirstPageItem(int bookId, int tocId)
        {
            await DomainEvents.Publish(new PublicationOpeningEvent(bookId, false));

            var currentPublication = GlobalAccess.Instance.CurrentPublication;

            if (currentPublication.HasPage)
            {
                var pages = await GetPagesByTOCID(bookId, tocId);

                return(pages.FirstOrDefault());
            }
            return(null);
        }
Esempio n. 22
0
        public static void Dispatch <TCommand>(TCommand command) where TCommand : ICommand
        {
            var commandInterface = typeof(TCommand).GetInterfaces().FirstOrDefault(t => t.GetInterfaces().Any(t1 => t1 == typeof(ICommand)));

            if (commandInterface == null)
            {
                CommandHandlerFactory.GetHandlerFor <TCommand>().Execute(command);
            }
            else
            {
                var cmd = CommandHandlerFactory.GetHandlerFor(commandInterface);
                cmd.GetType().GetMethod("Execute").Invoke(cmd, new object[] { command });
            }
            DomainEvents.Publish();
        }
Esempio n. 23
0
        public async Task <int> GetMaxPageNum(int bookId)
        {
            await DomainEvents.Publish(new PublicationOpeningEvent(bookId, false));

            var currentPublication = GlobalAccess.Instance.CurrentPublication;

            if (currentPublication.HasPage)
            {
                return(currentPublication.Pages.Max((o) => o.Identifier));
            }
            else
            {
                return(0);
            }
        }
Esempio n. 24
0
        public void AddComment(Comment comment)
        {
            const int requiredReputation = 1000;

            if (comment.GetContributorReputation() < requiredReputation)
            {
                throw new InsufficientReputationException(
                          $@"The contributor '{comment.GetContributorId()}', does not have the required reputation to comment on the question '{Id}', 
                        current reputation: {comment.GetContributorReputation()},
                        required reputation: {requiredReputation}");
            }

            Comments.Add(comment);

            DomainEvents.Publish(new QuestionCommentAdded(Id, comment.Id, comment.GetContributorId()));
        }
Esempio n. 25
0
        public void Decrypt(FileInfo fileToDecrypt, ICryptographyExecutionService cryptoCmdService)
        {
            CryptographyResponse response;

            try
            {
                response = cryptoCmdService.Execute(new DecryptionRequest(fileToDecrypt, this.PublicKey, this.PassPhrase));
                if (response == null || response.Files.Count() != 1)
                {
                    throw new Exception();
                }
            }
            catch (Exception e) { throw; }

            DomainEvents.Publish(new FileDecryptedEvent(this.Id, response.Files.First()));
        }
Esempio n. 26
0
        public void AddAnAnswer(Answer answer)
        {
            const int requiredReputation = 1000;

            if (answer.GetContributorReputation() < requiredReputation)
            {
                throw new InsufficientReputationException(
                          $@"The contributor '{answer.GetContributorId()}', does not have the required reputation to add an answer to the question '{Id}', 
                        current reputation: {answer.GetContributorReputation()},
                        required reputation: {requiredReputation}");
            }

            Answers.Add(answer);

            DomainEvents.Publish <AnswerAdded>(new AnswerAdded(Id, answer.Id, answer.GetContributorId()));
        }
Esempio n. 27
0
        public void PublishRaisesEventsToAllSubscribers(
            IEnumerable <Mock <IEventHandler <TestEvent> > > testHandlers,
            TestEvent eventData)
        {
            foreach (var testHandler in testHandlers)
            {
                DomainEvents.Subscribe(testHandler.Object);
            }

            DomainEvents.Publish(eventData);

            foreach (var testHandler in testHandlers)
            {
                testHandler.Verify(a => a.Handle(eventData), Times.Once());
            }
        }
Esempio n. 28
0
 public void ResetPassword(int userId)
 {
     if (this.Status == AccountStatus.Froze || this.Status == AccountStatus.Loss)
     {
         throw new AccountFrozeException("竞买号已冻结或挂失,不允许重置密码");
     }
     if (this.Trade.CreatorId != userId)
     {
         throw new AccountFrozeException("挂牌人只能重置自己宗地的竞买号的密码");
     }
     this.Password        = GeneratePassword();
     this.PasswordUpdated = false;
     DomainEvents.Publish(new ResetPasswordEvent()
     {
         Account = this
     });
 }
Esempio n. 29
0
        public void Add(T item)
        {
            Printer.Print(ConsoleColor.Yellow);

            var aggregate = Cloner.DeepClone(item);

            if (!Data.Events.ContainsKey(typeof(T)))
            {
                Data.Events.Add(typeof(T), new Dictionary <Guid, List <DomainEvent> >());
            }

            if (Data.Events[typeof(T)].ContainsKey(aggregate.Id))
            {
                if (aggregate.CommittedEvents.Count != Data.Events[typeof(T)][aggregate.Id].Count)
                {
                    var missingEvents = Data.Events[typeof(T)][aggregate.Id].Where(e => !aggregate.CommittedEvents.Any(ae => e.EventId == ae.EventId)).ToList();

                    if (!aggregate.TryResolveConflicts(missingEvents))
                    {
                        var eventsMissed      = string.Join(", ", missingEvents.Select(e => e.GetType().Name + " by: " + e.By + " at: " + e.At));
                        var uncommittedEvents = string.Join(", ", aggregate.UncommittedEvents.Select(e => e.GetType().Name));
                        throw new Exception("Concurrency Exception, missed the following events: " + eventsMissed + " conflicted with: " + uncommittedEvents);
                    }
                    else
                    {
                        var eventsMissed      = string.Join(", ", missingEvents.Select(e => e.GetType().Name + " by: " + e.By + " at: " + e.At));
                        var uncommittedEvents = string.Join(", ", aggregate.UncommittedEvents.Select(e => e.GetType().Name));
                        Printer.Print("Concurrency Resolved Successfully for events: " + eventsMissed + " merged with: " + uncommittedEvents, ConsoleColor.Yellow);
                    }
                }
                Data.Events[typeof(T)][aggregate.Id].AddRange(aggregate.UncommittedEvents);
            }
            else
            {
                Data.Events[typeof(T)].Add(aggregate.Id, aggregate.UncommittedEvents);
            }

            item.CommittedEvents.AddRange(item.UncommittedEvents);

            foreach (var uncommittedEvent in item.UncommittedEvents)
            {
                DomainEvents.Publish(uncommittedEvent);
            }

            item.UncommittedEvents.Clear();
        }
Esempio n. 30
0
        public void AcceptAnswer(Guid answerId, Guid contributorId)
        {
            if (contributorId != Poster.Id)
            {
                throw new InvalidContributorException("Only the question poster may accept the answer");
            }

            var answer = Answers.FirstOrDefault(x => x.Id == answerId);

            if (answer == null)
            {
                throw new InvalidAnswerException(Id, answerId);
            }

            answer.AcceptAnswer();

            DomainEvents.Publish(new AnswerAccepted(Id, answerId));
        }