исключение sqlclient при использовании sqlnotificationrequest - PullRequest
0 голосов
/ 29 июня 2018

Я делаю заявку на c # после урока https://code.msdn.microsoft.com/windowsdesktop/How-to-Execute-the-1e7c35d5

Я установил соединение с сервером, создал все необходимые процедуры и очереди в базе данных.

public class SqlNotificationRequestRegister
    {
        private readonly String serviceName;
        private readonly Int32 notificationTimeout;

        private readonly String connectionString;
        private readonly String listenSql;


        private SqlNotificationRequest request;
        private Task listenTask;
        private SqlCommand cmd = null;

        // This event will be invoked after the data is changed.
        public event EventHandler OnChanged;

        public SqlNotificationRequestRegister(String listenSqlStrig, String service, Int32 timeout,
            String connString)
        {
            listenSql = listenSqlStrig;
            serviceName = service;
            notificationTimeout = timeout;
            connectionString = connString;

            RegisterSqlNotificationRequest();
        }

        /// <summary>
        /// Begin to monitor the Service Broker queue
        /// </summary>
        public void StartSqlNotification()
        {
            listenTask = new Task(Listen);

            listenTask.Start();
        }

        /// <summary>
        /// Create a SqlNotificationRequest and invoke the event.
        /// </summary>
        private void RegisterSqlNotificationRequest()
        {
            request = new SqlNotificationRequest();
            request.UserData = new Guid().ToString();
            request.Options = String.Format("Service={0};", serviceName);
            request.Timeout = notificationTimeout;

            if (OnChanged != null)
            {
                OnChanged(this, null);
            }
        }

        /// <summary>
        /// Monitoring the Service Broker queue.
        /// </summary>
        private void Listen()
        {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    using (cmd = new SqlCommand(listenSql, conn))
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }

                        cmd.CommandTimeout = notificationTimeout + 120;

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                for (int i = 0; i <= reader.FieldCount - 1; i++)
                                    Debug.WriteLine(reader[i].ToString());
                            }
                        }
                    }
                }

            RegisterSqlNotificationRequest();
        }

        public void StopSqlNotification()
        {
            if (cmd != null)
            {
                cmd.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(Boolean disposed)
        {
            if (disposed)
            {
                StopSqlNotification();
            }
        }

        public SqlNotificationRequest NotificationRequest
        { get { return request; } }
    }

когда я запускаю приведенный выше код, я получаю sqlexception

Исключение типа 'System.Data.SqlClient.SqlException' произошло в System.Data.dll, но не был обработан в коде пользователя Неверное имя объекта 'StudentGradeChangeMessages'.

но я могу увидеть сообщения StudentGradeChange в моем ServerExplorer в очередях ServiceBroker. Что не так с кодом?

1 Ответ

0 голосов
/ 29 июня 2018

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

он уже упомянул предоставленную ссылку, как показано ниже

// StudentGradeChangeMessages is the name of the Service Broker service that has 
// been defined. 
private const String serviceName = "StudentGradeChangeNotifications"; 
...