public Appointment AddNewAppointment(Appointment appointment)
        {
            if (_appointments.Any(a => a.Id == appointment.Id))
            {
                throw new ArgumentException("Cannot add duplicate appointment to schedule.", "appointment");
            }

            appointment.State = TrackingState.Added;
            _appointments.Add(appointment);

            MarkConflictingAppointments();

            var appointmentScheduledEvent = new AppointmentScheduledEvent(appointment);

            DomainEvents.Raise(appointmentScheduledEvent);

            return(appointment);
        }
示例#2
0
        /// <summary>
        /// Removes the item.
        /// </summary>
        /// <param name="ItemId">The item identifier.</param>
        /// <exception cref="DomainException"></exception>
        public virtual void RemoveItem(Guid ItemId)
        {
            var ItemToDelete = OrderItems.Find(i => i.ItemId == ItemId);

            if (ItemToDelete != null)
            {
                OrderItems.Remove(ItemToDelete);
            }
            else
            {
                throw new DomainException($"Order {Id} does not have any items with Id {ItemId}");
            }

            DomainEvents.Raise(new OrderItemRemoved()
            {
                _OrderItem = ItemToDelete
            });
        }
示例#3
0
        //By not making it public I make it easier to ensure that no cart line items are created with non-existing variants before a foreign key error is thrown
        private void AddVariant(string variantId, int count = 1)
        {
            Guid cartLineItemId;
            var  existingCartLineItem = CartLineItems.SingleOrDefault(item => item.VariantId == variantId);

            if (existingCartLineItem != null)
            {
                cartLineItemId = existingCartLineItem.Id;
                existingCartLineItem.IncreaseCount(count);
                DomainEvents.Raise(new CartLineItemUpdatedEvent(Id, cartLineItemId, variantId, existingCartLineItem.Count));
            }
            else
            {
                cartLineItemId = Guid.NewGuid();
                CartLineItems.Add(new CartLineItem(cartLineItemId, Id, variantId));
                DomainEvents.Raise(new CartLineItemAddedEvent(Id, cartLineItemId, variantId));
            }
        }
        public bool AddJob(ScheduleJobsInfo job)
        {
            if (job == null)
            {
                return(false);
            }
            if (job.Id == Guid.Empty)
            {
                job.Id = Guid.NewGuid();
            }
            bool successed = repository.Save(job);

            if (successed)
            {
                DomainEvents.Raise <ScheduleJobSaveSuccessedEvent>(new ScheduleJobSaveSuccessedEvent(job));
            }
            return(successed);
        }
示例#5
0
        public static Cart Create(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            var cart = new Cart();

            cart.Id         = Guid.NewGuid();
            cart.CustomerId = customer.Id;

            DomainEvents.Raise(new CartCreated {
                Cart = cart
            });

            return(cart);
        }
示例#6
0
        public Customer(string firstName, string lastName)
        {
            if (String.IsNullOrEmpty(firstName))
            {
                throw new InvalidCustomerFirstNameException();
            }

            if (String.IsNullOrEmpty(lastName))
            {
                throw new InvalidCustomerLastNameException();
            }

            Id        = Guid.NewGuid();
            FirstName = firstName;
            LastName  = lastName;

            DomainEvents.Raise(new CustomerCreated(Id, FirstName, LastName));
        }
示例#7
0
        //public Person AddMember(Person person)
        //{
        //    if (person == null)
        //        return null;

        //    if (this.Members.Any(m => m.ID == person.ID))
        //        return null;

        //    this.Members.Add(person);

        //    DomainEvents.Raise(new MembersChangedEvent(this, person));

        //    return person;
        //}

        public void ChangeMembers(IEnumerable <Person> members)
        {
            if (members == null)
            {
                return;
            }

            // delete Members (Persons), that are not exist in new Member collection
            var memberToDelete = this.Members.Where(p => members.All(m => m.ID != p.ID)).ToList();

            memberToDelete.ForEach(p => this.Members.Remove(p));

            // new members to add
            var membersToAdd = members.Where(m => this.Members.All(p => p.ID != m.ID)).ToList();

            membersToAdd.ForEach(m => this.Members.Add(m));

            DomainEvents.Raise(new MembersChangedEvent(this, this.Members));
        }
示例#8
0
        /// <summary>
        /// Creates the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="name">The name.</param>
        /// <param name="cost">The cost.</param>
        /// <returns></returns>
        public static Item Create(Guid id, string name, double cost)
        {
            Item item = new Item()
            {
                Id       = id,
                Name     = name,
                Created  = DateTime.Now,
                Modified = DateTime.Now,
                Active   = true,
                Price    = cost
            };

            DomainEvents.Raise <ItemCreated>(new ItemCreated()
            {
                Item = item
            });

            return(item);
        }
示例#9
0
        /// <summary>
        /// Creates new order with the specified identifier.
        /// </summary>
        /// <param name="Id">The identifier.</param>
        /// <param name="userId">The user identifier.</param>
        /// <returns></returns>
        public static Order Create(Guid Id, Guid userId)
        {
            //if (user == null)
            //    throw new ArgumentNullException("customer");

            Order order = new Order
            {
                Id         = Id,
                CustomerId = userId,
                Created    = DateTime.Now
            };

            DomainEvents.Raise(new OrderCreated()
            {
                Order = order
            });

            return(order);
        }
示例#10
0
        public void RemoveVariant(string variantId)
        {
            var existingCartLineItem = CartLineItems.SingleOrDefault(item => item.VariantId == variantId);

            if (existingCartLineItem == null)
            {
                throw new VariantNotExistingInCartException(Id, variantId);
            }

            existingCartLineItem.DecreaseCount();
            if (existingCartLineItem.Count == 0)
            {
                DeleteCartLineItem(existingCartLineItem);
            }
            else
            {
                DomainEvents.Raise(new CartLineItemUpdatedEvent(Id, existingCartLineItem.Id, variantId, existingCartLineItem.Count));
            }
        }
示例#11
0
        public static Product Create(PlainText name, Quantity quantity, Cost cost, ProductCode productCode, PlainText description, string image)
        {
            Product product = new Product()
            {
                Id          = Guid.NewGuid(),
                Name        = name,
                Quantity    = quantity,
                Created     = DateTime.Now,
                Modified    = DateTime.Now,
                Active      = true,
                Cost        = cost,
                Code        = productCode,
                Description = description,
                Image       = image
            };

            DomainEvents.Raise <ProductCreated>(new ProductCreated(product));
            return(product);
        }
示例#12
0
        public bool UpdateJob(ScheduleJobsInfo job)
        {
            ScheduleJobsInfo info = repository.FindOne(job.Id);

            if (info == null)
            {
                return(false);
            }
            info.Mode    = job.Mode;
            info.RunPlan = job.RunPlan;

            bool successed = repository.Save(info);

            if (successed)
            {
                DomainEvents.Raise <ScheduleJobSaveSuccessedEvent>(new ScheduleJobSaveSuccessedEvent(job));
            }
            return(successed);
        }
示例#13
0
        public void SendMail(MailMessage mailMessage)
        {
            if (mailMessage.Attachments != null && mailMessage.Attachments.Count > 0)
            {
                IList <AttachStream> attachStreams = new List <AttachStream>();

                foreach (var item in mailMessage.Attachments)
                {
                    attachStreams.Add(new AttachStream()
                    {
                        FileName = item.Name, FileStream = item.ContentStream
                    });
                }
                MailMessageServiceContent sentmailMessage = new MailMessageServiceContent()
                {
                    From      = mailMessage.From.Address, To = String.Join(";", mailMessage.To.Select(a => a.Address).ToArray())
                    , Subject = mailMessage.Subject, Body = mailMessage.Body, AttachFiles = attachStreams
                };

                DomainEvents.Raise(new WebClientSentMailEvent()
                {
                    MailMessage = sentmailMessage
                });
            }
            else
            {
                IList <AttachStream> attachStreams = new List <AttachStream>();

                MailMessageServiceContent sentmailMessage = new MailMessageServiceContent()
                {
                    From = mailMessage.From.Address,
                    To   = String.Join(";", mailMessage.To.Select(a => a.Address).ToArray())
                    ,
                    Subject = mailMessage.Subject,
                    Body    = mailMessage.Body
                };

                DomainEvents.Raise(new WebClientSentMailEvent()
                {
                    MailMessage = sentmailMessage
                });
            }
        }
示例#14
0
 public virtual void Activate(
     string name,
     string reference,
     string address1,
     string address2,
     string address3,
     string phoneNumber,
     Guid?liasonEmployeeId)
 {
     Name             = name;
     Reference        = reference;
     Address1         = address1;
     Address2         = address2;
     Address3         = address3;
     PhoneNumber      = phoneNumber;
     LiasonEmployeeId = liasonEmployeeId;
     CurrentAgreement.Activate();
     DomainEvents.Raise(new ClientActivatedDomainEvent(this));
 }
示例#15
0
        public Comment ReplyTo(UserInfo user, string body)
        {
            if (!CommentsEnabled)
            {
                throw new Exception("Comments are not allowed");
            }

            var reply = new Comment(this, user, body);

            Comments.Add(reply);
            DomainEvents.Raise(new UserCommentedOnPost
            {
                User    = user,
                Comment = reply,
                Post    = this,
            });

            return(reply);
        }
示例#16
0
        public static Product Create(string name, Money price, string imageLink, ProductCategory category, string description)
        {
            Guard.ForNullOrEmpty(name, "name");
            Guard.ForNull(price, "price");

            var product = new Product();

            product.Name        = name;
            product.Description = description;
            product.Price       = price;
            product.Category    = category;
            product.ImageLink   = imageLink;
            product.State       = SaveState.UnSaved;


            DomainEvents.Raise(new ProductCreatedEvent(product));

            return(product);
        }
示例#17
0
        public Purchase Checkout(Customer customer, Cart cart)
        {
            var checkoutIssue = this.CanCheckOut(customer, cart);

            if (checkoutIssue.HasValue)
            {
                throw new Exception(checkoutIssue.Value.ToString());
            }

            var purchase = Purchase.Create(cart);

            _purchaseRepository.Add(purchase);

            cart.Clear();

            DomainEvents.Raise(new CustomerCheckedOut(purchase));

            return(purchase);
        }
        public static Stop Create(Group group, User by, string problem)
        {
            if (group == null)
            {
                throw new ValidationException("Group can't be empty");
            }

            if (by == null)
            {
                throw new ValidationException("User can't be empty");
            }

            if (String.IsNullOrEmpty(problem))
            {
                throw new ValidationException("Problem can't be empty");
            }

            if (!group.Users.Contains(by))
            {
                throw new ValidationException("Only user in the group");
            }

            Stop stop = new Stop();

            stop.Id         = Guid.NewGuid();
            stop.Problem    = problem;
            stop.Date       = TimeProvider.Current.UtcNow;
            stop.groupUsers = new List <string>();
            stop.By         = by.FullName;
            stop.ById       = by.Id;
            stop.GroupName  = group.Name;
            stop.GroupId    = group.Id;

            foreach (User groupUser in group.Users)
            {
                stop.groupUsers.Add(groupUser.FullName);
            }

            DomainEvents.Raise <Stopped>(new Stopped(stop));

            return(stop);
        }
        public static Customer Create(Guid id, string firstname, string lastname, string email, Country country)
        {
            if (string.IsNullOrEmpty(firstname))
            {
                throw new ArgumentNullException("firstname");
            }

            if (string.IsNullOrEmpty(lastname))
            {
                throw new ArgumentNullException("lastname");
            }

            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentNullException("email");
            }

            if (country == null)
            {
                throw new ArgumentNullException("country");
            }

            Customer customer = new Customer()
            {
                Id        = id,
                FirstName = firstname,
                LastName  = lastname,
                Email     = email,
                Active    = true,
                Created   = DateTime.Today,
                Country   = country
            };

            DomainEvents.Raise <CustomerCreated>(new CustomerCreated()
            {
                Customer = customer
            });

            customer.Cart = Cart.Create(customer);

            return(customer);
        }
示例#20
0
        public static TonerJob Create(
            long clientId,
            List <Toner> toners,
            long collectedById,
            long deliveredById,
            DateTime @in,
            DateTime @out,
            List <PurchaseItem> purchaseItems,
            string remarks,
            int otherCharges,
            double discount
            )
        {
            Guard.ForLessEqualZero(clientId, "clientId");
            Guard.ForLessEqualZero(collectedById, "collectedById");
            Guard.ForLessEqualZero(deliveredById, "deliveredById");
            Guard.ForNull(purchaseItems, "purchaseItems");
            purchaseItems.ForEach(p => Guard.ForNull(p.StockItem, "purchaseItems.StockItem"));
            Guard.ForNull(toners, "toners");

            if (@out < @in)
            {
                throw new ArgumentException("In time should be less than Out time!");
            }

            DomainEvents.Raise(new PurchasedItemsEvent(DateTime.Now, purchaseItems.ToArray()));

            return(new TonerJob(
                       clientId,
                       toners,
                       collectedById,
                       deliveredById,
                       @in,
                       @out,
                       purchaseItems,
                       remarks,
                       otherCharges,
                       discount,
                       DateTime.Now,
                       DateTime.Now
                       ));
        }
示例#21
0
    public Invoice Invoice(IInvoiceNumberGenerator generator, string vendorInvoiceNumber, DateTime date, decimal amount)
    {
        // These guards maintain business integrity of the PO.
        if (this.IsFullyInvoiced)
        {
            throw new Exception("The PO is fully invoiced.");
        }
        if (ContainsInvoice(vendorInvoiceNumber))
        {
            throw new Exception("Duplicate invoice!");
        }

        var invoiceNumber = generator.GenerateInvoiceNumber(this.VendorId, vendorInvoiceNumber, date);

        var invoice = new Invoice(invoiceNumber, vendorInvoiceNumber, date, amount);

        this.Invoices.Add(invoice);
        DomainEvents.Raise(new PurchaseOrderInvoicedEvent(this.Id, invoice.InvoiceNumber));
        return(invoice);
    }
        public KeyEdit CreateKey(KeyEdit key)
        {
            var existKeyActive = Keys.Any(x => x.Status == EKeyStatus.Active);

            if (!existKeyActive)
            {
                AddBrokenValidationRule(new ValidationFailure(nameof(Status), UserMessages.ErrorRuleKeyActiveExists));
            }
            else
            {
                _keys.Add(key);

                DomainEvents.Raise(new KeyAddedEvent()
                {
                    Key = key
                });
            }

            return(key);
        }
示例#23
0
        public static Product Create(Guid id, string name, int quantity, decimal cost, ProductCode productCode)
        {
            var product = new Product
            {
                Id       = id,
                Name     = name,
                Quantity = quantity,
                Created  = DateTime.Now,
                Modified = DateTime.Now,
                Active   = true,
                Cost     = cost,
                Code     = productCode
            };

            DomainEvents.Raise(new ProductCreated {
                Product = product
            });

            return(product);
        }
        internal static void EnsureSiteBootHasBeenStarted()
        {
            lock (_bootStartedSync)
            {
                if (_bootingStarted)
                {
                    return;
                }

                _bootingStarted = true;
                Task.Run(() =>
                {
                    Boot();
                    IsBooted = true;
                }).ContinueWith(x =>

                                DomainEvents.Raise(new SiteBootCompleted())
                                );
            }
        }
示例#25
0
        private void Raise_GivenMultipleRegisteredHandlersOnSameEvent_ThenAllhandlersAreCalledOnRaisedEvent()
        {
            // Arrange
            _kernel.Bind <IResultHolder>().To <ResultHolder>().InThreadScope();
            var firstHandlerResult  = new ResultHolder();
            var secondHandlerResult = new ResultHolder();

            _kernel.Bind <IDomainEventHandler <MyDomainEvent> >().ToConstant(new MyHandler(firstHandlerResult)).InThreadScope();
            _kernel.Bind <IDomainEventHandler <MyDomainEvent> >().ToConstant(new MyHandler(secondHandlerResult)).InThreadScope();
            var sut = new DomainEvents(_kernel);

            // Act
            sut.Raise(new MyDomainEvent {
                Id = ExpectedDomainEventId
            });

            // Assert
            Assert.Equal(ExpectedDomainEventId, firstHandlerResult.ResultingValue);
            Assert.Equal(ExpectedDomainEventId, secondHandlerResult.ResultingValue);
        }
示例#26
0
        public void SetUserName(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("User Name cannot be empty");
            }
            if (userName.Any(c => char.IsWhiteSpace(c)))
            {
                throw new ArgumentException("User Name cannot contain white-space characters");
            }

            var previousUserName = UserName;

            UserName = userName;

            if (!string.Equals(userName, previousUserName, StringComparison.InvariantCultureIgnoreCase))
            {
                DomainEvents.Raise(new Events.UserNameChanged(this, previousUserName));
            }
        }
        public void Execute(ZoomInCommand command)
        {
            var scatterPlot = _repository.Get <ScatterPlot>();

            var viewExtent = scatterPlot.GetViewExtent();

            var x = viewExtent.X + (command.Center.X * ZoomInFactor) + (viewExtent.Width * ZoomInFactor) / 2;

            var y = viewExtent.Y + (command.Center.Y * ZoomInFactor) + (viewExtent.Height * ZoomInFactor) / 2;

            var width = viewExtent.Width - viewExtent.Width * ZoomInFactor;

            var height = viewExtent.Height - viewExtent.Height * ZoomInFactor;

            var zoomedViewExtent = new Rect(x, y, width, height);

            scatterPlot.SetViewExtent(zoomedViewExtent);

            DomainEvents.Raise(new ScatterPlotChangedEvent());
        }
示例#28
0
        // An event is something that has happened in the past
        private static void Main(string[] args)
        {
            Bootstrap.Start();

            // Preparando o evento
            var idCliente = 10;
            var idObjeto  = 574;
            var encomenda = new Encomenda(idCliente, idObjeto);

            var fazerUmaEncomenda = new EncomendaRealizada
                                    (
                encomenda.ClienteId,
                encomenda.ObjetoId,
                encomenda.DataEntregaPrevista
                                    );

            // Realizando o evento
            DomainEvents.Raise(fazerUmaEncomenda);
            Console.ReadKey();
        }
示例#29
0
        protected override void Execute()
        {
            var offer = Session.Get <Offer>(OfferId);

            if (offer == null)
            {
                throw new InvalidOperationException("Cannot find offer.");
            }

            offer.CompleteOffer(false);
            // Some other things to do when offer is lost
            // ...

            Session.Update(offer);

            DomainEvents.Raise(new OfferLostEvent
            {
                Offer = offer
            });
        }
示例#30
0
        public bool Start()
        {
            while (!stop)
            {
                var data = new List <SensorData>();
                foreach (var tag in tags)
                {
                    data.Add(new SensorData(
                                 tag,
                                 DateTime.Now.Ticks,
                                 new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds(),
                                 "Good"));
                }
                var sensorDataEvent = new SensorDataEvent(data);
                DomainEvents.Raise(sensorDataEvent);
                Thread.Sleep(1000);
            }

            return(true);
        }