コード例 #1
0
ファイル: SetGetTests.cs プロジェクト: razzles67/NForum
		private ICategoryService GetCategoryService(UnitOfWork uow) {
			ICategoryRepository cateRepo = new CategoryRepository(uow);

			IState request = new DummyRequest();

			ILogger logger = new ConsoleLogger();

			IUserRepository userRepo = new UserRepository(uow);
			User user = userRepo.Create(new User {
				Name = "D. Ummy",
				ProviderId = "12345678",
				FullName = "Mr. Doh Ummy",
				EmailAddress = "[email protected]",
				Culture = "th-TH",
				TimeZone = "GMT Standard Time"
			});

			List<IEventSubscriber> subscribers = new List<IEventSubscriber>();

			IEventPublisher eventPublisher = new EventPublisher(subscribers, logger, request);
			IUserProvider userProvider = new DummyUserProvider(user);
			IPermissionService permService = new PermissionService();

			return new CategoryService(userProvider, cateRepo, eventPublisher, logger, permService);
		}
コード例 #2
0
 // Use this for initialization
 void Start()
 {
     m_behaviour = GetComponent<CartoonBehaviour>();
     m_spinRate = m_behaviour.m_spinRate;
     m_content = new GUIContent(m_text);
     eventPublisher = ObjectFinder.FindOrCreateComponent<EventPublisher>();
 }
コード例 #3
0
		private void GetPostService(UnitOfWork uow, out ICategoryService categoryService, out IForumService forumService, out ITopicService topicService, out IPostService postService) {
			ICategoryRepository cateRepo = new CategoryRepository(uow);
			IForumRepository forumRepo = new ForumRepository(uow);
			ITopicRepository topicRepo = new TopicRepository(uow);
			IPostRepository postRepo = new PostRepository(uow);
			IForumConfigurationRepository configRepo = new ForumConfigurationRepository(uow);

			IState request = new DummyRequest();

			ILogger logger = new ConsoleLogger();

			IUserRepository userRepo = new UserRepository(uow);
			User user = userRepo.Create(new User {
				Name = "D. Ummy",
				ProviderId = "12345678",
				FullName = "Mr. Doh Ummy",
				EmailAddress = "[email protected]",
				Culture = "th-TH",
				TimeZone = "GMT Standard Time"
			});

			List<IEventSubscriber> subscribers = new List<IEventSubscriber>();

			IEventPublisher eventPublisher = new EventPublisher(subscribers, logger, request);
			IUserProvider userProvider = new DummyUserProvider(user);
			IPermissionService permService = new PermissionService();
			IForumConfigurationService confService = new ForumConfigurationService(configRepo);

			categoryService = new CategoryService(userProvider, cateRepo, eventPublisher, logger, permService);
			forumService = new ForumService(userProvider, cateRepo, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService);
			topicService = new TopicService(userProvider, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService, confService);
			postService = new PostService(userProvider, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService, confService);
		}
コード例 #4
0
ファイル: Misc.cs プロジェクト: NuPattern/NuPattern
        public void WhenSourceEventRaised_ThenCollectedSubscriberIsNotNotified()
        {
            var source = new EventSource();
            var publisher = new EventPublisher(source);
            var subscriber = new EventSubscriber();

            var subscription = publisher.PropertyChanged.Subscribe(subscriber.OnChanged);

            try
            {
                subscriber = null;
                subscription.Dispose();
                GC.Collect();
                GC.WaitForFullGCApproach(-1);
                GC.WaitForFullGCComplete(-1);
                GC.WaitForPendingFinalizers();

                source.RaisePropertyChanged("Foo");

                Assert.Equal(0, EventSubscriber.ChangedProperties.Count);

            }
            finally
            {
                //subscription.Dispose();
            }
        }
コード例 #5
0
 private void SubscribeToEvents()
 {
     _eventPublisher = new EventPublisher();
     var numberCountedObserver = Observer.Create<NumberCountedEvent>(new Action<NumberCountedEvent>(OnNumberCounted));
     _eventPublisher.GetEvent<NumberCountedEvent>()
         .ObserveOnDispatcher()
         .Subscribe(numberCountedObserver);
 }
コード例 #6
0
 //need to have Start() so we can disable this.
 void Start()
 {
     if (GameObject.Find ("Level") != null) {
         eventPublisher = GameObject.Find ("Level").GetComponent<EventPublisher> ();
     } else {
         Debug.Log ("No level game object in scene: " + Application.loadedLevelName);
     }
 }
コード例 #7
0
			protected override void Context()
			{
				EventPublisher publisher = new EventPublisher();

				publisher.Publish(new EventData("1st"));
				publisher.Publish(new EventData("2nd"));

				eventData = publisher.GetMostRecentPublication<EventData>();
			}
コード例 #8
0
ファイル: Program.cs プロジェクト: rajeshdlabz/leanandmean
        private static void Main(string[] args)
        {
            var testEventHappened = new TestEventHappened
            {
                Message = "Hello Eventing World!"
            };
            var eventPublisher = new EventPublisher<TestEventHappened>();

            eventPublisher.Publish<object>(testEventHappened);
        }
コード例 #9
0
            public void EventEnvelopeCannotBeNull()
            {
                var messageFactory = new Mock<ICreateMessages>();
                var messageBus = new Mock<ISendMessages<EventEnvelope>>();
                var publisher = new EventPublisher(messageFactory.Object, messageBus.Object);

                var ex = Assert.Throws<ArgumentNullException>(() => publisher.Publish(HeaderCollection.Empty, null));

                Assert.Equal("payload", ex.ParamName);
            }
コード例 #10
0
            public void HeadersCanBeNull()
            {
                var messageFactory = new Mock<ICreateMessages>();
                var messageBus = new Mock<ISendMessages<EventEnvelope>>();
                var publisher = new EventPublisher(messageFactory.Object, messageBus.Object);

                publisher.Publish(null, EventEnvelope.Empty);

                messageFactory.Verify(mock => mock.Create(null, EventEnvelope.Empty), Times.Once);
                messageBus.Verify(mock => mock.Send(It.IsAny<Message<EventEnvelope>>()), Times.Once);
            }
コード例 #11
0
        // ReSharper disable InconsistentNaming
        public void EventPublisherGetEvent_UnitTest_FirstTimeForType_New()
        // ReSharper restore InconsistentNaming
        {
            var publisher = new EventPublisher();
            Assert.AreEqual(0, publisher.Count);

            var actual = publisher.GetEvent<object>();
            Assert.AreEqual(1, publisher.Count);
            Assert.IsNotNull(actual);
            Assert.IsInstanceOfType(actual, typeof(IObservable<object>));
        }
コード例 #12
0
        // ReSharper disable InconsistentNaming
        public void EventPublisherPublish_UnitTest_RegisteredType_FindsSubjectAndInvokesOnNext()
        // ReSharper restore InconsistentNaming
        {
            var memo = new DesignValidationMemo();

            var publisher = new EventPublisher();
            var subscription = publisher.GetEvent<DesignValidationMemo>().Subscribe(m => Assert.AreSame(memo, m));

            publisher.Publish(memo);
            subscription.Dispose();
        }
コード例 #13
0
            protected override void Context()
            {
                _handler = MockRepository.GenerateMock<IEventHandler<EventData>>();

                IEventPublisher eventPublisher = new EventPublisher();

                eventPublisher.RegisterHandler(_handler);
                eventPublisher.UnregisterHandler(_handler);

                eventPublisher.Publish(new EventData("My Event Data"));
            }
コード例 #14
0
ファイル: Configuration.cs プロジェクト: perokvist/Treefort
 public static IApplicationServer WithEventStore(Func<ILogger, IEnumerable<IApplicationService>, ICommandRouter> routerFactory, Func<IEventStore> eventStoreFactory, IEnumerable<Func<IEventStore, IEventPublisher, IApplicationService>> appServiceFactories, Func<IEnumerable<IProjection>> projections, Func<IEnumerable<IReceptor>> receptors)
 {
     var logger = new ConsoleLogger();
     var eventListner = new EventListener(projections());
     var eventPublisher = new EventPublisher(new List<IEventListener> { eventListner }, new ReceptorSubject(receptors(), logger), logger);
     var observableEventStore = new ObservableEventStore(eventStoreFactory());
     var router = routerFactory(logger, appServiceFactories.Select(fac => fac(observableEventStore, eventPublisher)));
     var appServer = new ApplicationServer(router, logger);
     observableEventStore.Subscribe(eventPublisher);
     eventPublisher.Subscribe(cmd => appServer.DispatchAsync(cmd));
     return appServer;
 }
コード例 #15
0
			protected override void Context()
			{
				_handler = MockRepository.GenerateMock<IEventHandler<EventData>>();
				_handler.Stub(h => h.Handle(null)).IgnoreArguments().Callback(delegate(EventData data)
					{
						_eventData = data.SomeData;
						return true;
					});

				IEventPublisher eventPublisher = new EventPublisher();
				eventPublisher.RegisterHandler(_handler);
				eventPublisher.Publish(new EventData("My Event Data"));
			}
コード例 #16
0
ファイル: Program.cs プロジェクト: leanwork/event-publisher
        static void Main(string[] args)
        {
            //add event subscriptions
            EventSubscriptions.Add<EmailOrderConfirmation>();
            EventSubscriptions.Add<NotifyWarehouse>();
            EventSubscriptions.Add<DeductOnHandInventory>();

            //publish
            IEventPublisher eventPublisher = new EventPublisher(new EventSubscriptions());
            eventPublisher.PublishAsync<OrderSubmittedEvent>(new OrderSubmittedEvent { OrderId = Guid.NewGuid().ToString() });
            eventPublisher.PublishAsync<OrderSubmittedEvent>(new OrderSubmittedEvent { OrderId = Guid.NewGuid().ToString() });

            //Console.ReadKey();
        }
コード例 #17
0
        public void ShouldPublishEvent()
        {

            var ringBuffer = new RingBuffer<LongEvent>(()=>new LongEvent(0), BufferSize);
            ringBuffer.SetGatingSequences(new NoOpEventProcessor(ringBuffer).Sequence);
            var eventPublisher = new EventPublisher<LongEvent>(ringBuffer);


            eventPublisher.PublishEvent(_translator);
            eventPublisher.PublishEvent(_translator);

            Assert.AreEqual(0L + ValueAdd, ringBuffer[0].Value);
            Assert.AreEqual(1L + ValueAdd, ringBuffer[1].Value);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: zuifengke/windy-dotnet
        static void Main(string[] args)
        {
            EventPublisher publisher = new EventPublisher();

            EventReader1 reader1 = new EventReader1(publisher);

            EventReader2 reader2 = new EventReader2(publisher);

            publisher.DoSomthing();

            Console.WriteLine("This program already finished!");

            Console.ReadLine();
        }
コード例 #19
0
			protected override void Context()
			{
				_handler = SetupHandlerToThrowException();

				IEventPublisher eventPublisher = new EventPublisher();

				eventPublisher.OnHandlerError(ex =>
					{
						handlerExecuted = true;
						caughtException = ex;
					});
				
				eventPublisher.RegisterHandler(_handler);
				eventPublisher.Publish(new EventData());
			}
コード例 #20
0
ファイル: Misc.cs プロジェクト: NuPattern/NuPattern
        public void WhenSourceEventRaised_ThenSubscriberIsNotified()
        {
            var source = new EventSource();
            var publisher = new EventPublisher(source);

            var subscriber = new EventSubscriber();

            publisher.PropertyChanged.Subscribe(subscriber.OnChanged);

            Assert.Equal(0, EventSubscriber.ChangedProperties.Count);

            source.RaisePropertyChanged("Foo");

            Assert.Equal(1, EventSubscriber.ChangedProperties.Count);
            Assert.Equal("Foo", EventSubscriber.ChangedProperties[0]);
        }
コード例 #21
0
        // ReSharper disable InconsistentNaming
        public void EventPublisherGetEvent_UnitTest_SecondTimeForType_Existing()
        // ReSharper restore InconsistentNaming
        {
            var publisher = new EventPublisher();
            Assert.AreEqual(0, publisher.Count);

            var first = publisher.GetEvent<object>();
            Assert.AreEqual(1, publisher.Count);
            Assert.IsNotNull(first);
            Assert.IsInstanceOfType(first, typeof(IObservable<object>));

            var second = publisher.GetEvent<object>();
            Assert.AreEqual(1, publisher.Count);
            Assert.IsNotNull(second);
            Assert.IsInstanceOfType(second, typeof(IObservable<object>));
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: Xamarui/LocationTracker
        static void Main(string[] args)
        {
            var storageLocation = @"d:\test.log";
            if (args.Length > 0)
            {
                storageLocation = args[0];
            }
            var start = DateTime.Now;

            EventPublisher<TrackedObject> publisher = null; // will be initialized below, after ring buffer created
            var simulator = new Simulator(ObjectsCount, obj =>
            {
                publisher.PublishEvent((entry, sequenceNo) =>
                {
                    entry.Latitude = obj.Latitude;
                    entry.Longitude = obj.Longitude;
                    entry.Id = obj.Id;
                    return entry;
                });
            });

            var disruptor = new Disruptor.Dsl.Disruptor<TrackedObject>(() => new TrackedObject(), RingBufferSize, TaskScheduler.Default);
            
            var distanceHandler = new DistanceHandler();
            var aknowledgementHandler = new AknowledgementHandler(simulator);
            var consoleLogHandler = new ConsoleLogHandler();
            using (var persistHandler = new ObjectPersistHandler(storageLocation))
            {
                disruptor.HandleEventsWith(persistHandler)
                         .Then(consoleLogHandler, distanceHandler)
                         .Then(aknowledgementHandler);
                
                var ringBuffer = disruptor.Start();
                publisher = new EventPublisher<TrackedObject>(ringBuffer);
                
                simulator.PublishStartPositions();
                
                Thread.Sleep(10000);

                simulator.Stop();
                
                disruptor.Shutdown();
            }
            Console.WriteLine(distanceHandler.GetSummary());
            Console.WriteLine("Processed {0} events. Speed: {1:#.##} events per second.", simulator.MoveCount, simulator.MoveCount / (DateTime.Now - start).TotalSeconds);
            Console.ReadKey();
        }
コード例 #23
0
        public void AssumptionWeakEventProxyStandardEventIntroducesLeaks()
        {
            // Create an event publisher (a long-lived object) and an event subscriber
            // using standard .NET events. We only have a weak reference to the subscriber,
            // so the only other GC reference will be the publisher - this is what introduces
            // memory issues in binding and WPF applications.
            var publisher = new EventPublisher();
            var subscriberReference = CreateEventSubscriber(publisher);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            // Prove that the subscriber is being kept alive by the publisher's reference back to it,
            // and that it is still subscribed (even though it unsubscribes in the finalizer - so it can't
            // have been finalized).
            Assert.IsNotNull(subscriberReference.Target);
            Assert.AreEqual(1, publisher.Subscribers);
        }
コード例 #24
0
        private Form GetMainForm()
        {
            IEmployeeRepository employeeRepository = new InMemoryEmployeeRepository();

            IEventPublisher eventPublisher = new EventPublisher();

            MainForm mainForm = new MainForm();
            EmployeeDetailPresenter employeeDetailPresenter = new EmployeeDetailPresenter(mainForm.ViewEmployeeDetail);
            eventPublisher.RegisterHandlers(employeeDetailPresenter);

            ICommand<AddNewEmployeeData> addNewEmployeeCommand = new AddNewEmployeeCommand(employeeRepository, eventPublisher);

            OrgChartPresenter presenter = new OrgChartPresenter(mainForm, employeeRepository, eventPublisher, addNewEmployeeCommand);
            eventPublisher.RegisterHandlers(presenter);
            presenter.Run();

            return mainForm;
        }
コード例 #25
0
        public void WeakEventProxyWeakEventsFixLeaks()
        {
            // Create an event publisher (a long-lived object) and an event subscriber
            // using our custom weak event handler code. We will only have a weak reference
            // to the created subscriber, and since the weak event handler should remove the
            // reference from the publisher to the subscriber, the subscriber should be
            // marked for collection and finalized.
            var publisher = new EventPublisher();
            var subscriberReference = CreateWeakEventSubscriber(publisher);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            // Prove that the weak event reference worked - the subscriber should not have been
            // referenced from the publishers' event handler, and since we have no other normal
            // references to it, it should have been collected and the finalizer should have
            // unhooked the event handler.
            Assert.IsNull(subscriberReference.Target);
            Assert.AreEqual(0, publisher.Subscribers);
        }
コード例 #26
0
        void Run()
        {
            var eventPublisher = new EventPublisher();
            var connection = new Mock<IEnvironmentConnection>();
            connection.Setup(e => e.ServerEvents).Returns(eventPublisher);
            connection.Setup(e => e.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>())).Returns(new StringBuilder());

            var envMock = new Mock<IEnvironmentModel>();
            envMock.Setup(e => e.Connection).Returns(connection.Object);
            envMock.Setup(e => e.ResourceRepository.DeployResource(It.IsAny<IResourceModel>())).Verifiable();
            envMock.Setup(e => e.IsConnected).Returns(true);

            var dtoMock = new Mock<IDeployDto>();
            dtoMock.Setup(d => d.ResourceModels).Returns(CreateModels(envMock.Object));

            var ds = new DeployService();
            ds.Deploy(dtoMock.Object, envMock.Object);

            envMock.Verify(e => e.ResourceRepository.DeployResource(It.IsAny<IResourceModel>()), Times.Exactly(_numModels));
        }
コード例 #27
0
        public void ShouldPublishEvent()
        {
            const long valueAdd = 29L;

            var ringBuffer = new RingBuffer<LongEvent>(()=>new LongEvent(0), 32);
            ringBuffer.SetGatingSequences(new NoOpEventProcessor(ringBuffer).Sequence);
            var eventPublisher = new EventPublisher<LongEvent>(ringBuffer);

            Func<LongEvent, long, LongEvent> translator = (evt, seq) =>
                                                              {
                                                                  evt.Value = seq + valueAdd;
                                                                  return evt;
                                                              };

            eventPublisher.PublishEvent(translator);
            eventPublisher.PublishEvent(translator);

            Assert.AreEqual(0L + valueAdd, ringBuffer[0].Value);
            Assert.AreEqual(1L + valueAdd, ringBuffer[1].Value);
        }
コード例 #28
0
        public void ShouldTryPublishEvent()
        {
            RingBuffer<LongEvent> ringBuffer = new RingBuffer<LongEvent>(()=>new LongEvent(0), BufferSize);
            ringBuffer.SetGatingSequences(new Sequence());
            EventPublisher<LongEvent> eventPublisher = new EventPublisher<LongEvent>(ringBuffer);



            for (int i = 0; i < BufferSize; i++)
            {
                Assert.IsTrue(eventPublisher.TryPublishEvent(_translator, 1));
            }

            for (int i = 0; i < BufferSize; i++)
            {
                Assert.AreEqual(i + ValueAdd, ringBuffer[i].Value);
            }

            Assert.IsFalse(eventPublisher.TryPublishEvent(_translator, 1));
    }
コード例 #29
0
        public void Test_PublishEvent()
        {
            var initializer = new InitializeEventReceiver();
            var publisher = new EventPublisher();

            m_builder.Add(initializer);
            m_builder.Add(publisher);

            m_builder.Connect(initializer.Pin(x => x.Fired), publisher);

            var context = m_builder.Compile();
            context.PublishEvent(new WorkflowEventData());

            context.Run();
            Assert.That(publisher.ExecutionCount, Is.EqualTo(1));

            context.Run();
            Assert.That(publisher.ExecutionCount, Is.EqualTo(2));

            context.Run();
            Assert.That(publisher.ExecutionCount, Is.EqualTo(2));
        }
コード例 #30
0
        /// <summary>
        /// 提交审核(审核银行信息)
        /// </summary>
        /// <param name="entity"></param>
        public virtual RefundBalanceInfo SubmitAudit(RefundBalanceInfo entity)
        {
            RefundBalanceInfo refundBalanceInfo = GetRefundBalanceBySysNo(entity.SysNo.Value);

            if (refundBalanceInfo == null)
            {
                throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "RefundBalanceNotExists"));
            }
            refundBalanceInfo.PointAmt = refundBalanceInfo.PointAmt ?? 0;

            if (refundBalanceInfo.Status != RefundBalanceStatus.WaitingRefund)
            {
                throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Audit_RefundBalanceWaitingRefundValid"));
            }
            if (refundBalanceInfo.CashAmt == null)
            {
                throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "CashAmtRequired"));
            }
            if (refundBalanceInfo.CashAmt.Value < 0)
            {
                throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Audit_CashAmtValid"));
            }
            SOIncomeRefundInfo oldIncomeBankInfo = ExternalDomainBroker.GetSOIncomeRefundInfo(entity.SysNo.Value, RefundOrderType.RO_Balance);
            SOIncomeRefundInfo newIncomeBankInfo = new SOIncomeRefundInfo()
            {
                RefundReason   = 9, // RefundReason.RefundBalance
                BankName       = entity.IncomeBankInfo.BankName,
                BranchBankName = entity.IncomeBankInfo.BranchBankName,
                CardNumber     = entity.IncomeBankInfo.CardNumber,
                CardOwnerName  = entity.IncomeBankInfo.CardOwnerName,
                PostAddress    = entity.IncomeBankInfo.PostAddress,
                PostCode       = entity.IncomeBankInfo.PostCode,
                ReceiverName   = entity.IncomeBankInfo.ReceiverName,
                Note           = entity.IncomeBankInfo.Note,
                CompanyCode    = refundBalanceInfo.CompanyCode
            };

            TransactionScopeFactory.TransactionAction(() =>
            {
                if (oldIncomeBankInfo == null)
                {
                    newIncomeBankInfo.RefundPayType = refundBalanceInfo.RefundPayType;
                    newIncomeBankInfo.SOSysNo       = refundBalanceInfo.OriginalSOSysNo;
                    newIncomeBankInfo.OrderType     = RefundOrderType.RO_Balance;
                    newIncomeBankInfo.OrderSysNo    = refundBalanceInfo.SysNo;
                    newIncomeBankInfo.HaveAutoRMA   = false;

                    if (newIncomeBankInfo.RefundPayType == RefundPayType.CashRefund)
                    {
                        newIncomeBankInfo.Status = ECCentral.BizEntity.Invoice.RefundStatus.Audit;
                    }
                    else
                    {
                        newIncomeBankInfo.Status = ECCentral.BizEntity.Invoice.RefundStatus.Origin;
                    }

                    if (newIncomeBankInfo.RefundPayType == RefundPayType.TransferPointRefund)
                    {
                        newIncomeBankInfo.RefundCashAmt = 0;
                        newIncomeBankInfo.RefundPoint   = Convert.ToInt32(Decimal.Round((refundBalanceInfo.CashAmt ?? 0M)
                                                                                        * pointExchangeRate, 0));
                        if (refundBalanceInfo.PointAmt > 0)//如果有积分累加到bankInfo的PointAmt字段上
                        {
                            newIncomeBankInfo.RefundPoint += refundBalanceInfo.PointAmt;
                        }
                    }
                    else
                    {
                        newIncomeBankInfo.RefundCashAmt = refundBalanceInfo.CashAmt;
                        newIncomeBankInfo.RefundPoint   = refundBalanceInfo.PointAmt;
                    }
                    newIncomeBankInfo.RefundGiftCard = refundBalanceInfo.GiftCardAmt;

                    ExternalDomainBroker.CreateSOIncomeRefundInfo(newIncomeBankInfo);
                }
                else if (oldIncomeBankInfo.Status == RefundStatus.Origin ||
                         (oldIncomeBankInfo.Status != RefundStatus.Origin && oldIncomeBankInfo.RefundPayType == RefundPayType.CashRefund))
                {
                    newIncomeBankInfo.SysNo          = oldIncomeBankInfo.SysNo;
                    newIncomeBankInfo.OrderType      = oldIncomeBankInfo.OrderType;
                    newIncomeBankInfo.RefundPayType  = oldIncomeBankInfo.RefundPayType;
                    newIncomeBankInfo.RefundReason   = oldIncomeBankInfo.RefundReason;
                    newIncomeBankInfo.HaveAutoRMA    = oldIncomeBankInfo.HaveAutoRMA;
                    newIncomeBankInfo.RefundCashAmt  = oldIncomeBankInfo.RefundCashAmt;
                    newIncomeBankInfo.RefundGiftCard = oldIncomeBankInfo.RefundGiftCard;
                    newIncomeBankInfo.RefundPoint    = oldIncomeBankInfo.RefundPoint;
                    newIncomeBankInfo.ToleranceAmt   = oldIncomeBankInfo.ToleranceAmt;
                    newIncomeBankInfo.Status         = oldIncomeBankInfo.Status;

                    ExternalDomainBroker.UpdateSOIncomeRefundInfo(newIncomeBankInfo);
                }
                else if (oldIncomeBankInfo.Status == RefundStatus.Abandon)
                {
                    throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Audit_RefundBalanceAbandonStatusValid"));
                }
                else
                {
                    throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Audit_RefundBalanceStatusValid"));
                }
                entity.IncomeBankInfo = newIncomeBankInfo;

                //完成RMA退款调整单待审核 - 待办事项:
                EventPublisher.Publish <RMACompleteRefundBalanceWaitingForAuditMessage>(new RMACompleteRefundBalanceWaitingForAuditMessage()
                {
                    RefundBalanceSysNo = entity.SysNo.Value,
                    RefundSysNo        = entity.OriginalRefundSysNo.Value,
                    CurrentUserSysNo   = ServiceContext.Current.UserSysNo
                });
            });
            return(entity);
        }
コード例 #31
0
        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="entity"></param>
        public virtual void Refund(RefundBalanceInfo entity)
        {
            RefundBalanceInfo refundBalanceInfo;
            SOInfo            soInfo;

            VerifyForRefund(entity, out soInfo, out refundBalanceInfo);
            soInfo.BaseInfo.GiftCardPay   = soInfo.BaseInfo.GiftCardPay ?? 0M;
            refundBalanceInfo.GiftCardAmt = refundBalanceInfo.GiftCardAmt ?? 0M;
            refundBalanceInfo.PointAmt    = refundBalanceInfo.PointAmt ?? 0;

            decimal availShipPrice, cashRemoveGiftCard, availGiftCard, totalRoBoBalanceAmt;
            int     availPointAmt;

            CalculateAvailRefundAmt(entity, soInfo.BaseInfo, out availShipPrice, out cashRemoveGiftCard, out availGiftCard, out availPointAmt, out totalRoBoBalanceAmt);

            if (refundBalanceInfo.CashAmt > cashRemoveGiftCard || refundBalanceInfo.GiftCardAmt > availGiftCard ||
                refundBalanceInfo.PointAmt > availPointAmt)
            {
                throw new BizException(
                          ResouceManager.GetMessageString("RMA.RefundBalance", "Refund_ReCreateRefundBalance"));
            }


            decimal ROAmt;

            PreCheckForRefund(refundBalanceInfo, totalRoBoBalanceAmt, availShipPrice, out ROAmt);

            int tmpNewOrderSysNo = 0;

            #region 事务中执行退款操作
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            options.Timeout        = TransactionManager.DefaultTimeout;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                AbandonPoint(refundBalanceInfo);

                if (refundBalanceInfo.RefundPayType == RefundPayType.PrepayRefund)
                {
                    if (refundBalanceInfo.CashAmt.Value > soInfo.BaseInfo.SOAmount)
                    {
                        throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Refund_CashAmtValid"));
                    }

                    RefundPrepay(refundBalanceInfo);
                }
                else if (refundBalanceInfo.RefundPayType == RefundPayType.TransferPointRefund)
                {
                    if (refundBalanceInfo.CashAmt.Value > soInfo.BaseInfo.SOAmount)
                    {
                        throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Refund_CashAmtValid"));
                    }

                    TransferPointRefund(refundBalanceInfo);
                }

                CreateSOIncome(refundBalanceInfo);

                // 现金部分生成新礼品卡
                RefundInfo refundInfo = refundProcessor.LoadBySysNo(entity.OriginalRefundSysNo.Value);
                if (refundBalanceInfo.RefundPayType == RefundPayType.GiftCardRefund && refundBalanceInfo.CashAmt > 0)
                {
                    refundProcessor.CreateElectronicGiftCard(refundInfo, refundBalanceInfo.CashAmt.Value, "ROBalance");
                }
                //礼品卡部分依次退返
                if (refundBalanceInfo.GiftCardAmt > 0)
                {
                    refundProcessor.RefundGiftCard(refundInfo, refundBalanceInfo.GiftCardAmt.Value, "ROBalance", refundBalanceInfo.SysNo.Value);
                }

                UpdateRefundBalanceForRefund(entity.SysNo.Value, ROAmt, out tmpNewOrderSysNo);

                //20130808 Chester Added:完成RMA退款调整单待审核- 待办事项:
                EventPublisher.Publish <RMACompleteRefundBalanceWaitingForAuditMessage>(new RMACompleteRefundBalanceWaitingForAuditMessage()
                {
                    RefundBalanceSysNo = entity.SysNo.Value,
                    RefundSysNo        = entity.OriginalRefundSysNo.Value,
                    CurrentUserSysNo   = ServiceContext.Current.UserSysNo
                });

                scope.Complete();
            }
            #endregion

            //发送SSB
            string stockID = ExternalDomainBroker.GetSOItemList(soInfo.SysNo.Value).FirstOrDefault().StockSysNo.Value.ToString();

            if (stockID != null && soInfo != null)
            {
                //if (stockID.Trim() == RMAConst.WarehouseNo_GZ
                //   || stockID.Trim() == RMAConst.WarehouseNo_XA
                //   || soInfo.InvoiceInfo.IsVAT == true)
                if (soInfo.InvoiceInfo.IsVAT == true)
                {
                    ObjectFactory <SendSSBProcessor> .Instance.SendADJUSTMessage(tmpNewOrderSysNo, stockID, entity.CompanyCode);
                }
            }
        }
コード例 #32
0
            public async Task Should_Invoke_All_Registered_Event_Handlers_In_Registration_For_Each_Events()
            {
                var asyncHandler1 = new TestEventAsyncHandler1(_testOutputHelper);
                var asyncHandler2 = new TestEventAsyncHandler2(_testOutputHelper);
                var asyncHandler3 = new TestEventAsyncHandler3(_testOutputHelper);
                var handler1      = new TestEventHandler1(_testOutputHelper);
                var handler2      = new TestEventHandler2(_testOutputHelper);
                var handler3      = new TestEventHandler3(_testOutputHelper);

                var registration = new EventHandlerRegistration();

                registration.Register <TestEvent1>(() => asyncHandler1);
                registration.Register <TestEvent1>(() => asyncHandler2);
                registration.Register <TestEvent1>(() => asyncHandler3);
                registration.Register <TestEvent1>(() => handler1);
                registration.Register <TestEvent1>(() => handler2);
                registration.Register <TestEvent1>(() => handler3);

                registration.Register <TestEvent2>(() => asyncHandler1);
                registration.Register <TestEvent2>(() => asyncHandler2);
                registration.Register <TestEvent2>(() => asyncHandler3);
                registration.Register <TestEvent2>(() => handler1);
                registration.Register <TestEvent2>(() => handler2);
                registration.Register <TestEvent2>(() => handler3);

                registration.Register <TestEvent3>(() => asyncHandler1);
                registration.Register <TestEvent3>(() => asyncHandler2);
                registration.Register <TestEvent3>(() => asyncHandler3);
                registration.Register <TestEvent3>(() => handler1);
                registration.Register <TestEvent3>(() => handler2);
                registration.Register <TestEvent3>(() => handler3);

                var publisher = new EventPublisher(registration);

                publisher.OnError += (@event, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);
                };

                await publisher.PublishAsync(new List <IEvent> {
                    new TestEvent1(), new TestEvent2(), new TestEvent3()
                });

                // Event may not have yet been handled in background.
                await Task.Delay(500);

                // AsyncHandler1 should have 3 events.
                // 1. TestEvent1
                // 2. TestEvent2
                // 3. TestEvent3
                Assert.Equal(3, asyncHandler1.HandledEvents.Count);
                Assert.Contains(asyncHandler1.HandledEvents, (e) => e is TestEvent1);
                Assert.Contains(asyncHandler1.HandledEvents, (e) => e is TestEvent2);
                Assert.Contains(asyncHandler1.HandledEvents, (e) => e is TestEvent3);

                // AsyncHandler2 should have 3 events.
                // 1. TestEvent1
                // 2. TestEvent2
                // 3. TestEvent3
                Assert.Equal(3, asyncHandler2.HandledEvents.Count);
                Assert.Contains(asyncHandler2.HandledEvents, (e) => e is TestEvent1);
                Assert.Contains(asyncHandler2.HandledEvents, (e) => e is TestEvent2);
                Assert.Contains(asyncHandler2.HandledEvents, (e) => e is TestEvent3);

                // AsyncHandler3 should have 3 events.
                // 1. TestEvent1
                // 2. TestEvent2
                // 3. TestEvent3
                Assert.Equal(3, asyncHandler3.HandledEvents.Count);
                Assert.Contains(asyncHandler3.HandledEvents, (e) => e is TestEvent1);
                Assert.Contains(asyncHandler3.HandledEvents, (e) => e is TestEvent2);
                Assert.Contains(asyncHandler3.HandledEvents, (e) => e is TestEvent3);

                // Handler1 should have 3 events.
                // 1. TestEvent1
                // 2. TestEvent2
                // 3. TestEvent3
                Assert.Equal(3, handler1.HandledEvents.Count);
                Assert.Contains(handler1.HandledEvents, (e) => e is TestEvent1);
                Assert.Contains(handler1.HandledEvents, (e) => e is TestEvent2);
                Assert.Contains(handler1.HandledEvents, (e) => e is TestEvent3);

                // Handler2 should have 3 events.
                // 1. TestEvent1
                // 2. TestEvent2
                // 3. TestEvent3
                Assert.Equal(3, handler2.HandledEvents.Count);
                Assert.Contains(handler2.HandledEvents, (e) => e is TestEvent1);
                Assert.Contains(handler2.HandledEvents, (e) => e is TestEvent2);
                Assert.Contains(handler2.HandledEvents, (e) => e is TestEvent3);

                // Handler3 should have 3 events.
                // 1. TestEvent1
                // 2. TestEvent2
                // 3. TestEvent3
                Assert.Equal(3, handler3.HandledEvents.Count);
                Assert.Contains(handler3.HandledEvents, (e) => e is TestEvent1);
                Assert.Contains(handler3.HandledEvents, (e) => e is TestEvent2);
                Assert.Contains(handler3.HandledEvents, (e) => e is TestEvent3);
            }
コード例 #33
0
 public PublisherController(EventPublisher publisherEvent)
 {
     _publisherEvent = publisherEvent;
 }
コード例 #34
0
 /// <summary>
 /// Creates and returns a delegate for the event handler.
 /// </summary>
 /// <param name="publisher">The corresponding event publisher</param>
 /// <returns>The delegate. Never returns null.</returns>
 public virtual Delegate GetDelegate(EventPublisher publisher)
 {
     return(Delegate.CreateDelegate(publisher.EventHandlerType, Model, MethodInfo));
 }
コード例 #35
0
 private static void SendMessage(object sender, string message)
 {
     EventPublisher.OnSendMessageEvent(sender, new SendMessageArgs(message, sender));
 }
コード例 #36
0
        /// <summary>
        /// PMCC审核通过
        /// </summary>
        /// <param name="refundInfo"></param>
        /// <returns></returns>
        public virtual VendorRefundInfo PMCCApproveVendorRefund(VendorRefundInfo refundInfo)
        {
            //编号不能为空
            if (!refundInfo.SysNo.HasValue || refundInfo.SysNo.Value <= 0)
            {
                //供应商退款编号无效
                throw new BizException(GetMessageString("VendorRefund_SysNoEmpty"));
            }
            VendorRefundInfo localEntity = VendorRefundDA.LoadVendorRefundInfo(refundInfo.SysNo.Value);

            if (localEntity == null)
            {
                //供应商退款单在数据中不存在
                throw new BizException(GetMessageString("VendorRefund_RefundNotExist"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.Abandon)
            {
                //该供应商退款单为作废状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_Abandon_Invalid"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.Origin)
            {
                //该供应商退款单为初始状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_Origin_Invalid"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.PMDVerify)
            {
                //该供应商退款单为PMD审核状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_PMDVerify_Invalid"));
            }
            if (localEntity.Status.Value == VendorRefundStatus.PMCCVerify)
            {
                throw new BizException("该供应商退款单为PMCC审核状态,不允许进行当前操作!");
            }

            //if (localEntity.CreateUserSysNo == ServiceContext.Current.UserSysNo)
            //{
            //    //供应商退款单中,创建人,PM审核人,PMD审核人,PMCC审核人,不能相同
            //    throw new BizException(GetMessageString("VendorRefund_OperatorCannotSame_Invalid"));
            //}

            localEntity.PMCCUserSysNo = ServiceContext.Current.UserSysNo;
            localEntity.PMCCAuditTime = System.DateTime.Now;
            localEntity.PMCCMemo      = refundInfo.PMCCMemo;
            localEntity.Status        = VendorRefundStatus.PMCCVerify;

            //加载当前商家退款单Items:
            List <VendorRefundItemInfo> localItem = VendorRefundDA.LoadVendorRefundItems(localEntity.SysNo.Value);

            #region 调用RMA接口:判断单件是否可以关闭
            List <int> RegisterSysNo = new List <int>();
            localItem.ForEach(a => RegisterSysNo.Add(a.RegisterSysNo.Value));
            //调用RMA接口,判断单件是否可以关闭
            List <RMARegisterInfo> getList = ExternalDomainBroker.GetRMARegisterList(RegisterSysNo);
            foreach (var item in getList)
            {
                if (item.BasicInfo.Status != RMARequestStatus.Handling)  //RMARequestStatus.Handling 1 表示 处理中
                {
                    throw new BizException(string.Format(GetMessageString("VendorRefund_CloseInvalid"), item.SysNo.Value));
                }
            }
            #endregion

            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            options.Timeout        = TransactionManager.DefaultTimeout;

            List <VendorRefundItemInfo>     list           = new List <VendorRefundItemInfo>();
            List <KeyValuePair <int, int> > registerList   = new List <KeyValuePair <int, int> >();
            List <VendorRefundInfo>         deductOnVendor = new List <VendorRefundInfo>();
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                //更新状态 :
                localEntity = VendorRefundDA.UpdateVendorRefundInfo(localEntity);
                //关闭单件并扣减RMA库存中OnVendorQty数量:
                list = VendorRefundDA.LoadVendorRefundItems(localEntity.SysNo.Value);
                foreach (var item in list)
                {
                    int registerNo = item.RegisterSysNo.Value;
                    registerList.Add(new KeyValuePair <int, int>(registerNo, localEntity.PMDUserSysNo.Value));

                    ////调用RMA接口,根据单件号获取接收仓库:
                    string[] str = ExternalDomainBroker.GetReceiveWarehouseByRegisterSysNo(registerNo);
                    if (!string.IsNullOrEmpty(str[0]) && !string.IsNullOrEmpty(str[1]))
                    {
                        deductOnVendor.Add(new VendorRefundInfo
                        {
                            WarehouseSysNo = Convert.ToInt32(str[0]),
                            ProductSysNo   = Convert.ToInt32(str[1]),
                            RegisterSysNo  = registerNo
                        });
                    }
                }

                ////调用RMA接口,关闭送修单:
                List <int> OutBound = ExternalDomainBroker.GetOutBoundSysNoListByRegisterSysNo(registerList.ToListString("Key"));
                ExternalDomainBroker.UpdateOutBound(OutBound.ToListString());

                //发送ESB消息
                EventPublisher.Publish <VendorRefundInfoAuditMessage>(new VendorRefundInfoAuditMessage()
                {
                    AuditUserSysNo = ServiceContext.Current.UserSysNo,
                    SysNo          = refundInfo.SysNo.Value
                });

                scope.Complete();
            }
            ////调用RMA接口:关闭单件
            List <int> registerSysNos = new List <int>();
            registerList.ForEach(x =>
            {
                registerSysNos.Add(x.Key);
            });

            ExternalDomainBroker.BatchCloseRegisterForVendorRefund(registerSysNos);

            //扣减RMA库存中OnVendorQty数量

            ExternalDomainBroker.BatchDeductOnVendorQty(deductOnVendor);

            ////调用Invoice接口,生成财务POR记录
            PayableInfo payableInfo = new PayableInfo()
            {
                OrderSysNo        = localEntity.SysNo.Value,
                CurrencySysNo     = 1,
                OrderAmt          = -1 * localEntity.RefundCashAmt.Value,
                PayStatus         = 0,
                InvoiceStatus     = 0,
                OrderType         = PayableOrderType.RMAPOR,        //9
                InvoiceUpdateTime = DateTime.Parse("1900-1-1"),
                InvoiceFactStatus = PayableInvoiceFactStatus.Others // 3
            };
            PayableInfo createdPayableInfo = ExternalDomainBroker.CreatePayable(payableInfo);
            if (null != createdPayableInfo && 0 < createdPayableInfo.SysNo)
            {
                int financePaySysNo = createdPayableInfo.SysNo.Value;

                List <PayItemInfo> payItemList = new List <PayItemInfo>();
                list.ForEach(x =>
                {
                    PayItemInfo item = new PayItemInfo()
                    {
                        PaySysNo   = financePaySysNo,
                        PayStyle   = PayItemStyle.Normal,
                        Status     = PayItemStatus.Origin,
                        PayAmt     = x.RefundCash.HasValue ? (-1 * x.RefundCash.Value) : -999999,
                        OrderType  = PayableOrderType.RMAPOR,
                        OrderSysNo = x.RefundSysNo.Value
                    };
                    payItemList.Add(item);
                });

                ExternalDomainBroker.BatchCreatePayItem(payItemList);
            }

            return(localEntity);
        }
コード例 #37
0
ファイル: ArcGlobeBusiness.cs プロジェクト: siszoey/MapFrame
        // 处理波束数据
        public void DealBeamData(Model.BeamData beamData)
        {
            if (beamData.PointType == 1)   //  波束
            {
                // 先获取卫星,如果没有,则不创建波束
                string  satelliteId = string.Format("卫星{0}", beamData.SatelliteId);
                Model3D model       = modelMgr.FindModel(satelliteId);
                if (model == null)
                {
                    return;
                }

                EventPublisher.PublishMapDealBeamDataEvent(this, beamData);

                Beam beam = CreateBeam(beamData, model);
                beam.SatellitePoint = model.Coordinate;

                if (beamMgr.HasBeam(satelliteId, beam))   // 波束存在,移动波束
                {
                    UpdateBeamElement(beam, model);
                    beamMgr.UpdataBeamCenterPoint(satelliteId, beam);
                }
                else                         // 波束不存在,创建波束
                {
                    if (AddBeamElement(beam, model))
                    {
                        beamMgr.AddBeam(satelliteId, beam);
                    }
                }
            }
            else   // 卫星
            {
                string  modelName = string.Format("卫星{0}", beamData.SatelliteId);
                Model3D model     = CreateSatelliteModel(modelName, beamData.Point);

                if (modelMgr.HasModel(model))                                 // 卫星存在,则更新卫星信息,并移动波束的位置
                {
                    modelMgr.UpdataModel(model);                              // 刷新卫星信息
                    UpdateModelPosition(model);                               // 更新卫星位置

                    beamMgr.UpdataBeamCenterPoint(modelName, beamData.Point); // 刷新波束信息

                    // 移动波束的位置
                    List <Beam> beamList = beamMgr.FindBeams(modelName, o => o.SatelliteID == beamData.SatelliteId);
                    if (beamList == null)
                    {
                        return;
                    }
                    foreach (Beam b in beamList)
                    {
                        UpdateBeamElement(b, model);
                    }
                }
                else     // 卫星不存在,则创建卫星
                {
                    if (AddModel2Earth(model))
                    {
                        modelMgr.AddModel(model);
                    }
                }
            }
        }
コード例 #38
0
 public EventMonitorViewModel()
 {
     EventPublisher.AddEventSubScriptionTokener(
         Assembly.GetExecutingAssembly().GetName().ToString(), FundEventHandler, FundOrderFilter);
 }
コード例 #39
0
 public void SelfDestruct()
 {
     EventPublisher.UnregisterListener <EIObjectClicked <GameObject> >(onObjectClickedListener);
 }
コード例 #40
0
        /// <summary>
        /// 提交PMCC审核
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public VendorRefundInfo SubmitToPMCC(VendorRefundInfo entity)
        {
            //编号不能为空
            if (!entity.SysNo.HasValue || entity.SysNo.Value <= 0)
            {
                //供应商退款编号无效
                throw new BizException(GetMessageString("VendorRefund_SysNoEmpty"));
            }

            VendorRefundInfo localEntity = VendorRefundDA.LoadVendorRefundInfo(entity.SysNo.Value);

            if (localEntity == null)
            {
                throw new BizException(GetMessageString("VendorRefund_RefundNotExist"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.Abandon)
            {
                //该供应商退款单为作废状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_Abandon_Invalid"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.Origin)
            {
                //该供应商退款单为初始状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_Origin_Invalid"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.PMDVerify)
            {
                //该供应商退款单为PMD审核状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_PMDVerify_Invalid"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.PMCCToVerify)
            {
                //该供应商退款单为PMD审核状态,不允许进行当前操作!
                throw new BizException("该供应商退款单为待PMCC审核状态,不允许进行当前操作!");
            }

            if (localEntity.Status.Value == VendorRefundStatus.PMCCVerify)
            {
                //该供应商退款单为PMD审核状态,不允许进行当前操作!
                throw new BizException("该供应商退款单为PMCC已审核状态,不允许进行当前操作!");
            }
            localEntity.PMDUserSysNo = ServiceContext.Current.UserSysNo;
            localEntity.PMDAuditTime = System.DateTime.Now;
            localEntity.PMDMemo      = entity.PMDMemo;
            localEntity.Status       = VendorRefundStatus.PMCCToVerify;

            using (TransactionScope scope = new TransactionScope())
            {
                localEntity = VendorRefundDA.UpdateVendorRefundInfo(localEntity);

                //发送ESB消息
                EventPublisher.Publish <VendorRefundInfoSubmitMessage>(new VendorRefundInfoSubmitMessage()
                {
                    SubmitUserSysNo = ServiceContext.Current.UserSysNo,
                    SysNo           = entity.SysNo.Value
                });

                scope.Complete();
            }

            return(localEntity);
        }
コード例 #41
0
ファイル: ArcGlobeBusiness.cs プロジェクト: siszoey/MapFrame
        // 添加波束图元
        private bool AddBeamElement(Beam beam, Model3D model)
        {
            var coverLayer = mapLogic.AddLayer(coverLayerName);
            var beamLayer  = mapLogic.AddLayer(beam.BeamLayerName);

            if (beamLayer == null)
            {
                return(false);
            }

            string           elementName      = beam.BeamName;
            List <MapLngLat> pointListPolygon = new List <MapLngLat>();
            List <MapLngLat> pointListCover   = new List <MapLngLat>();

            pointListPolygon.Add(model.Coordinate);
            //pointListCover.Add(new MapLngLat(beam.CenterPoint.Lng, beam.CenterPoint.Lat, 100000));

            for (double tempAngle = -180; tempAngle <= 180; tempAngle = tempAngle + beam.StepValue)
            {
                var p = Utils.GetPointByDistanceAndAngle(beam.Radius, beam.CenterPoint, tempAngle);
                if (p != null)
                {
                    pointListPolygon.Add(p);
                    pointListCover.Add(new MapLngLat(p.Lng, p.Lat, 100000));
                }
            }

            if (coverLayer != null)
            {
                // 创建覆盖图元
                Kml polygonCover = new Kml();
                polygonCover.Placemark.Name  = elementName + "cover";
                polygonCover.Placemark.Graph = new KmlPolygon()
                {
                    Description = elementName + "cover", PositionList = pointListCover, OutLineColor = Color.Red, FillColor = Color.FromArgb(20, Color.Blue), OutLineSize = 2
                };
                coverLayer.AddElement(polygonCover);

                // 线
                Kml kmlLine = new Kml();
                kmlLine.Placemark.Name = elementName + "cover_line";
                KmlLineString linekml = new KmlLineString();
                linekml.Color           = Color.Blue;
                linekml.Width           = 2;
                linekml.PositionList    = pointListCover;
                linekml.Rasterize       = false;
                kmlLine.Placemark.Graph = linekml;
                coverLayer.AddElement(kmlLine);
            }

            // 创建波束图元
            Kml polygonKml = new Kml();

            polygonKml.Placemark.Name  = elementName;
            polygonKml.Placemark.Graph = new KmlPolygon()
            {
                Description = elementName, PositionList = pointListPolygon, OutLineColor = Color.Red, FillColor = Color.FromArgb(beamAlpha, Color.YellowGreen), OutLineSize = 3
            };
            if (beamLayer.AddElement(polygonKml))
            {
                EventPublisher.PublishElementAddEvent(this, new ElementAddEventArgs(beam.BeamLayerName, elementName));
            }

            beamLayer.Refresh();   // 波束整体刷新

            return(true);
        }
コード例 #42
0
        /// <summary>
        /// PMCC审核拒绝
        /// </summary>
        /// <param name="refundInfo"></param>
        /// <returns></returns>
        public virtual VendorRefundInfo PMCCReject(VendorRefundInfo refundInfo)
        {
            //编号不能为空
            if (!refundInfo.SysNo.HasValue || refundInfo.SysNo.Value <= 0)
            {
                //供应商退款编号无效
                throw new BizException(GetMessageString("VendorRefund_SysNoEmpty"));
            }
            //获取当前的VendorRefundInfo:
            VendorRefundInfo localEntity = VendorRefundDA.LoadVendorRefundInfo(refundInfo.SysNo.Value);

            if (localEntity == null)
            {
                //供应商退款单在数据中不存在
                throw new BizException(GetMessageString("VendorRefund_RefundNotExist"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.Abandon)
            {
                //该供应商退款单为作废状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_Abandon_Invalid"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.Origin)
            {
                //该供应商退款单为初始状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_Origin_Invalid"));
            }

            if (localEntity.Status.Value == VendorRefundStatus.PMDVerify)
            {
                //该供应商退款单为PMD审核状态,不允许进行当前操作!
                throw new BizException(GetMessageString("VendorRefund_PMDVerify_Invalid"));
            }
            if (localEntity.Status.Value == VendorRefundStatus.PMCCVerify)
            {
                throw new BizException("该供应商退款单为PMCC审核状态,不允许进行当前操作!");
            }
            //if (localEntity.CreateUserSysNo == ServiceContext.Current.UserSysNo)
            //{
            //    //供应商退款单中,创建人,PM审核人,PMD审核人,PMCC审核人,不能相同
            //    throw new BizException(GetMessageString("VendorRefund_OperatorCannotSame_Invalid"));
            //}
            ///更新操作:
            localEntity.PMCCUserSysNo = ServiceContext.Current.UserSysNo;
            localEntity.PMDAuditTime  = System.DateTime.Now;
            localEntity.PMCCMemo      = refundInfo.PMCCMemo;
            localEntity.Status        = VendorRefundStatus.Origin;

            using (TransactionScope scope = new TransactionScope())
            {
                localEntity = VendorRefundDA.UpdateVendorRefundInfo(localEntity);

                //发送ESB消息
                EventPublisher.Publish <VendorRefundInfoRejectMessage>(new VendorRefundInfoRejectMessage()
                {
                    RejectUserSysNo = ServiceContext.Current.UserSysNo,
                    SysNo           = refundInfo.SysNo.Value
                });

                scope.Complete();
            }

            return(localEntity);
        }
コード例 #43
0
ファイル: Program.cs プロジェクト: Bigsby/PoC
 public EventSubscriber(EventPublisher publisher)
 {
     publisher.TheEvent += (s, e) => { };
 }
コード例 #44
0
 // 接收波束数据
 private void RecvBeamData(BeamData beamData)
 {
     EventPublisher.PublishBeamDataComeEvent(this, beamData);
 }
コード例 #45
0
 /// <summary>
 /// Checks the subscriber's subscription to see if it's still active.
 /// </summary>
 /// <param name="subscriber">The subscriber.</param>
 /// <returns>
 /// true if the subscription is still active, otherwise false
 /// </returns>
 public bool SubscriptionActive(Uri subscriber)
 {
     return(EventPublisher.CheckSubscription(subscriber));
 }
コード例 #46
0
        private CustomerOrderServiceImpl GetCustomerOrderService()
        {
            Func<IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository("VirtoCommerce", new EntityPrimaryKeyGeneratorInterceptor(), new AuditableInterceptor());
            Func<IOrderRepository> orderRepositoryFactory = () =>
            {
                return new OrderRepositoryImpl("VirtoCommerce", new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor());
            };

            Func<ICartRepository> repositoryFactory = () =>
            {
                return new CartRepositoryImpl("VirtoCommerce", new AuditableInterceptor());
            };

            var dynamicPropertyService = new DynamicPropertyService(platformRepositoryFactory);
            var orderEventPublisher = new EventPublisher<OrderChangeEvent>(Enumerable.Empty<IObserver<OrderChangeEvent>>().ToArray());
            var cartEventPublisher = new EventPublisher<CartChangeEvent>(Enumerable.Empty<IObserver<CartChangeEvent>>().ToArray());
            var cartService = new ShoppingCartServiceImpl(repositoryFactory, cartEventPublisher, null, dynamicPropertyService);
            var settingManager = new SettingsManager(null, null, null, null);

            var orderService = new CustomerOrderServiceImpl(orderRepositoryFactory, new TimeBasedNumberGeneratorImpl(), orderEventPublisher, cartService, GetItemService(), dynamicPropertyService, settingManager, null, null);
            return orderService;
        }
コード例 #47
0
ファイル: ServiceProxyProvider.cs プロジェクト: zche/microdot
        private async Task <object> InvokeCore(HttpServiceRequest request, Type resultReturnType, JsonSerializerSettings jsonSettings)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            request.Overrides   = TracingContext.TryGetOverrides();
            request.TracingData = new TracingData
            {
                HostName         = CurrentApplicationInfo.HostName?.ToUpperInvariant(),
                ServiceName      = CurrentApplicationInfo.Name,
                RequestID        = TracingContext.TryGetRequestID(),
                SpanID           = Guid.NewGuid().ToString("N"), //Each call is new span
                ParentSpanID     = TracingContext.TryGetSpanID(),
                SpanStartTime    = DateTimeOffset.UtcNow,
                AbandonRequestBy = TracingContext.AbandonRequestBy,
            };
            PrepareRequest?.Invoke(request);
            var requestContent = _serializationTime.Time(() => JsonConvert.SerializeObject(request, jsonSettings));

            while (true)
            {
                var config          = GetConfig();
                var clientCallEvent = EventPublisher.CreateEvent();
                clientCallEvent.TargetService = ServiceName;
                clientCallEvent.RequestId     = request.TracingData?.RequestID;
                clientCallEvent.TargetMethod  = request.Target.MethodName;
                clientCallEvent.SpanId        = request.TracingData?.SpanID;
                clientCallEvent.ParentSpanId  = request.TracingData?.ParentSpanID;

                string responseContent;
                HttpResponseMessage response;
                IEndPointHandle     endPoint = await ServiceDiscovery.GetNextHost(clientCallEvent.RequestId).ConfigureAwait(false);

                int?effectivePort = GetEffectivePort(endPoint, config);
                if (effectivePort == null)
                {
                    throw new ConfigurationException("Cannot access service. Service Port not configured. See tags to find missing configuration", unencrypted: new Tags {
                        { "ServiceName", ServiceName },
                        { "Required configuration key", $"Discovery.{ServiceName}.DefaultPort" }
                    });
                }

                // The URL is only for a nice experience in Fiddler, it's never parsed/used for anything.
                var uri = BuildUri(endPoint.HostName, effectivePort.Value, config) + ServiceName;
                if (request.Target.MethodName != null)
                {
                    uri += $".{request.Target.MethodName}";
                }
                if (request.Target.Endpoint != null)
                {
                    uri += $"/{request.Target.Endpoint}";
                }

                try
                {
                    Log.Debug(_ => _("ServiceProxy: Calling remote service. See tags for details.",
                                     unencryptedTags: new
                    {
                        remoteEndpoint    = endPoint.HostName,
                        remotePort        = effectivePort,
                        remoteServiceName = ServiceName,
                        remoteMethodName  = request.Target.MethodName
                    }));

                    clientCallEvent.TargetHostName = endPoint.HostName;
                    clientCallEvent.TargetPort     = effectivePort.Value;

                    var httpContent = new StringContent(requestContent, Encoding.UTF8, "application/json");
                    httpContent.Headers.Add(GigyaHttpHeaders.Version, HttpServiceRequest.Version);

                    clientCallEvent.RequestStartTimestamp = Stopwatch.GetTimestamp();
                    try
                    {
                        response = await GetHttpClient(config).PostAsync(uri, httpContent).ConfigureAwait(false);

                        responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                    finally
                    {
                        clientCallEvent.ResponseEndTimestamp = Stopwatch.GetTimestamp();
                    }
                    if (response.Headers.TryGetValues(GigyaHttpHeaders.ExecutionTime, out IEnumerable <string> values))
                    {
                        var time = values.FirstOrDefault();
                        if (TimeSpan.TryParse(time, out TimeSpan executionTime))
                        {
                            clientCallEvent.ServerTimeMs = executionTime.TotalMilliseconds;
                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    Log.Error("The remote service failed to return a valid HTTP response. Continuing to next " +
                              "host. See tags for URL and exception for details.",
                              exception: ex,
                              unencryptedTags: new { uri });

                    endPoint.ReportFailure(ex);
                    _hostFailureCounter.Increment("RequestFailure");
                    clientCallEvent.Exception = ex;
                    EventPublisher.TryPublish(clientCallEvent); // fire and forget!
                    continue;
                }
                catch (TaskCanceledException ex)
                {
                    _failureCounter.Increment("RequestTimeout");

                    Exception rex = new RemoteServiceException("The request to the remote service exceeded the " +
                                                               "allotted timeout. See the 'RequestUri' property on this exception for the URL that was " +
                                                               "called and the tag 'requestTimeout' for the configured timeout.",
                                                               uri,
                                                               ex,
                                                               unencrypted: new Tags
                    {
                        { "requestTimeout", LastHttpClient?.Timeout.ToString() },
                        { "requestUri", uri }
                    });

                    clientCallEvent.Exception = rex;

                    EventPublisher.TryPublish(clientCallEvent); // fire and forget!
                    throw rex;
                }

                if (response.Headers.Contains(GigyaHttpHeaders.ServerHostname) || response.Headers.Contains(GigyaHttpHeaders.Version))
                {
                    try
                    {
                        endPoint.ReportSuccess();

                        if (response.IsSuccessStatusCode)
                        {
                            var returnObj = _deserializationTime.Time(() => JsonConvert.DeserializeObject(responseContent, resultReturnType, jsonSettings));

                            clientCallEvent.ErrCode = 0;
                            EventPublisher.TryPublish(clientCallEvent); // fire and forget!
                            _successCounter.Increment();

                            return(returnObj);
                        }
                        else
                        {
                            Exception remoteException;

                            try
                            {
                                remoteException = _deserializationTime.Time(() => ExceptionSerializer.Deserialize(responseContent));
                            }
                            catch (Exception ex)
                            {
                                _applicationExceptionCounter.Increment("ExceptionDeserializationFailure");

                                throw new RemoteServiceException("The remote service returned a failure response " +
                                                                 "that failed to deserialize.  See the 'RequestUri' property on this exception " +
                                                                 "for the URL that was called, the inner exception for the exact error and the " +
                                                                 "'responseContent' encrypted tag for the original response content.",
                                                                 uri,
                                                                 ex,
                                                                 unencrypted: new Tags {
                                    { "requestUri", uri }
                                },
                                                                 encrypted: new Tags {
                                    { "responseContent", responseContent }
                                });
                            }

                            _applicationExceptionCounter.Increment();

                            clientCallEvent.Exception = remoteException;
                            EventPublisher.TryPublish(clientCallEvent); // fire and forget!

                            if (remoteException is RequestException || remoteException is EnvironmentException)
                            {
                                ExceptionDispatchInfo.Capture(remoteException).Throw();
                            }

                            if (remoteException is UnhandledException)
                            {
                                remoteException = remoteException.InnerException;
                            }

                            throw new RemoteServiceException("The remote service returned a failure response. See " +
                                                             "the 'RequestUri' property on this exception for the URL that was called, and the " +
                                                             "inner exception for details.",
                                                             uri,
                                                             remoteException,
                                                             unencrypted: new Tags {
                                { "requestUri", uri }
                            });
                        }
                    }
                    catch (JsonException ex)
                    {
                        _failureCounter.Increment("Serialization");

                        Log.Error("The remote service returned a response with JSON that failed " +
                                  "deserialization. See the 'uri' tag for the URL that was called, the exception for the " +
                                  "exact error and the 'responseContent' encrypted tag for the original response content.",
                                  exception: ex,
                                  unencryptedTags: new { uri },
                                  encryptedTags: new { responseContent });

                        clientCallEvent.Exception = ex;
                        EventPublisher.TryPublish(clientCallEvent); // fire and forget!
                        throw new RemoteServiceException("The remote service returned a response with JSON that " +
                                                         "failed deserialization. See the 'RequestUri' property on this exception for the URL " +
                                                         "that was called, the inner exception for the exact error and the 'responseContent' " +
                                                         "encrypted tag for the original response content.",
                                                         uri,
                                                         ex,
                                                         new Tags {
                            { "responseContent", responseContent }
                        },
                                                         new Tags {
                            { "requestUri", uri }
                        });
                    }
                }
                else
                {
                    var exception = response.StatusCode == HttpStatusCode.ServiceUnavailable ?
                                    new Exception($"The remote service is unavailable (503) and is not recognized as a Gigya host at uri: {uri}"):
                                    new Exception($"The remote service returned a response but is not recognized as a Gigya host at uri: {uri}");

                    endPoint.ReportFailure(exception);
                    _hostFailureCounter.Increment("NotGigyaHost");

                    if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        Log.Error("The remote service is unavailable (503) and is not recognized as a Gigya host. Continuing to next host.", unencryptedTags: new { uri });
                    }
                    else
                    {
                        Log.Error("The remote service returned a response but is not recognized as a Gigya host. Continuing to next host.", unencryptedTags: new { uri, statusCode = response.StatusCode }, encryptedTags: new { responseContent });
                    }

                    clientCallEvent.ErrCode = 500001;           //(int)GSErrors.General_Server_Error;
                    EventPublisher.TryPublish(clientCallEvent); // fire and forget!
                }
            }
        }