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

C# BrokeredMessage类代码示例

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

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



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

示例1: SendMessage

        public JsonResult SendMessage(string topicName, string message, bool messageIsUrgent, bool messageIsImportant)
        {
            TopicClient topicClient = this.messagingFactory.CreateTopicClient(topicName);
            var customMessage = new CustomMessage() { Body = message, Date = DateTime.Now };
            bool success = false;
            BrokeredMessage bm = null;

            try
            {
                bm = new BrokeredMessage(customMessage);
                bm.Properties["Urgent"] = messageIsUrgent ? "1" : "0";
                bm.Properties["Important"] = messageIsImportant ? "1" : "0";
                bm.Properties["Priority"] = "Low";
                topicClient.Send(bm);
                success = true;
            }
            catch (Exception)
            {
                // TODO: do something
            }
            finally
            {
                if (bm != null)
                {
                    bm.Dispose();
                }
            }

            return this.Json(success, JsonRequestBehavior.AllowGet);
        }
开发者ID:kirpasingh,项目名称:MicrosoftAzureTrainingKit,代码行数:30,代码来源:HomeController.cs


示例2: AddToAzureQueue

        public static void AddToAzureQueue(this object o, string queueName, string nameSpace, string issuerName, string issuerKey)
        {
            if (_queueClient == null || queueName.ToLower() != _queueName || nameSpace.ToLower() != _nameSpace || issuerName.ToLower() != _issuerName || issuerKey.ToLower() != _issuerKey)
            {
                _queueName = queueName.ToLower();
                _nameSpace = nameSpace.ToLower();
                _issuerName = issuerName.ToLower();
                _issuerKey = issuerKey.ToLower();

                ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;
                System.Net.ServicePointManager.DefaultConnectionLimit = int.MaxValue;
                System.Net.ServicePointManager.Expect100Continue = false;
                System.Net.ServicePointManager.UseNagleAlgorithm = false;

                var credentials = GetToken(issuerName, issuerKey);

                // Get a client to the queue
                var messagingFactory = MessagingFactory.Create(GetAddress(nameSpace), credentials);
                _queueClient = messagingFactory.CreateQueueClient(queueName);
            }

            BrokeredMessage message = new BrokeredMessage(o);

            _queueClient.Send(message);
        }
开发者ID:eulalie367,项目名称:Helpers,代码行数:25,代码来源:AzureExtensions.cs


示例3: Send

        /// <summary>
        /// Save Message to Queue
        /// </summary>
        /// <param name="message">Message</param>
        /// <returns>Task</returns>
        public async Task Send(BrokeredMessage message)
        {
            if (null == message)
            {
                throw new ArgumentNullException("message");
            }

            while (true)
            {
                try
                {
                    await this.client.Send(message);

                    break;
                }
                catch (MessagingException ex)
                {
                    if (ex.IsTransient)
                    {
                        this.HandleTransientError(ex);
                    }
                    else
                    {
                        Trace.TraceError("Error: '{0}'", ex.ToString());

                        throw;
                    }
                }
            }
        }
开发者ID:modulexcite,项目名称:King.Service.ServiceBus,代码行数:35,代码来源:TopicSender.cs


示例4: OnBrokerMessage

        private void OnBrokerMessage(BrokeredMessage brokeredMessage)
        {
            try
            {
                //Ignore messages from self
                if (brokeredMessage.Properties[SidAttributeName].ToString() == _sid)
                {
                    brokeredMessage.Complete();
                    return;
                }

                var json = brokeredMessage.Properties[DataAttributeName].ToString();
                var message = _jsonSerializer.DeserializeFromString<Message>(json);

                var pipeline = Composable.GetExport<IXSocketPipeline>();
                var controller = Composable.GetExports<IXSocketController>().First(p => p.Alias == message.Controller);
                controller.ProtocolInstance = new XSocketInternalProtocol();
                pipeline.OnIncomingMessage(controller, message);
                brokeredMessage.Complete();
            }
            catch (Exception ex)
            {
                Composable.GetExport<IXLogger>().Error(ex.ToString());

                // Indicates a problem
                if (brokeredMessage.DeliveryCount > 3)
                {
                    brokeredMessage.DeadLetter();
                }
                else
                {
                    brokeredMessage.Abandon();
                }
            }
        }
开发者ID:acandocodecamp,项目名称:xsockets,代码行数:35,代码来源:AzureServiceBusScaleout.cs


示例5: BuildMessage

        /// <summary>
        /// Convert the brokered message to an envelope.
        /// </summary>
        /// <param name="brokeredMessage"></param>
        /// <returns></returns>
        public async Task<IEnvelope<IMessage>> BuildMessage(BrokeredMessage brokeredMessage)
        {
            using (var stream = brokeredMessage.GetBody<Stream>())
            using (var ms = new MemoryStream())
            {
                var messageType = brokeredMessage.ContentType;

                // Log.
                MessagingEventSource.Log.DeserializingMessage(messageType, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId);

                // Helps us get access to the byte array.
                await stream.CopyToAsync(ms);

                // Build the envelope.
                var envelope = Envelope.Create<IMessage>(null)
                    .CorrelationId(brokeredMessage.CorrelationId)
                    .SessionId(brokeredMessage.SessionId)
                    .TimeToLive(brokeredMessage.TimeToLive)
                    .Properties(brokeredMessage.Properties);

                // Handle interceptors, then deserialize.
                var serializedMessage = await Configuration.MessageFilterInvoker.BeforeDeserialization(envelope, ms.ToArray());
                var message = await Configuration.Serializer.Deserialize<IMessage>(serializedMessage);

                // Log.
                MessagingEventSource.Log.DeserializationComplete(messageType, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId);

                // Done.
                return envelope.Body(message);
            }
        }
开发者ID:RobinSoenen,项目名称:RedDog,代码行数:36,代码来源:MessageProcessor.cs


示例6: BuildMessage

        private BrokeredMessage BuildMessage(Envelope<ICommand> command)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            this.serializer.Serialize(writer, command.Body);
            stream.Position = 0;

            var message = new BrokeredMessage(stream, true);
            if (!default(Guid).Equals(command.Body.Id))
            {
                message.MessageId = command.Body.Id.ToString();
            }

            var metadata = this.metadataProvider.GetMetadata(command.Body);
            if (metadata != null)
            {
                foreach (var pair in metadata)
                {
                    message.Properties[pair.Key] = pair.Value;
                }
            }

            if (command.Delay != TimeSpan.Zero)
                message.ScheduledEnqueueTimeUtc = DateTime.UtcNow.Add(command.Delay);

            return message;
        }
开发者ID:garystanford,项目名称:cqrs-journey-code,代码行数:27,代码来源:CommandBus.cs


示例7: PumpMessage

        protected override void PumpMessage(BrokeredMessage message)
        {
            var correlationId = Guid.Parse(message.CorrelationId);
            var responseCorrelationWrapper = _requestResponseCorrelator.TryGetWrapper(correlationId);
            if (responseCorrelationWrapper == null)
            {
                Logger.Debug("Could not find correlation wrapper for reply {0} ({1}", correlationId, message.Properties[MessagePropertyKeys.MessageType]);
                return;
            }

            var success = (bool) message.Properties[MessagePropertyKeys.RequestSuccessfulKey];
            if (success)
            {
                Logger.Debug("Request {0} was successful. Dispatching reply to correlation wrapper.", correlationId);

                var responseType = responseCorrelationWrapper.ResponseType;
                var response = message.GetBody(responseType);
                responseCorrelationWrapper.Reply(response);

                Logger.Debug("Response {0} dispatched.", correlationId);
            }
            else
            {
                var exceptionMessage = (string) message.Properties[MessagePropertyKeys.ExceptionMessageKey];
                var exceptionStackTrace = (string) message.Properties[MessagePropertyKeys.ExceptionStackTraceKey];

                Logger.Debug("Request {0} failed. Dispatching exception to correlation wrapper: {1} {2}", correlationId, exceptionMessage, exceptionStackTrace);

                responseCorrelationWrapper.Throw(exceptionMessage, exceptionStackTrace);
            }
        }
开发者ID:Joshscorp,项目名称:Nimbus,代码行数:31,代码来源:ResponseMessagePump.cs


示例8: SendMessage

 private static void SendMessage(string name, string message)
 {
     Greeting g = new Greeting() { Name = name, Message = message };
     while(true){
         try
         {
             BrokeredMessage bmsg = new BrokeredMessage(g);
             queueClient.Send(bmsg);
             Console.Out.WriteLine("Sent message with id {0}", bmsg.MessageId);
             break;
         }
         catch (MessagingException mex)
         {
             if (!mex.IsTransient)
             {
                 throw;
             }
             else
             {
                 Console.Out.WriteLine("We experienced a temporary setback due to {0}", mex.Message);
                 Console.Out.WriteLine("Retrying in 2 seconds.");
                 Thread.Sleep(2000);
             }
         }
     }
 }
开发者ID:kennethahn,项目名称:ServiceBusRelayDemo,代码行数:26,代码来源:Producer.cs


示例9: Enqueue

        public async Task Enqueue(object message)
        {
            var brokeredMessage = new BrokeredMessage(message);

            var topicClient = QueueClient.CreateFromConnectionString(_serviceBusNamespaceConnectionString, QueueName);
            await topicClient.SendAsync(brokeredMessage);
        }
开发者ID:kkrzaczkowski-fp,项目名称:AzureConstructionsProgressTracker-AzureWorkshopFP,代码行数:7,代码来源:ServiceBusManager.cs


示例10: SendSBM

 public void SendSBM(string msg, string channel)
 {
     message = new BrokeredMessage(msg);
     message.Properties["channel"] = channel;
     message.TimeToLive = timetolive;
     client.Send(message);
 }
开发者ID:foxjazz,项目名称:IRCAL,代码行数:7,代码来源:SBMessage.cs


示例11: When

 protected override async Task When()
 {
     _request = new BrokeredMessage();
     _sessionId = Guid.NewGuid().ToString();
     _request.ReplyToSessionId = _sessionId;
     _response = await Subject.CreateSuccessfulResponse(new TestResponse(), _request);
 }
开发者ID:AtmosphereMessaging,项目名称:Cumulus,代码行数:7,代码来源:WhenCreatingASuccesfulResponseToARequestWithReplyToSessionIdSet.cs


示例12: CreateInstance

        /// <summary>
        /// Create a new session handler.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public IMessageSessionAsyncHandler CreateInstance(MessageSession session, BrokeredMessage message)
        {
            ServiceBusEventSource.Log.SessonAccepted(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId);

            // Use the current handler.
            return new SessionMessageAsyncHandler(_receiverNamespace, _receiverPath, session, _messageHandler, _options);
        }
开发者ID:Mecabot,项目名称:RedDog,代码行数:13,代码来源:SessionMessageAsyncHandlerFactory.cs


示例13: Main

        static void Main(string[] args)
        {

            try
            {
                //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

                string topicName = "sb-salesorder-topic";
                string sbconnection = "Endpoint=sb://sb-twocents-ns.servicebus.windows.net/;SharedAccessKeyName=Sender;SharedAccessKey=TzYnAEaXHAP3dVJ0J/knLc+2+99C/E2ytbo8qDJQ+TI=";
                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(sbconnection);
                TopicClient client = factory.CreateTopicClient(topicName);

                string postBody = "{'ServiceNumber': 'TST100', 'AddressCode': 'HAG', 'ServiceContractNumber': 'SOC920001', Description': 'Testmelding'}";

                BrokeredMessage msg = new BrokeredMessage(postBody);
                msg.Properties["Priority"] = 1;

                client.Send(msg);

                msg = null;

                Console.WriteLine("Press Enter");
                Console.Read();

            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error: {0}", ex.ToString()));
                Console.Read();
            }

        }
开发者ID:PaulBaars,项目名称:TwoCents,代码行数:32,代码来源:Program.cs


示例14: Main

        static void Main(string[] args)
        {
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            NamespaceManager ConnectorNamespaceMgr = NamespaceManager.CreateFromConnectionString(connectionString);
            if (!ConnectorNamespaceMgr.QueueExists("TestQueue"))
            {
                ConnectorNamespaceMgr.CreateQueue("TestQueue");
            }

            QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "TestQueue", ReceiveMode.PeekLock);

            for (int i = 0; i < 5; i++)
            {
                // Create message, passing a string message for the body.
                BrokeredMessage message = new BrokeredMessage("Test message " + i);

                // Set some addtional custom app-specific properties.
                message.Properties["TestProperty"] = "TestValue";
                message.Properties["Message number"] = i;

                // Send message to the queue.
                Client.Send(message);
            }
            ReceiveQueueMessages(Client);
        }
开发者ID:aravindnet,项目名称:AzureServiceBusSample,代码行数:26,代码来源:Program.cs


示例15: FromBrokeredMessage

 public static SBMessage FromBrokeredMessage(BrokeredMessage message)
 {
     SBMessage ret = new SBMessage(message.GetBody());
     foreach (var key in message.Properties.Keys)
         ret.Headers.Add(key, message.Properties[key]);
     return ret;
 }
开发者ID:HaishiBai,项目名称:EnterpriseIntegrationPatterns,代码行数:7,代码来源:SBMessage.cs


示例16: SendMessage

        public static string SendMessage(MessageFormat msg,string SharedKey)
        {
            try
            {
                string connectionString = string.Format("Endpoint=sb://myflow-ns.servicebus.windows.net/;SharedAccessKeyName={0};SharedAccessKey={1}", msg.PolicyName, SharedKey);
                string JsonMessage = JsonConvert.SerializeObject(msg);
                var jsonObjStream = new MemoryStream(Encoding.UTF8.GetBytes(JsonMessage));
                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);
                MessageSender MessageSender = factory.CreateMessageSender("flowspec");
                BrokeredMessage Message = new BrokeredMessage(jsonObjStream);
                MessageSender.Send(Message);
                if (msg.Action == "Add")
                {
                    return "The Filter is added";
                }
                else
                {
                    return "The Filter is removed";
                }

            }
            catch (MessagingCommunicationException)
            {

                return "Client is not able to establish a connection to Service Bus.";
            }

            catch (UnauthorizedAccessException)
            {
                return "PolicyName or SharedAccessKey is incorrect";
            }
        }
开发者ID:moimran,项目名称:flowspec1,代码行数:32,代码来源:servicebusMessage.cs


示例17: HandleMessage

        public void HandleMessage(BrokeredMessage message)
        {
            if (message.GetMessageType() == "Create")
            {
                var virtualMachine = message.GetObject<VirtualMachine>();
                var imageName = CloudConfigurationManager.GetSetting("VirtualMachineBaseImageName");
                var dataDiskBase = CloudConfigurationManager.GetSetting("DataDiskName");
                var dataDiskName = String.Format("{0}-{1}", dataDiskBase, virtualMachine.Name);
                var sourceVhdName = String.Format("{0}.vhd", dataDiskBase);
                var storageContainerUrl = CloudConfigurationManager.GetSetting("StorageContainerUrl");
                var vhdContainerName = CloudConfigurationManager.GetSetting("VhdContainerName"); //TODO: does this work with multiple storage accounts?
                var serviceName = CloudConfigurationManager.GetSetting("ServiceName");

                //var subscriptionId = CloudConfigurationManager.GetSetting("Azure.SubscriptionId");
                //var managementCertificateString = CloudConfigurationManager.GetSetting("Azure.ManagementCertificate");
                //var managementCertificate = new X509Certificate2(Convert.FromBase64String(managementCertificateString));
                //var credentials = new CertificateCloudCredentials(subscriptionId, managementCertificate);

                //TODO: find a subscription?

                //TODO: get storage account?

                if (AzureVmExists(_executor, virtualMachine) == false)
                {
                    CreateNewVirtualMachine(_executor, virtualMachine, imageName, serviceName, sourceVhdName, storageContainerUrl, vhdContainerName, dataDiskName);
                }
            }
            else
            {
                throw new ArgumentException("Invalid Message Type.", "message");
            }
        }
开发者ID:jamesology,项目名称:AzureVmFarmer,代码行数:32,代码来源:SowMessageHandler.cs


示例18: ToTransportMessage

        public TransportMessage ToTransportMessage(BrokeredMessage message)
        {
            TransportMessage t;
            var rawMessage = message.GetBody<byte[]>();

            if (message.Properties.Count == 0)
            {
                t = DeserializeMessage(rawMessage);
            }
            else
            {
                t = new TransportMessage(message.MessageId, message.Properties.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value.ToString()))
                        {
                            CorrelationId = message.CorrelationId,
                            TimeToBeReceived = message.TimeToLive
                        };

                t.MessageIntent =
                    (MessageIntentEnum)
                    Enum.Parse(typeof(MessageIntentEnum), message.Properties[Headers.MessageIntent].ToString());

                if ( !String.IsNullOrWhiteSpace( message.ReplyTo ) )
                {
                    t.ReplyToAddress = Address.Parse( message.ReplyTo ); // Will this work?
                }

                t.Body = rawMessage;
            }

            return t;
        }
开发者ID:afyles,项目名称:NServiceBus,代码行数:31,代码来源:BrokeredMessageConverter.cs


示例19: ProcessMessage

        private async Task ProcessMessage(BrokeredMessage message)
        {
            try
            {
                if (!this.IsValidMessage(message))
                {
                    // Send the message to the Dead Letter queue for further analysis.
                    await message.DeadLetterAsync("Invalid message", "The message Id is invalid");
                    Trace.WriteLine("Invalid Message. Sending to Dead Letter queue");
                }

                // Simulate message processing.
                await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);

                Trace.WriteLine("Consumer " + RoleEnvironment.CurrentRoleInstance.Id + " : Message processed successfully: " + message.MessageId);

                // Complete the message.
                await message.CompleteAsync();
            }
            catch (Exception ex)
            {
                // Abandon the message when appropriate.  If the message reaches the MaxDeliveryCount limit, it will be automatically deadlettered.
                message.Abandon();
                Trace.TraceError("An error has occurred while processing the message: " + ex.Message);
            }
        }
开发者ID:calebjenkins,项目名称:cloud-design-patterns,代码行数:26,代码来源:WorkerRole.cs


示例20: SendToQueue_Click

        private void SendToQueue_Click(object sender, RoutedEventArgs e)
        {
            Trace.WriteLine("SendMessage()");

            var namespaceManager = NamespaceManager.Create();

            if (namespaceManager.QueueExists(QueueName))
            {
                try
                {
                    BrokeredMessage message = new BrokeredMessage(messageBody);
                    message.MessageId = messageId;

                    queueClient.Send(message);
                }
                catch (MessagingException ex)
                {
                    if (!ex.IsTransient)
                    {
                        Trace.WriteLine(ex.Message);
                        throw;
                    }
                    else
                    {
                        HandleTransientErrors(e);
                    }
                }
            }
            else
            {
                Trace.WriteLine("Queue does not exist: " + QueueName);
            }
        }
开发者ID:Eugene-Murray,项目名称:SignalR_Notifications,代码行数:33,代码来源:MainWindow.xaml.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# BronieContext类代码示例发布时间:2022-05-24
下一篇:
C# BrokerRouterProxy类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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