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:
- Publisher starts up and loads subscriptions from storage(memory, queue, or DB)
- 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.
- Publisher makes a call to Bus.Publish.
- 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)
- MSMQ takes over and pushes the messages to their destination queues.
- 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
Adam
ReplyDeleteI 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
ReplyDeleteAfter 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
It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
ReplyDeletepython Training institute in Chennai
python Training institute in Bangalore
python Training in Pune
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.
ReplyDeletehonor service center chennai
honor service center in chennai
honor service centre chennai
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.
ReplyDeleteI liked this post. It was really helpful and informative. Keep blogging and sharing with us. Thanks!! Artificial Intelligence Course
ReplyDeleteVisit for AI training in Bangalore:- Artificial Intelligence training in Bangalore
ReplyDeleteFor Python training in Bangalore, Visit:- Python training in Bangalore
ReplyDeleteVisit for AI training in Bangalore :- Artificial Intelligence training in Bangalore
ReplyDeleteYour articles are inventive. I am looking forward to reading the plethora of articles that you have linked here. Thumbs up! 1337x
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteA complete sententious blog, intended to impress people.
ReplyDeletemp3 juice
This comment has been removed by the author.
ReplyDeleteVery useful and information content has been shared out here, Thanks for sharing it.sap testing Training in Bangalore
ReplyDeleteYour articles really impressed for me,because of all information so nice.sap security Training in Bangalore
ReplyDeleteLinking 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
ReplyDeletePullover, I should say only that its awesome! The blog is informational and always produce amazing things. Capital Bra
ReplyDeleteIt proved to be Very helpful to me and I am sure to all the commentators here! dotent
ReplyDeleteThanks for sharing this quality information with us. I really enjoyed reading. Will surely going to share this URL with my friends.WordPress
ReplyDeletenice blog
ReplyDeletehttps://www.analyticspath.com/artificial-intelligence-training-in-hyderabad
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
ReplyDeleteThanks for sharing such an amazing post. Your style of writing is very unique. It made me mesmerized in your words. Keep on writing.
ReplyDeletedevops training in chennai | devops training in anna nagar | devops training in omr | devops training in porur | devops training in tambaram | devops training in velachery
Nice post. Thanks for sharing! It’s interesting content and Great work.
ReplyDeleteAI Training in Hyderabad
I read this article is very awesome. Its interested content and very informative.
ReplyDeletePython Training in Chennai | Certification | Online Training Course | Python Training in Bangalore | Certification | Online Training Course | Python Training in Hyderabad | Certification | Online Training Course | Python Training in Coimbatore | Certification | Online Training Course | Python Training in Online | Python Certification Training Course
It's really a great and helpful piece of info. I'm happy that you simply shared this useful info with us. Please keep us informed like this.
ReplyDeleteWeb Designing Training in Chennai
Web Designing Course in Chennai
Web Designing Training in Bangalore
Web Designing Course in Bangalore
Web Designing Training in Hyderabad
Web Designing Course in Hyderabad
Web Designing Training in Coimbatore
Web Designing Training
Web Designing Online Training
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
ReplyDeleteVery 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.
ReplyDeleteAI Training in Hyderabad
Thank you for the informative post. It was thoroughly helpful to me. Keep posting more such articles and enlighten us.
ReplyDeleteData Science Training in Hyderabad
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
ReplyDeleteDevOps Training in Hyderabad
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
ReplyDeleteWow, 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
ReplyDeleteWonderful 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!
ReplyDeleteBest Institute for Data Science in Hyderabad
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
ReplyDeleteThanks 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. 성인
ReplyDeleteIt'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.
ReplyDeletedata scientist certification
Thankyou for the valuable content.It was really helpful in understanding the concept50 High Quality for just 50 INR
ReplyDelete2000 Backlink at cheapest
5000 Backlink at cheapest
Boost DA upto 15+ at cheapest
Boost DA upto 25+ at cheapest
Boost DA upto 35+ at cheapest
Boost DA upto 45+ at cheapest
It was wonderfull reading your article. Great writing styleiamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder
ReplyDeleteKim 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
ReplyDeleteDavid Forbes is president of Alliance Marketing Associates IncIamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder
ReplyDeleteWe are used to the fact that we know only religious and public holidays and celebrate only them.Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder
ReplyDeleteAnnabelle loves to write and has been doing so for many years.Cheapest and fastest Backlink Indexing Best GPL Store TECKUM IS ALL ABOUT TECH NEWS AND MOBILE REVIEWS
ReplyDeleteAnnabelle loves to write and has been doing so for many years.Backlink Indexer My GPL Store Teckum-All about Knowledge
ReplyDeleteUseful article with detailed explanation. Thanks for sharing. keep up the good work Angular training in Chennai
ReplyDeletegreat post ! This was actually what i was looking for and i am glad to came here!
ReplyDeleteSAP Ariba Training
MuleSoft Training
Very nice job... Thanks for sharing this amazing and educative blog post!
ReplyDeletedata science training in malaysia
Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post .
ReplyDeletedata science coaching in hyderabad
Informative blog, big thumbs up for sharing this blog with us.
ReplyDeleteAI Patasala Data Science Training in Hyderabad
The Kashmir Files Full Movie Download Filmyzilla
ReplyDeletebatman movie download in hindi filmyzilla
Wonder Woman 1984 Full Movie Download in Hindi Filmyzilla
Silence Movie Download in Hindi Filmyzilla
RRR Movie Download in Hindi 480p Filmyzilla
The Matrix Resurrections Movie Download Filmyzilla
kgf chapter 2 full movie in hindi download filmyzilla
yeni perde modelleri
ReplyDeleteMOBİL ONAY
mobil ödeme bozdurma
nft nasıl alınır
ankara evden eve nakliyat
Trafik sigortasi
dedektör
web sitesi kurma
Ask Romanlari
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
ReplyDeleteSisters 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
I truly adored visiting your post and this content was very unique. Thanks a lot for sharing this...
ReplyDeleteSpousal Support in VA
Spousal Support in Virginia
Get Data Science Certification from top-ranked universities UTM, Malaysia, and IBM. We provide extensive training for the future-ready workforce.
ReplyDeletedata science training in malaysia
You may connect to a cloud and use Boxcryptor as a note-taking and editing platform using this handy cloud-based editor.
ReplyDeletehttps://thepcsoft.com/boxcryptor/
For site up. Region best and today town. State management within involve foot. Beyond cell professional occur seem style face.
ReplyDelete