• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Messaging.MessageQueue类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Messaging.MessageQueue的典型用法代码示例。如果您正苦于以下问题:C# MessageQueue类的具体用法?C# MessageQueue怎么用?C# MessageQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



MessageQueue类属于System.Messaging命名空间,在下文中一共展示了MessageQueue类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: btnAdd_Click

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string queueName = ConfigurationManager.AppSettings["MSMQLocation"];

            MessageQueue rmTxnQ = new MessageQueue(queueName);

            rmTxnQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(ProcessMessage) });

            foreach (ListBoxItem itm in files.Items)
            {
                MessageQueueTransaction msgTx = new MessageQueueTransaction();
                msgTx.Begin();
                try
                {
                    string argument = "-i \"{0}\" -o \"{1}\" --preset \"" + ConfigurationManager.AppSettings["HandbrakePreset"] + "\"";

                    string destination = txtDestination.Text + "\\" + System.IO.Path.GetFileNameWithoutExtension(itm.ToolTip.ToString()) + ".m4v";

                    ProcessMessage p = new ProcessMessage() { CommandLine = argument, DestinationURL = destination, OrignalFileURL = itm.ToolTip.ToString() };

                    rmTxnQ.Send(p, msgTx);
                    results.Items.Insert(0, string.Format("{0} added to queue", p.OrignalFileURL));

                    msgTx.Commit();
                }
                catch (Exception ex)
                {
                    results.Items.Insert(0, ex.Message);
                    msgTx.Abort();
                }
            }
        }
开发者ID:tiernano,项目名称:HandbrakeCluster,代码行数:32,代码来源:MainWindow.xaml.cs


示例2: Requestor

 public Requestor(string requestQueueName,string replyQueueName)
 {
     requestQueue = new MessageQueue(requestQueueName);
     replyQueue = new MessageQueue(replyQueueName);
     replyQueue.MessageReadPropertyFilter.SetAll();
     ((XmlMessageFormatter)replyQueue.Formatter).TargetTypeNames = new string[] { "System.String,mscorlib" };
 }
开发者ID:xqlcrystal,项目名称:MSMQStudy,代码行数:7,代码来源:Requestor.cs


示例3: An_undecipherable_blob_should_be_discarded

		public void An_undecipherable_blob_should_be_discarded()
		{
			var formatName = Endpoint.Address.Uri.GetInboundFormatName();
			using (var queue = new MessageQueue(formatName, QueueAccessMode.Send))
			{
				queue.Send("This is just crap, it will cause pain");
			}

			try
			{
				Endpoint.Receive(context =>
					{
						IConsumeContext<PingMessage> pingContext;
						context.TryGetContext(out pingContext);

						Assert.Fail("Receive should have thrown a serialization exception");

						return null;
					}, TimeSpan.Zero);
			}
			catch (Exception ex)
			{
				Assert.Fail("Did not expect " + ex.GetType() + " = " + ex.Message);
			}

			Assert.AreEqual(0, EndpointAddress.GetMsmqMessageCount(), "Endpoint was not empty");
			Assert.AreEqual(1, ErrorEndpointAddress.GetMsmqMessageCount(), "Error endpoint did not contain bogus message");
		}
开发者ID:cstick,项目名称:MassTransit,代码行数:28,代码来源:Receive_Specs.cs


示例4: receiveByID

        public object receiveByID(string MessageID, string InputQueue)
        {
            // Open existing queue
            using (MessageQueue queue = new MessageQueue(InputQueue))
            {
                //Peek to find message with the MessageID in the label
                while (true)
                {
                    Message[] peekedmessage = queue.GetAllMessages();
                    foreach (Message m in peekedmessage)
                    {
                        if (m.Label.StartsWith(MessageID))
                        {
                            using (Message message = queue.ReceiveById(m.Id))
                            {
                                RequestGuid = MessageID;
                                // Gets object type from the message label
                                Type objType = Type.GetType(message.Label.Split('|')[1], true, true);

                                // Derializes object from the stream
                                DataContractSerializer serializer = new DataContractSerializer(objType);
                                return serializer.ReadObject(message.BodyStream);
                            }
                        }
                    }
                    System.Threading.Thread.Sleep(10);
                }
            }
        }
开发者ID:NickABoen,项目名称:CIS526_TeamProjects,代码行数:29,代码来源:ObjectMessageQueue.cs


示例5: InsertMessageinQueue

        public void InsertMessageinQueue()
        {
            try
            {
                MessageQueue msmq = null;
                if (MessageQueue.Exists(connection))
                {
                    msmq = new MessageQueue(connection);
                }
                else
                {
                    msmq = MessageQueue.Create(connection);
                }

                var msg = new Message();
                msg.Body = "SampleMessage ";

                msg.Label = "Msg" + i.ToString();
                ++i;
                msmq.Send(msg);
                msmq.Refresh();
                //msmq.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
开发者ID:gordonlee,项目名称:testlab,代码行数:28,代码来源:Program.cs


示例6: GetElementFromSource

		public string GetElementFromSource(string pQueuePach)
		{
			System.Messaging.Message sourceMessage;
			string str="";
			
			try
			{
				sourceQueue = new System.Messaging.MessageQueue(pQueuePach);
				((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[]{"System.String"};
				if(sourceQueue.GetAllMessages ().Length >0)
				{
					sourceMessage = sourceQueue.Receive(System.Messaging.MessageQueueTransactionType.Automatic);
					// Set the formatter.
					//	sourceQueue.Formatter = new XmlMessageFormatter(new Type[]	{typeof(String)});
					((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[]{"Empleado"};

					str = (string)sourceMessage.Body;
				}
			
				return str;
			}
			catch(MessageQueueException e)
			{
				throw e;
			}
			catch(Exception e)
			{
				throw e;
			}
		}
开发者ID:spzenk,项目名称:sfdocsamples,代码行数:30,代码来源:MessageMover.cs


示例7: MessageCreator

        public void MessageCreator()
        {
            MessageQueueTemplate mqt = applicationContext["txqueue"] as MessageQueueTemplate;
            Assert.IsNotNull(mqt);        
            string path = @".\Private$\mlptestqueue";
            if (MessageQueue.Exists(path))
            {
                MessageQueue.Delete(path);
            }
            MessageQueue.Create(path, true);
            mqt.MessageQueueFactory.RegisterMessageQueue("newQueueDefinition", delegate
                                                                               {
                                                                                   MessageQueue mq = new MessageQueue();
                                                                                   mq.Path = path;                                                                                                      
                                                                                   // other properties
                                                                                   return mq;
                                                                               });

            Assert.IsTrue(mqt.MessageQueueFactory.ContainsMessageQueue("newQueueDefinition"));

            SendAndReceive("newQueueDefinition",mqt);

            SimpleCreator sc  = new SimpleCreator();
            mqt.MessageQueueFactory.RegisterMessageQueue("fooQueueDefinition", sc.CreateQueue );

        }
开发者ID:fgq841103,项目名称:spring-net,代码行数:26,代码来源:MessageQueueTemplateTests.cs


示例8: EditValue

        /// <include file='doc\QueuePathEditor.uex' path='docs/doc[@for="QueuePathEditor.EditValue"]/*' />
        /// <devdoc>
        ///      Edits the given object value using the editor style provided by
        ///      GetEditorStyle.  A service provider is provided so that any
        ///      required editing services can be obtained.
        /// </devdoc>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (provider != null)
            {
                IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                if (edSvc != null)
                {
                    QueuePathDialog dialog = new QueuePathDialog(provider);
                    MessageQueue queue = null;
                    if (value is MessageQueue)
                        queue = (MessageQueue)value;
                    else if (value is string)
                        queue = new MessageQueue((string)value);
                    else if (value != null)
                        return value;

                    if (queue != null)
                        dialog.SelectQueue(queue);

                    IDesignerHost host = (IDesignerHost)provider.GetService(typeof(IDesignerHost));
                    DesignerTransaction trans = null;
                    if (host != null)
                        trans = host.CreateTransaction();

                    try
                    {
                        if ((context == null || context.OnComponentChanging()) && edSvc.ShowDialog(dialog) == DialogResult.OK)
                        {
                            if (dialog.Path != String.Empty)
                            {
                                if (context.Instance is MessageQueue || context.Instance is MessageQueueInstaller)
                                    value = dialog.Path;
                                else
                                {
                                    value = MessageQueueConverter.GetFromCache(dialog.Path);
                                    if (value == null)
                                    {
                                        value = new MessageQueue(dialog.Path);
                                        MessageQueueConverter.AddToCache((MessageQueue)value);
                                        if (context != null)
                                            context.Container.Add((IComponent)value);
                                    }
                                }

                                context.OnComponentChanged();
                            }
                        }
                    }
                    finally
                    {
                        if (trans != null)
                        {
                            trans.Commit();
                        }
                    }
                }
            }

            return value;
        }
开发者ID:JianwenSun,项目名称:cc,代码行数:66,代码来源:QueuePathEditor.cs


示例9: OnStart

        protected override void OnStart(string[] args)
        {
            try
            {
                string queueName = ConfigurationManager.AppSettings["ProvisionQueueName"];
                //if (!MessageQueue.Exists(queueName))MessageQueue.Create(queueName, true);
                var queue = new MessageQueue(queueName);
                Trace.WriteLine("Queue Created in MSMQService at:" + DateTime.Now);
                //Console.ReadLine();
                queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
                //Below code reads from queue once

                Message[] messages = queue.GetAllMessages();
                Trace.WriteLine("Reading from queue in MSMQService : " + queueName);
                Trace.WriteLine("Number of messages in MSMQService: " + messages.Length);
                /**foreach (Message msg in messages)
                {
                   // var decoded = JsonConvert.DeserializeObject(msg.Body.ToString());
                    Console.WriteLine("message:" + msg.Body);
                    Console.ReadLine();
                }
                Console.WriteLine("End of messages");
                Console.ReadLine();
                **/
                //Below code keeps reading from queue
                queue.ReceiveCompleted += QueueMessageReceived;
                queue.BeginReceive();
                signal.WaitOne();
                //Console.ReadLine();
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error in receiving in MSMQService: " + e.Message);
            }
        }
开发者ID:tsmithsoftware,项目名称:SoloProjects,代码行数:35,代码来源:MSMQService.cs


示例10: addReservation

 public bool addReservation(DemandeReservation reservation)
 {
     MessageQueue queue = new MessageQueue(FlyHotelConstant.ADRESSE_QUEUE);
     queue.Send(reservation);
     queue.Close();
     return true;
 }
开发者ID:math-th,项目名称:net-resa-tp,代码行数:7,代码来源:clsMsmq.cs


示例11: Main

        static void Main(string[] args)
        {
            Console.WriteLine("Simple Text");
            Console.WriteLine("Input for MSMQ Message:");
            string input = Console.ReadLine();

            MessageQueue queue = new MessageQueue(@".\private$\test");

            queue.Send(input);

            Console.WriteLine("Press Enter to continue");
            Console.ReadLine();

            Console.WriteLine("Output for MSMQ Queue");
            Console.WriteLine(queue.Receive().Body.ToString());
            Console.ReadLine();

            Console.WriteLine("Complex Text");

            User tester = new User();
            tester.Birthday = DateTime.Now;
            tester.Name = "Test Name";
            queue.Send(tester);

            Console.WriteLine("Output for MSMQ Queue");
            User output = (User)queue.Receive().Body;
            Console.WriteLine(output.Birthday.ToShortDateString());
            Console.ReadLine();
        }
开发者ID:davidalmas,项目名称:Samples,代码行数:29,代码来源:Program.cs


示例12: DoLoginLog

        /// <summary>
        /// 作者:Vincen
        /// 时间:2013.11.14 PM
        /// 描述:处理登录日志(消息队列)
        /// </summary>
        public static void DoLoginLog()
        {
            InitQueue(MsmqType.LoginLog);

            using (var mq = new MessageQueue(MsmpPath + MsmqType.LoginLog))
            {
                var msgs = mq.GetAllMessages();
                foreach (var msg in msgs)
                {
                    try
                    {
                        msg.Formatter = new XmlMessageFormatter(new[] { typeof(LoginLogs) });
                        var item = msg.Body as LoginLogs;
                        if (null == item)
                        {
                            continue;
                        }
                        LoginLogsBLL.CreateLoginLogs(item);
                    }
                    //记录下(异常)日志信息
                    catch (Exception e)
                    {
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = Utility.CommonHelper.To<int>(ExceptionType.Msmq),
                            Message = string.Format("MSMQ-DoLoginLog:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = 0,
                            CreateTime = DateTime.Now
                        });
                    }
                }
                mq.Purge();
            }
        }
开发者ID:kylin589,项目名称:EmePro,代码行数:40,代码来源:QueueManager.cs


示例13: Configure

        public override void Configure(System.Xml.XmlElement element)
        {
            // Reflect some of the necessary protected methods on the SimpleCache class that are needed
            Type type = typeof(SimpleCache);
            getCachedItemMethod = type.GetMethod("GetCachedItem", BindingFlags.Instance | BindingFlags.NonPublic);
            purgeMethod = type.GetMethod("Purge", BindingFlags.Instance | BindingFlags.NonPublic);

            // Instantiate and configure the SimpleCache instance to be used for the local cache
            cache = new SimpleCache();
            cache.Configure(element);

            // Allow the base CacheBase class to configure itself
            base.Configure(element);

            // Check for and configure the queue
            if (element.HasAttribute("path"))
            {
                string path = element.GetAttribute("path");
                if (MessageQueue.Exists(path))
                {
                    queue = new MessageQueue(path);
                    queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(CachedItem) });

                    // Start the listener thread
                    listen = true;
                    listenThread = new Thread(new ThreadStart(Listen));
                    listenThread.IsBackground = true;
                    listenThread.Start();
                }
                else
                {
                    throw new ConfigurationErrorsException("The specified queue path (" + path + ") does not exist.");
                }
            }
        }
开发者ID:SolidSnake74,项目名称:SharpCore,代码行数:35,代码来源:MessageQueueCache.cs


示例14: Main

        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.RegisterType<ITradeContextFactory, TradeContextFactory>();

            container.RegisterType<IMessageHandler, ValidateTradeHandler>("ValidateTradeHandler");
            container.RegisterType<IMessageHandler, EnrichPartyHandler>("EnrichParty1Handler",
                                                        new InjectionConstructor(
                                                                new ResolvedParameter<ITradeContextFactory>(),
                                                                true, false));
            container.RegisterType<IMessageHandler, EnrichPartyHandler>("EnrichParty2Handler",
                                                        new InjectionConstructor(
                                                                new ResolvedParameter<ITradeContextFactory>(),
                                                                false, true));

            container.RegisterType<MessageHandlerFactory>();

            _HandlerFactory = container.Resolve<MessageHandlerFactory>();

            var arguments = Args.Configuration.Configure<Arguments>().CreateAndBind(args);
            var queue = new MessageQueue(arguments.InputQueue, QueueAccessMode.Receive);
            while (true)
            {
                var msg = queue.Receive();
                Handle(msg);
            }
        }
开发者ID:ravigonella,项目名称:going-async,代码行数:27,代码来源:Program.cs


示例15: MessageQueue

        void ISubscriptionStorage.Init()
        {
            var path = MsmqUtilities.GetFullPath(Queue);

            q = new MessageQueue(path);

            bool transactional;
            try
            {
                transactional = q.Transactional;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(string.Format("There is a problem with the subscription storage queue {0}. See enclosed exception for details.", Queue), ex);
            }

            if (!transactional && TransactionsEnabled)
                throw new ArgumentException("Queue must be transactional (" + Queue + ").");

            var messageReadPropertyFilter = new MessagePropertyFilter { Id = true, Body = true, Label = true };

            q.Formatter = new XmlMessageFormatter(new[] { typeof(string) });

            q.MessageReadPropertyFilter = messageReadPropertyFilter;

            foreach (var m in q.GetAllMessages())
            {
                var subscriber = Address.Parse(m.Label);
                var messageTypeString = m.Body as string;
                var messageType = new MessageType(messageTypeString); //this will parse both 2.6 and 3.0 type strings

                entries.Add(new Entry { MessageType = messageType, Subscriber = subscriber });
                AddToLookup(subscriber, messageType, m.Id);
            }
        }
开发者ID:xqfgbc,项目名称:NServiceBus,代码行数:35,代码来源:MsmqSubscriptionStorage.cs


示例16: HandleError

        public static void HandleError(MsmqPoisonMessageException error)
        {
            ProcessorQueue processorQueue = (ProcessorQueue)error.Data["processorQueue"];
            MessageQueue poisonQueue = new System.Messaging.MessageQueue(processorQueue.PoisonQueue);
            MessageQueue errorQueue = new System.Messaging.MessageQueue(processorQueue.ErrorQueue);

            using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    // Send the message to the poison and error message queues.
                    poisonQueue.Send((IWorkflowMessage)error.Data["message"], MessageQueueTransactionType.Automatic);
                    errorQueue.Send((WorkflowErrorMessage)error.Data["errorMessage"], MessageQueueTransactionType.Automatic);
                    txScope.Complete();
                }
                catch (InvalidOperationException)
                {

                }
                finally
                {
                    poisonQueue.Dispose();
                    errorQueue.Dispose();
                }
            }
        }
开发者ID:invertedsoftware,项目名称:Inverted-Software-Workflow-Engine,代码行数:26,代码来源:QueueOperationsHandler.cs


示例17: MsmqMessageQueue

        /// <summary>
        /// Constructs the <see cref="MsmqMessageQueue"/>, using the specified input queue. If the queue does not exist,
        /// it will attempt to create it. If it already exists, it will assert that the queue is transactional.
        /// </summary>
        public MsmqMessageQueue(string inputQueueName, bool allowRemoteQueue = false)
        {
            if (inputQueueName == null) return;

            try
            {
                machineAddress = GetMachineAddress();

                inputQueuePath = MsmqUtil.GetPath(inputQueueName);
                MsmqUtil.EnsureMessageQueueExists(inputQueuePath);
                MsmqUtil.EnsureMessageQueueIsTransactional(inputQueuePath);

                if (!allowRemoteQueue)
                {
                    EnsureMessageQueueIsLocal(inputQueueName);
                }

                inputQueue = GetMessageQueue(inputQueuePath);

                this.inputQueueName = inputQueueName;
            }
            catch (MessageQueueException e)
            {
                throw new ArgumentException(
                    string.Format(
                        @"An error occurred while initializing MsmqMessageQueue - attempted to use '{0}' as input queue",
                        inputQueueName), e);
            }
        }
开发者ID:CasperTDK,项目名称:RebusSnoopRefactor,代码行数:33,代码来源:MsmqMessageQueue.cs


示例18: getFirstReservation

 public Message getFirstReservation()
 {
     MessageQueue queue = new MessageQueue(FlyHotelConstant.ADRESSE_QUEUE);
     queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(DemandeReservation) });
     Message messageResa = queue.Peek();
     return messageResa;
 }
开发者ID:math-th,项目名称:net-resa-tp,代码行数:7,代码来源:clsMsmq.cs


示例19: MessageReceiver

 public string MessageReceiver()
 {
     const string queue_name = @".\private$\dynamics";
     var queue = new MessageQueue(queue_name);
     queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
     return queue.Receive().Body.ToString();
 }
开发者ID:fernandolobo,项目名称:fortesdynamics,代码行数:7,代码来源:MicrosoftQueue.cs


示例20: Purge

		public void Purge()
		{
			using (var queue = new MessageQueue(_address.LocalName, QueueAccessMode.ReceiveAndAdmin))
			{
				queue.Purge();
			}
		}
开发者ID:RTroywest,项目名称:MassTransit,代码行数:7,代码来源:MsmqEndpointManagement.cs



注:本文中的System.Messaging.MessageQueue类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Messaging.MessageQueueTransaction类代码示例发布时间:2022-05-26
下一篇:
C# Messaging.Message类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap