Skip to main content

Service Bus Queues from Windows Azure - How to iterate

In one of my last post I described how we can use Service Bus Queue from Windows Azure. Now, we will see if we can iterate through this queue.
In a normal MSMQ from Windows we could very simple iterate through the messages from the queue. We could get an iterator from this queue and after that is very simple to iterate.
Queue myQueue = ...
IEnumerator myQueueEnumerator = myQueue.GetEnumerator();
while(myQueueEnumerator.MoveNext())
{
var ourItemFromQueue = myQueueEnumerator.Current;
}

The GetEnumerator method generate an enumerator for queue with the current state of it. For example after we obtain the iterator we add another item in the queue, this item will not be obtained in the current iterator.
So we saw how we can iterate in through a MSMSQ. Nothing special, an old problem with classic solution. But how we can iterate through a Service Bus Queue?
If we look on the API that is available for QueueClient we will see that we don’t have any method to get the iterator for the current queue. In theory we should not be able to iterate the queue.
If you rememeber, in the last post that that describe how we can use a Service Bus Queue I told you about two ways to get a message from a queue. The receive&delete pattern when a message is automaticaly deleted from the queue when is send to the client.
The other option to consume messages from a Service Bus Queue is to get each message from the queue and send a confirmation call to the queue. This confirmation message notify the queue that the message was processed with success and can be removed from the queue. If we don’t send this confirmation message, after a specific type the message will be unlocked from the queue an other consumers will be able to process it. This expiration time period can be set when we create the queue.
If we set this experiation time period to a higher value (default value is 60 secconds), we can extract all the messages that a queue have using the Receive method and without calling the Complete() method. In this way all the messages that we will received will be automatically unlock after the given periond of time will pass and other consumer will be able to consume it.
QueueClient qc = ...;
int maxQueueNumber = 100;
List<BrokeredMessage> messages = new List<BrokeredMessage>();
try
{
while ( messages < maxQueueNumber )
{
messages.Add(qc.Receive(0));
}
}
catch(TimeoutException ex)
{
...
}
We specify the Receive tymeout to 0, because we don’t want to wait other messages to be added to the queue. The TimeoutException is throw when we will not have any more messages to the queue. Also we need to set a maxim limit of messages that we want to load from the queue. Be aware that there is a risk to add the same message twice in the queue if the confirmation timeout will expire. Because of this we should check if the message was already added to the queue. In this way we can detect the we excited this time and we don’t need anymore to iterate thgouth the Service Bus Queue. Each BrokeredMessage has a unique id that can be used for this check. The above code can be rewrite like this:
QueueClient qc = ...;
int maxQueueNumber = 100;
Dictionary<string,BrokeredMessage> messages = new Dictionary<,stringBrokeredMessage>();
try
{
while ( messages < maxQueueNumber )
{
BrokeredMessage message = qc.Receive(0);
string messageId = message.MessageId;
if (!messages.ContainsKey(messageId))
{
messages.Add(messageId,message);
}
else
{
break;
}
}
}
catch(TimeoutException ex)
{
...
}
This solution can work pretty good when we have queues that are not very big. Be aware that for each message that we received from the queue we will do two transcations and this can increase the our costs.
When we should use this „iteration“. Normally, if we use queues we should not have the need to iterate through a queue. The need of this is a warning for us that maybe soemthing we don’t do or use as we should. But a valid scenario to iterate thgouth a queue is when we want to debug our application and we need what messages we have in a queue. In this case this is the only way to see the messages from our Service Bus Queue.

Comments

Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…