Quantcast
Channel: SQL Service Broker forum
Viewing all 461 articles
Browse latest View live

Service Broker causes SqlExceptions

$
0
0
Hello,

I have used sql server service borker notification service and queue for my .Net application (windows service) to get query notification when any update in query(table).

in application i have used sqlDependency to get query notification on change.

this service and queue is working fine and i am getting query notitication in application.

In window service there are many (50 or more) sql operation perform in 1 seconds. if i am using sql server service broker,
i was getting SQLException like :

System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is open.
System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.

if i disable borker and delete service/queue, then everything working fine (no sql exception)

Question : does Service borker caues sql server performance issue with connection from C# ?

if you need sample then will provide sample how i have implemented service borker in .Net application.

it would be great if you provide any solution for this.


Thanks in Advance.

Are error messages created somewhere when an event_notifications are misconfigured?

$
0
0

Newbie question: We discovered that we had a value in sys.event_notifications.broker_instance that did not correspond to the value of sys.databases.service_broker_guid for any existing database. We were unaware of this for some time. Are there any error messages generated by Service Broker when this happens or is does it just not work?

Thanks,

Ron Rice


Ron Rice

SqlDependency OnChange Event Fires repeatedly

$
0
0

I am using the SqlDependency to notify me of data changes in a table. However, as soon as I start it, the OnChange event fires over and over even though no data has changed.

 

Essentially All I want to do is be notified when records are inserted into a table. I am able to get another example to work using a Service Broker Queue and a sql query of WAITFOR ( RECEIVE CONVERT(int, message_body) AS msg FROM QueueMailReceiveQueue ) However I would prefer not to use a queue for once my messages have been read they are taken off the queue and I would rather control that manually.

 

Any help with getting SqlDependency to notify my app when records are added and not over and over when the data has changed would be great.

 

Here is my code:

 

Code Snippet

public

partialclassForm1 : Form {

 

publicstaticeventOnChangeEventHandler OnChange;

string _strConnString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=email_queue;Pooling=False;";

string _strSql = "SELECT email_id from email where isprocessed = 0";

privateDataSet dataToWatch = null;

privateSqlConnection connection = null;

privateSqlCommand command = null;

SqlDependency dependency = null;

SqlDataReader sdr = null;

 

public Form1() {

InitializeComponent();

}

 

privatevoid button1_Click(object sender, EventArgs e) {

SqlDependency.Stop(_strConnString);

SqlDependency.Start(_strConnString);

if (connection == null) {

connection = newSqlConnection(_strConnString);

connection.Open();

}

if (command == null) {

command = newSqlCommand(_strSql, connection);

}

if (dataToWatch == null) {

dataToWatch = newDataSet();

}

GetData();

}

 

privatevoid GetData() {

dataToWatch.Clear();

command.Notification = null;

dependency = newSqlDependency(command);

dependency.OnChange += newOnChangeEventHandler(dependency_OnChange);

command.CommandTimeout = 400;

using (SqlDataAdapter adapter = newSqlDataAdapter(command)) {

adapter.Fill(dataToWatch, "email");

}

}

 

privatevoid dependency_OnChange(object sender, SqlNotificationEventArgs e) {

ISynchronizeInvoke i = (ISynchronizeInvoke)this;

if (i.InvokeRequired) {

OnChangeEventHandler tempDelegate = newOnChangeEventHandler(dependency_OnChange);

object[] args = { sender, e };

i.BeginInvoke(tempDelegate, args);

return;

}

dependency = (SqlDependency)sender;

dependency.OnChange -= dependency_OnChange;

this.Text = DateTime.Now.ToString();

GetData();

}

 

privatevoid Form1_FormClosed(object sender, FormClosedEventArgs e) {

SqlDependency.Stop(_strConnString);

if (connection != null) {

connection.Close();

}

}

}

 

 

Message only arrives on queue once.

$
0
0

Hi,

I am new to SQL Service Broker and am currently trying to develop a POC.
I need to call a web service when a insert is made on a table. I have setup 3 queues and 3 services with associated message types (code below).

I have had some success after running the code below and performing an insert I see the messages appear on the following queues:

TargetPostQueue
InitiatorPostQueue
NotificationPostQueue

Then I start the Service Broker External Activator and the message is taken off NotificationPostQueue as expected and passed to my dummy console app that just prints out the args passed; for now.

The problem is after this no other messages appear on the NotificationPostQueue no matter how many inserts I do.
I see them appear on the TargetPost and InitiatorPost queues but nothing moves to the NotificationPostQueue. I'm sure this has something to do with me not ending the conversation but am unsure. What I can do when this happens, for now, is drop and delete the database then recreate it to give me one more go but it's taking too long.

Code for creating queue's and services

-- Create message types
CREATE MESSAGE TYPE [//MetLife/BPA/RequestPostMessage]  VALIDATION = WELL_FORMED_XML;
CREATE MESSAGE TYPE [//MetLife/BPA/ReplyPostMessage]    VALIDATION = WELL_FORMED_XML;
GO

-- Create contract
CREATE CONTRACT [//MetLife/BPA/PostContract]
     ([//MetLife/BPA/RequestPostMessage] SENT BY INITIATOR,
     [//MetLife/BPA/ReplyPostMessage] SENT BY TARGET
);
GO

-- Create target queue and service
CREATE QUEUE TargetPostQueue WITH RETENTION = ON;
CREATE SERVICE [//MetLife/BPA/TargetPostService]
     ON QUEUE TargetPostQueue([//MetLife/BPA/PostContract]);
GO

-- Create the initiator queue and service
CREATE QUEUE InitiatorPostQueue WITH RETENTION = ON;
CREATE SERVICE [//MetLife/BPA/InitiatorPostService]
     ON QUEUE InitiatorPostQueue([//MetLife/BPA/PostContract]);
GO

-- Create a notification for External Activator
CREATE QUEUE NotificationPostQueue
CREATE SERVICE [//MetLife/BPA/NotificationPostService]
    ON QUEUE NotificationPostQueue([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
CREATE EVENT NOTIFICATION EventQueueActivation
    ON QUEUE [TargetPostQueue]
    FOR QUEUE_ACTIVATION
    TO SERVICE '//MetLife/BPA/NotificationPostService', 'current database';
GO

Code for Trigger and Test Table

CREATE TABLE [Policies]
(
    PolicyId INT NOT NULL IDENTITY(1,1),
    Amount MONEY NOT NULL,
    BrokerName NVARCHAR(50) NOT NULL
)
GO
-- Trigger will add a message into a ImportQueue
CREATE TRIGGER OnPolicyInserted ON [Policies] FOR INSERT
AS
BEGIN 
    BEGIN TRANSACTION;
        DECLARE @ch UNIQUEIDENTIFIER
%2

SQL Server 2008 R2 service broker implementation

$
0
0

Hi, We are using a SQL Server 2008 R2 database to support an e-commerce application which is written in C#. I am pretty new to the concept of service broker.

Could you please help me understand what service broker is?

I am trying to understand how would implementing service broker help?

What benefits do I get if I were to implement it?

Is service broker supported in future SQL Server releases?

Thanks in advance..........


Ione

Clearing all messages from a service broker queue

$
0
0

Hi All,

Iam currently trying to remove the messages from the queue if the count is more than 15000 as shown below in the stored procedure :

      Declare @CountMBSClientStatusSendQueue BIGINT
      SELECT  @CountMBSClientStatusSendQueue=rows
      From sys.partitions P
      Inner Join sys.internal_tables IT On IT.object_id = P.object_id
      Where IT.parent_object_id = object_id('MBSClientStatusSendQueue')
      And P.index_id In (1, 0)

      IF @CountMBSClientStatusSendQueue > 15000 
            ALTER DATABASE MBS SET NEW_BROKER WITH ROLLBACK IMMEDIATE

But the memory usage of the Sql server was very high and effecting the performance of the sql server. So I would like to know the easiest and the best way to cleanup the messages in the queues after the count is more than 10000

Kindly help me on the same.

Thanks,

Ram


ram

"Broker / DBM Transport:Receive I/O Bytes Total" counter is missing.

$
0
0

Hi

I noticed that "Receive I/O Bytes Total" and "Send I/O Bytes Total" counters are missing under "Broker / DBM Transport" object.


However, documentation says it should be there, http://msdn.microsoft.com/en-us/library/ms191226.aspx

My SQL server version is 2014 CU3. 


Любовь долготерпит, ...

Issue with SQLDependency along with Enity Framework and C#

$
0
0

Hi All,

I am trying to run a sample created using C# for SQL dependency. Whenever certain data is inserted in given table, I want a notification in my C# application. Right now, I am having both (my C# application as well as my SWl Server 2008 R2) the setups on the same machine which is not connected to any network.

My problem is, although my broker service is enabled  SQL server is not throwing me notification back in my C# application, although I modified data in my database. In simpler words, my sqlDependency_Onchange event is not firing.

Please help me out.


Regards, http://www.shwetalodha.blogspot.in/



Log shipping failed when cluster failed over to second node

$
0
0

i have a clustered environment with node 1 and node 2

node one is active node and up 99 % of the time so while it was on node one i setup log shipping for this server.

while configuring the log shipping i chosed a local drive to store log backups and also gave the shared path of same drive in the configuration option.

when clustered failed over to second node log shipping started failing, even thogh there was shared paht of the same folder and should have been accessable to node 2 for backing up log for log shipping,

Please advise the solution.

Regards

 

k

Unable to enable service broker

$
0
0

Dear all,

I tried to create DBMail in one of our prod server, i did the following operation at start getting error. Kindly help me how to avoid this problem

alter database msdb set enable_broker with no_wait

Error: Database state can't be changed while other users are using the database 'msdb'

Alter database statement failed

Note: I just verified may be anyone using the database but i'm the only user working on that.


DBA

Best practice for cleaning up conversations after a recieve timeout

$
0
0

We have a pattern where sql server sends a message through service broker and waits for a response (say 10 ten secs), if it doesn't get a response, it will assume a default response and carry on. The response may come later and also end the conversation target side. However there is no-one to receive the response (which is no longer needed). We have clean up script on a sql agent job but we were wondering if there is a cleaner way to handle these situations


When to use WAITFOR?

$
0
0

Hi all,

I'm in doubt whether to use WAITFOR RECEIVE in my activation SP or not.

Actually I'm confused if WAITFOR is necessary in case I have activation SP or just RECEIVE is enough inside it.

Any help would be greatly appreciated.

Leila


Determine if Notifications Firing

$
0
0
I am now to Service Broker and SQL Notifications and am working on an application that needs SQL Notification. I am having problems with the application working intermittently depending on the environment (Windows 7, 8, or Server 2012). In troubleshooting, I am trying to determine if the notifications are firing correctly to eliminate one issue, but I am not sure how to do this. I have verified Service Broker for the database is enabled, but am not sure how to monitor if notifications are sent when the database changes. Any help would be appreciated.

Service Broker Messages

$
0
0

Hi,

I've the below messages appearing in the sql error logs plenty of times. No idea what's the problem. Any insight ?

spid25s	The query notification dialog on conversation handle '{8BCD7D78-1340-E411-A2AF-0050569D1B40}.' closed due to the following error: '<?xml version="1.0"?><Error xmlns="http://schemas.microsoft.com/SQL/ServiceBroker/Error"><Code>-8490</Code><Description>Cannot find the remote service &apos;SqlQueryNotificationService-34610a75-1b8a-427b-9d14-076b22dff07e&apos; because it does not exist.</Description></Error>'.
spid59	Error: 28054, Severity: 11, State: 1.
spid59	Service Broker needs to access the master key in the database 'MyData'. Error code:26. The master key has to exist and the service master key encryption is required.
TIA !

Event Notifications: insufficient system memory

$
0
0

I'm looking for a sanity check.  Service broker and Event Notifications are new to me, so it is possible I'm either abusing or incorrectly using the technology.  I'm experimenting with using Event Notifications and Server Broker to log error messages.  The process works pretty well as long as I don't do something stupid such as stressing the process by calling raiserror in a loop of a 100000 - twice.  It processed for a while, but eventual either SQL Server terminates (sev 25) or I had to force the SQL service to stop by killing it's process via task manager.  I could not connect to SQL Server or stop the service normally.  

 

I have several general questions.  I think they are good questions.  Any thoughts or suggestions would be appreciated. 

 

1) I'm looking into generating deadlock and blocking email alerts.  It appears that Event Notification is the way to go since there are very few events and I can respond to the event with an email.  Is there a better method to automate blocking and deadlock email alerts that include event details? 

 

2) If I wanted to retain some history of errors for the developers, should Event Notifications be avoided if a high number of errors can be generated by a badly formed T-SQL?  Avoid TRC_ERRORS_AND_WARNINGS and USER_ERROR_MESSAGE?  (I could tell the developers not to be stupid, but why would that stop them if it does not stop me?)

 

3) Is there a way to efficiently filter a Event Notification from entering the queue before the Receive statement is called?  I get some events that I throw away after receiving them.  For example, perhaps I want all events from all non-system databases without having to add a notification for each single non-system database.  Or I want all errors with severity 11-17 only? 

 

4) Is there a trick to filter out events from the procedure activated by the event.  I tried using raiserror to debug a procedure without thinking.  The result was that the queue never was empty because the processing produced more events to process.  As a result, I don't use raiserror and use a try-catch to avoid raising errors in the procedure activated. 

 

5) I can receive one message at a time using local variables or receive a batch of messages using a local table.  Is a small batch the best way even if there is memory pressure? 

 

6) In the activated procedure I continue processing in a loop until there are no more messages.  This seems to be the most efficient.  Is this always the case?  Should I exit the procedure after a set number (large) of messages have been received?  The procedure would activate again to continue processing? 

 

7) Is there any point to using the MAX_QUEUE_READERS setting when processing event notifications?  Should it be 1? 

 

8) I currently get the next conversation group id and process its messages within a transaction.  Is this a bad idea with event notifications?  Should I just call Receive and get the next batch?  I don't really care if I lose some messages if things are going badly.  Should I avoid wrapping the receive in a transaction? 

 

9) I could run a trace that starts with SQL Server; however, I think my only choice is to log to a file.  Is there a way to trace to a table using SQLTrace without running profiler?  I would like to automate the process and have the data in a table so that it can be easily queried and parsed for each database/team. 

 

10) Is there a way to fix my process and handle 100000 messages a minute?  Is there a way to skip messages when it gets to busy?  Can the query generating the messages get throttled - perhaps along with the query designer - before the server gets into trouble?  Query the memory used by a queue and drop/create the queue with a delay if there is an issue? 

 

I'm using a single CPU test machine with only 1 GB and 2 GB pagefile and a single disk.  OS: Windows 2003 R2 SP2.  SQL: 9.0.3054 and on 9.0.3228 (update package 6 just came out today).  I could add memory, but I think that would just permit me to queue more message before running into trouble. 

 

I'll add code shortly - length limit.

Where is the query notification coming from?

$
0
0

When I execute a stored procedure and look at the execution plan, I see some "clustered index scans" where I'm not expecting them ... and they appear to be coming from "query_notification" objects.

Is there anyway in SQL Server to see what the source of the query notification is, and to actually stop or clear that notification?

Monitoring service broker queues through a .NET process

$
0
0

Is there a way for a .NET application to receive a notification when a service broker queue has been updated with a new message? I tried using SqlDependency on an SB queue but I got an "invalid" error in my notification  handler.

 

Such a notification would be much better than having to poll the queue every N seconds.

 

Thanks

 

How to handle sequence of my messages in this scenario?

$
0
0

Hi all,

I am sending two messages from Service1 to Service2. The first message indicates DELETE command to delete a row, the second message has the information for INSERTing a new row. Actually it's the process of updating a row but splitted into two phases (Delete/Insert at the target).

When I check the transmission queue at Service1 (initiator), my messages are queued correctly: First delete, Second insert.

But when they are delivered to Service2, they are not necessarily in the same order. Sometimes the Insert message is delivered earlier, that causes duplication of PK in my table.

How can I instruct SSB to deliver these messages to Service2 at the same order as they are queued in TQ at Service1?

Any help would be greatly appreciated.

Leila 

Event Notifications not firing - even with something very simple - ultimately i want the block_process_report to fire

$
0
0

So i am following the example here:  http://www.sqlservercentral.com/articles/Event+Notifications/68831/

When i get to this point there isn't anything returned from ErrorLogNotificationsQueue.  This is just the beginning of the problem because i really want deadlock and blocked process reports collected but i can't get this to work yet.

-- Test the Event Notification by raising an Error
RAISERROR (N'Test ERRORLOG Event Notifications', 10, 1) WITH LOG;
GO
SELECT *
FROM ErrorLogNotificationQueue
GO

Full SQL follows.

USE Master;
DROP EVENT NOTIFICATION CaptureErrorLogEvents  ON SERVER
GO
DROP DATABASE system_notifications;
GO
CREATE DATABASE system_notifications;
GO
ALTER DATABASE system_notifications
SET ENABLE_BROKER ;
GO
USE system_notifications;
GO
CREATE QUEUE ErrorLogNotificationQueue;
GO
CREATE SERVICE ErrorLogNotificationService
 ON QUEUE ErrorLogNotificationQueue ([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
GO
CREATE EVENT NOTIFICATION CaptureErrorLogEvents
 ON SERVER
 WITH FAN_IN
 FOR ERRORLOG
 TO SERVICE 'ErrorLogNotificationService', 'current database';
GO
-- Query the catalog to see the queue
SELECT *
FROM sys.service_queues
WHERE name = 'ErrorLogNotificationQueue';
GO
-- Query the catalog to see the service
SELECT *
FROM sys.services
WHERE name = 'ErrorLogNotificationService';
GO
-- Query the catalog to see the notification
SELECT *
FROM sys.server_event_notifications
WHERE name = 'CaptureErrorLogEvents';
GO
-- Test the Event Notification by raising an Error
RAISERROR (N'Test ERRORLOG Event Notifications', 10, 1) WITH LOG;
GO
SELECT *
FROM ErrorLogNotificationQueue
GO



-- dan http://dnhlmssql.blogspot.com/

Could not obtain information about Windows NT group/user .......error code 0x534...

$
0
0

== I asked this question directly to Remus and wanted to share the response to all of those people using this forum ==

We recently moved our database server from SQL Server 2000 to SQL Server 2005. All applications on our intranet development server stay the same [VS.NET 2003], but recently resources in our Dev DB server ran out of space. While doing a thorough investigation, I noticed ERRORLOG file was occupying about 35 Gig of HDD space. I immediately checked SQL Server error log and noticed an entry which says –

===========================================================================================

Date                 7/7/2006 4:45:37 PM

Log                   SQL Server (Current - 7/7/2006 4:45:00 PM)

Source              spid77s

Message

The activated proc [dbo].[SqlQueryNotificationStoredProcedure-5eaf8465-d0cb-4be7-93b6-44bb979dd41c] running on queue BW_Content.dbo.SqlQueryNotificationService-5eaf8465-d0cb-4be7-93b6-44bb979dd41c output the following:  'Could not obtain information about Windows NT group/user 'BWCINC\HoffK', error code 0x534.'

===========================================================================================

What is this SqlQueryNotificationService in my database? Is it a SQL Server 2005 thing? Why the same kind of stored procedure does not exist in other databases, but BW_Content? This error is getting repeated most probably every second and is filling up our server.

 I believe our corporate IT people removed our domain accounts from BWCINC domain to BWCORP domain and probably some application which is using BWCINC\HoffK credential is getting errored out. I tried to locate this application and was not successful.

 Is there anyway that I can stop this ERRORLOG from growing? How can I delete these log entries so that I can make space on our Hard Drive? Is there an easy way in SQL Server 2005 to locate which application is creating this error?

Response from Remus:

The 'SqlQueryNotificationService-...' is the service created by SqlDependency when you call SqlDependency.Start (). The problem you describe appears because the 'dbo' user of the database is mapped to the login that originally created this database. The SqlDependency created queue has an EXECUTE AS OWNER clause, owner is 'dbo' and therefore this is equivalent to an EXECUTE AS USER = 'dbo'. The error you see is reported by the domain controller when asked to give information about the original account 'dbo' mapps to (that is, BWCINC\HoffK'): Error code: (Win32) 0x534 (1332) - No mapping between account names and security IDs was done.
 
To solve the issue, change 'dbo' to match a correct login, using either sp_changedbowneror ALTER AUTHORIZATION ON DATABASE::[dbname] TO [somavalidlogin]
To find the databases that have this problem, run this query:

select

name,suser_sname(owner_sid)fromsys.databases
The databses that have the problem will show NULL on the second column.
 
To remove the entries, use sp_cycle_errorlog to force a new errorlog file, then delete the huge log file.
---------------------------------------
 
I executed ALTER AUTHORIZATION ON DATABASE::[BW_Content] TO [sa];
 
I got this error in SQL Error Log once and the growth of ERRORLOG was stopped.
===============================================================
Date                         7/10/2006 1:16:55 PM
Log                          SQL Server (Current - 7/10/2006 1:17:00 PM)
Source                    spid20s
 
Message

The query notification dialog on conversation handle '{6BDE95F7-0EFB-DA11-9064-000C2921B41B}.' closed due to the following error: '<?xml version="1.0"?><Error xmlns="http://schemas.microsoft.com/SQL/ServiceBroker/Error"><Code>-8490</Code><Description>Cannot find the remote service &apos;SqlQueryNotificationService-c15bb868-ed56-47d2-bf91-ce18b320989a&apos; because it does not exist.</Description></Error>'.
===============================================================
 
Should I be concerned about this error?
 
Thanks
-Binoy
Viewing all 461 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>