public void ShouldReturnErrorWhenDocumentExists()
        {
            var emailService      = new FakeEmailService();
            var studentRepository = new FakeStudentRepository();
            var handler           = new SubscriptionHandle(studentRepository, emailService);

            var command = new CreateBoletoSubscriptionCommand();

            command.FirstName         = "Tony";
            command.LastName          = "Stark";
            command.Document          = "99999999999";
            command.Email             = "*****@*****.**";
            command.BoletoNumber      = "1324254342";
            command.BarCode           = "1234456245";
            command.PaymentNumber     = "3134324";
            command.PaidDate          = DateTime.Now;
            command.ExpireDate        = DateTime.Now.AddMonths(1);
            command.Total             = 60;
            command.TotalPaid         = 60;
            command.Payer             = "Empresas Stark";
            command.PayerDocument     = "12345678910";
            command.PayerDocumentType = EDocumentType.CPF;
            command.PayerEmail        = "*****@*****.**";
            command.Street            = "rua teste";
            command.City    = "cidade teste";
            command.State   = "estado teste";
            command.Country = "USA";
            command.ZipCode = "877659870";

            handler.Handle(command);

            Assert.AreEqual(false, handler.Valid);
        }
Example #2
0
 internal new void HandleEvent(object data, SubscriptionHandle handle)
 {
     if (data is String || data is DateTime)
     {
         eventReceived = true;
     }
 }
Example #3
0
        /// <summary>
        /// Processes the event correlation.
        /// </summary>
        /// <param name="e">The <see cref="MessageEventArgs"/> instance containing the event data.</param>
        /// <exception cref="IllegalAttributeUsageException"></exception>
        private void ProcessEventCorrelation(MessageEventArgs e)
        {
            var         correlation = Serializer.Deserialize <KeyValuePair <EventHandle, EventHandle> >(e.Message.Data);
            EventHandle first       = correlation.Key;
            EventHandle second      = correlation.Value;

            /*
             * Add to list of correlations?
             * Deliver to subscribers
             *      The subscriptions point directly to the subscriber instances, the handle is matching already
             */
            var groupings           = EllaModel.Instance.FilterSubscriptions(s => true).GroupBy(s => s.Subscriber);
            var relevantsubscribers = groupings
                                      .Where(
                g =>
                g.Any(g1 => Equals(g1.Handle.EventHandle, first)) &&
                g.Any(g2 => Equals(g2.Handle.EventHandle, second)));
            var results = relevantsubscribers
                          .Select(
                g =>
                new
            {
                Object = g.Key,
                Method =
                    ReflectionUtils.GetAttributedMethod(g.Key.GetType(), typeof(AssociateAttribute))
            });

            _log.DebugFormat("Found {0} relevant subscribers for event correlation", results.Count());
            foreach (var result in results)
            {
                if (result.Method != null)
                {
                    if (result.Method.GetParameters().Count() != 2 || result.Method.GetParameters().Any(p => p.ParameterType != typeof(SubscriptionHandle)))
                    {
                        throw new IllegalAttributeUsageException(String.Format("Method {0} attributed as Associate has invalid parameters (count or type)", result.Method));
                    }
                    int subscriberid = EllaModel.Instance.GetSubscriberId(result.Object);
                    var subscriber   = relevantsubscribers.Single(g => g.Key == result.Object);
                    var subscription = subscriber
                                       .Where(s => Equals(s.Handle.EventHandle, first));
                    SubscriptionHandle handle1 = subscription
                                                 .Select(s => s.Handle).First();
                    SubscriptionHandle handle2 = relevantsubscribers.Where(g => g.Key == result.Object).First().Where(s => Equals(s.Handle.EventHandle, second)).Select(s => s.Handle).First();
                    result.Method.Invoke(result.Object, new object[] { handle1, handle2 });
                    result.Method.Invoke(result.Object, new object[] { handle2, handle1 });
                }
            }
        }
        /// <summary>
        /// Performs a callback to a publisher that a new subscriber has been added
        /// </summary>
        /// <param name="ev">The ev.</param>
        /// <param name="handle">The handle.</param>
        internal static void NotifyPublisher(Event ev, SubscriptionHandle handle)
        {
            string callback = ev.EventDetail.SubscriptionCallback;

            if (callback == null)
            {
                _log.DebugFormat("No subscription callback supplied for event {0} of publisher {1}", ev.EventDetail.ID, ev.Publisher.GetType().Name);
                return;
            }

            MethodInfo info = ev.Publisher.GetType().GetMethod(callback);


            if (info != null)
            {
                object[] parameters = { ev.EventDetail.ID, handle };
                info.Invoke(ev.Publisher, parameters);
            }
            else
            {
                _log.DebugFormat("Could not find callback method {0}", callback);
            }
        }
Example #5
0
        /// <summary>
        /// Handles a new event by serializing and sending it to the remote subscriber
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="handle">The handle.</param>
        internal void HandleEvent(object data, SubscriptionHandle handle)
        {
            /*
             * check that incoming data object is serializable
             * Serialize it
             * Transfer
             */
            try
            {
                if (data.GetType().IsSerializable)
                {
                    Message m = new Message();
                    m.Type = MessageType.Publish;
                    byte[] serialize = Serializer.Serialize(data);
                    //PublisherID
                    //EventID
                    //data
                    byte[] payload = new byte[serialize.Length + 4];
                    Array.Copy(BitConverter.GetBytes((int)EllaModel.Instance.GetPublisherId(EventToHandle.Publisher)), payload, 2);
                    Array.Copy(BitConverter.GetBytes(EventToHandle.EventDetail.ID), 0, payload, 2, 2);
                    Array.Copy(serialize, 0, payload, 4, serialize.Length);
                    m.Data = payload;
                    _log.DebugFormat("Sending message with data type {0} to remote stub", data.GetType().Name);

                    Send(m);
                }
                else
                {
                    _log.ErrorFormat("Object {0} of Event {1} is not serializable", data, handle);
                }
            }
            catch (Exception ex)
            {
                _log.FatalFormat("Could not send {0}: {1}", data.GetType(), ex.Message);
                throw;
            }
        }
        /// <summary>
        /// Does the local subscription.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="subscriberInstance">The subscriber instance.</param>
        /// <param name="newDataCallback">The new data callback.</param>
        /// <param name="evaluateTemplateObject">The evaluate template object.</param>
        /// <param name="subscriptionCallback">The subscription callback.</param>
        /// <param name="policy">The modification policy.</param>
        /// <exception cref="System.ArgumentException">subscriberInstance must be a valid subscriber</exception>
        /// <exception cref="IllegalAttributeUsageException"></exception>
        internal static void DoLocalSubscription <T>(object subscriberInstance, Action <T, SubscriptionHandle> newDataCallback, Func <T, bool> evaluateTemplateObject, Action <Type, SubscriptionHandle> subscriptionCallback, DataModifyPolicy policy)
        {
            /*
             * find all matching events from currently active publishers
             * check if subscriber instace is valid subscriber
             * hold a list of subscriptions
             */
            if (!Is.Subscriber(subscriberInstance.GetType()))
            {
                _log.ErrorFormat("{0} is not a valid subscriber", subscriberInstance.GetType().ToString());
                throw new ArgumentException("subscriberInstance must be a valid subscriber");
            }
            var matches = EllaModel.Instance.ActiveEvents.FirstOrDefault(g => g.Key == typeof(T));

            if (matches != null)
            {
                Dictionary <SubscriptionHandle, SubscriptionHandle> correlatedEvents = new Dictionary <SubscriptionHandle, SubscriptionHandle>();
                MethodBase associateMethod = ReflectionUtils.GetAttributedMethod(subscriberInstance.GetType(), typeof(AssociateAttribute));

                _log.DebugFormat("Found {0} matches for subsription to {1}", matches.Count(), typeof(T));
                foreach (var m in matches)
                {
                    if (m.Publisher == subscriberInstance)
                    {
                        _log.DebugFormat("Not subscribing {0} for itself", subscriberInstance);
                        continue;
                    }
                    object templateObject = Create.TemplateObject(m.Publisher, m.EventDetail.ID);
                    T      template       = templateObject != null ? (T)templateObject : default(T);
                    //SubscriptionID in the handle is set automatically when assigning it to a subscription
                    SubscriptionHandle handle = new SubscriptionHandle
                    {
                        EventID      = m.EventDetail.ID,
                        PublisherId  = EllaModel.Instance.GetPublisherId(m.Publisher),
                        SubscriberId = EllaModel.Instance.GetSubscriberId(subscriberInstance)
                    };

                    var subscription = new Subscription
                    {
                        Event          = m,
                        Subscriber     = subscriberInstance,
                        CallbackMethod = newDataCallback.Method,
                        CallbackTarget = newDataCallback.Target,
                        Handle         = handle,
                        DataType       = typeof(T),
                        ModifyPolicy   = policy
                    };



                    if (templateObject == null || evaluateTemplateObject(template))
                    {
                        if (!EllaModel.Instance.ContainsSubscriptions(subscription))
                        {
                            _log.InfoFormat("Subscribing {0} to {1} for type {2}", subscriberInstance, m.Publisher,
                                            m.EventDetail.DataType);
                            EllaModel.Instance.AddSubscription(subscription);
                            if (subscriptionCallback != null)
                            {
                                subscriptionCallback(typeof(T), subscription.Handle);
                            }
                            NotifyPublisher(subscription.Event, subscription.Handle);
                            if (associateMethod != null)
                            {
                                var correlations = EllaModel.Instance.GetEventCorrelations(handle.EventHandle);
                                if (correlations != null)
                                {
                                    foreach (
                                        SubscriptionHandle correlationHandle in
                                        correlations.Select(correlation => new SubscriptionHandle()
                                    {
                                        EventHandle = correlation,
                                    }))
                                    {
                                        correlationHandle.SubscriberId =
                                            handle.SubscriberId;
                                        correlatedEvents.Add(handle, correlationHandle);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        _log.DebugFormat("Templateobject from {0} was rejected by {1}", m.Publisher, subscriberInstance);
                    }
                }
                if (associateMethod != null)
                {
                    if (associateMethod.GetParameters().Count() != 2 || associateMethod.GetParameters().Any(p => p.ParameterType != typeof(SubscriptionHandle)))
                    {
                        throw new IllegalAttributeUsageException(String.Format("Method {0} attributed as Associate has invalid parameters (count or type)", associateMethod));
                    }
                    foreach (var handlePair in correlatedEvents)
                    {
                        //Only do this if subscriber is subscribed to both events
                        if (EllaModel.Instance.FilterSubscriptions(s =>
                                                                   Equals(s.Handle.EventHandle,
                                                                          handlePair.Value.EventHandle) &&
                                                                   s.Subscriber == subscriberInstance).Any())
                        {
                            associateMethod.Invoke(subscriberInstance,
                                                   new object[] { handlePair.Key, handlePair.Value });
                        }
                    }
                }
            }
        }
Example #7
0
 public Task UnsubscribeFromAllAsync(SubscriptionHandle subscriptionHandle, CancellationToken cancellationToken = default)
 {
     return(@delegate.UnsubscribeFromAllAsync(subscriptionHandle, cancellationToken));
 }
 public DelegateAnonymousMessageObserver(SubscriptionHandle subscriptionHandle, Func <AnonymousMessage, MessageHandle, Task> messageCallback, Func <SubscriptionHandle, Task> onSubscriptionEnded)
 {
     this.subscriptionHandle  = subscriptionHandle ?? throw new ArgumentNullException(nameof(subscriptionHandle));
     this.messageCallback     = messageCallback ?? throw new ArgumentNullException(nameof(messageCallback));
     this.onSubscriptionEnded = onSubscriptionEnded ?? throw new ArgumentNullException(nameof(onSubscriptionEnded));
 }