Sunday, September 19, 2010

Getting Started with NServiceBus Part 5: MVC Music Store Basic Pub/Sub

To recap, thus far we've implemented a basic Command/Query Segregation pattern in the ASP.NET MVC Music Store application.  This has decoupled us from the UI for performing important operations which include allowing users to shop and place orders.

Now we are going to expand upon our application to provide the facility to ship products.  The way we'll do this is by publishing a message when an Order has been accepted.  Publishing a message is fundamentally different than sending a message.  When you publish a message it is intended to be received by multiple parties.  Also you must be aware that there can only be one logical Publisher.  If you have multiple Publishers publishing the same message, then the system does not know who to listen to.  In our example we'll initially only have one Subscriber, the Shipping service.  The Shipping service will handle updating inventory and creating shipping notes for the shipping department.  In future installments we'll add more Subscribers to our Order Accepted message.

To get started we have to enhance our data model a bit so we have some place to store our inventory and our shipping notes.  I found the hard way that it is significantly easier to update the database and then the model when using the Entity Framework.  That being said, we'll add the new tables to the database and then update the model:
We start with our table of inventory positions, which tells us how much of the product we have on hand and how much we need to order.  When an order comes in, we'll check this table to see if we have the product, and if we do we'll add that to the Shipped Quantity on our shipping note.  If we don't have the product, we'll put it on back order on our note.

The first thing we need to do is modify our Music Store command handler to become a Publisher.  This is a change to our EndpointConfig.cs which previously was configured AsA_Server.  We'll change this to be configured AsA_Publisher.  So what does this do for us?  First and foremost it tells the endpoint to expect to receive not only the messages we've defined, but also subscription messages.  When a Subscriber starts up, it will put a subscription message into the Publishers input queue, the SAME queue it is currently handling commands upon.  The AsA_Publisher configuration also configures NSB to handle things like how to store the subscription messages.  For the Lite profile, subscriptions are held in memory, for Integration the messages are stored in a queue, and for Production the messages are stored in a database(leveraging NHibernate). Below is our small tweak to the endpoint configuration:
public class EndpointConfig : IConfigureThisEndpoint, AsA_Server
    {
    }
The next thing we need to do is actually publish the message. To accomplish this, we'll modify the PlaceOrderHandler to publish a message after it has successfully saved the order. The message we'll publish is the IOrderAcceptedEvent message:
public interface IOrderAcceptedEvent : IEvent
    {
        Int32 OrderId { get; set; }
    }
This message has been added to our public schema project(Messages.csproj). All we pass along here is the order id. We can look up the Order on the other side when we go to ship the product, so there is no need to publish the entire Order. There may be a reason to publish the entire order in the future, especially if there exists components that don't have a way to query for Orders. Note that I'm using the naming convention of provided an "Event" suffix. This is so that I can easily know what is an Event versus what is a Command(namespacing would also do).

Now we have a message to publish, we can update our IPlaceOrderHandler. The first thing we need to do is add a public property of type IBus so that NSB will inject a reference to the bus into our handler. After we have the reference, at the end of the handler we call Bus.Publish and provide an instance of the message using an Action:
public class IPlaceOrderHandler : IHandleMessages<IPlaceOrderCommand>
    {
        public IBus Bus { get; set; }

        public void Handle(IPlaceOrderCommand message)
        {
            MusicStoreEntities storeDB = new MusicStoreEntities();

            var order = new MvcMusicStore.Models.Order();

            order.Username = message.UserId;
            order.OrderDate = DateTime.Now;
            order.OrderId = message.OrderId;

            // Save Order
            storeDB.AddToOrders(order);
            storeDB.SaveChanges();

            //Process the order
            var cart = new ShoppingCart(message.CartId);

            cart.CreateOrder(order);

            this.Bus.Publish<IOrderAcceptedEvent>( o => o.OrderId = order.OrderId);
        }
    }
Now we have our handler publishing messages out to the bus for all subscribers. Next we'll build up our Shipping Subscriber. Add a new project and configure the endpoint AsA_Server just like our original command handler. Next we'll take a look at how we reference the Publisher. We need to know where to drop off our subscription messages. In our subscription message is the Subscriber address along with some other endpoint information. By giving our address to the Publisher, it knows where to push published messages to. To achieve this we add a reference to the Publisher in our app.config:


  
    
      
      
    
  
The overall pub/sub semantics goes something like this:

  1. Publisher starts up and loads subscriptions from storage(memory, queue, or DB)
  2. Subscriber starts up and sends a subscription message to the Publisher.  If the Publisher already has stored the subscription, it gets ignored.  If it does not have the subscription, store the message.
  3. Publisher makes a call to Bus.Publish.
  4. Publisher looks to see who is subscribed to that message.  It creates a message for each Subscriber and puts it on its outbound queue(this is an internal queue to MSMQ that you don't see unless it is sending the machine to another machine)
  5. MSMQ takes over and pushes the messages to their destination queues.  
  6. If the subscriber is up and running it will receive the message and call the appropriate handler.  If not, the message remains in the subscriber input queue.
Please note that if you have a lot of Subscribers and their queues are down, the messages will build up on the Publishers' outbound queue so you will have to size your storage appropriately.
The last thing we need to do is implement the logic for the Shipping service. We will hydrate the order from the order id in the message and then check our inventory. If we have the product, we ship it, otherwise we back order it. From there our processing is complete and we have a full implementation of Pub/Sub:
public class ShippingHandler : IHandleMessages<IOrderAcceptedEvent>
    {
        #region IMessageHandler<IOrderAcceptedEvent> Members

        public void Handle(IOrderAcceptedEvent message)
        {
            MusicStoreEntities storeDB = new MusicStoreEntities();

            var order = storeDB.Orders.Single(o => o.OrderId == message.OrderId);

            var shipNote = new ShippingNote
            { 
                FirstName = order.FirstName,
                LastName = order.LastName,
                Address = order.Address,
                City = order.City,
                State = order.State,
                PostalCode = order.PostalCode
            };

            foreach (var detail in order.OrderDetails)
            {
                var inventoryPosition = storeDB.InventoryPositions.Single(p => p.Album.AlbumId == detail.AlbumId);

                if (inventoryPosition.BalanceOnHand >= detail.Quantity)
                {
                    inventoryPosition.BalanceOnHand -= detail.Quantity;
                    shipNote.ShippedQuantity += detail.Quantity;
                }
                else
                {
                    shipNote.BackOrderQuantity = detail.Quantity - shipNote.ShippedQuantity;
                }
            }

            storeDB.AddToShippingNotes(shipNote);

            storeDB.SaveChanges();

        }

        #endregion
    }
Code is at github

55 comments:

  1. Adam

    I have to say that this is a really great series of articles and very useful to help understand NServiceBus.

    It's taken a few readings, but I finally get why I didn't get it before. It is easy to confuse subscription storage with the message storage (you answered a question of mine on SO that was rooted in this misunderstanding).

    Thanks very much for this top class set of articles!

    Cheers

    Sean

    ReplyDelete

  2. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience.
    Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in



    selenium training in Bangalore
    selenium training in Marathahalli
    selenium training in Btm layout
    selenium training in Jaya nagar
    selenium training in Electronic city
    selenium training in Kalyan nagar



    ReplyDelete
  3. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    python Training institute in Chennai
    python Training institute in Bangalore
    python Training in Pune

    ReplyDelete
  4. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.
    honor service center chennai
    honor service center in chennai
    honor service centre chennai

    ReplyDelete
  5. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.

    ReplyDelete
  6. I liked this post. It was really helpful and informative. Keep blogging and sharing with us. Thanks!! Artificial Intelligence Course

    ReplyDelete
  7. For Python training in Bangalore, Visit:- Python training in Bangalore

    ReplyDelete
  8. Your articles are inventive. I am looking forward to reading the plethora of articles that you have linked here. Thumbs up! 1337x

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. A complete sententious blog, intended to impress people.
    mp3 juice

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Very useful and information content has been shared out here, Thanks for sharing it.sap testing Training in Bangalore

    ReplyDelete
  13. Linking is very useful thing.you have really helped lots of people who visit blog and provide them use full information.sap wm Training in Bangalore

    ReplyDelete
  14. Pullover, I should say only that its awesome! The blog is informational and always produce amazing things. Capital Bra

    ReplyDelete
  15. It proved to be Very helpful to me and I am sure to all the commentators here! dotent

    ReplyDelete
  16. Thanks for sharing this quality information with us. I really enjoyed reading. Will surely going to share this URL with my friends.WordPress

    ReplyDelete
  17. nice blog

    https://www.analyticspath.com/artificial-intelligence-training-in-hyderabad

    ReplyDelete
  18. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you! logging framework

    ReplyDelete
  19. Thanks for sharing such an amazing post. Your style of writing is very unique. It made me mesmerized in your words. Keep on writing.
    devops training in chennai | devops training in anna nagar | devops training in omr | devops training in porur | devops training in tambaram | devops training in velachery

    ReplyDelete
  20. Nice post. Thanks for sharing! It’s interesting content and Great work.
    AI Training in Hyderabad

    ReplyDelete
  21. I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information. Grizzly Beatz

    ReplyDelete
  22. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.

    AI Training in Hyderabad

    ReplyDelete
  23. Thank you for the informative post. It was thoroughly helpful to me. Keep posting more such articles and enlighten us.

    Data Science Training in Hyderabad

    ReplyDelete
  24. This blog is really helpful regarding all educational knowledge I earned. It covered a great area of subject which can assist a lot of needy people. Everything mentioned here is clear and very useful

    DevOps Training in Hyderabad

    ReplyDelete
  25. I am thankful to you for sharing this plethora of useful information. I found this resource utmost beneficial for me. Thanks a lot for hard work. cbd tinctures

    ReplyDelete
  26. Wow, cool post. I’d like to write like this too – taking time and real hard work to make a great article… but I put things off too much and never seem to get started. Thanks though. cheapest cbd gummies

    ReplyDelete
  27. Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You've really made my day today with this. I hope you keep this up!
    Best Institute for Data Science in Hyderabad

    ReplyDelete
  28. The cost and need of gadgets is all the while going high and by taking a gander at these methodology we can plainly expect the circumstance of our penny and requirements.Check This Out

    ReplyDelete
  29. Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. 성인

    ReplyDelete
  30. It's really nice and meanful. it's really cool blog. Linking is very useful thing.you have really helped lots of people who visit blog and provide them usefull information.
    data scientist certification

    ReplyDelete
  31. Kim Ravida is a lifestyle and business coach who helps women in business take powerful money actions and make solid, productiveIamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder

    ReplyDelete
  32. Useful article with detailed explanation. Thanks for sharing. keep up the good work Angular training in Chennai

    ReplyDelete
  33. great post ! This was actually what i was looking for and i am glad to came here!
    SAP Ariba Training
    MuleSoft Training

    ReplyDelete
  34. Very nice job... Thanks for sharing this amazing and educative blog post!
    data science training in malaysia

    ReplyDelete
  35. Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post .
    data science coaching in hyderabad

    ReplyDelete
  36. Mega Downloader APK gives client controlled scrambled distributed storage space and talk from one side to another ordinary internet browsers, mutually with dedicated applications for portable methodology. Mega Crack

    ReplyDelete

  37. Sisters carry that unique bond only they can understand. They may argue, fight and annoy each other but, at the end of the day, they still have each other’s back. They share childhood memories, secrets and aspirations. Sisters Day Quotes In English

    ReplyDelete
  38. I truly adored visiting your post and this content was very unique. Thanks a lot for sharing this...
    Spousal Support in VA
    Spousal Support in Virginia

    ReplyDelete
  39. Get Data Science Certification from top-ranked universities UTM, Malaysia, and IBM. We provide extensive training for the future-ready workforce.
    data science training in malaysia

    ReplyDelete
  40. You may connect to a cloud and use Boxcryptor as a note-taking and editing platform using this handy cloud-based editor.
    https://thepcsoft.com/boxcryptor/

    ReplyDelete
  41. For site up. Region best and today town. State management within involve foot. Beyond cell professional occur seem style face.

    ReplyDelete