Пример #1
0
    static void Main()
    {
        Console.Title = "Samples.Castle";
        Configure.Serialization.Json();
        #region ContainerConfiguration
        var configure = Configure.With();
        configure.Log4Net();
        configure.DefineEndpointName("Samples.Castle");
        var container = new WindsorContainer();
        container.Register(Component.For<MyService>().Instance(new MyService()));
        configure.CastleWindsorBuilder(container);
        #endregion
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        configure.UseTransport<Msmq>();
        using (var startableBus = configure.UnicastBus().CreateBus())
        {
            var bus = startableBus.Start(() => configure.ForInstallationOn<Windows>().Install());

            var myMessage = new MyMessage();
            bus.SendLocal(myMessage);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Пример #2
0
    static void Main()
    {
        Console.Title = "Samples.Logging.CommonLogging";

        #region ConfigureLogging

        Common.Logging.LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter
        {
            Level = LogLevel.Info
        };

        NServiceBus.Logging.LogManager.Use<CommonLoggingFactory>();

        var busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.Logging.CommonLogging");

        #endregion

        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence<InMemoryPersistence>();

        using (var bus = Bus.Create(busConfiguration).Start())
        {
            var myMessage = new MyMessage();
            bus.SendLocal(myMessage);
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Пример #3
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.Logging.CustomFactory";
        #region ConfigureLogging

        var loggerDefinition = LogManager.Use<ConsoleLoggerDefinition>();

        // optionally set the log level in code or read from app.config
        loggerDefinition.Level(LogLevel.Info);

        // logging configuration should occur prior to endpoint configuration
        var endpointConfiguration = new EndpointConfiguration("Samples.Logging.CustomFactory");

        #endregion
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.UsePersistence<InMemoryPersistence>();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        try
        {
            var myMessage = new MyMessage();
            await endpointInstance.SendLocal(myMessage)
                .ConfigureAwait(false);
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
Пример #4
0
    public void SendMessage(int number)
    {
        MyMessage msg = new MyMessage();
        msg.number = number;

        myClient.Send(MyMsgType.CustomMsgType, msg);
    }
Пример #5
0
    static void Main()
    {
        LogManager.Use<DefaultFactory>()
            .Level(LogLevel.Warn);

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.ErrorHandling.WithSLR");
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.UsePersistence<InMemoryPersistence>();
        busConfiguration.EnableInstallers();
        using (IBus bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press enter to send a message that will throw an exception.");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                MyMessage m = new MyMessage
                {
                    Id = Guid.NewGuid()
                };
                bus.SendLocal(m);
            }
        }
    }
Пример #6
0
    static void Main()
    {
        Console.Title = "Samples.Logging.CustomFactory";
        #region ConfigureLogging

        var loggerDefinition = LogManager.Use<ConsoleLoggerDefinition>();

        // optionally set the log level in code or read from app.config
        loggerDefinition.Level(LogLevel.Info);

        // logging configuration should occur prior to endpoint configuration
        var busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.Logging.CustomFactory");

        #endregion
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence<InMemoryPersistence>();

        using (var bus = Bus.Create(busConfiguration).Start())
        {
            var myMessage = new MyMessage();
            bus.SendLocal(myMessage);
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Пример #7
0
    static void Start(IBus bus)
    {
        Console.WriteLine("Press 'p' to Publish MyEvent");
        Console.WriteLine("Press 's' to SendLocal MyMessage");
        Console.WriteLine("Press any other key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            var id = Guid.NewGuid();
            if (key.Key == ConsoleKey.P)
            {
                var myEvent = new MyEvent
                {
                    Id = id,
                };
                bus.Publish(myEvent);
                Console.WriteLine("Published MyEvent with Id {0}.", id);
                continue;
            }
            if (key.Key == ConsoleKey.S)
            {
                var eventMessage = new MyMessage
                {
                    Id = id,
                };
                bus.SendLocal(eventMessage);
                Console.WriteLine("Sent MyMessage with Id {0}.", id);
                continue;
            }
            return;
        }
    }
Пример #8
0
    static async Task AsyncMain()
    {
        LogManager.Use<DefaultFactory>()
            .Level(LogLevel.Warn);

        #region DisableSLR
        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.ErrorHandling.WithoutSLR");
        busConfiguration.DisableFeature<SecondLevelRetries>();
        #endregion
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.UsePersistence<InMemoryPersistence>();
        busConfiguration.EnableInstallers();
        busConfiguration.SendFailedMessagesTo("error");

        using (IBus bus = await Bus.Create(busConfiguration).StartAsync())
        {
            Console.WriteLine("Press enter to send a message that will throw an exception.");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                MyMessage m = new MyMessage
                {
                    Id = Guid.NewGuid()
                };
                await bus.SendLocalAsync(m);
            }
        }
    }
Пример #9
0
    static void Main()
    {
        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.Headers");

        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence<InMemoryPersistence>();

        busConfiguration.RegisterComponents(components =>
        {
            components.ConfigureComponent<MutateIncomingMessages>(DependencyLifecycle.InstancePerCall);
            components.ConfigureComponent<MutateIncomingTransportMessages>(DependencyLifecycle.InstancePerCall);
            components.ConfigureComponent<MutateOutgoingMessages>(DependencyLifecycle.InstancePerCall);
            components.ConfigureComponent<MutateOutgoingTransportMessages>(DependencyLifecycle.InstancePerCall);
        });

        #region global-all-outgoing
        busConfiguration.AddHeaderToAllOutgoingMessages("AllOutgoing", "ValueAllOutgoing");
        IStartableBus startableBus = Bus.Create(busConfiguration);
        using (IBus bus = startableBus.Start())
        {
            #endregion

            #region sending
            MyMessage myMessage = new MyMessage();
            bus.SendLocal(myMessage);
            #endregion
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Пример #10
0
    static void Main()
    {
        Console.Title = "Samples.Logging.SerilogCustom";
        #region ConfigureSerilog
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File("logFile.txt")
            .CreateLogger();
        #endregion

        #region UseConfig
        LogManager.Use<SerilogFactory>();

        var busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.Logging.SerilogCustom");

        #endregion

        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence<InMemoryPersistence>();

        using (var bus = Bus.Create(busConfiguration).Start())
        {
            var myMessage = new MyMessage();
            bus.SendLocal(myMessage);
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Пример #11
0
    static void Main()
    {
        Console.Title = "Samples.Spring";
        Configure.Serialization.Json();
        #region ContainerConfiguration
        var configure = Configure.With();
        configure.Log4Net();
        configure.DefineEndpointName("Samples.Spring");
        var applicationContext = new GenericApplicationContext();
        applicationContext.ObjectFactory.RegisterSingleton("MyService", new MyService());
        configure.SpringFrameworkBuilder(applicationContext);
        #endregion
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        configure.UseTransport<Msmq>();
        using (var startableBus = configure.UnicastBus().CreateBus())
        {
            var bus = startableBus.Start(() => configure.ForInstallationOn<Windows>().Install());
            var myMessage = new MyMessage();
            bus.SendLocal(myMessage);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }

    }
Пример #12
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.RabbitMQ.Simple";
        #region ConfigureRabbit

        var endpointConfiguration = new EndpointConfiguration("Samples.RabbitMQ.Simple");
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        #endregion
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.UsePersistence<InMemoryPersistence>();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        var myMessage = new MyMessage();
        await endpointInstance.SendLocal(myMessage)
            .ConfigureAwait(false);
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
Пример #13
0
    static void Main()
    {
        Console.Title = "Samples.Castle";
        #region ContainerConfiguration
        var busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.Castle");

        var container = new WindsorContainer();
        container.Register(Component.For<MyService>().Instance(new MyService()));

        busConfiguration.UseContainer<WindsorBuilder>(c => c.ExistingContainer(container));
        #endregion

        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.UsePersistence<InMemoryPersistence>();
        busConfiguration.EnableInstallers();

        using (var bus = Bus.Create(busConfiguration).Start())
        {
            var myMessage = new MyMessage();
            bus.SendLocal(myMessage);
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Пример #14
0
    static void Main()
    {
        LogManager.Use<DefaultFactory>()
            .Level(LogLevel.Warn);

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.ErrorHandling.WithoutSLR");
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.UsePersistence<InMemoryPersistence>();
        busConfiguration.DisableFeature<SecondLevelRetries>();
        busConfiguration.EnableInstallers();

        using (IBus bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press any key to send a message that will throw an exception.");
            Console.WriteLine("To exit, press Ctrl + C");

            while (true)
            {
                Console.ReadLine();
                MyMessage m = new MyMessage
                              {
                                  Id = Guid.NewGuid()
                              };
                bus.SendLocal(m);
            }
        }
    }
        public void Should_run_a_batch_nicely()
        {
            const int batchSize = 10000;
            var callbackCount = 0;
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            using (var channel = bus.OpenPublishChannel(x => x.WithPublisherConfirms()))
            {
                for (int i = 0; i < batchSize; i++)
                {
                    var message = new MyMessage {Text = string.Format("Hello Message {0}", i)};
                    channel.Publish(message, x =>
                        x.OnSuccess(() => {
                            callbackCount++;
                        })
                        .OnFailure(() =>
                        {
                            callbackCount++;
                        }));
                }

                // wait until all the publications have been acknowleged.
                while (callbackCount < batchSize)
                {
                    if (stopwatch.Elapsed.Seconds > 10)
                    {
                        throw new ApplicationException("Aborted batch with timeout");
                    }
                    Thread.Sleep(10);
                }
            }
        }
Пример #16
0
    static async Task Start()
    {
        Console.Title = "Samples.Ninject";
        #region ContainerConfiguration
        var endpointConfiguration = new EndpointConfiguration("Samples.Ninject");
        endpointConfiguration.SendFailedMessagesTo("error");

        var kernel = new StandardKernel();
        kernel.Bind<MyService>().ToConstant(new MyService());
        endpointConfiguration.UseContainer<NinjectBuilder>(c => c.ExistingKernel(kernel));
        #endregion
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
        endpointConfiguration.EnableInstallers();


        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);

        try
        {
            var myMessage = new MyMessage();
            await endpointInstance.SendLocal(myMessage)
                .ConfigureAwait(false);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally 
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
Пример #17
0
    static void Main()
    {
        Console.Title = "Samples.ErrorHandling.WithSLR";
        Configure.Serialization.Json();
        Configure configure = Configure.With();
        configure.Log4Net();
        configure.DefineEndpointName("Samples.ErrorHandling.WithSLR");
        configure.DefaultBuilder();
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        configure.UseTransport<Msmq>();
        using (IStartableBus startableBus = configure.UnicastBus().CreateBus())
        {
            IBus bus = startableBus
                .Start(() => configure.ForInstallationOn<Windows>().Install());
            Console.WriteLine("Press enter to send a message that will throw an exception.");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                MyMessage m = new MyMessage
                {
                    Id = Guid.NewGuid()
                };
                bus.SendLocal(m);
            }
        }
    }
Пример #18
0
    static void Main()
    {
        Console.Title = "Samples.Logging.Default";
        Configure.Serialization.Json();
        #region ConfigureLogging
        var configure = Configure.With();
        //Configures a ConsoleAppender with a threshold of Debug
        configure.Log4Net();
        configure.DefineEndpointName("Samples.Logging.Default");
        #endregion
        configure.DefaultBuilder();
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        configure.UseTransport<Msmq>();
        using (var startableBus = configure.UnicastBus().CreateBus())
        {
            var bus = startableBus.Start(() => configure.ForInstallationOn<Windows>().Install());
            var myMessage = new MyMessage();
            bus.SendLocal(myMessage);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }

    }
Пример #19
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.Unity";
        #region ContainerConfiguration
        var endpointConfiguration = new EndpointConfiguration("Samples.Unity");
        var container = new UnityContainer();
        container.RegisterInstance(new MyService());
        endpointConfiguration.UseContainer<UnityBuilder>(c => c.UseExistingContainer(container));
        #endregion
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.SendFailedMessagesTo("error");

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        try
        {
            var myMessage = new MyMessage();
            await endpointInstance.SendLocal(myMessage)
                .ConfigureAwait(false);
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
 public void Should_be_able_to_publish()
 {
     var publishedMessage = new MyMessage {Text = "Hello There Fido!"};
     using (var channel = bus.OpenPublishChannel())
     {
         channel.Publish(publishedMessage);
     }
 }
Пример #21
0
 public void Should_be_able_to_publish()
 {
     var message = new MyMessage { Text = "Hello! " + Guid.NewGuid().ToString().Substring(0, 5) };
     using (var publishChannel = bus.OpenPublishChannel())
     {
         publishChannel.Publish(message);
     }
     Console.Out.WriteLine("message.Text = {0}", message.Text);
 }
Пример #22
0
        protected void MakeRequest(Action<MyOtherMessage> responseHandler = null)
        {
            using (var channel = mockBuilder.Bus.OpenPublishChannel())
            {
                var request = new MyMessage { Text = "Hello World!" };

                channel.Request(request, responseHandler ?? (response => { }));
            }
        }
Пример #23
0
        void SetMessageHeader(IBus bus)
        {
            #region 3to4SetMessageHeader

            MyMessage myMessage = new MyMessage();
            myMessage.SetHeader("SendingMessage", "ValueSendingMessage");
            bus.SendLocal(myMessage);

            #endregion
        }
 static IOutgoingSendContext CreateContext(SendOptions options, bool fromHandler)
 {
     var message = new MyMessage();
     var context = new OutgoingSendContext(new OutgoingLogicalMessage(message.GetType(), message), options, new RootContext(null, null, null));
     if (fromHandler)
     {
         context.Extensions.Set(new PendingTransportOperations());
     }
     return context;
 }
        public void CorrectCyclicReferenceSerialization()
        {
            var message = new MyMessage();
            message.Msg = message;

            var serialized = _serializer.Serialize(message);

            var deserialized = (MyMessage) _deserializer.Deserialize(serialized);
            deserialized.Should(Is.Not.Null);
            deserialized.Msg.Should(Is.Null);
        }
 public void MySend(MyMessage msg)
 {
     if (String.IsNullOrEmpty(msg.Client))
     {
         Clients.All.sendMessage(msg.Name, msg.Message, msg.Time );
     }
     else
     {
         Clients.Client(msg.Client).clientMessage(msg.Name, msg.Message, msg.Time);
     }
 }
Пример #27
0
        Usage(IBus bus)
        {
            #region RequestImmediateDispatchUsingScope
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                var myMessage = new MyMessage();
                bus.Send(myMessage);
            }

            #endregion
        }
Пример #28
0
        public void SetMessageHeader()
        {
            IBus bus = null;

            #region 3to4SetMessageHeader

            MyMessage myMessage = new MyMessage();
            bus.SetMessageHeader(myMessage, "SendingMessage", "ValueSendingMessage");
            bus.SendLocal(myMessage);

            #endregion
        }
Пример #29
0
        public void The_reliable_attribute_should_be_specified()
        {
            MyMessage message = new MyMessage();

            object[] attributes = message.GetType().GetCustomAttributes(typeof (ReliableAttribute), false);

            Assert.That(attributes.Length, Is.GreaterThan(0));

            foreach (ReliableAttribute reliable in attributes)
            {
                Assert.That(reliable.Enabled, Is.True);
            }
        }
Пример #30
0
        public void The_message_should_use_an_expiration_attribute()
        {
            MyMessage message = new MyMessage();

            object[] attributes = message.GetType().GetCustomAttributes(typeof (ExpiresInAttribute), false);

            Assert.That(attributes.Length, Is.GreaterThan(0));

            foreach (ExpiresInAttribute expiresIn in attributes)
            {
                Assert.That(expiresIn.TimeToLive, Is.EqualTo(TimeSpan.FromMinutes(5)));
            }
        }
Пример #31
0
 public void Handle(MyMessage message)
 {
     //do something
 }
Пример #32
0
        public async Task HandleAsync(MyMessage message)
        {
            await Task.Delay(100);

            //do something
        }
Пример #33
0
 public MyResponse NameDoesntMatter(MyMessage message)
 {
     return(new MyResponse());
 }
        /// <summary>
        /// 将人脸对象批量上传的回调函数(错误的保存)
        /// </summary>
        /// <param name="ar"></param>
        private void PicHandle(IAsyncResult ar)
        {
            lock (tIPViewModel)
            {
                try
                {
                    upedCount++;
                    FaceObj     _FaceObj = ar.AsyncState as FaceObj;
                    AsyncResult a        = (AsyncResult)ar;
                    ThreadImportPicIntoDbDelegate trys = (ThreadImportPicIntoDbDelegate)a.AsyncDelegate;
                    List <ErrorInfo> ListErrorInfo     = trys.EndInvoke(ar);
                    if (ListErrorInfo.Count > 0)
                    {
                        for (int l = 0; l < ListErrorInfo.Count; l++)
                        {
                            Console.WriteLine(ListErrorInfo[l].ErrCode + "");
                            if (ListErrorInfo[l].ErrCode == -1)//小于0,注册失败
                            {
                                byte[]               photo  = _FaceObj.Tmplate[0].Img;
                                MemoryStream         stream = new MemoryStream(photo);
                                System.Drawing.Image img    = System.Drawing.Image.FromStream(stream);
                                //判断文件夹存在
                                DirectoryInfo directory = new DirectoryInfo(tIPViewModel.ErrorAddress);
                                if (!directory.Exists)
                                {
                                    //重新生成文件夹
                                    Directory.CreateDirectory(tIPViewModel.ErrorAddress);
                                }

                                string strPath = "";

                                strPath = tIPViewModel.ErrorAddress + @"\" + _FaceObj.TcName + @".jpg";
                                img.Save(strPath, img.RawFormat);
                                tIPViewModel.ErrorCount++;
                            }
                            if (ListErrorInfo[l].ErrCode == -3 || ListErrorInfo[l].ErrCode == -2)//图片不存在
                            {
                                tIPViewModel.ErrorCount++;
                                string message = "第" + upedCount + "行注册失败";
                            }
                        }
                    }
                    else
                    {
                        ++tIPViewModel.SuccessCount;
                    }
                }
                catch (Exception ex)
                {
                    _WriteLog.WriteToLog("PicHandle", ex);
                    tIPViewModel.ErrorCount++;
                    //System.Windows.MessageBox.Show("PicHandle" + ex.Message);
                }
                finally
                {
                    ++tIPViewModel.CurrentLength;
                    tIPViewModel.ImportInfo = "总数量:" + tIPViewModel.MaxLength + "  上传数量:" + tIPViewModel.CurrentLength + "成功数量:" + tIPViewModel.SuccessCount + "";
                    //Console.WriteLine("总数量:" + tIPViewModel.MaxLength + "  上传数量:" + tIPViewModel.CurrentLength + "成功数量:" + tIPViewModel.SuccessCount + "");
                    upingCount--;
                    if (tIPViewModel.MaxLength == tIPViewModel.CurrentLength)
                    {
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            MyMessage.showYes("模版已全部导入完成!");
                        }));
                    }
                }
            }
        }
        // This method is about what we ended up with in "Fund." - with a few changes done for Adv.
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // SplitPay is in a Session-variable (bool)
            string paymentProcessResult = String.Empty;

            // Load the cart, it should be one there
            var cart = _orderRepository.Load <ICart>(GetContactId(), "Default").FirstOrDefault();

            if (cart == null)
            {
                throw new InvalidOperationException("No cart found"); // make nicer
            }

            #region What actually happens when loading a cart - Adv.

            //Cart cart = OrderContext.Current.GetCart(
            //    "SomeCart"
            //    , CustomerContext.Current.CurrentContactId
            //    , MarketId.Default); // ...is still what happens in behind

            #endregion

            // should clean-up among payments here if the  first time failed - Qty 10 test
            // quick fixdon in the base class

            // From Fund
            IOrderAddress theAddress = AddAddressToOrder(cart);

            // ToDo: Added this field for Adv. & Find ... doing it simple now using one Address
            // The address is for Find, but we need to add it to MDP to be able to use it properly
            // This is a Serialized cart, so doesn't crash if the field is not added to MDP
            theAddress.Properties["AddressType"] = "Shipping";

            #region Ship & Pay from Fund

            // ToDo: Define Shipping - From Fund
            AdjustFirstShipmentInOrder(cart, theAddress, model.SelectedShipId); // ...as a Shipment is added by epi

            // ToDo: Define Payment - From Fund
            AddPaymentToOrder(cart, model.SelectedPayId); // ...as this is not added by default

            #endregion

            #region Split Pay

            // RoCe: Fix this - addSecondPayment comes in as a param (bool)
            // ... force for now if BF-Card is found ... using Session
            if ((bool)Session["SecondPayment"] == true)
            {
                ccService.AddSecondPaymentToOrder(cart);
            }

            // gathered info
            this.frontEndMessage = ccService.FrontEndMessage;

            #endregion

            // Possible change of the cart... adding this
            // would have this done if a flag were set
            var cartReference = _orderRepository.Save(cart);

            // Original Fund... (with additions)
            IPurchaseOrder purchaseOrder;
            OrderReference orderReference;

            #region Transaction Scope

            using (var scope = new Mediachase.Data.Provider.TransactionScope()) // one in BF, also
            {
                var validationIssues = new Dictionary <ILineItem, ValidationIssue>();

                // Added - sets a lock on inventory...
                // ...could come earlier (outside tran) depending on TypeOf-"store"
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.InProgress, (item, issue) => validationIssues.Add(item, issue));

                if (validationIssues.Count >= 1)
                {
                    throw new Exception("Not possible right now"); // ...change approach
                }

                // just checking the cart in watch window
                var theShipping  = cart.GetFirstShipment();
                var theLineItems = cart.GetAllLineItems();
                var firstPayment = cart.GetFirstForm().Payments.First(); // no "GetFirstPayment()"
                var theforms     = cart.Forms;

                //_lineItemCalculator.GetDiscountedPrice()
                // second payment is added in the Trousers-Controller
                // ...fiddling with the GiftCarde as well

                // before 11
                //cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator);

                // Gets the older one
                //IEnumerable<PaymentProcessingResult> theResult
                //    = cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator);
                //paymentProcessResult = theResult.First().Message;

                PaymentProcessingResult otherResult =
                    _paymentProcessor.ProcessPayment(cart, cart.GetFirstForm().Payments.First(), cart.GetFirstShipment());

                frontEndMessage += otherResult.Message;

                if (otherResult.IsSuccessful)
                {
                    IPayment thePay = cart.GetFirstForm().Payments.First();
                    thePay.Status = PaymentStatus.Processed.ToString();
                }
                else
                {
                    IPayment thePay = cart.GetFirstForm().Payments.First();
                    thePay.Status = PaymentStatus.Failed.ToString();
                    throw new System.Exception("Bad payment"); // could have more grace
                }
                // A custom "shipping-processor" created (needs to do OldSchool-things right now)
                // Have a custom (very simple) Shipping-Provider added to the solution.
                // the processor can be cleaned up a lot, no need to show it

                // Custom thing... Error in 11... on currency... check later
                //ShippingProcessor p = new ShippingProcessor();
                //p.ProcessShipments(cart as OrderGroup); // have to go Old-school

                // ...only one form, still
                var totalProcessedAmount = cart.GetFirstForm().Payments.Where
                                               (x => x.Status.Equals(PaymentStatus.Processed.ToString())).Sum(x => x.Amount);

                // nice extension method
                var cartTotal = cart.GetTotal();

                // Do inventory - decrement or put back in stock
                if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount)
                {
                    // put back the reserved request
                    _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                        , OrderStatus.Cancelled, (item, issue) => validationIssues.Add(item, issue));

                    #region OldSchool Inventory - no demo,just checking ... were undocumented and wrong in SDK
                    //List<InventoryRequestItem> requestItems = new List<InventoryRequestItem>(); // holds the "items"
                    //InventoryRequestItem requestItem = new InventoryRequestItem();

                    //// calls for some logic
                    //requestItem.RequestType = InventoryRequestType.Cancel; // as a demo
                    //requestItem.OperationKey = reqKey;

                    //requestItems.Add(requestItem);

                    //InventoryRequest inventoryRequest = new InventoryRequest(DateTime.UtcNow, requestItems, null);
                    //InventoryResponse inventoryResponse = _invService.Service.Request(inventoryRequest);

                    //InventoryRecord rec4 = _invService.Service.Get(LI.Code, wh.Code);
                    #endregion OldSchool

                    throw new InvalidOperationException("Wrong amount"); // maybe change approach
                }

                // RoCe: have to do Promos here also ... move stuff from cart to "base"

                // simulation... should be an "else"
                cart.GetFirstShipment().OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;
                // decrement inventory and let it go
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.Completed, (item, issue) => validationIssues.Add(item, issue));

                // Should do the ClubCard thing here - ClubMembers are logged in
                // PaymentMethodName = "GiftCard"
                if (CustomerContext.Current.CurrentContact != null)
                {
                    // check if GiftCard was used, don't give bonus for that payment
                    IEnumerable <IPayment> giftCardPayment = cart.GetFirstForm().Payments.Where
                                                                 (x => x.PaymentMethodName.Equals("GiftCard"));

                    if (giftCardPayment.Count() >= 1)
                    {
                        ccService.UpdateClubCard(cart, totalProcessedAmount - giftCardPayment.First().Amount);
                    }
                    else
                    {
                        // no GiftCard, but collecting points
                        ccService.UpdateClubCard(cart, totalProcessedAmount);
                    }
                }

                #region OldSchool Inventory check

                //List<InventoryRequestItem> requestItems1 = new List<InventoryRequestItem>(); // holds the "items"
                //InventoryRequestItem requestItem1 = new InventoryRequestItem();

                //// calls for some logic
                //requestItem1.RequestType = InventoryRequestType.Complete; // as a demo
                //requestItem1.OperationKey = reqKey;

                //requestItems1.Add(requestItem1);

                //InventoryRequest inventoryRequest1 = new InventoryRequest(DateTime.UtcNow, requestItems1, null);
                //InventoryResponse inventoryResponse1 = _invService.Service.Request(inventoryRequest1);

                //InventoryRecord rec3 = _invService.Service.Get(LI.Code, wh.Code); // inventory reserved, but not decremented

                #endregion OldSchool

                orderReference = _orderRepository.SaveAsPurchaseOrder(cart);
                _orderRepository.Delete(cart.OrderLink);

                //InventoryRecord rec5 = _invService.Service.Get(LI.Code, wh.Code); // just checking

                scope.Complete();
            } // End Tran

            #endregion

            #region JustChecking

            //Guid custLock;
            //OrderGroupLockManager.IsOrderGroupLocked(orderReference.OrderGroupId, out (Guid)CustomerContext.Current.CurrentContact.PrimaryKeyId));

            /*
             * OrderGroupLockManager.LockOrderGroup(orderReference.OrderGroupId
             *  , (Guid)CustomerContext.Current.CurrentContact.PrimaryKeyId);
             *
             * OrderGroupLockManager.UnlockOrderGroup(orderReference.OrderGroupId);
             */
            #endregion

            // just demoing (Find using this further down)
            purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);

            // check the below
            var theType  = purchaseOrder.OrderLink.OrderType;
            var toString = purchaseOrder.OrderLink.ToString(); // Gets ID and Type ... combined

            #region ThisAndThat - from Fund

            // should do some with OrderStatusManager

            OrderStatus poStatus;
            poStatus = purchaseOrder.OrderStatus;
            //purchaseOrder.OrderStatus = OrderStatus.InProgress;

            //var info = OrderStatusManager.GetPurchaseOrderStatus(PO);

            var shipment = purchaseOrder.GetFirstShipment();
            var status   = shipment.OrderShipmentStatus;

            //shipment. ... no that much to do
            shipment.OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;

            #region Old-School, but some useful stuff

            //OrderStatusManager.ReleaseOrderShipment(purchaseOrder.GetFirstShipment() as Shipment);
            //OrderStatusManager.ReleaseOrderShipment(PO.OrderForms[0].Shipments[0]); // it gets released
            //OrderStatusManager.HoldOrder(PO); // it gets hold
            //OrderStatusManager.

            // seems to be a DTO involved... don't neeed to set the time like this... could use the new ordernote
            //OrderNotesManager.AddNoteToPurchaseOrder(PO, DateTime.UtcNow.ToShortDateString() + " done some for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId);

            //            _orderRepository.Save(purchaseOrder); // check if it's like before ... yes it is needed to save again

            #endregion

            var notes = purchaseOrder.Notes; // IOrderNote is 0
            // RoCe - possible BUG
            // PO.OrderNotes works and contain the note above
            //IOrderNote theNewNote =
            Mediachase.Commerce.Orders.OrderNote otherNote = new OrderNote //IOrderNote
            {
                // Created = DateTime.Now, // do we need to set this ?? Nope .ctor does
                CustomerId = new Guid(), // can set this - regarded
                Detail     = "Order ToString(): " + toString + " - Shipment tracking number: " + shipment.ShipmentTrackingNumber,
                LineItemId = purchaseOrder.GetAllLineItems().First().LineItemId,
                // OrderGroupId = 12, R/O - error
                // OrderNoteId = 12, // can define it, but it's disregarded - no error
                Title = "Some title",
                Type  = OrderNoteTypes.Custom.ToString()
            };                                  // bug issued

            purchaseOrder.Notes.Add(otherNote); // void back
            purchaseOrder.ExpirationDate = DateTime.Now.AddMonths(1);


            PurchaseOrder oldPO = (PurchaseOrder)purchaseOrder;
            //oldPO.OrderAddresses.

            // yes, still need to come after adding notes
            _orderRepository.Save(purchaseOrder); // checking down here ... yes it needs to be saved again

            #endregion

            string conLang0 = ContentLanguage.PreferredCulture.Name;
            //string conLang1 = ContentLanguage.PreferredCulture.NativeName;
            //string conLang2 = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName;

            // original shipment, could rewrite and get the dto so it can be used for the second shipment also
            // or grab the dto when loading into the dropdowns
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            #region Find & Queue plumbing

            // would be done async...
            if (IsOnLine) // just checking if the below is possible, if we have network access
            {
                // index PO and addresses for BoughtThisBoughtThat & demographic analysis
                IClient     client = Client.CreateFromConfig(); // native
                FindQueries Qs     = new FindQueries(client, true);
                Qs.OrderForFind(purchaseOrder);
            }

            if (poToQueue) // could have better tran-integrity, Extraction later in PO_Extract.sln/Sheduled job
            {
                // ToDo: Put a small portion of data from the PO to msmq, will eventually (out-of-process) go to the ERP
                string       QueueName = ".\\Private$\\MyQueue";
                MessageQueue Q1        = new MessageQueue(QueueName);
                MyMessage    m         = new MyMessage()
                {
                    poNr         = purchaseOrder.OrderNumber,
                    status       = purchaseOrder.OrderStatus.ToString(),
                    orderGroupId = orderReference.OrderGroupId
                };

                //Q1.Send(m); //didn't have messaging installed on my laptop so I get an exception if this is not commented out (BG).
            }

            #endregion

            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = frontEndMessage + paymentProcessResult + " - " + purchaseOrder.OrderNumber;
            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }
Пример #36
0
        public async Task <MyResponse> HandleWithResponseAsync(MyMessage message)
        {
            await Task.Delay(100);

            return(new MyResponse());
        }
Пример #37
0
    async Task AsyncOnStart()
    {
        #region logging

        var layout = new PatternLayout
        {
            ConversionPattern = "%d %-5p %c - %m%n"
        };
        layout.ActivateOptions();
        var appender = new ConsoleAppender
        {
            Layout    = layout,
            Threshold = Level.Info
        };
        appender.ActivateOptions();

        BasicConfigurator.Configure(appender);

        LogManager.Use <Log4NetFactory>();

        #endregion

        #region create-config

        var endpointConfiguration = new EndpointConfiguration("Samples.FirstEndpoint");

        #endregion

        #region container

        var builder = new ContainerBuilder();
        //configure custom services
        //builder.RegisterInstance(new MyService());
        var container = builder.Build();
        endpointConfiguration.UseContainer <AutofacBuilder>(c => c.ExistingLifetimeScope(container));

        #endregion

        #region serialization

        endpointConfiguration.UseSerialization <JsonSerializer>();

        #endregion

        #region error

        endpointConfiguration.SendFailedMessagesTo("error");

        #endregion

        #region transport

        endpointConfiguration.UseTransport <MsmqTransport>();

        #endregion

        #region persistence

        endpointConfiguration.UsePersistence <InMemoryPersistence, StorageType.Sagas>();
        endpointConfiguration.UsePersistence <InMemoryPersistence, StorageType.Subscriptions>();
        endpointConfiguration.UsePersistence <InMemoryPersistence, StorageType.Timeouts>();

        #endregion

        #region critical-errors

        endpointConfiguration.DefineCriticalErrorAction(async context =>
        {
            // Log the critical error
            logger.Fatal($"CRITICAL: {context.Error}", context.Exception);

            await context.Stop()
            .ConfigureAwait(false);

            // Kill the process on a critical error
            string output = $"The following critical error was encountered by NServiceBus:\n{context.Error}\nNServiceBus is shutting down.";
            Environment.FailFast(output, context.Exception);
        });

        #endregion

        #region start-bus

        endpointConfiguration.EnableInstallers();
        endpointInstance = await Endpoint.Start(endpointConfiguration)
                           .ConfigureAwait(false);

        #endregion

        var myMessage = new MyMessage();
        await endpointInstance.SendLocal(myMessage)
        .ConfigureAwait(false);
    }
Пример #38
0
 public void Handle(MyMessage message)
 {
     IDictionary <string, string> headers = Bus.CurrentMessageContext.Headers;
     string nsbVersion   = headers[Headers.NServiceBusVersion];
     string customHeader = headers["MyCustomHeader"];
 }