WCF (Sender) to MSMQ to WCF (handler ER)

Source: Internet
Author: User
Tags msmq
// WCF.MSMQ.Message.Sender.(WCF.to.MSMQ).csnamespace WCF.MSMQ.MessageSender.Host{    using System;    using System.Transactions;    using System.ServiceModel.MsmqIntegration;    using System.ServiceModel;    using Contracts.Entitys;    using Contracts.Operations;    using Contracts.Operations.ClientsProxys;    class Program    {        static void Main(string[] args)        {            Console.Title = "Sender";            // Create the purchase order            PurchaseOrder po = new PurchaseOrder();            po.customerId = "somecustomer.com";            po.poNumber = Guid.NewGuid().ToString();            PurchaseOrderLineItem lineItem1 = new PurchaseOrderLineItem();            lineItem1.productId = "Blue Widget";            lineItem1.quantity = 54;            lineItem1.unitCost = 29.99F;            PurchaseOrderLineItem lineItem2 = new PurchaseOrderLineItem();            lineItem2.productId = "Red Widget";            lineItem2.quantity = 890;            lineItem2.unitCost = 45.89F;            po.orderLineItems = new PurchaseOrderLineItem[2];            po.orderLineItems[0] = lineItem1;            po.orderLineItems[1] = lineItem2;            string queueAddress = @"msmq.formatname:DIRECT=OS:.\private$\Orders";            MsmqIntegrationBinding binding = new MsmqIntegrationBinding();            binding.Security.Transport.MsmqAuthenticationMode = MsmqAuthenticationMode.None;            binding.Security.Mode = MsmqIntegrationSecurityMode.None;            EndpointAddress address = new EndpointAddress(queueAddress);            ChannelFactory<IOrderProcessor> factory = new ChannelFactory<IOrderProcessor>(binding, new EndpointAddress(queueAddress));            IOrderProcessor proxy = factory.CreateChannel();            OrderProcessorClient client = new OrderProcessorClient(binding, address);            int count = 1;            string input = string.Empty;            while ("q" != (input = Console.ReadLine().ToLower()))            {                for (int i = 0; i < 1000 ; i++)                {                    po.count = count++;                    MsmqMessage<PurchaseOrder> ordermsg = new MsmqMessage<PurchaseOrder>(po);                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))                    {                        client.SubmitPurchaseOrder(ordermsg);                        scope.Complete();                    }                }                Console.WriteLine("WCF to MSMQ:");                Console.WriteLine("Order has been submitted:{0}", po);            }            //Closing the client gracefully closes the connection and cleans up resources            client.Close();            Console.WriteLine();            Console.WriteLine("Press <ENTER> to terminate client.");            Console.ReadLine();        }    }}namespace Contracts.Operations.ClientsProxys{    using System.ServiceModel;    using System.ServiceModel.Channels;    using System.ServiceModel.MsmqIntegration;    using Contracts.Entitys;    public partial class OrderProcessorClient : ClientBase<IOrderProcessor>, IOrderProcessor    {///        public OrderProcessorClient()///        {///        }//////        public OrderProcessorClient(string configurationName)///            :///                base(configurationName)///        {///        }        public OrderProcessorClient(Binding binding, EndpointAddress address)            :                base(binding, address)        {        }        public void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> msg)        {            base.Channel.SubmitPurchaseOrder(msg);        }    }}//=================================================================================================================// WCF.MSMQ.Message.Receiver.(MSMQ.to.WCF).csnamespace WCF.MSMQ.MessageReceiver.Host{    using System;    using System.ServiceModel;    using System.ServiceModel.MsmqIntegration;    using System.Messaging;    using Contracts.Operations;    using Contracts.Entitys;    public class OrderProcessorService : IOrderProcessor    {        [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]        public void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> ordermsg)        {            PurchaseOrder po = ordermsg.Body;            Random statusIndexer = new Random();            po.Status = (OrderStates)statusIndexer.Next(3);            Console.WriteLine("Processing {0} ", po);        }        // Host the service within this EXE console application.        public static void Main()        {            // Get MSMQ queue name from app settings in configuration            Console.Title = "Receiver";            string queueName = @".\private$\Orders";//ConfigurationManager.AppSettings["orderQueueName"];            // Create the transacted MSMQ queue if necessary.            if (!MessageQueue.Exists(queueName))            {                MessageQueue.Create(queueName, true);            }            // Create a ServiceHost for the OrderProcessorService type.            using (ServiceHost serviceHost = new ServiceHost(typeof(OrderProcessorService)))            {                string queueAddress = @"msmq.formatname:DIRECT=OS:.\private$\Orders";                MsmqIntegrationBinding binding = new MsmqIntegrationBinding();                binding.Security.Transport.MsmqAuthenticationMode = MsmqAuthenticationMode.None;                binding.Security.Mode = MsmqIntegrationSecurityMode.None;                serviceHost.AddServiceEndpoint(typeof(IOrderProcessor), binding, queueAddress);                serviceHost.Open();                // The service can now be accessed.                Console.WriteLine("The MSMQ to WCF service is ready.");                Console.WriteLine("Press <ENTER> to terminate service.");                Console.ReadLine();            }        }    }}//=================================================================================================================// Contracts.Share.csnamespace Contracts.Operations{    using System.ServiceModel;    using System.ServiceModel.MsmqIntegration;    using Contracts.Entitys;    // Define a service contract.     [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]    [ServiceKnownType(typeof(PurchaseOrder))]    public interface IOrderProcessor    {        [OperationContract(IsOneWay = true, Action = "*")]        void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> msg);    }}namespace Contracts.Entitys{    using System;    using System.Text;    // Define the Purchase Order Line Item    [Serializable]    public class PurchaseOrderLineItem    {        public string productId;        public float unitCost;        public int quantity;        public override string ToString()        {            string displayString = "Order LineItem: " + quantity + " of " + productId + " @unit price: $" + unitCost + "\n";            return displayString;        }        public float TotalCost        {            get { return unitCost * quantity; }        }    }    public enum OrderStates    {        Pending,        Processed,        Shipped    }    // Define Purchase Order    [Serializable]    public class PurchaseOrder    {    public static string[] orderStates = { "Pending", "Processed", "Shipped" };        public int count;        public string poNumber;        public string customerId;        public PurchaseOrderLineItem[] orderLineItems;        public OrderStates orderStatus;        public float TotalCost        {            get            {                float totalCost = 0;                foreach (PurchaseOrderLineItem lineItem in orderLineItems)                    totalCost += lineItem.TotalCost;                return totalCost;            }        }        public OrderStates Status        {            get            {                return orderStatus;            }            set            {                orderStatus = value;            }        }        public override string ToString()        {            StringBuilder strbuf = new StringBuilder("Purchase Order: " + poNumber + "\n");            strbuf.Append("\tCustomer: " + customerId + "\n");            strbuf.Append("\tOrderDetails\n");            foreach (PurchaseOrderLineItem lineItem in orderLineItems)            {                strbuf.Append("\t\t" + lineItem.ToString());            }            strbuf.Append("\tTotal cost of this order: $" + TotalCost + "\n");            strbuf.Append("\tOrder status: " + Status + "\n");            strbuf.Append("\tOrder count: " + count + "\n");            return strbuf.ToString();        }    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.