forked from Azure/azure-service-bus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
164 lines (142 loc) · 6.49 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//
// Copyright © Microsoft Corporation, All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
// ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
// PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache License, Version 2.0 for the specific language
// governing permissions and limitations under the License.
namespace SendersReceiversWithQueues
{
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
public class Program : MessagingSamples.Sample
{
async Task SendMessagesAsync(string connectionString, string queueName)
{
var senderFactory = MessagingFactory.CreateFromConnectionString(connectionString);
var sender = await senderFactory.CreateMessageSenderAsync(queueName);
dynamic data = new[]
{
new {name = "Einstein", firstName = "Albert"},
new {name = "Heisenberg", firstName = "Werner"},
new {name = "Curie", firstName = "Marie"},
new {name = "Hawking", firstName = "Steven"},
new {name = "Newton", firstName = "Isaac"},
new {name = "Bohr", firstName = "Niels"},
new {name = "Faraday", firstName = "Michael"},
new {name = "Galilei", firstName = "Galileo"},
new {name = "Kepler", firstName = "Johannes"},
new {name = "Kopernikus", firstName = "Nikolaus"}
};
for (int i = 0; i < data.Length; i++)
{
var message = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data[i]))))
{
ContentType = "application/json",
Label = "Scientist",
MessageId = i.ToString(),
TimeToLive = TimeSpan.FromMinutes(2)
};
await sender.SendAsync(message);
lock (Console.Out)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Message sent: Id = {0}", message.MessageId);
Console.ResetColor();
}
}
}
async Task ReceiveMessagesAsync(string connectionString, string queueName, CancellationToken cancellationToken)
{
var receiverFactory = MessagingFactory.CreateFromConnectionString(connectionString);
var receiver = await receiverFactory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock);
var doneReceiving = new TaskCompletionSource<bool>();
// close the receiver and factory when the CancellationToken fires
cancellationToken.Register(
async () =>
{
await receiver.CloseAsync();
await receiverFactory.CloseAsync();
doneReceiving.SetResult(true);
});
// register the OnMessageAsync callback
receiver.OnMessageAsync(
async message =>
{
if (message.Label != null &&
message.ContentType != null &&
message.Label.Equals("Scientist", StringComparison.InvariantCultureIgnoreCase) &&
message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
{
var body = message.GetBody<Stream>();
dynamic scientist = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd());
lock (Console.Out)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(
"\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = {0}, \n\t\t\t\t\t\tSequenceNumber = {1}, \n\t\t\t\t\t\tEnqueuedTimeUtc = {2}," +
"\n\t\t\t\t\t\tExpiresAtUtc = {5}, \n\t\t\t\t\t\tContentType = \"{3}\", \n\t\t\t\t\t\tSize = {4}, \n\t\t\t\t\t\tContent: [ firstName = {6}, name = {7} ]",
message.MessageId,
message.SequenceNumber,
message.EnqueuedTimeUtc,
message.ContentType,
message.Size,
message.ExpiresAtUtc,
scientist.firstName,
scientist.name);
Console.ResetColor();
}
await message.CompleteAsync();
}
else
{
await message.DeadLetterAsync("ProcessingError", "Don't know what to do with this message");
}
},
new OnMessageOptions {AutoComplete = false, MaxConcurrentCalls = 1});
await doneReceiving.Task;
}
public async Task Run(string connectionString)
{
Console.WriteLine("Press any key to exit the scenario");
var cts = new CancellationTokenSource();
var sendTask = this.SendMessagesAsync(connectionString, BasicQueueName);
var receiveTask = this.ReceiveMessagesAsync(connectionString, BasicQueueName, cts.Token);
await Task.WhenAny(
Task.Run(() => Console.ReadKey()),
Task.Delay(TimeSpan.FromSeconds(10))
);
cts.Cancel();
await Task.WhenAll(sendTask, receiveTask);
}
public static int Main(string[] args)
{
try
{
var app = new Program();
app.RunSample(args, app.Run);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return 1;
}
return 0;
}
}
}