Отправка сообщения в очередь служебной шины Azure с помощью .Net Framework .4.5.2 - PullRequest
0 голосов
/ 28 июня 2018

В настоящее время я пытаюсь отправить сообщение в очередь служебной шины Azure и, похоже, всегда сталкиваюсь с ошибками.

Вот мой пример.

namespace azure_queue
{
    class sendtoAzure
    {    
        public  async Task sendAsync(string message)
        {
            const string ServiceBusConnectString = "<connection-string>";
            const string QueueName = "<QueueName>";
            var AzureClient = Microsoft.ServiceBus.Messaging.QueueClient.CreateFromConnectionString(ServiceBusConnectString, QueueName);
            await AzureClient.SendAsync(new Microsoft.ServiceBus.Messaging.BrokeredMessage(message));
        }
    }
    class Program
    {

        static void Main(string[] args)
        {

            string transferObject_string = "This is a test";
            Microsoft.ServiceBus.Messaging.BrokeredMessage message = new Microsoft.ServiceBus.Messaging.BrokeredMessage(transferObject_string);
            Console.WriteLine("Sending message to azure");
            sendtoAzure client = new sendtoAzure();

            try
            {

                client.sendAsync(transferObject_string).Wait(TimeSpan.FromSeconds(60));
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Exception: " + ex.StackTrace);
                Console.WriteLine("Message: " + ex.Message);
                Console.WriteLine("HelpLink: " + ex.HelpLink);
                Console.WriteLine("Source: " + ex.Source);
                Console.ReadLine();

                if (ex is System.TimeoutException)
                {
                    Console.WriteLine("Timeout exeption");
                }

                if (ex is System.ArgumentException)
                {
                    Console.WriteLine("Message is empty");
                }

                if (ex is System.UnauthorizedAccessException)
                {
                    Console.WriteLine("Unauthorized access!");
                }

                if (ex is Microsoft.ServiceBus.Messaging.SessionCannotBeLockedException)
                {
                    Console.WriteLine("Attempt to accept a session with a specific session ID, but the session is currently locked by another client.");
                }
            }
        Console.WriteLine("Message Sent!");
            Console.ReadLine();


        }
    }
}

И сообщение об ошибке, которое я получаю:

Sending message to azure
Exception:    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at azure_queue.Program.Main(String[] args) in C:\Users\keer\Source\Repos\azure_queue\azure_queue\Program.cs:line 39
Message: One or more errors occurred.
HelpLink:
Source: mscorlib

Message Sent!

Я попытался без async aswell, и это сработало, но, кажется, ничего не входит в очередь, когда я проверяю портал. Чем вызвана эта ошибка?

Тот же самый пример только с send

пример:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus;
using System.Configuration;
using System.Messaging;
using System.ServiceModel;
using System.Net;


namespace azure_queue
{
    public class sendtoAzure
    {
        public string ServiceBusConnectString;
        public string QueueName;
        public Microsoft.ServiceBus.Messaging.QueueClient AzureClient;

        public sendtoAzure()
        {
            ServiceBusConnectString = "<connectionstring>";
            QueueName = "<Queue-name>";
            AzureClient = Microsoft.ServiceBus.Messaging.QueueClient.CreateFromConnectionString(ServiceBusConnectString, QueueName);
        }

        public void send (string message)
        { 
            AzureClient.Send(new Microsoft.ServiceBus.Messaging.BrokeredMessage(message));
        }
    }
    class Program
    {

        static void Main(string[] args)
        {

            string transferObject_string = "This is a test";
            Microsoft.ServiceBus.Messaging.BrokeredMessage message = new Microsoft.ServiceBus.Messaging.BrokeredMessage(transferObject_string);
            Console.WriteLine("Sending message to azure");
            sendtoAzure client = new sendtoAzure();
            try
            {
                client.send(transferObject_string);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Exception: " + ex.StackTrace);
                Console.WriteLine("Message: " + ex.Message);
                Console.WriteLine("HelpLink: " + ex.HelpLink);
                Console.WriteLine("Source: " + ex.Source);
                Console.WriteLine("InnerExeption: " + ex.InnerException);

                Console.ReadLine();

                if (ex is System.TimeoutException)
                {
                    Console.WriteLine("Timeout exeption");
                }

                if (ex is System.ArgumentException)
                {
                    Console.WriteLine("Message is empty");
                }

                if (ex is System.UnauthorizedAccessException)
                {
                    Console.WriteLine("Unauthorized access!");
                }

                if (ex is Microsoft.ServiceBus.Messaging.SessionCannotBeLockedException)
                {
                    Console.WriteLine("Attempt to accept a session with a specific session ID, but the session is currently locked by another client.");
                }
            }
            Console.WriteLine("Message Sent!");
            Console.ReadLine();

        }
    }
}

Дает эту ошибку - включая внутреннее исключение:

Sending message to azure
Exception:    at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.RunSynchronously()
   at Microsoft.ServiceBus.Messaging.MessageSender.OnSend(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
   at Microsoft.ServiceBus.Messaging.MessageSender.Send(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
   at Microsoft.ServiceBus.Messaging.MessageSender.Send(BrokeredMessage message)
   at Microsoft.ServiceBus.Messaging.QueueClient.Send(BrokeredMessage message)
   at azure_queue.sendtoAzure.send(String message) in C:\Users\keer\Source\Repos\azure_queue\azure_queue\Program.cs:line 30
   at azure_queue.Program.Main(String[] args) in C:\Users\keer\Source\Repos\azure_queue\azure_queue\Program.cs:line 45
Message: 40400: Endpoint not found., Resource:sb://x-shared.servicebus.windows.net/x%20-%20test. TrackingId:fd30b288-cc6a-4360-9922-0b044e9de8f4_G28, SystemTracker:x-shared.servicebus.windows.net:x%20-%20test, Timestamp:6/28/2018 1:57:25 PM
HelpLink:
Source: Microsoft.ServiceBus
InnerExeption: System.ServiceModel.FaultException: 40400: Endpoint not found., Resource:sb://x-shared.servicebus.windows.net/x%20-%20test. TrackingId:fd30b288-cc6a-4360-9922-0b044e9de8f4_G28, SystemTracker:x-shared.servicebus.windows.net:x%20-%20test, Timestamp:6/28/2018 1:57:25 PM
   at Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.ThrowIfFaultMessage(Message wcfMessage)
   at Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.HandleMessageReceived(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<>c.<GetAsyncSteps>b__9_3(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Common.AsyncResult`1.End(IAsyncResult asyncResult)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.RequestAsyncResult.<>c__DisplayClass8_1.<GetAsyncSteps>b__4(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Common.AsyncResult`1.End(IAsyncResult asyncResult)
   at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<>c.<GetAsyncSteps>b__9_3(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Common.AsyncResult`1.End(IAsyncResult asyncResult)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpTransactionalAsyncResult`1.<>c.<GetAsyncSteps>b__18_3(TIteratorAsyncResult thisPtr, IAsyncResult a)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.EndSendCommand(IAsyncResult result)

Ответы [ 2 ]

0 голосов
/ 03 июля 2018

Сообщения можно отправлять в служебные автобусные очереди Azure, как показано ниже

namespace ServiceBus_Queue { class Program { const string ServiceBusConnectionString = ""; const string QueueName = ""; static void Main(string[] args) { MainAsync().GetAwaiter().GetResult(); } static async Task MainAsync() { var queueClient = QueueClient.CreateFromConnectionString(ServiceBusConnectionString, QueueName); string Message = "I'm in Azure Service Bus Queue"; BrokeredMessage message = new BrokeredMessage(Message); await queueClient.SendAsync(message); } } }

0 голосов
/ 01 июля 2018

Мне удалось успешно отправить посредническое сообщение, используя реализацию sendAsync () .

Кроме того, мне удалось воспроизвести ту же ошибку, которая указана в вашем вопросе , когда очередь НЕ существует (например, taskqueue1).

Message: 40400: Endpoint not found., Resource:sb://{valid service bus namespace}.servicebus.windows.net/taskqueue1. TrackingId:7ce43d17-d339-4ded-b3be-71364a64f685_G17, SystemTracker:{valid service bus namespace}.servicebus.windows.net:taskqueue1, Timestamp:7/1/2018 1:23:04 AM...

Имя очереди x% 20-% 20test в конечной точке, извлеченной из отправленного вами исключения, не соответствует действительности из-за пробелов (например,% 20).

sb://x-shared.servicebus.windows.net/x%20-%20test

Итак, дважды проверьте правильность / допустимость имени очереди Azure Service Bus и выход.


Кроме того, полное доменное имя Azure Service Bus, которое вы используете , вероятно, является правильным . В противном случае будет создано следующее исключение вместо того, которое описано в вашем вопросе:

Microsoft.ServiceBus.Messaging.MessagingCommunicationException: The remote name could not be resolved: '{nonexistent service bus namespace}.servicebus.windows.net'...
...