-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
376 lines (316 loc) · 13.2 KB
/
MainWindow.xaml.cs
File metadata and controls
376 lines (316 loc) · 13.2 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Azure.Identity;
using Azure.Messaging.EventHubs.Consumer;
using Azure.ResourceManager;
using Azure.ResourceManager.EventHubs;
using Azure.ResourceManager.Resources;
using EventHubListener.Models;
namespace EventHubListener
{
public partial class MainWindow : Window, IDisposable
{
private DefaultAzureCredential _credential = null!;
private ArmClient _arm = null!;
private TenantResource? _selectedTenant;
private SubscriptionResource? _selectedSubscription;
private EventHubsNamespaceResource? _selectedNamespace;
private EventHubResource? _selectedEventHub;
private CancellationTokenSource? _listenCts;
private Task? _listenTask;
public ObservableCollection<SubscriptionItem> Subs { get; } = [];
public ObservableCollection<NamespaceItem> Namespaces { get; } = [];
public ObservableCollection<NamespaceItem> FilteredNamespaces { get; } = [];
public ObservableCollection<EventHubItem> EventHubs { get; } = [];
private static readonly JsonSerializerOptions _indentedJsonOptions = new() { WriteIndented = true };
private readonly string TenantId;
public MainWindow()
{
TenantId = ReadTenantIdFromConfig() ?? throw new InvalidOperationException("TenantId missing in config.");
InitializeComponent();
Loaded += MainWindow_Loaded;
SubCombo.ItemsSource = Subs;
NsCombo.ItemsSource = Namespaces;
EhCombo.ItemsSource = EventHubs;
}
private static string? ReadTenantIdFromConfig()
{
var exeDir = AppDomain.CurrentDomain.BaseDirectory;
var configPath = Path.Combine(exeDir, "appsettings.json");
if (!File.Exists(configPath))
throw new FileNotFoundException("Config file not found: " + configPath);
using var stream = File.OpenRead(configPath);
using var doc = JsonDocument.Parse(stream);
if (doc.RootElement.TryGetProperty("TenantId", out var tenantIdProp))
return tenantIdProp.GetString();
throw new InvalidOperationException("TenantId not found in config file.");
}
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
TenantIdBox.Text = TenantId;
try
{
_credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
TenantId = TenantId,
ExcludeInteractiveBrowserCredential = false
});
_arm = new ArmClient(_credential);
Subs.Clear();
Namespaces.Clear();
EventHubs.Clear();
_selectedSubscription = null;
_selectedNamespace = null;
_selectedEventHub = null;
TenantResource? tenant = null;
await foreach (var t in _arm.GetTenants().GetAllAsync())
{
if (t.Data.TenantId.ToString() == TenantId)
{
tenant = t;
break;
}
}
if (tenant is null)
{
MessageBox.Show(this, $"Tenant {TenantId} not found.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
TenantIdBox.Text = $"{tenant.Data.DisplayName} ({TenantId})";
_selectedTenant = tenant;
var subs = new List<SubscriptionItem>();
await foreach (var sub in _selectedTenant.GetSubscriptions().GetAllAsync())
{
subs.Add(new SubscriptionItem(sub, $"{sub.Data.DisplayName} ({sub.Data.SubscriptionId})"));
}
Subs.Clear();
foreach (var item in subs)
Subs.Add(item);
if (Subs.Count > 0)
{
SubCombo.IsEnabled = true;
SubCombo.SelectedIndex = 0;
}
}
catch (Exception ex)
{
MessageBox.Show(this, $"Błąd inicjalizacji: {ex.Message}", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private async void SubCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Namespaces.Clear();
EventHubs.Clear();
_selectedNamespace = null;
_selectedEventHub = null;
if (SubCombo.SelectedItem is SubscriptionItem s)
{
_selectedSubscription = s.Resource;
await LoadNamespacesAsync(_selectedSubscription);
}
}
private async Task LoadNamespacesAsync(SubscriptionResource subscription)
{
var namespaces = new List<NamespaceItem>();
await foreach (var ns in subscription.GetEventHubsNamespacesAsync())
{
var fqdn = ns.Data?.ServiceBusEndpoint ?? $"{ns.Data?.Name}.servicebus.windows.net";
namespaces.Add(new NamespaceItem(ns, $"{ns.Data?.Name} ({fqdn})", fqdn));
}
await Dispatcher.BeginInvoke(() =>
{
Namespaces.Clear();
foreach (var item in namespaces)
Namespaces.Add(item);
if (Namespaces.Count > 0)
{
NsCombo.IsEnabled = true;
NsCombo.SelectedIndex = 0;
}
});
}
private async void NsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
EventHubs.Clear();
_selectedEventHub = null;
if (NsCombo.SelectedItem is NamespaceItem nsi)
{
_selectedNamespace = nsi.Resource;
await LoadEventHubsAsync(_selectedNamespace);
}
}
private void NsCombo_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Enter || e.Key == Key.Tab)
return;
var textBox = GetComboBoxTextBox(NsCombo);
int caretIndex = textBox?.CaretIndex ?? NsCombo.Text.Length;
int selLength = textBox?.SelectionLength ?? 0;
var text = NsCombo.Text;
var textLower = text.ToLowerInvariant();
List<NamespaceItem> localNamespaces;
lock (Namespaces)
{
localNamespaces = [.. Namespaces];
}
FilteredNamespaces.Clear();
foreach (var ns in localNamespaces.Where(n => n.Display.Contains(textLower, StringComparison.InvariantCultureIgnoreCase)))
{
FilteredNamespaces.Add(ns);
}
NsCombo.ItemsSource = FilteredNamespaces;
NsCombo.IsDropDownOpen = true;
NsCombo.Text = text;
if (textBox != null)
{
textBox.CaretIndex = caretIndex;
textBox.SelectionLength = selLength;
}
}
private void EhCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (EhCombo.SelectedItem is EventHubItem)
{
ConsumerGroupBox.IsEnabled = true;
StartButton.IsEnabled = true;
FromLatestCheck.IsEnabled = true;
}
else
StartButton.IsEnabled = false;
_selectedEventHub = EhCombo.SelectedItem is EventHubItem eh ? eh.Resource : null;
}
private async Task LoadEventHubsAsync(EventHubsNamespaceResource ns)
{
var eventHubs = new List<EventHubItem>();
await foreach (var eh in ns.GetEventHubs().GetAllAsync())
{
eventHubs.Add(new EventHubItem(eh, eh.Data.Name));
}
await Dispatcher.BeginInvoke(() =>
{
EventHubs.Clear();
foreach (var item in eventHubs)
EventHubs.Add(item);
if (EventHubs.Count > 0)
{
EhCombo.IsEnabled = true;
EhCombo.SelectedIndex = 0;
}
});
}
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
if (EhCombo.SelectedItem is not EventHubItem ehItem)
{
MessageBox.Show(this, "Select Event Hub.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
_selectedEventHub = ehItem.Resource;
if (NsCombo.SelectedItem is not NamespaceItem nsItem)
{
MessageBox.Show(this, "Select Event Hub Namespace.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
string fqdn = nsItem.FullyQualifiedNamespace;
string hubName = _selectedEventHub.Data.Name;
string consumerGroup = string.IsNullOrWhiteSpace(ConsumerGroupBox.Text)
? EventHubConsumerClient.DefaultConsumerGroupName
: ConsumerGroupBox.Text.Trim();
bool fromLatest = FromLatestCheck.IsChecked == true;
await Dispatcher.BeginInvoke(() =>
{
DisableSelectors(true);
StartButton.IsEnabled = false;
StopButton.IsEnabled = true;
});
AppendLine($">>> Start listening: {fqdn} / {hubName} / cg: {consumerGroup}");
_listenCts = new CancellationTokenSource();
_listenTask = Task.Run(async () =>
{
try
{
await ListenLoopAsync(fqdn, hubName, consumerGroup, fromLatest, _listenCts.Token);
}
catch (OperationCanceledException)
{
AppendLine(">>> Listening canceled.");
}
catch (Exception ex)
{
AppendLine($">>> ERROR: {ex.Message}");
}
finally
{
await Dispatcher.BeginInvoke(() =>
{
StopButton.IsEnabled = false;
StartButton.IsEnabled = true;
DisableSelectors(false);
});
}
});
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
_listenCts?.Cancel();
}
private async Task ListenLoopAsync(string fqdn, string hubName, string consumerGroup, bool fromLatest, CancellationToken ct)
{
var startPosition = fromLatest ? EventPosition.Latest : EventPosition.Earliest;
await using var client = new EventHubConsumerClient(consumerGroup, fqdn, hubName, _credential);
await foreach (PartitionEvent ev in client.ReadEventsAsync(ct))
{
if (ev.Data != null)
{
var enqueued = ev.Data.EnqueuedTime.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff 'UTC'", CultureInfo.InvariantCulture);
var bodyBytes = ev.Data.Body.ToArray();
string bodyRaw = Encoding.UTF8.GetString(bodyBytes);
string bodyBeautified = bodyRaw;
try
{
using var doc = JsonDocument.Parse(bodyRaw);
bodyBeautified = JsonSerializer.Serialize(doc, _indentedJsonOptions);
}
catch { }
var systemProps = string.Join(", ", ev.Data.SystemProperties.Select(kvp => $"{kvp.Key}={kvp.Value}"));
var appProps = string.Join(", ", ev.Data.Properties.Select(kvp => $"{kvp.Key}={kvp.Value}"));
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"[{enqueued}]");
sb.AppendLine(bodyBeautified);
sb.AppendLine();
AppendLine(sb.ToString());
}
}
}
private void AppendLine(string text)
{
Dispatcher.BeginInvoke(() =>
{
OutputBox.AppendText(text + Environment.NewLine);
OutputBox.ScrollToEnd();
});
}
private void DisableSelectors(bool disable)
{
SubCombo.IsEnabled = !disable;
NsCombo.IsEnabled = !disable;
EhCombo.IsEnabled = !disable;
ConsumerGroupBox.IsEnabled = !disable;
FromLatestCheck.IsEnabled = !disable;
}
private static TextBox? GetComboBoxTextBox(ComboBox comboBox)
{
return comboBox.Template.FindName("PART_EditableTextBox", comboBox) as TextBox;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
}