diff --git a/PurpleExplorer/App.xaml.cs b/PurpleExplorer/App.xaml.cs index d73f642..57d9e45 100644 --- a/PurpleExplorer/App.xaml.cs +++ b/PurpleExplorer/App.xaml.cs @@ -10,36 +10,35 @@ using ReactiveUI; using Splat; -namespace PurpleExplorer +namespace PurpleExplorer; + +public class App : Application { - public class App : Application + public override void Initialize() { - public override void Initialize() - { - AvaloniaXamlLoader.Load(this); - } + AvaloniaXamlLoader.Load(this); + } - public override void OnFrameworkInitializationCompleted() + public override void OnFrameworkInitializationCompleted() + { + var appStatePath = "appstate.json"; + if (!File.Exists(appStatePath)) { - var appStatePath = "appstate.json"; - if (!File.Exists(appStatePath)) - { - File.Create(appStatePath).Close(); - } + File.Create(appStatePath).Close(); + } - var suspension = new AutoSuspendHelper(ApplicationLifetime); - RxApp.SuspensionHost.CreateNewAppState = () => new AppState(); - RxApp.SuspensionHost.SetupDefaultSuspendResume(new NewtonsoftJsonSuspensionDriver(appStatePath)); - suspension.OnFrameworkInitializationCompleted(); - var state = RxApp.SuspensionHost.GetAppState(); + var suspension = new AutoSuspendHelper(ApplicationLifetime); + RxApp.SuspensionHost.CreateNewAppState = () => new AppState(); + RxApp.SuspensionHost.SetupDefaultSuspendResume(new NewtonsoftJsonSuspensionDriver(appStatePath)); + suspension.OnFrameworkInitializationCompleted(); + var state = RxApp.SuspensionHost.GetAppState(); - Locator.CurrentMutable.RegisterLazySingleton(() => state, typeof(IAppState)); - Locator.CurrentMutable.RegisterLazySingleton(() => new LoggingService(), typeof(ILoggingService)); - Locator.CurrentMutable.Register(() => new TopicHelper(state.AppSettings), typeof(ITopicHelper)); - Locator.CurrentMutable.Register(() => new QueueHelper(state.AppSettings), typeof(IQueueHelper)); + Locator.CurrentMutable.RegisterLazySingleton(() => state, typeof(IAppState)); + Locator.CurrentMutable.RegisterLazySingleton(() => new LoggingService(), typeof(ILoggingService)); + Locator.CurrentMutable.Register(() => new TopicHelper(state.AppSettings), typeof(ITopicHelper)); + Locator.CurrentMutable.Register(() => new QueueHelper(state.AppSettings), typeof(IQueueHelper)); - new MainWindow { DataContext = new MainWindowViewModel() }.Show(); - base.OnFrameworkInitializationCompleted(); - } + new MainWindow { DataContext = new MainWindowViewModel() }.Show(); + base.OnFrameworkInitializationCompleted(); } } \ No newline at end of file diff --git a/PurpleExplorer/Helpers/AppVersionHelper.cs b/PurpleExplorer/Helpers/AppVersionHelper.cs index c8d4247..5c2244a 100644 --- a/PurpleExplorer/Helpers/AppVersionHelper.cs +++ b/PurpleExplorer/Helpers/AppVersionHelper.cs @@ -3,34 +3,35 @@ using System.Threading.Tasks; using Newtonsoft.Json; -namespace PurpleExplorer.Services +namespace PurpleExplorer.Helpers; + +public static class AppVersionHelper { - public static class AppVersionHelper + public static async Task GetLatestRelease() { - public static async Task GetLatestRelease() - { - using (var httpClient = new HttpClient()) - { - httpClient.DefaultRequestHeaders.Add("User-Agent", "Application"); - var response = - await httpClient.GetAsync( - "https://api.github.com/repos/telstrapurple/PurpleExplorer/releases/latest"); - var content = await response.Content.ReadAsStringAsync(); - var githubRelease = JsonConvert.DeserializeObject(content); - return githubRelease; - } - } + using var httpClient = new HttpClient(); + httpClient.DefaultRequestHeaders.Add("User-Agent", "Application"); + var response = + await httpClient.GetAsync( + "https://api.github.com/repos/telstrapurple/PurpleExplorer/releases/latest"); + var content = await response.Content.ReadAsStringAsync(); + var githubRelease = JsonConvert.DeserializeObject(content); + return githubRelease; } +} - public class GithubRelease - { - public int id { get; set; } - public string url { get; set; } - public string html_url { get; set; } - public string tag_name { get; set; } - public string name { get; set; } - public DateTime created_at { get; set; } - public DateTime published_at { get; set; } - public string body { get; set; } - } +public class GithubRelease +{ + [JsonProperty("id")] + public int Id { get; set; } + [JsonProperty("url")] + public string Url { get; set; } + [JsonProperty("html_url")] + public string HtmlUrl { get; set; } + [JsonProperty("name")] + public string Name { get; set; } + [JsonProperty("created_at")] + public DateTime CreatedAt { get; set; } + [JsonProperty("published_at")] + public DateTime PublishedAt { get; set; } } \ No newline at end of file diff --git a/PurpleExplorer/Helpers/BaseHelper.cs b/PurpleExplorer/Helpers/BaseHelper.cs index 7544ac7..17fa0db 100644 --- a/PurpleExplorer/Helpers/BaseHelper.cs +++ b/PurpleExplorer/Helpers/BaseHelper.cs @@ -5,59 +5,53 @@ using Microsoft.Azure.ServiceBus.Primitives; using PurpleExplorer.Models; -namespace PurpleExplorer.Helpers -{ - public class BaseHelper - { - public BaseHelper() - { - } +namespace PurpleExplorer.Helpers; - protected ManagementClient GetManagementClient(ServiceBusConnectionString connectionString) +public abstract class BaseHelper +{ + protected ManagementClient GetManagementClient(ServiceBusConnectionString connectionString) + { + if (connectionString.UseManagedIdentity) { - if (connectionString.UseManagedIdentity) - { - var tokenProvider = GetTokenProvider(connectionString); - return new ManagementClient(connectionString.ConnectionString, tokenProvider); - } - else - { - return new ManagementClient(connectionString.ConnectionString); - } + var tokenProvider = GetTokenProvider(connectionString); + return new ManagementClient(connectionString.ConnectionString, tokenProvider); } - - protected TokenProvider GetTokenProvider(ServiceBusConnectionString connectionString) + else { - if (connectionString.UseManagedIdentity) - { - return TokenProvider.CreateManagedIdentityTokenProvider(); - } - else - { - throw new NotImplementedException("Unknown token provider."); - } + return new ManagementClient(connectionString.ConnectionString); } + } - protected MessageReceiver GetMessageReceiver(ServiceBusConnectionString connectionString, string path, ReceiveMode receiveMode) + private TokenProvider GetTokenProvider(ServiceBusConnectionString connectionString) + { + if (connectionString.UseManagedIdentity) { - return connectionString.UseManagedIdentity - ? new MessageReceiver(connectionString.ConnectionString, path, GetTokenProvider(connectionString), receiveMode: receiveMode) - : new MessageReceiver(connectionString.ConnectionString, path, receiveMode); + return TokenProvider.CreateManagedIdentityTokenProvider(); } - - protected TopicClient GetTopicClient(ServiceBusConnectionString connectionString, string path) + else { - return connectionString.UseManagedIdentity - ? new TopicClient(connectionString.ConnectionString, path, GetTokenProvider(connectionString)) - : new TopicClient(connectionString.ConnectionString, path); + throw new NotImplementedException("Unknown token provider."); } + } - protected QueueClient GetQueueClient(ServiceBusConnectionString connectionString, string queueName) - { - return connectionString.UseManagedIdentity - ? new QueueClient(connectionString.ConnectionString, queueName, GetTokenProvider(connectionString)) - : new QueueClient(connectionString.ConnectionString, queueName); - } + protected MessageReceiver GetMessageReceiver(ServiceBusConnectionString connectionString, string path, ReceiveMode receiveMode) + { + return connectionString.UseManagedIdentity + ? new MessageReceiver(connectionString.ConnectionString, path, GetTokenProvider(connectionString), receiveMode: receiveMode) + : new MessageReceiver(connectionString.ConnectionString, path, receiveMode); } -} + protected TopicClient GetTopicClient(ServiceBusConnectionString connectionString, string path) + { + return connectionString.UseManagedIdentity + ? new TopicClient(connectionString.ConnectionString, path, GetTokenProvider(connectionString)) + : new TopicClient(connectionString.ConnectionString, path); + } + + protected QueueClient GetQueueClient(ServiceBusConnectionString connectionString, string queueName) + { + return connectionString.UseManagedIdentity + ? new QueueClient(connectionString.ConnectionString, queueName, GetTokenProvider(connectionString)) + : new QueueClient(connectionString.ConnectionString, queueName); + } +} \ No newline at end of file diff --git a/PurpleExplorer/Helpers/Extensions.cs b/PurpleExplorer/Helpers/Extensions.cs index a25649d..8d8c894 100644 --- a/PurpleExplorer/Helpers/Extensions.cs +++ b/PurpleExplorer/Helpers/Extensions.cs @@ -1,19 +1,18 @@ using AzureMessage = Microsoft.Azure.ServiceBus.Message; -namespace PurpleExplorer.Helpers +namespace PurpleExplorer.Helpers; + +public static class Extensions { - public static class Extensions + public static AzureMessage CloneMessage(this AzureMessage original) { - public static AzureMessage CloneMessage(this AzureMessage original) + return new AzureMessage { - return new AzureMessage - { - Body = original.Body, - Label = original.Label, - To = original.To, - SessionId = original.SessionId, - ContentType = original.ContentType - }; - } + Body = original.Body, + Label = original.Label, + To = original.To, + SessionId = original.SessionId, + ContentType = original.ContentType + }; } } \ No newline at end of file diff --git a/PurpleExplorer/Helpers/IQueueHelper.cs b/PurpleExplorer/Helpers/IQueueHelper.cs index 33cbdb4..ef78004 100644 --- a/PurpleExplorer/Helpers/IQueueHelper.cs +++ b/PurpleExplorer/Helpers/IQueueHelper.cs @@ -4,20 +4,19 @@ using Message = PurpleExplorer.Models.Message; using AzureMessage = Microsoft.Azure.ServiceBus.Message; -namespace PurpleExplorer.Helpers +namespace PurpleExplorer.Helpers; + +public interface IQueueHelper { - public interface IQueueHelper - { - Task> GetQueues(ServiceBusConnectionString connectionString); - public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, string content); - public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, AzureMessage message); - Task> GetMessages(ServiceBusConnectionString connectionString, string queueName); - Task> GetDlqMessages(ServiceBusConnectionString connectionString, string queueName); - Task DeadletterMessage(ServiceBusConnectionString connectionString, string queue, Message message); - Task DeleteMessage(ServiceBusConnectionString connectionString, string queue, - Message message, bool isDlq); - Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string queue, Message message); - Task PurgeMessages(ServiceBusConnectionString connectionString, string queue, bool isDlq); - Task TransferDlqMessages(ServiceBusConnectionString connectionString, string queue); - } + Task> GetQueues(ServiceBusConnectionString connectionString); + public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, string content); + public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, AzureMessage message); + Task> GetMessages(ServiceBusConnectionString connectionString, string queueName); + Task> GetDlqMessages(ServiceBusConnectionString connectionString, string queueName); + Task DeadletterMessage(ServiceBusConnectionString connectionString, string queue, Message message); + Task DeleteMessage(ServiceBusConnectionString connectionString, string queue, + Message message, bool isDlq); + Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string queue, Message message); + Task PurgeMessages(ServiceBusConnectionString connectionString, string queue, bool isDlq); + Task TransferDlqMessages(ServiceBusConnectionString connectionString, string queue); } \ No newline at end of file diff --git a/PurpleExplorer/Helpers/ITopicHelper.cs b/PurpleExplorer/Helpers/ITopicHelper.cs index 829f340..0e7b6cf 100644 --- a/PurpleExplorer/Helpers/ITopicHelper.cs +++ b/PurpleExplorer/Helpers/ITopicHelper.cs @@ -4,25 +4,24 @@ using PurpleExplorer.Models; using AzureMessage = Microsoft.Azure.ServiceBus.Message; -namespace PurpleExplorer.Helpers +namespace PurpleExplorer.Helpers; + +public interface ITopicHelper { - public interface ITopicHelper - { - public Task GetNamespaceInfo(ServiceBusConnectionString connectionString); - public Task> GetTopicsAndSubscriptions(ServiceBusConnectionString connectionString); - public Task GetTopic(ServiceBusConnectionString connectionString, string topicPath, bool retrieveSubscriptions); - public Task> GetSubscriptions(ServiceBusConnectionString connectionString, string topicPath); - public Task GetSubscription(ServiceBusConnectionString connectionString, string topicPath, string subscriptionName); - public Task> GetDlqMessages(ServiceBusConnectionString connectionString, string topic, string subscription); - public Task> GetMessagesBySubscription(ServiceBusConnectionString connectionString, string topicName, string subscriptionName); - public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, string content); - public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, AzureMessage message); - public Task DeleteMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, Message message, bool isDlq); - public Task PurgeMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, bool isDlq); - public Task TransferDlqMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath); - public Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, - Message message); - public Task DeadletterMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, - Message message); - } + public Task GetNamespaceInfo(ServiceBusConnectionString connectionString); + public Task> GetTopicsAndSubscriptions(ServiceBusConnectionString connectionString); + public Task GetTopic(ServiceBusConnectionString connectionString, string topicPath, bool retrieveSubscriptions); + public Task> GetSubscriptions(ServiceBusConnectionString connectionString, string topicPath); + public Task GetSubscription(ServiceBusConnectionString connectionString, string topicPath, string subscriptionName); + public Task> GetDlqMessages(ServiceBusConnectionString connectionString, string topic, string subscription); + public Task> GetMessagesBySubscription(ServiceBusConnectionString connectionString, string topicName, string subscriptionName); + public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, string content); + public Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, AzureMessage message); + public Task DeleteMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, Message message, bool isDlq); + public Task PurgeMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, bool isDlq); + public Task TransferDlqMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath); + public Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, + Message message); + public Task DeadletterMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, + Message message); } \ No newline at end of file diff --git a/PurpleExplorer/Helpers/MessageBoxHelper.cs b/PurpleExplorer/Helpers/MessageBoxHelper.cs index 84b79f7..6f418b4 100644 --- a/PurpleExplorer/Helpers/MessageBoxHelper.cs +++ b/PurpleExplorer/Helpers/MessageBoxHelper.cs @@ -4,40 +4,41 @@ using MessageBox.Avalonia.Enums; using System.Threading.Tasks; -namespace PurpleExplorer.Helpers +namespace PurpleExplorer.Helpers; + +public static class MessageBoxHelper { - public class MessageBoxHelper + public static async Task ShowConfirmation(string title, string message) { - public static async Task ShowConfirmation(string title, string message) - { - return await ShowMessageBox(ButtonEnum.YesNo, Icon.Warning, title, message); - } + return await ShowMessageBox(ButtonEnum.YesNo, Icon.Warning, title, message); + } - public static async Task ShowError(string message) - { - return await ShowMessageBox(ButtonEnum.Ok, Icon.Error, "Error", message); - } + // ReSharper disable once UnusedMethodReturnValue.Global + public static async Task ShowError(string message) + { + return await ShowMessageBox(ButtonEnum.Ok, Icon.Error, "Error", message); + } - public static async Task ShowMessage(string title, string message) - { - return await ShowMessageBox(ButtonEnum.Ok, Icon.Info, title, message); - } - - public static async Task ShowMessageBox(ButtonEnum buttons, Icon icon, string title, string message) + // ReSharper disable once UnusedMethodReturnValue.Global + public static async Task ShowMessage(string title, string message) + { + return await ShowMessageBox(ButtonEnum.Ok, Icon.Info, title, message); + } + + private static async Task ShowMessageBox(ButtonEnum buttons, Icon icon, string title, string message) + { + var msBoxStandardWindow = MessageBox.Avalonia.MessageBoxManager.GetMessageBoxStandardWindow(new MessageBoxStandardParams { - var msBoxStandardWindow = MessageBox.Avalonia.MessageBoxManager.GetMessageBoxStandardWindow(new MessageBoxStandardParams - { - ButtonDefinitions = buttons, - ContentTitle = title, - ContentMessage = message, - ShowInCenter = true, - Icon = icon, - CanResize = true, - WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterOwner - }); + ButtonDefinitions = buttons, + ContentTitle = title, + ContentMessage = message, + ShowInCenter = true, + Icon = icon, + CanResize = true, + WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterOwner + }); - return await msBoxStandardWindow.ShowDialog((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime) - .Windows[0]); - } + return await msBoxStandardWindow.ShowDialog((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime) + .Windows[0]); } -} +} \ No newline at end of file diff --git a/PurpleExplorer/Helpers/ModalWindowHelper.cs b/PurpleExplorer/Helpers/ModalWindowHelper.cs index bb7bbda..9dab26d 100644 --- a/PurpleExplorer/Helpers/ModalWindowHelper.cs +++ b/PurpleExplorer/Helpers/ModalWindowHelper.cs @@ -4,35 +4,34 @@ using PurpleExplorer.ViewModels; using System.Threading.Tasks; -namespace PurpleExplorer.Helpers +namespace PurpleExplorer.Helpers; + +public static class ModalWindowHelper { - public class ModalWindowHelper + public static async Task ShowModalWindow(ViewModelBase viewModel) where T : Window, new() { - public static async Task ShowModalWindow(ViewModelBase viewModel) where T : Window, new() - { - var mainWindow = (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime) - .Windows[0]; + var mainWindow = (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime) + .Windows[0]; - var window = new T - { - DataContext = viewModel - }; + var window = new T + { + DataContext = viewModel + }; - await window.ShowDialog(mainWindow); - } + await window.ShowDialog(mainWindow); + } - public static async Task ShowModalWindow(ViewModelBase viewModel) where T : Window, new() where U : ViewModelBase - { - var mainWindow = (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime) - .Windows[0]; + public static async Task ShowModalWindow(ViewModelBase viewModel) where T : Window, new() where U : ViewModelBase + { + var mainWindow = (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime) + .Windows[0]; - var window = new T - { - DataContext = viewModel - }; + var window = new T + { + DataContext = viewModel + }; - await window.ShowDialog(mainWindow); - return window.DataContext as U; - } + await window.ShowDialog(mainWindow); + return window.DataContext as U; } -} +} \ No newline at end of file diff --git a/PurpleExplorer/Helpers/QueueHelper.cs b/PurpleExplorer/Helpers/QueueHelper.cs index d1f8574..1e674da 100644 --- a/PurpleExplorer/Helpers/QueueHelper.cs +++ b/PurpleExplorer/Helpers/QueueHelper.cs @@ -5,152 +5,178 @@ using System.Threading.Tasks; using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Core; -using Microsoft.Azure.ServiceBus.Management; using PurpleExplorer.Models; using Message = PurpleExplorer.Models.Message; using AzureMessage = Microsoft.Azure.ServiceBus.Message; -namespace PurpleExplorer.Helpers +namespace PurpleExplorer.Helpers; + +public class QueueHelper : BaseHelper, IQueueHelper { - public class QueueHelper : BaseHelper, IQueueHelper + private readonly AppSettings _appSettings; + + public QueueHelper(AppSettings appSettings) { - private readonly AppSettings _appSettings; + _appSettings = appSettings; + } - public QueueHelper(AppSettings appSettings) + public async Task> GetQueues(ServiceBusConnectionString connectionString) + { + IList queues = new List(); + var client = GetManagementClient(connectionString); + var queuesInfo = await client.GetQueuesRuntimeInfoAsync(_appSettings.QueueListFetchCount); + await client.CloseAsync(); + + await Task.WhenAll(queuesInfo.Select(async queue => { - _appSettings = appSettings; - } + var queueName = queue.Path; - public async Task> GetQueues(ServiceBusConnectionString connectionString) - { - IList queues = new List(); - var client = GetManagementClient(connectionString); - var queuesInfo = await client.GetQueuesRuntimeInfoAsync(_appSettings.QueueListFetchCount); - await client.CloseAsync(); - - await Task.WhenAll(queuesInfo.Select(async queue => + var newQueue = new ServiceBusQueue(queue) { - var queueName = queue.Path; - - var newQueue = new ServiceBusQueue(queue) - { - Name = queueName - }; + Name = queueName + }; - queues.Add(newQueue); - })); + queues.Add(newQueue); + })); - return queues; - } + return queues; + } - public async Task SendMessage(ServiceBusConnectionString connectionString, string queueName, string content) - { - var message = new AzureMessage {Body = Encoding.UTF8.GetBytes(content)}; - await SendMessage(connectionString, queueName, message); - } + public async Task SendMessage(ServiceBusConnectionString connectionString, string queueName, string content) + { + var message = new AzureMessage {Body = Encoding.UTF8.GetBytes(content)}; + await SendMessage(connectionString, queueName, message); + } - public async Task SendMessage(ServiceBusConnectionString connectionString, string queueName, AzureMessage message) - { - var client = GetQueueClient(connectionString, queueName); - await client.SendAsync(message); - await client.CloseAsync(); - } + public async Task SendMessage(ServiceBusConnectionString connectionString, string queueName, AzureMessage message) + { + var client = GetQueueClient(connectionString, queueName); + await client.SendAsync(message); + await client.CloseAsync(); + } - public async Task> GetMessages(ServiceBusConnectionString connectionString, string queueName) - { - var receiver = GetMessageReceiver(connectionString, queueName, ReceiveMode.PeekLock); - var messages = await receiver.PeekAsync(_appSettings.QueueMessageFetchCount); - return messages.Select(msg => new Message(msg, false)).ToList(); - } + public async Task> GetMessages(ServiceBusConnectionString connectionString, string queueName) + { + var receiver = GetMessageReceiver(connectionString, queueName, ReceiveMode.PeekLock); + var messages = await receiver.PeekAsync(_appSettings.QueueMessageFetchCount); + return messages.Select(msg => new Message(msg, false)).ToList(); + } - public async Task> GetDlqMessages(ServiceBusConnectionString connectionString, string queueName) - { - var deadletterPath = EntityNameHelper.FormatDeadLetterPath(queueName); + public async Task> GetDlqMessages(ServiceBusConnectionString connectionString, string queueName) + { + var deadletterPath = EntityNameHelper.FormatDeadLetterPath(queueName); - var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); - var receivedMessages = await receiver.PeekAsync(_appSettings.QueueMessageFetchCount); - await receiver.CloseAsync(); + var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); + var receivedMessages = await receiver.PeekAsync(_appSettings.QueueMessageFetchCount); + await receiver.CloseAsync(); - return receivedMessages.Select(message => new Message(message, true)).ToList(); - } + return receivedMessages.Select(message => new Message(message, true)).ToList(); + } - public async Task DeadletterMessage(ServiceBusConnectionString connectionString, string queue, Message message) - { - var receiver = GetMessageReceiver(connectionString, queue, ReceiveMode.PeekLock); + public async Task DeadletterMessage(ServiceBusConnectionString connectionString, string queue, Message message) + { + var receiver = GetMessageReceiver(connectionString, queue, ReceiveMode.PeekLock); - while (true) + while (true) + { + var messages = await receiver.ReceiveAsync(_appSettings.QueueMessageFetchCount); + if (messages == null || messages.Count == 0) { - var messages = await receiver.ReceiveAsync(_appSettings.QueueMessageFetchCount); - if (messages == null || messages.Count == 0) - { - break; - } - - var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); - if (foundMessage != null) - { - await receiver.DeadLetterAsync(foundMessage.SystemProperties.LockToken); - break; - } + break; } - await receiver.CloseAsync(); + var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); + if (foundMessage != null) + { + await receiver.DeadLetterAsync(foundMessage.SystemProperties.LockToken); + break; + } } + + await receiver.CloseAsync(); + } - public async Task DeleteMessage(ServiceBusConnectionString connectionString, string queue, - Message message, bool isDlq) - { - var path = isDlq ? EntityNameHelper.FormatDeadLetterPath(queue) : queue; + public async Task DeleteMessage(ServiceBusConnectionString connectionString, string queue, + Message message, bool isDlq) + { + var path = isDlq ? EntityNameHelper.FormatDeadLetterPath(queue) : queue; - var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); + var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); - while (true) + while (true) + { + var messages = await receiver.ReceiveAsync(_appSettings.QueueMessageFetchCount); + if (messages == null || messages.Count == 0) { - var messages = await receiver.ReceiveAsync(_appSettings.QueueMessageFetchCount); - if (messages == null || messages.Count == 0) - { - break; - } - - var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); - if (foundMessage != null) - { - await receiver.CompleteAsync(foundMessage.SystemProperties.LockToken); - break; - } + break; } - await receiver.CloseAsync(); + var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); + if (foundMessage != null) + { + await receiver.CompleteAsync(foundMessage.SystemProperties.LockToken); + break; + } } + + await receiver.CloseAsync(); + } - private async Task PeekDlqMessageBySequenceNumber(ServiceBusConnectionString connectionString, string queue, long sequenceNumber) - { - var deadletterPath = EntityNameHelper.FormatDeadLetterPath(queue); + private async Task PeekDlqMessageBySequenceNumber(ServiceBusConnectionString connectionString, string queue, long sequenceNumber) + { + var deadletterPath = EntityNameHelper.FormatDeadLetterPath(queue); - var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); - var azureMessage = await receiver.PeekBySequenceNumberAsync(sequenceNumber); - await receiver.CloseAsync(); + var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); + var azureMessage = await receiver.PeekBySequenceNumberAsync(sequenceNumber); + await receiver.CloseAsync(); - return azureMessage; - } + return azureMessage; + } - public async Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string queue, Message message) - { - var azureMessage = await PeekDlqMessageBySequenceNumber(connectionString, queue, message.SequenceNumber); - var clonedMessage = azureMessage.CloneMessage(); + public async Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string queue, Message message) + { + var azureMessage = await PeekDlqMessageBySequenceNumber(connectionString, queue, message.SequenceNumber); + var clonedMessage = azureMessage.CloneMessage(); - await SendMessage(connectionString, queue, clonedMessage); + await SendMessage(connectionString, queue, clonedMessage); - await DeleteMessage(connectionString, queue, message, true); - } + await DeleteMessage(connectionString, queue, message, true); + } + + public async Task PurgeMessages(ServiceBusConnectionString connectionString, string queue, bool isDlq) + { + var path = isDlq ? EntityNameHelper.FormatDeadLetterPath(queue) : queue; - public async Task PurgeMessages(ServiceBusConnectionString connectionString, string queue, bool isDlq) + long purgedCount = 0; + + var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); + var operationTimeout = TimeSpan.FromSeconds(5); + while (true) { - var path = isDlq ? EntityNameHelper.FormatDeadLetterPath(queue) : queue; + var messages = await receiver.ReceiveAsync(_appSettings.QueueMessageFetchCount, operationTimeout); + if (messages == null || messages.Count == 0) + { + break; + } - long purgedCount = 0; + purgedCount += messages.Count; + } + + await receiver.CloseAsync(); + return purgedCount; + } + + public async Task TransferDlqMessages(ServiceBusConnectionString connectionString, string queuePath) + { + var path = EntityNameHelper.FormatDeadLetterPath(queuePath); - var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); + long transferredCount = 0; + MessageReceiver receiver = null; + QueueClient sender = null; + try + { + receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); + sender = GetQueueClient(connectionString, queuePath); var operationTimeout = TimeSpan.FromSeconds(5); while (true) { @@ -160,48 +186,20 @@ public async Task PurgeMessages(ServiceBusConnectionString connectionStrin break; } - purgedCount += messages.Count; - } + await sender.SendAsync(messages); - await receiver.CloseAsync(); - return purgedCount; + transferredCount += messages.Count; + } } - - public async Task TransferDlqMessages(ServiceBusConnectionString connectionString, string queuePath) + finally { - var path = EntityNameHelper.FormatDeadLetterPath(queuePath); + if (receiver != null) + await receiver.CloseAsync(); - long transferredCount = 0; - MessageReceiver receiver = null; - QueueClient sender = null; - try - { - receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); - sender = GetQueueClient(connectionString, queuePath); - var operationTimeout = TimeSpan.FromSeconds(5); - while (true) - { - var messages = await receiver.ReceiveAsync(_appSettings.QueueMessageFetchCount, operationTimeout); - if (messages == null || messages.Count == 0) - { - break; - } - - await sender.SendAsync(messages); - - transferredCount += messages.Count; - } - } - finally - { - if (receiver != null) - await receiver.CloseAsync(); - - if (sender != null) - await sender.CloseAsync(); - } - - return transferredCount; + if (sender != null) + await sender.CloseAsync(); } + + return transferredCount; } } \ No newline at end of file diff --git a/PurpleExplorer/Helpers/TopicHelper.cs b/PurpleExplorer/Helpers/TopicHelper.cs index bf553db..f8e1212 100644 --- a/PurpleExplorer/Helpers/TopicHelper.cs +++ b/PurpleExplorer/Helpers/TopicHelper.cs @@ -2,7 +2,6 @@ using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Core; using Microsoft.Azure.ServiceBus.Management; -using Microsoft.Azure.ServiceBus.Primitives; using PurpleExplorer.Models; using System.Collections.Generic; using System.Linq; @@ -10,159 +9,186 @@ using System.Threading.Tasks; using Message = PurpleExplorer.Models.Message; using AzureMessage = Microsoft.Azure.ServiceBus.Message; -using Microsoft.Azure.Amqp.Framing; -namespace PurpleExplorer.Helpers +namespace PurpleExplorer.Helpers; + +public class TopicHelper : BaseHelper, ITopicHelper { - public class TopicHelper : BaseHelper, ITopicHelper + private readonly AppSettings _appSettings; + + public TopicHelper(AppSettings appSettings) { - private readonly AppSettings _appSettings; + _appSettings = appSettings; + } - public TopicHelper(AppSettings appSettings) - { - _appSettings = appSettings; - } + public async Task> GetTopicsAndSubscriptions(ServiceBusConnectionString connectionString) + { + IList topics = new List(); + var client = GetManagementClient(connectionString); + var busTopics = await client.GetTopicsAsync(_appSettings.TopicListFetchCount); + await client.CloseAsync(); - public async Task> GetTopicsAndSubscriptions(ServiceBusConnectionString connectionString) + await Task.WhenAll(busTopics.Select(async topic => { - IList topics = new List(); - var client = GetManagementClient(connectionString); - var busTopics = await client.GetTopicsAsync(_appSettings.TopicListFetchCount); - await client.CloseAsync(); + var newTopic = new ServiceBusTopic(topic); - await Task.WhenAll(busTopics.Select(async topic => - { - var newTopic = new ServiceBusTopic(topic); + var subscriptions = await GetSubscriptions(connectionString, newTopic.Name); + newTopic.AddSubscriptions(subscriptions.ToArray()); + topics.Add(newTopic); + })); - var subscriptions = await GetSubscriptions(connectionString, newTopic.Name); - newTopic.AddSubscriptions(subscriptions.ToArray()); - topics.Add(newTopic); - })); + return topics; + } - return topics; - } + public async Task GetTopic(ServiceBusConnectionString connectionString, string topicPath, bool retrieveSubscriptions) + { + var client = GetManagementClient(connectionString); + var busTopics = await client.GetTopicAsync(topicPath); + await client.CloseAsync(); + + var newTopic = new ServiceBusTopic(busTopics); - public async Task GetTopic(ServiceBusConnectionString connectionString, string topicPath, bool retrieveSubscriptions) + if (retrieveSubscriptions) { - var client = GetManagementClient(connectionString); - var busTopics = await client.GetTopicAsync(topicPath); - await client.CloseAsync(); + var subscriptions = await GetSubscriptions(connectionString, newTopic.Name); + newTopic.AddSubscriptions(subscriptions.ToArray()); + } + + return newTopic; + } + + public async Task GetSubscription(ServiceBusConnectionString connectionString, string topicPath, string subscriptionName) + { + var client = GetManagementClient(connectionString); + var runtimeInfo = await client.GetSubscriptionRuntimeInfoAsync(topicPath, subscriptionName); + await client.CloseAsync(); - var newTopic = new ServiceBusTopic(busTopics); + return new ServiceBusSubscription(runtimeInfo); + } - if (retrieveSubscriptions) - { - var subscriptions = await GetSubscriptions(connectionString, newTopic.Name); - newTopic.AddSubscriptions(subscriptions.ToArray()); - } + public async Task> GetSubscriptions(ServiceBusConnectionString connectionString, string topicPath) + { + IList subscriptions = new List(); + var client = GetManagementClient(connectionString); + var topicSubscription = await client.GetSubscriptionsRuntimeInfoAsync(topicPath); + await client.CloseAsync(); - return newTopic; - } - - public async Task GetSubscription(ServiceBusConnectionString connectionString, string topicPath, string subscriptionName) + foreach (var sub in topicSubscription) { - var client = GetManagementClient(connectionString); - var runtimeInfo = await client.GetSubscriptionRuntimeInfoAsync(topicPath, subscriptionName); - await client.CloseAsync(); - - return new ServiceBusSubscription(runtimeInfo); + subscriptions.Add(new ServiceBusSubscription(sub)); } - public async Task> GetSubscriptions(ServiceBusConnectionString connectionString, string topicPath) - { - IList subscriptions = new List(); - var client = GetManagementClient(connectionString); - var topicSubscription = await client.GetSubscriptionsRuntimeInfoAsync(topicPath); - await client.CloseAsync(); + return subscriptions; + } - foreach (var sub in topicSubscription) - { - subscriptions.Add(new ServiceBusSubscription(sub)); - } + public async Task> GetMessagesBySubscription(ServiceBusConnectionString connectionString, string topicName, + string subscriptionName) + { + var path = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName); - return subscriptions; - } + var messageReceiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); + var subscriptionMessages = await messageReceiver.PeekAsync(_appSettings.TopicMessageFetchCount); + await messageReceiver.CloseAsync(); - public async Task> GetMessagesBySubscription(ServiceBusConnectionString connectionString, string topicName, - string subscriptionName) - { - var path = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName); + var result = subscriptionMessages.Select(message => new Message(message, false)).ToList(); + return result; + } - var messageReceiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); - var subscriptionMessages = await messageReceiver.PeekAsync(_appSettings.TopicMessageFetchCount); - await messageReceiver.CloseAsync(); + public async Task> GetDlqMessages(ServiceBusConnectionString connectionString, string topic, string subscription) + { + var path = EntityNameHelper.FormatSubscriptionPath(topic, subscription); + var deadletterPath = EntityNameHelper.FormatDeadLetterPath(path); - var result = subscriptionMessages.Select(message => new Message(message, false)).ToList(); - return result; - } + var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); + var receivedMessages = await receiver.PeekAsync(_appSettings.TopicMessageFetchCount); + await receiver.CloseAsync(); - public async Task> GetDlqMessages(ServiceBusConnectionString connectionString, string topic, string subscription) - { - var path = EntityNameHelper.FormatSubscriptionPath(topic, subscription); - var deadletterPath = EntityNameHelper.FormatDeadLetterPath(path); + var result = receivedMessages.Select(message => new Message(message, true)).ToList(); + return result; + } - var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); - var receivedMessages = await receiver.PeekAsync(_appSettings.TopicMessageFetchCount); - await receiver.CloseAsync(); + public async Task GetNamespaceInfo(ServiceBusConnectionString connectionString) + { + var client = GetManagementClient(connectionString); + return await client.GetNamespaceInfoAsync(); + } - var result = receivedMessages.Select(message => new Message(message, true)).ToList(); - return result; - } + public async Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, string content) + { + var message = new AzureMessage {Body = Encoding.UTF8.GetBytes(content)}; + await SendMessage(connectionString, topicPath, message); + } - public async Task GetNamespaceInfo(ServiceBusConnectionString connectionString) - { - var client = GetManagementClient(connectionString); - return await client.GetNamespaceInfoAsync(); - } + public async Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, AzureMessage message) + { + var topicClient = GetTopicClient(connectionString, topicPath); + await topicClient.SendAsync(message); + await topicClient.CloseAsync(); + } - public async Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, string content) - { - var message = new AzureMessage {Body = Encoding.UTF8.GetBytes(content)}; - await SendMessage(connectionString, topicPath, message); - } + public async Task DeleteMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, + Message message, bool isDlq) + { + var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); + path = isDlq ? EntityNameHelper.FormatDeadLetterPath(path) : path; + + var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); - public async Task SendMessage(ServiceBusConnectionString connectionString, string topicPath, AzureMessage message) + while (true) { - var topicClient = GetTopicClient(connectionString, topicPath); - await topicClient.SendAsync(message); - await topicClient.CloseAsync(); + var messages = await receiver.ReceiveAsync(_appSettings.TopicMessageFetchCount); + if (messages == null || messages.Count == 0) + { + break; + } + + var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); + if (foundMessage != null) + { + await receiver.CompleteAsync(foundMessage.SystemProperties.LockToken); + break; + } } - public async Task DeleteMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, - Message message, bool isDlq) - { - var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); - path = isDlq ? EntityNameHelper.FormatDeadLetterPath(path) : path; + await receiver.CloseAsync(); + } - var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); + public async Task PurgeMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, + bool isDlq) + { + var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); + path = isDlq ? EntityNameHelper.FormatDeadLetterPath(path) : path; - while (true) + long purgedCount = 0; + var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); + var operationTimeout = TimeSpan.FromSeconds(5); + while (true) + { + var messages = await receiver.ReceiveAsync(_appSettings.TopicMessageFetchCount, operationTimeout); + if (messages == null || messages.Count == 0) { - var messages = await receiver.ReceiveAsync(_appSettings.TopicMessageFetchCount); - if (messages == null || messages.Count == 0) - { - break; - } - - var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); - if (foundMessage != null) - { - await receiver.CompleteAsync(foundMessage.SystemProperties.LockToken); - break; - } + break; } - await receiver.CloseAsync(); + purgedCount += messages.Count; } - public async Task PurgeMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, - bool isDlq) - { - var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); - path = isDlq ? EntityNameHelper.FormatDeadLetterPath(path) : path; + await receiver.CloseAsync(); + return purgedCount; + } - long purgedCount = 0; - var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); + public async Task TransferDlqMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath) + { + var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); + path = EntityNameHelper.FormatDeadLetterPath(path); + + long transferredCount = 0; + MessageReceiver receiver = null; + TopicClient sender = null; + try + { + receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); + sender = GetTopicClient(connectionString, topicPath); var operationTimeout = TimeSpan.FromSeconds(5); while (true) { @@ -172,100 +198,71 @@ public async Task PurgeMessages(ServiceBusConnectionString connectionStrin break; } - purgedCount += messages.Count; - } + await sender.SendAsync(messages); - await receiver.CloseAsync(); - return purgedCount; + transferredCount += messages.Count; + } } - - public async Task TransferDlqMessages(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath) + finally { - var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); - path = EntityNameHelper.FormatDeadLetterPath(path); - - long transferredCount = 0; - MessageReceiver receiver = null; - TopicClient sender = null; - try - { - receiver = GetMessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete); - sender = GetTopicClient(connectionString, topicPath); - var operationTimeout = TimeSpan.FromSeconds(5); - while (true) - { - var messages = await receiver.ReceiveAsync(_appSettings.TopicMessageFetchCount, operationTimeout); - if (messages == null || messages.Count == 0) - { - break; - } - - await sender.SendAsync(messages); - - transferredCount += messages.Count; - } - } - finally - { - if (receiver != null) - await receiver.CloseAsync(); + if (receiver != null) + await receiver.CloseAsync(); - if (sender != null) - await sender.CloseAsync(); - } - - return transferredCount; + if (sender != null) + await sender.CloseAsync(); } - private async Task PeekDlqMessageBySequenceNumber(ServiceBusConnectionString connectionString, string topicPath, - string subscriptionPath, long sequenceNumber) - { - var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); - var deadletterPath = EntityNameHelper.FormatDeadLetterPath(path); + return transferredCount; + } - var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); - var azureMessage = await receiver.PeekBySequenceNumberAsync(sequenceNumber); - await receiver.CloseAsync(); + private async Task PeekDlqMessageBySequenceNumber(ServiceBusConnectionString connectionString, string topicPath, + string subscriptionPath, long sequenceNumber) + { + var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); + var deadletterPath = EntityNameHelper.FormatDeadLetterPath(path); + + var receiver = GetMessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock); + var azureMessage = await receiver.PeekBySequenceNumberAsync(sequenceNumber); + await receiver.CloseAsync(); - return azureMessage; - } + return azureMessage; + } - public async Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, - Message message) - { - var azureMessage = await PeekDlqMessageBySequenceNumber(connectionString, topicPath, subscriptionPath, - message.SequenceNumber); - var clonedMessage = azureMessage.CloneMessage(); + public async Task ResubmitDlqMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, + Message message) + { + var azureMessage = await PeekDlqMessageBySequenceNumber(connectionString, topicPath, subscriptionPath, + message.SequenceNumber); + var clonedMessage = azureMessage.CloneMessage(); - await SendMessage(connectionString, topicPath, clonedMessage); + await SendMessage(connectionString, topicPath, clonedMessage); - await DeleteMessage(connectionString, topicPath, subscriptionPath, message, true); - } + await DeleteMessage(connectionString, topicPath, subscriptionPath, message, true); + } - public async Task DeadletterMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, - Message message) - { - var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); + public async Task DeadletterMessage(ServiceBusConnectionString connectionString, string topicPath, string subscriptionPath, + Message message) + { + var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath); - var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); + var receiver = GetMessageReceiver(connectionString, path, ReceiveMode.PeekLock); - while (true) + while (true) + { + var messages = await receiver.ReceiveAsync(_appSettings.TopicMessageFetchCount); + if (messages == null || messages.Count == 0) { - var messages = await receiver.ReceiveAsync(_appSettings.TopicMessageFetchCount); - if (messages == null || messages.Count == 0) - { - break; - } - - var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); - if (foundMessage != null) - { - await receiver.DeadLetterAsync(foundMessage.SystemProperties.LockToken); - break; - } + break; } - await receiver.CloseAsync(); + var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId)); + if (foundMessage != null) + { + await receiver.DeadLetterAsync(foundMessage.SystemProperties.LockToken); + break; + } } + + await receiver.CloseAsync(); } } \ No newline at end of file diff --git a/PurpleExplorer/Models/AppState.cs b/PurpleExplorer/Models/AppState.cs index 84bb1f6..dc9f2bc 100644 --- a/PurpleExplorer/Models/AppState.cs +++ b/PurpleExplorer/Models/AppState.cs @@ -2,25 +2,24 @@ using System.Runtime.Serialization; using PurpleExplorer.ViewModels; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +[DataContract] +public class AppState: ViewModelBase, IAppState { - [DataContract] - public class AppState: ViewModelBase, IAppState - { - [DataMember] - public ObservableCollection SavedConnectionStrings { get; set; } + [DataMember] + public ObservableCollection SavedConnectionStrings { get; set; } - [DataMember] - public ObservableCollection SavedMessages { get; set; } + [DataMember] + public ObservableCollection SavedMessages { get; set; } - [DataMember] - public AppSettings AppSettings { get; set; } + [DataMember] + public AppSettings AppSettings { get; set; } - public AppState() - { - SavedConnectionStrings = new ObservableCollection(); - SavedMessages = new ObservableCollection(); - AppSettings = new AppSettings(); - } + public AppState() + { + SavedConnectionStrings = new ObservableCollection(); + SavedMessages = new ObservableCollection(); + AppSettings = new AppSettings(); } } \ No newline at end of file diff --git a/PurpleExplorer/Models/IAppState.cs b/PurpleExplorer/Models/IAppState.cs index dddb8f9..8e47883 100644 --- a/PurpleExplorer/Models/IAppState.cs +++ b/PurpleExplorer/Models/IAppState.cs @@ -1,12 +1,10 @@ using System.Collections.ObjectModel; -using PurpleExplorer.ViewModels; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +public interface IAppState { - public interface IAppState - { - public ObservableCollection SavedConnectionStrings { get; set; } - public ObservableCollection SavedMessages { get; set; } - public AppSettings AppSettings { get; set; } - } + public ObservableCollection SavedConnectionStrings { get; set; } + public ObservableCollection SavedMessages { get; set; } + public AppSettings AppSettings { get; set; } } \ No newline at end of file diff --git a/PurpleExplorer/Models/Message.cs b/PurpleExplorer/Models/Message.cs index 39f23d4..97baec9 100644 --- a/PurpleExplorer/Models/Message.cs +++ b/PurpleExplorer/Models/Message.cs @@ -2,39 +2,38 @@ using System.Text; using AzureMessage = Microsoft.Azure.ServiceBus.Message; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +public class Message { - public class Message - { - public string MessageId { get; set; } - public string ContentType { get; set; } - public string Content { get; set; } - public string Label { get; set; } - public long Size { get; set; } - public string CorrelationId { get; set; } - public int DeliveryCount { get; set; } - public long SequenceNumber { get; set; } - public TimeSpan TimeToLive { get; set; } - public DateTime EnqueueTimeUtc { get; set; } - public string DeadLetterReason { get; set; } - public bool IsDlq { get; } + public string MessageId { get; set; } + public string ContentType { get; set; } + public string Content { get; set; } + public string Label { get; set; } + public long Size { get; set; } + public string CorrelationId { get; set; } + public int DeliveryCount { get; set; } + public long SequenceNumber { get; set; } + public TimeSpan TimeToLive { get; set; } + public DateTime EnqueueTimeUtc { get; set; } + public string DeadLetterReason { get; set; } + public bool IsDlq { get; } - public Message(AzureMessage azureMessage, bool isDlq) - { - this.Content = azureMessage.Body is not null ? Encoding.UTF8.GetString(azureMessage.Body) : string.Empty; - this.MessageId = azureMessage.MessageId; - this.CorrelationId = azureMessage.CorrelationId; - this.DeliveryCount = azureMessage.SystemProperties.DeliveryCount; - this.ContentType = azureMessage.ContentType; - this.Label = azureMessage.Label; - this.SequenceNumber = azureMessage.SystemProperties.SequenceNumber; - this.Size = azureMessage.Size; - this.TimeToLive = azureMessage.TimeToLive; - this.IsDlq = isDlq; - this.EnqueueTimeUtc = azureMessage.SystemProperties.EnqueuedTimeUtc; - this.DeadLetterReason = azureMessage.UserProperties.ContainsKey("DeadLetterReason") - ? azureMessage.UserProperties["DeadLetterReason"].ToString() - : string.Empty; - } + public Message(AzureMessage azureMessage, bool isDlq) + { + this.Content = azureMessage.Body is not null ? Encoding.UTF8.GetString(azureMessage.Body) : string.Empty; + this.MessageId = azureMessage.MessageId; + this.CorrelationId = azureMessage.CorrelationId; + this.DeliveryCount = azureMessage.SystemProperties.DeliveryCount; + this.ContentType = azureMessage.ContentType; + this.Label = azureMessage.Label; + this.SequenceNumber = azureMessage.SystemProperties.SequenceNumber; + this.Size = azureMessage.Size; + this.TimeToLive = azureMessage.TimeToLive; + this.IsDlq = isDlq; + this.EnqueueTimeUtc = azureMessage.SystemProperties.EnqueuedTimeUtc; + this.DeadLetterReason = azureMessage.UserProperties.ContainsKey("DeadLetterReason") + ? azureMessage.UserProperties["DeadLetterReason"].ToString() + : string.Empty; } } \ No newline at end of file diff --git a/PurpleExplorer/Models/MessageCollection.cs b/PurpleExplorer/Models/MessageCollection.cs index 0661d0d..bb100a1 100644 --- a/PurpleExplorer/Models/MessageCollection.cs +++ b/PurpleExplorer/Models/MessageCollection.cs @@ -4,78 +4,77 @@ using DynamicData; using ReactiveUI; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +/// +/// Represents either a subscription or a queue +/// +public abstract class MessageCollection : ReactiveObject { - /// - /// Represents either a subscription or a queue - /// - public abstract class MessageCollection : ReactiveObject - { - // These are needed to be set before fetching messages, in the second constructor - private long _messageCount; - private long _dlqCount; + // These are needed to be set before fetching messages, in the second constructor + private long _messageCount; + private long _dlqCount; - public ObservableCollection Messages { get; } - public ObservableCollection DlqMessages { get; } + public ObservableCollection Messages { get; } + public ObservableCollection DlqMessages { get; } - public long MessageCount - { - get => _messageCount; - private set => this.RaiseAndSetIfChanged(ref _messageCount, value); - } + public long MessageCount + { + get => _messageCount; + private set => this.RaiseAndSetIfChanged(ref _messageCount, value); + } - public long DlqCount - { - get => _dlqCount; - private set => this.RaiseAndSetIfChanged(ref _dlqCount, value); - } + public long DlqCount + { + get => _dlqCount; + private set => this.RaiseAndSetIfChanged(ref _dlqCount, value); + } - protected MessageCollection() - { - Messages = new ObservableCollection(); - DlqMessages = new ObservableCollection(); - } + protected MessageCollection() + { + Messages = new ObservableCollection(); + DlqMessages = new ObservableCollection(); + } - protected MessageCollection(long messageCount, long dlqCount) : this() - { - _messageCount = messageCount; - _dlqCount = dlqCount; - } + protected MessageCollection(long messageCount, long dlqCount) : this() + { + _messageCount = messageCount; + _dlqCount = dlqCount; + } - public void AddMessages(IEnumerable messages) - { - Messages.AddRange(messages); - MessageCount = Messages.Count; - } + public void AddMessages(IEnumerable messages) + { + Messages.AddRange(messages); + MessageCount = Messages.Count; + } - public void RemoveMessage(string messageId) - { - Messages.Remove(Messages.Single(msg => msg.MessageId.Equals(messageId))); - MessageCount = Messages.Count; - } + public void RemoveMessage(string messageId) + { + Messages.Remove(Messages.Single(msg => msg.MessageId.Equals(messageId))); + MessageCount = Messages.Count; + } - public void ClearMessages() - { - Messages.Clear(); - MessageCount = Messages.Count; - } + public void ClearMessages() + { + Messages.Clear(); + MessageCount = Messages.Count; + } - public void AddDlqMessages(IEnumerable dlqMessages) - { - DlqMessages.AddRange(dlqMessages); - DlqCount = DlqMessages.Count; - } + public void AddDlqMessages(IEnumerable dlqMessages) + { + DlqMessages.AddRange(dlqMessages); + DlqCount = DlqMessages.Count; + } - public void RemoveDlqMessage(string messageId) - { - DlqMessages.Remove(DlqMessages.Single(msg => msg.MessageId.Equals(messageId))); - DlqCount = DlqMessages.Count; - } + public void RemoveDlqMessage(string messageId) + { + DlqMessages.Remove(DlqMessages.Single(msg => msg.MessageId.Equals(messageId))); + DlqCount = DlqMessages.Count; + } - public void ClearDlqMessages() - { - DlqMessages.Clear(); - DlqCount = DlqMessages.Count; - } + public void ClearDlqMessages() + { + DlqMessages.Clear(); + DlqCount = DlqMessages.Count; } } \ No newline at end of file diff --git a/PurpleExplorer/Models/SavedMessage.cs b/PurpleExplorer/Models/SavedMessage.cs index 39a4214..831bc2a 100644 --- a/PurpleExplorer/Models/SavedMessage.cs +++ b/PurpleExplorer/Models/SavedMessage.cs @@ -1,8 +1,7 @@ -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +public class SavedMessage { - public class SavedMessage - { - public string Title { get; set; } - public string Message { get; set; } - } + public string Title { get; set; } + public string Message { get; set; } } \ No newline at end of file diff --git a/PurpleExplorer/Models/ServiceBusConnectionString.cs b/PurpleExplorer/Models/ServiceBusConnectionString.cs index a98a0d2..3cb90fd 100644 --- a/PurpleExplorer/Models/ServiceBusConnectionString.cs +++ b/PurpleExplorer/Models/ServiceBusConnectionString.cs @@ -1,10 +1,7 @@ -using Microsoft.Azure.ServiceBus.Management; +namespace PurpleExplorer.Models; -namespace PurpleExplorer.Models +public class ServiceBusConnectionString { - public class ServiceBusConnectionString - { - public bool UseManagedIdentity { get; set; } - public string ConnectionString { get; set; } - } + public bool UseManagedIdentity { get; set; } + public string ConnectionString { get; set; } } \ No newline at end of file diff --git a/PurpleExplorer/Models/ServiceBusQueue.cs b/PurpleExplorer/Models/ServiceBusQueue.cs index f12cbb8..9e0125e 100644 --- a/PurpleExplorer/Models/ServiceBusQueue.cs +++ b/PurpleExplorer/Models/ServiceBusQueue.cs @@ -1,16 +1,15 @@ using Microsoft.Azure.ServiceBus.Management; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +public class ServiceBusQueue : MessageCollection { - public class ServiceBusQueue : MessageCollection - { - public string Name { get; set; } - public ServiceBusResource ServiceBus { get; set; } + public string Name { get; set; } + public ServiceBusResource ServiceBus { get; set; } - public ServiceBusQueue(QueueRuntimeInfo runtimeInfo) - : base(runtimeInfo.MessageCountDetails.ActiveMessageCount, runtimeInfo.MessageCountDetails.DeadLetterMessageCount) - { + public ServiceBusQueue(QueueRuntimeInfo runtimeInfo) + : base(runtimeInfo.MessageCountDetails.ActiveMessageCount, runtimeInfo.MessageCountDetails.DeadLetterMessageCount) + { - } } } \ No newline at end of file diff --git a/PurpleExplorer/Models/ServiceBusResource.cs b/PurpleExplorer/Models/ServiceBusResource.cs index 8c7fb3c..dae65da 100644 --- a/PurpleExplorer/Models/ServiceBusResource.cs +++ b/PurpleExplorer/Models/ServiceBusResource.cs @@ -1,42 +1,41 @@ using System; using System.Collections.ObjectModel; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +public class ServiceBusResource { - public class ServiceBusResource - { - public string Name { get; set; } - public DateTime CreatedTime { get; set; } - public ServiceBusConnectionString ConnectionString { get; set; } - public ObservableCollection Queues { get; private set; } - public ObservableCollection Topics { get; private set; } + public string Name { get; set; } + public DateTime CreatedTime { get; set; } + public ServiceBusConnectionString ConnectionString { get; set; } + public ObservableCollection Queues { get; private set; } + public ObservableCollection Topics { get; private set; } - public void AddTopics(params ServiceBusTopic[] topics) - { - Topics ??= new ObservableCollection(); + public void AddTopics(params ServiceBusTopic[] topics) + { + Topics ??= new ObservableCollection(); - foreach (var topic in topics) - { - topic.ServiceBus = this; - Topics.Add(topic); - } - } - - public void AddQueues(params ServiceBusQueue[] queues) + foreach (var topic in topics) { - Queues ??= new ObservableCollection(); - - foreach (var queue in queues) - { - queue.ServiceBus = this; - Queues.Add(queue); - } + topic.ServiceBus = this; + Topics.Add(topic); } + } + + public void AddQueues(params ServiceBusQueue[] queues) + { + Queues ??= new ObservableCollection(); - public override bool Equals(object? obj) + foreach (var queue in queues) { - var comparingResource = obj as ServiceBusResource; - return comparingResource != null && Name.Equals(comparingResource.Name) && CreatedTime.Equals(comparingResource.CreatedTime); + queue.ServiceBus = this; + Queues.Add(queue); } } + + public override bool Equals(object? obj) + { + var comparingResource = obj as ServiceBusResource; + return comparingResource != null && Name.Equals(comparingResource.Name) && CreatedTime.Equals(comparingResource.CreatedTime); + } } \ No newline at end of file diff --git a/PurpleExplorer/Models/ServiceBusSubscription.cs b/PurpleExplorer/Models/ServiceBusSubscription.cs index 1ed842b..535fab8 100644 --- a/PurpleExplorer/Models/ServiceBusSubscription.cs +++ b/PurpleExplorer/Models/ServiceBusSubscription.cs @@ -1,17 +1,16 @@ using Microsoft.Azure.ServiceBus.Management; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +public class ServiceBusSubscription : MessageCollection { - public class ServiceBusSubscription : MessageCollection - { - public string Name { get; set; } + public string Name { get; set; } - public ServiceBusTopic Topic { get; set; } + public ServiceBusTopic Topic { get; set; } - public ServiceBusSubscription(SubscriptionRuntimeInfo subscription) + public ServiceBusSubscription(SubscriptionRuntimeInfo subscription) : base(subscription.MessageCountDetails.ActiveMessageCount, subscription.MessageCountDetails.DeadLetterMessageCount) - { - Name = subscription.SubscriptionName; - } + { + Name = subscription.SubscriptionName; } } \ No newline at end of file diff --git a/PurpleExplorer/Models/ServiceBusTopic.cs b/PurpleExplorer/Models/ServiceBusTopic.cs index d4b1bc9..ef6f9e0 100644 --- a/PurpleExplorer/Models/ServiceBusTopic.cs +++ b/PurpleExplorer/Models/ServiceBusTopic.cs @@ -1,33 +1,32 @@ using System.Collections.ObjectModel; using Microsoft.Azure.ServiceBus.Management; -namespace PurpleExplorer.Models +namespace PurpleExplorer.Models; + +public class ServiceBusTopic { - public class ServiceBusTopic + public string Name { get; set; } + public ObservableCollection Subscriptions { get; private set; } + public ServiceBusResource ServiceBus { get; set; } + + public ServiceBusTopic() { - public string Name { get; set; } - public ObservableCollection Subscriptions { get; private set; } - public ServiceBusResource ServiceBus { get; set; } + } - public ServiceBusTopic() - { - } + public ServiceBusTopic(TopicDescription topicDescription) + { + Name = topicDescription.Path; + } - public ServiceBusTopic(TopicDescription topicDescription) - { - Name = topicDescription.Path; - } + public void AddSubscriptions(params ServiceBusSubscription[] subscriptions) + { + Subscriptions ??= new ObservableCollection(); - public void AddSubscriptions(params ServiceBusSubscription[] subscriptions) + foreach (var subscription in subscriptions) { - Subscriptions ??= new ObservableCollection(); - - foreach (var subscription in subscriptions) - { - subscription.Topic = this; - Subscriptions.Add(subscription); - } + subscription.Topic = this; + Subscriptions.Add(subscription); } } } \ No newline at end of file diff --git a/PurpleExplorer/Program.cs b/PurpleExplorer/Program.cs index b68d16b..e246488 100644 --- a/PurpleExplorer/Program.cs +++ b/PurpleExplorer/Program.cs @@ -3,23 +3,22 @@ using Projektanker.Icons.Avalonia; using Projektanker.Icons.Avalonia.FontAwesome; -namespace PurpleExplorer +namespace PurpleExplorer; + +static class Program { - static class Program - { - // Initialization code. Don't use any Avalonia, third-party APIs or any - // SynchronizationContext-reliant code before AppMain is called: things aren't initialized - // yet and stuff might break. - public static void Main(string[] args) => BuildAvaloniaApp() - .StartWithClassicDesktopLifetime(args); + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + public static void Main(string[] args) => BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); - // Avalonia configuration, don't remove; also used by visual designer. - public static AppBuilder BuildAvaloniaApp() - => AppBuilder.Configure() - .UsePlatformDetect() - .LogToTrace() - .UseReactiveUI() - .WithIcons(container => container - .Register()); - } + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .LogToTrace() + .UseReactiveUI() + .WithIcons(container => container + .Register()); } \ No newline at end of file diff --git a/PurpleExplorer/PurpleExplorer.csproj b/PurpleExplorer/PurpleExplorer.csproj index 721d50a..f4ab090 100644 --- a/PurpleExplorer/PurpleExplorer.csproj +++ b/PurpleExplorer/PurpleExplorer.csproj @@ -18,16 +18,16 @@ - - - + + + - - - + + + - - + + diff --git a/PurpleExplorer/Services/ILoggingService.cs b/PurpleExplorer/Services/ILoggingService.cs index 4877e5b..4beb729 100644 --- a/PurpleExplorer/Services/ILoggingService.cs +++ b/PurpleExplorer/Services/ILoggingService.cs @@ -1,8 +1,7 @@ -namespace PurpleExplorer.Services +namespace PurpleExplorer.Services; + +public interface ILoggingService { - public interface ILoggingService - { - void Log(string message); - string Logs { get; } - } -} + void Log(string message); + string Logs { get; } +} \ No newline at end of file diff --git a/PurpleExplorer/Services/LoggingService.cs b/PurpleExplorer/Services/LoggingService.cs index a714e9b..3b995df 100644 --- a/PurpleExplorer/Services/LoggingService.cs +++ b/PurpleExplorer/Services/LoggingService.cs @@ -2,23 +2,22 @@ using System.Text; using ReactiveUI; -namespace PurpleExplorer.Services +namespace PurpleExplorer.Services; + +public class LoggingService : ReactiveObject, ILoggingService { - public class LoggingService : ReactiveObject, ILoggingService - { - private readonly StringBuilder _log; + private readonly StringBuilder _log; - public LoggingService() - { - _log = new StringBuilder(); - } + public LoggingService() + { + _log = new StringBuilder(); + } - public string Logs => _log.ToString(); + public string Logs => _log.ToString(); - public void Log(string message) - { - _log.Insert(0, "[" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + "] " + message + "\n"); - this.RaisePropertyChanged(nameof(Logs)); - } + public void Log(string message) + { + _log.Insert(0, "[" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + "] " + message + "\n"); + this.RaisePropertyChanged(nameof(Logs)); } -} +} \ No newline at end of file diff --git a/PurpleExplorer/Services/NewtonSoftJsonSuspensionDriver.cs b/PurpleExplorer/Services/NewtonSoftJsonSuspensionDriver.cs index 00abe2b..14fc581 100644 --- a/PurpleExplorer/Services/NewtonSoftJsonSuspensionDriver.cs +++ b/PurpleExplorer/Services/NewtonSoftJsonSuspensionDriver.cs @@ -5,39 +5,37 @@ using System.Reactive; using System.Reactive.Linq; -namespace PurpleExplorer.Services +namespace PurpleExplorer.Services; + +public class NewtonsoftJsonSuspensionDriver : ISuspensionDriver { - public class NewtonsoftJsonSuspensionDriver : ISuspensionDriver + private readonly string _file; + private readonly JsonSerializerSettings _settings = new JsonSerializerSettings { - private readonly string _file; - private readonly JsonSerializerSettings _settings = new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.All, - Formatting = Formatting.Indented - }; - - public NewtonsoftJsonSuspensionDriver(string file) => _file = file; + TypeNameHandling = TypeNameHandling.All, + Formatting = Formatting.Indented + }; - public IObservable InvalidateState() - { - if (File.Exists(_file)) - File.Delete(_file); - return Observable.Return(Unit.Default); - } + public NewtonsoftJsonSuspensionDriver(string file) => _file = file; - public IObservable LoadState() - { - var lines = File.ReadAllText(_file); - var state = JsonConvert.DeserializeObject(lines, _settings); - return Observable.Return(state); - } + public IObservable InvalidateState() + { + if (File.Exists(_file)) + File.Delete(_file); + return Observable.Return(Unit.Default); + } - public IObservable SaveState(object state) - { - var lines = JsonConvert.SerializeObject(state, _settings); - File.WriteAllText(_file, lines); - return Observable.Return(Unit.Default); - } + public IObservable LoadState() + { + var lines = File.ReadAllText(_file); + var state = JsonConvert.DeserializeObject(lines, _settings); + return Observable.Return(state); } -} + public IObservable SaveState(object state) + { + var lines = JsonConvert.SerializeObject(state, _settings); + File.WriteAllText(_file, lines); + return Observable.Return(Unit.Default); + } +} \ No newline at end of file diff --git a/PurpleExplorer/ViewLocator.cs b/PurpleExplorer/ViewLocator.cs index 37281f3..54e0886 100644 --- a/PurpleExplorer/ViewLocator.cs +++ b/PurpleExplorer/ViewLocator.cs @@ -6,30 +6,29 @@ using Avalonia.Controls.Templates; using PurpleExplorer.ViewModels; -namespace PurpleExplorer +namespace PurpleExplorer; + +public class ViewLocator : IDataTemplate { - public class ViewLocator : IDataTemplate + public bool SupportsRecycling => false; + + public IControl Build(object data) { - public bool SupportsRecycling => false; + var name = data.GetType().FullName.Replace("ViewModel", "View"); + var type = Type.GetType(name); - public IControl Build(object data) + if (type != null) { - var name = data.GetType().FullName.Replace("ViewModel", "View"); - var type = Type.GetType(name); - - if (type != null) - { - return (Control) Activator.CreateInstance(type); - } - else - { - return new TextBlock {Text = "Not Found: " + name}; - } + return (Control) Activator.CreateInstance(type); } - - public bool Match(object data) + else { - return data is ViewModelBase; + return new TextBlock {Text = "Not Found: " + name}; } } + + public bool Match(object data) + { + return data is ViewModelBase; + } } \ No newline at end of file diff --git a/PurpleExplorer/ViewModels/AddMessageWindowViewModal.cs b/PurpleExplorer/ViewModels/AddMessageWindowViewModal.cs index 5d2d0a3..deb8a9b 100644 --- a/PurpleExplorer/ViewModels/AddMessageWindowViewModal.cs +++ b/PurpleExplorer/ViewModels/AddMessageWindowViewModal.cs @@ -3,42 +3,41 @@ using ReactiveUI; using Splat; -namespace PurpleExplorer.ViewModels +namespace PurpleExplorer.ViewModels; + +public class AddMessageWindowViewModal : DialogViewModelBase { - public class AddMessageWindowViewModal : DialogViewModelBase - { - private string _message; - private string _title; - private readonly IAppState _appState; + private string _message; + private string _title; + private readonly IAppState _appState; - public string Message - { - get => _message; - set => this.RaiseAndSetIfChanged(ref _message, value); - } + public string Message + { + get => _message; + set => this.RaiseAndSetIfChanged(ref _message, value); + } - public string Title - { - get => _title; - set => this.RaiseAndSetIfChanged(ref _title, value); - } + public string Title + { + get => _title; + set => this.RaiseAndSetIfChanged(ref _title, value); + } - public ObservableCollection SavedMessages { get; set; } + public ObservableCollection SavedMessages { get; set; } - public AddMessageWindowViewModal(IAppState appState = null) - { - _appState = appState ?? Locator.Current.GetService(); - SavedMessages = _appState.SavedMessages; - } + public AddMessageWindowViewModal(IAppState appState = null) + { + _appState = appState ?? Locator.Current.GetService(); + SavedMessages = _appState.SavedMessages; + } - public void SaveMessage() + public void SaveMessage() + { + var newMessage = new SavedMessage { - var newMessage = new SavedMessage - { - Message = Message, - Title = Title - }; - SavedMessages.Add(newMessage); - } + Message = Message, + Title = Title + }; + SavedMessages.Add(newMessage); } } \ No newline at end of file diff --git a/PurpleExplorer/ViewModels/AppWindowViewModel.cs b/PurpleExplorer/ViewModels/AppWindowViewModel.cs index 27ca4a2..601a0b9 100644 --- a/PurpleExplorer/ViewModels/AppWindowViewModel.cs +++ b/PurpleExplorer/ViewModels/AppWindowViewModel.cs @@ -2,24 +2,23 @@ using PurpleExplorer.Helpers; using ReactiveUI; -namespace PurpleExplorer.ViewModels +namespace PurpleExplorer.ViewModels; + +public class AppWindowViewModel : ViewModelBase { - public class AppWindowViewModel : ViewModelBase + public AppWindowViewModel() { - public AppWindowViewModel() - { - AboutPageCommand = ReactiveCommand.Create(AboutPage); - } + AboutPageCommand = ReactiveCommand.Create(AboutPage); + } - public ReactiveCommand AboutPageCommand { get; } + public ReactiveCommand AboutPageCommand { get; } - public async void AboutPage() - { - await MessageBoxHelper.ShowMessage("About Purple Explorer", - "Purple Explorer - cross-platform Azure Service Bus explorer (Windows, macOS, Linux) \n\n" + - "Thank you for using Purple Explorer! \n " + - "For updated information on the functionalities that Purple Explorer supports, please visit: \n " + - "https://github.com/telstrapurple/PurpleExplorer "); - } + public async void AboutPage() + { + await MessageBoxHelper.ShowMessage("About Purple Explorer", + "Purple Explorer - cross-platform Azure Service Bus explorer (Windows, macOS, Linux) \n\n" + + "Thank you for using Purple Explorer! \n " + + "For updated information on the functionalities that Purple Explorer supports, please visit: \n " + + "https://github.com/telstrapurple/PurpleExplorer "); } } \ No newline at end of file diff --git a/PurpleExplorer/ViewModels/ConnectionStringWindowViewModel.cs b/PurpleExplorer/ViewModels/ConnectionStringWindowViewModel.cs index ca7237c..7972268 100644 --- a/PurpleExplorer/ViewModels/ConnectionStringWindowViewModel.cs +++ b/PurpleExplorer/ViewModels/ConnectionStringWindowViewModel.cs @@ -3,31 +3,30 @@ using PurpleExplorer.Models; using Splat; -namespace PurpleExplorer.ViewModels +namespace PurpleExplorer.ViewModels; + +public class ConnectionStringWindowViewModel : DialogViewModelBase { - public class ConnectionStringWindowViewModel : DialogViewModelBase + private string _connectionString; + private bool _useManagedIdentity; + private readonly IAppState _appState; + public ObservableCollection SavedConnectionStrings { get; set; } + public string ConnectionString { - private string _connectionString; - private bool _useManagedIdentity; - private readonly IAppState _appState; - public ObservableCollection SavedConnectionStrings { get; set; } - public string ConnectionString - { - get => _connectionString; - set => this.RaiseAndSetIfChanged(ref _connectionString, value); - } - - public bool UseManagedIdentity - { - get => _useManagedIdentity; - set => this.RaiseAndSetIfChanged(ref _useManagedIdentity, value); - } + get => _connectionString; + set => this.RaiseAndSetIfChanged(ref _connectionString, value); + } - public ConnectionStringWindowViewModel(IAppState appState = null) - { - _appState = appState ?? Locator.Current.GetService(); - SavedConnectionStrings = _appState.SavedConnectionStrings; - } + public bool UseManagedIdentity + { + get => _useManagedIdentity; + set => this.RaiseAndSetIfChanged(ref _useManagedIdentity, value); + } + public ConnectionStringWindowViewModel(IAppState appState = null) + { + _appState = appState ?? Locator.Current.GetService(); + SavedConnectionStrings = _appState.SavedConnectionStrings; } + } \ No newline at end of file diff --git a/PurpleExplorer/ViewModels/DialogViewModelBase.cs b/PurpleExplorer/ViewModels/DialogViewModelBase.cs index 970928b..8e336c7 100644 --- a/PurpleExplorer/ViewModels/DialogViewModelBase.cs +++ b/PurpleExplorer/ViewModels/DialogViewModelBase.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace PurpleExplorer.ViewModels; -namespace PurpleExplorer.ViewModels +public class DialogViewModelBase : ViewModelBase { - public class DialogViewModelBase : ViewModelBase - { - public bool Cancel { get; set; } + public bool Cancel { get; set; } - public DialogViewModelBase() - { - this.Cancel = true; - } + public DialogViewModelBase() + { + this.Cancel = true; } -} +} \ No newline at end of file diff --git a/PurpleExplorer/ViewModels/MainWindowViewModel.cs b/PurpleExplorer/ViewModels/MainWindowViewModel.cs index 9e4bfa4..b494206 100644 --- a/PurpleExplorer/ViewModels/MainWindowViewModel.cs +++ b/PurpleExplorer/ViewModels/MainWindowViewModel.cs @@ -14,512 +14,511 @@ using Splat; using Message = PurpleExplorer.Models.Message; -namespace PurpleExplorer.ViewModels +namespace PurpleExplorer.ViewModels; + +public class MainWindowViewModel : ViewModelBase { - public class MainWindowViewModel : ViewModelBase - { - private readonly ITopicHelper _topicHelper; - private readonly IQueueHelper _queueHelper; - private readonly ILoggingService _loggingService; - private string _messageTabHeader; - private string _dlqTabHeader; - private string _topicTabHeader; - private string _queueTabHeader; + private readonly ITopicHelper _topicHelper; + private readonly IQueueHelper _queueHelper; + private readonly ILoggingService _loggingService; + private string _messageTabHeader; + private string _dlqTabHeader; + private string _topicTabHeader; + private string _queueTabHeader; - private ServiceBusSubscription _currentSubscription; - private ServiceBusTopic _currentTopic; - private ServiceBusQueue _currentQueue; - private Message _currentMessage; - private IObservable _queueLevelActionEnabled; - private MessageCollection _currentMessageCollection; - private IAppState _appState; + private ServiceBusSubscription _currentSubscription; + private ServiceBusTopic _currentTopic; + private ServiceBusQueue _currentQueue; + private Message _currentMessage; + private IObservable _queueLevelActionEnabled; + private MessageCollection _currentMessageCollection; + private IAppState _appState; - public ObservableCollection Messages { get; } - public ObservableCollection DlqMessages { get; } - public ObservableCollection ConnectedServiceBuses { get; } + public ObservableCollection Messages { get; } + public ObservableCollection DlqMessages { get; } + public ObservableCollection ConnectedServiceBuses { get; } - public ServiceBusConnectionString ConnectionString { get; set; } + public ServiceBusConnectionString ConnectionString { get; set; } - public string MessagesTabHeader - { - get => _messageTabHeader; - set => this.RaiseAndSetIfChanged(ref _messageTabHeader, value); - } + public string MessagesTabHeader + { + get => _messageTabHeader; + set => this.RaiseAndSetIfChanged(ref _messageTabHeader, value); + } - public string DlqTabHeader - { - get => _dlqTabHeader; - set => this.RaiseAndSetIfChanged(ref _dlqTabHeader, value); - } + public string DlqTabHeader + { + get => _dlqTabHeader; + set => this.RaiseAndSetIfChanged(ref _dlqTabHeader, value); + } - public string TopicTabHeader - { - get => _topicTabHeader; - set => this.RaiseAndSetIfChanged(ref _topicTabHeader, value); - } + public string TopicTabHeader + { + get => _topicTabHeader; + set => this.RaiseAndSetIfChanged(ref _topicTabHeader, value); + } - public string QueueTabHeader - { - get => _queueTabHeader; - set => this.RaiseAndSetIfChanged(ref _queueTabHeader, value); - } + public string QueueTabHeader + { + get => _queueTabHeader; + set => this.RaiseAndSetIfChanged(ref _queueTabHeader, value); + } - public ServiceBusSubscription CurrentSubscription - { - get => _currentSubscription; - set => this.RaiseAndSetIfChanged(ref _currentSubscription, value); - } + public ServiceBusSubscription CurrentSubscription + { + get => _currentSubscription; + set => this.RaiseAndSetIfChanged(ref _currentSubscription, value); + } - public ServiceBusTopic CurrentTopic - { - get => _currentTopic; - set => this.RaiseAndSetIfChanged(ref _currentTopic, value); - } + public ServiceBusTopic CurrentTopic + { + get => _currentTopic; + set => this.RaiseAndSetIfChanged(ref _currentTopic, value); + } - public Message CurrentMessage - { - get => _currentMessage; - set => this.RaiseAndSetIfChanged(ref _currentMessage, value); - } + public Message CurrentMessage + { + get => _currentMessage; + set => this.RaiseAndSetIfChanged(ref _currentMessage, value); + } - public ServiceBusQueue CurrentQueue - { - get => _currentQueue; - set => this.RaiseAndSetIfChanged(ref _currentQueue, value); - } + public ServiceBusQueue CurrentQueue + { + get => _currentQueue; + set => this.RaiseAndSetIfChanged(ref _currentQueue, value); + } - public MessageCollection CurrentMessageCollection + public MessageCollection CurrentMessageCollection + { + get { - get - { - if (CurrentSubscription != null) - return CurrentSubscription; - if (CurrentQueue != null) - return CurrentQueue; - return null; - } + if (CurrentSubscription != null) + return CurrentSubscription; + if (CurrentQueue != null) + return CurrentQueue; + return null; } + } - public ILoggingService LoggingService => _loggingService; - public Version AppVersion => Assembly.GetExecutingAssembly().GetName().Version; - public string AppVersionText { get; set; } + public ILoggingService LoggingService => _loggingService; + public Version AppVersion => Assembly.GetExecutingAssembly().GetName().Version; + public string AppVersionText { get; set; } - public IObservable QueueLevelActionEnabled - { - get => _queueLevelActionEnabled; - set => this.RaiseAndSetIfChanged(ref _queueLevelActionEnabled, value); - } - public MainWindowViewModel() - { - _loggingService = Locator.Current.GetService(); - _topicHelper = Locator.Current.GetService(); - _queueHelper = Locator.Current.GetService(); - _appState = Locator.Current.GetService(); + public IObservable QueueLevelActionEnabled + { + get => _queueLevelActionEnabled; + set => this.RaiseAndSetIfChanged(ref _queueLevelActionEnabled, value); + } + public MainWindowViewModel() + { + _loggingService = Locator.Current.GetService(); + _topicHelper = Locator.Current.GetService(); + _queueHelper = Locator.Current.GetService(); + _appState = Locator.Current.GetService(); - Messages = new ObservableCollection(); - DlqMessages = new ObservableCollection(); - ConnectedServiceBuses = new ObservableCollection(); + Messages = new ObservableCollection(); + DlqMessages = new ObservableCollection(); + ConnectedServiceBuses = new ObservableCollection(); - _queueLevelActionEnabled = this.WhenAnyValue( - x => x.CurrentSubscription, - x=> x.CurrentQueue, - (subscription, queue) => subscription != null || queue != null - ); + _queueLevelActionEnabled = this.WhenAnyValue( + x => x.CurrentSubscription, + x=> x.CurrentQueue, + (subscription, queue) => subscription != null || queue != null + ); - RefreshTabHeaders(); + RefreshTabHeaders(); - AppVersionText = AppVersion.ToString(3); - LoggingService.Log($"PurpleExplorer v{AppVersionText}"); + AppVersionText = AppVersion.ToString(3); + LoggingService.Log($"PurpleExplorer v{AppVersionText}"); - // Checking for new version asynchronous. no need to await on it + // Checking for new version asynchronous. no need to await on it #pragma warning disable 4014 - CheckForNewVersion(); + CheckForNewVersion(); #pragma warning restore 4014 + } + + private async Task CheckForNewVersion() + { + var latestRelease = await AppVersionHelper.GetLatestRelease(); + var latestReleaseVersion = new Version(latestRelease.Name); + if (latestReleaseVersion > AppVersion) + { + AppVersionText = $"new v{latestReleaseVersion} is available"; + this.RaisePropertyChanged(nameof(AppVersionText)); + + var message = + $"New version v{latestReleaseVersion} is available. \n Download today at {latestRelease.HtmlUrl}"; + LoggingService.Log(message); + await MessageBoxHelper.ShowMessage("New version available", message); + } + else + { + LoggingService.Log($"v{AppVersion} is the latest released version"); } + } + + public async void ConnectionBtnPopupCommand() + { + var viewModel = new ConnectionStringWindowViewModel(); - private async Task CheckForNewVersion() + var returnedViewModel = + await ModalWindowHelper.ShowModalWindow( + viewModel); + + if (returnedViewModel.Cancel) { - var latestRelease = await AppVersionHelper.GetLatestRelease(); - var latestReleaseVersion = new Version(latestRelease.name); - if (latestReleaseVersion > AppVersion) - { - AppVersionText = $"new v{latestReleaseVersion} is available"; - this.RaisePropertyChanged(nameof(AppVersionText)); - - var message = - $"New version v{latestReleaseVersion} is available. \n Download today at {latestRelease.html_url}"; - LoggingService.Log(message); - await MessageBoxHelper.ShowMessage("New version available", message); - } - else - { - LoggingService.Log($"v{AppVersion} is the latest released version"); - } + return; } - public async void ConnectionBtnPopupCommand() + ConnectionString = new ServiceBusConnectionString { - var viewModel = new ConnectionStringWindowViewModel(); + ConnectionString = returnedViewModel.ConnectionString, + UseManagedIdentity= returnedViewModel.UseManagedIdentity + }; - var returnedViewModel = - await ModalWindowHelper.ShowModalWindow( - viewModel); + if (string.IsNullOrEmpty(ConnectionString.ConnectionString)) + { + return; + } - if (returnedViewModel.Cancel) - { - return; - } + try + { + LoggingService.Log("Connecting..."); - ConnectionString = new ServiceBusConnectionString - { - ConnectionString = returnedViewModel.ConnectionString, - UseManagedIdentity= returnedViewModel.UseManagedIdentity - }; + var namespaceInfo = await _topicHelper.GetNamespaceInfo(ConnectionString); + var topics = await _topicHelper.GetTopicsAndSubscriptions(ConnectionString); + var queues = await _queueHelper.GetQueues(ConnectionString); - if (string.IsNullOrEmpty(ConnectionString.ConnectionString)) + var serviceBusResource = new ServiceBusResource { - return; - } + Name = namespaceInfo.Name, + CreatedTime = namespaceInfo.CreatedTime, + ConnectionString = ConnectionString + }; - try - { - LoggingService.Log("Connecting..."); - - var namespaceInfo = await _topicHelper.GetNamespaceInfo(ConnectionString); - var topics = await _topicHelper.GetTopicsAndSubscriptions(ConnectionString); - var queues = await _queueHelper.GetQueues(ConnectionString); - - var serviceBusResource = new ServiceBusResource - { - Name = namespaceInfo.Name, - CreatedTime = namespaceInfo.CreatedTime, - ConnectionString = ConnectionString - }; - - serviceBusResource.AddQueues(queues.ToArray()); - serviceBusResource.AddTopics(topics.ToArray()); - ConnectedServiceBuses.Add(serviceBusResource); - LoggingService.Log("Connected to Service Bus: " + namespaceInfo.Name); - } - catch (ArgumentException) - { - await MessageBoxHelper.ShowError("The connection string is invalid."); - LoggingService.Log("Connection failed: The connection string is invalid"); - } - catch (UnauthorizedException) - { - await MessageBoxHelper.ShowError("Unable to connect to Service Bus; unauthorized."); - LoggingService.Log("Connection failed: Unauthorized"); - } - catch (ServiceBusException ex) - { - await MessageBoxHelper.ShowError($"Unable to connect to Service Bus; {ex.Message}"); - LoggingService.Log($"Connection failed: {ex.Message}"); - } - finally - { - RefreshTabHeaders(); - } + serviceBusResource.AddQueues(queues.ToArray()); + serviceBusResource.AddTopics(topics.ToArray()); + ConnectedServiceBuses.Add(serviceBusResource); + LoggingService.Log("Connected to Service Bus: " + namespaceInfo.Name); } - - public async Task FetchSubscriptionMessages() + catch (ArgumentException) { - if (CurrentSubscription == null) - { - return; - } - - Messages.Clear(); - CurrentSubscription.ClearMessages(); - var messages = - await _topicHelper.GetMessagesBySubscription(CurrentSubscription.Topic.ServiceBus.ConnectionString, - CurrentSubscription.Topic.Name, - CurrentSubscription.Name); - CurrentSubscription.AddMessages(messages); - Messages.AddRange(messages); + await MessageBoxHelper.ShowError("The connection string is invalid."); + LoggingService.Log("Connection failed: The connection string is invalid"); + } + catch (UnauthorizedException) + { + await MessageBoxHelper.ShowError("Unable to connect to Service Bus; unauthorized."); + LoggingService.Log("Connection failed: Unauthorized"); + } + catch (ServiceBusException ex) + { + await MessageBoxHelper.ShowError($"Unable to connect to Service Bus; {ex.Message}"); + LoggingService.Log($"Connection failed: {ex.Message}"); + } + finally + { + RefreshTabHeaders(); } + } - public async Task FetchSubscriptionDlqMessages() + public async Task FetchSubscriptionMessages() + { + if (CurrentSubscription == null) { - if (CurrentSubscription == null) - { - return; - } + return; + } - DlqMessages.Clear(); - CurrentSubscription.ClearDlqMessages(); - var dlqMessages = - await _topicHelper.GetDlqMessages(CurrentSubscription.Topic.ServiceBus.ConnectionString, - CurrentSubscription.Topic.Name, CurrentSubscription.Name); - CurrentSubscription.AddDlqMessages(dlqMessages); - DlqMessages.AddRange(dlqMessages); + Messages.Clear(); + CurrentSubscription.ClearMessages(); + var messages = + await _topicHelper.GetMessagesBySubscription(CurrentSubscription.Topic.ServiceBus.ConnectionString, + CurrentSubscription.Topic.Name, + CurrentSubscription.Name); + CurrentSubscription.AddMessages(messages); + Messages.AddRange(messages); + } + + public async Task FetchSubscriptionDlqMessages() + { + if (CurrentSubscription == null) + { + return; } + + DlqMessages.Clear(); + CurrentSubscription.ClearDlqMessages(); + var dlqMessages = + await _topicHelper.GetDlqMessages(CurrentSubscription.Topic.ServiceBus.ConnectionString, + CurrentSubscription.Topic.Name, CurrentSubscription.Name); + CurrentSubscription.AddDlqMessages(dlqMessages); + DlqMessages.AddRange(dlqMessages); + } - public async Task FetchQueueMessages() + public async Task FetchQueueMessages() + { + if (CurrentQueue == null) { - if (CurrentQueue == null) - { - return; - } - - Messages.Clear(); - CurrentQueue.ClearMessages(); - var messages = await _queueHelper.GetMessages(CurrentQueue.ServiceBus.ConnectionString, CurrentQueue.Name); - CurrentQueue.AddMessages(messages); - Messages.AddRange(messages); + return; } + + Messages.Clear(); + CurrentQueue.ClearMessages(); + var messages = await _queueHelper.GetMessages(CurrentQueue.ServiceBus.ConnectionString, CurrentQueue.Name); + CurrentQueue.AddMessages(messages); + Messages.AddRange(messages); + } - public async Task FetchQueueDlqMessages() + public async Task FetchQueueDlqMessages() + { + if (CurrentQueue == null) { - if (CurrentQueue == null) - { - return; - } - - DlqMessages.Clear(); - CurrentQueue.ClearDlqMessages(); - var messages = await _queueHelper.GetDlqMessages(CurrentQueue.ServiceBus.ConnectionString, CurrentQueue.Name); - CurrentQueue.AddDlqMessages(messages); - DlqMessages.AddRange(messages); + return; } + + DlqMessages.Clear(); + CurrentQueue.ClearDlqMessages(); + var messages = await _queueHelper.GetDlqMessages(CurrentQueue.ServiceBus.ConnectionString, CurrentQueue.Name); + CurrentQueue.AddDlqMessages(messages); + DlqMessages.AddRange(messages); + } - public void RefreshTabHeaders() + public void RefreshTabHeaders() + { + if (CurrentMessageCollection != null) { - if (CurrentMessageCollection != null) - { - MessagesTabHeader = $"Messages ({CurrentMessageCollection.MessageCount})"; - DlqTabHeader = $"Dead-letter ({CurrentMessageCollection.DlqCount})"; - } - else - { - MessagesTabHeader = "Messages"; - DlqTabHeader = "Dead-letter"; - } - - var topicCount = ConnectedServiceBuses.Sum(x => x.Topics.Count); - var queueCount = ConnectedServiceBuses.Sum(x => x.Queues.Count); - if (topicCount > 0 || queueCount > 0) - { - TopicTabHeader = $"Topics ({topicCount})"; - QueueTabHeader = $"Queues ({queueCount})"; - } - else - { - TopicTabHeader = "Topics"; - QueueTabHeader = "Queues"; - } + MessagesTabHeader = $"Messages ({CurrentMessageCollection.MessageCount})"; + DlqTabHeader = $"Dead-letter ({CurrentMessageCollection.DlqCount})"; } - - public async Task RefreshConnectedServiceBuses() + else { - foreach (var serviceBusResource in ConnectedServiceBuses) - { - var topicsAndSubscriptions = await _topicHelper.GetTopicsAndSubscriptions(serviceBusResource.ConnectionString); - var serviceBusQueues = await _queueHelper.GetQueues(serviceBusResource.ConnectionString); + MessagesTabHeader = "Messages"; + DlqTabHeader = "Dead-letter"; + } - serviceBusResource.Topics.Clear(); - serviceBusResource.Queues.Clear(); - serviceBusResource.AddTopics(topicsAndSubscriptions.ToArray()); - serviceBusResource.AddQueues(serviceBusQueues.ToArray()); - } + var topicCount = ConnectedServiceBuses.Sum(x => x.Topics.Count); + var queueCount = ConnectedServiceBuses.Sum(x => x.Queues.Count); + if (topicCount > 0 || queueCount > 0) + { + TopicTabHeader = $"Topics ({topicCount})"; + QueueTabHeader = $"Queues ({queueCount})"; } - - public async void AddMessage() + else { - var viewModal = new AddMessageWindowViewModal(); + TopicTabHeader = "Topics"; + QueueTabHeader = "Queues"; + } + } - var returnedViewModal = - await ModalWindowHelper.ShowModalWindow(viewModal); + public async Task RefreshConnectedServiceBuses() + { + foreach (var serviceBusResource in ConnectedServiceBuses) + { + var topicsAndSubscriptions = await _topicHelper.GetTopicsAndSubscriptions(serviceBusResource.ConnectionString); + var serviceBusQueues = await _queueHelper.GetQueues(serviceBusResource.ConnectionString); - if (returnedViewModal.Cancel) - { - return; - } + serviceBusResource.Topics.Clear(); + serviceBusResource.Queues.Clear(); + serviceBusResource.AddTopics(topicsAndSubscriptions.ToArray()); + serviceBusResource.AddQueues(serviceBusQueues.ToArray()); + } + } + + public async void AddMessage() + { + var viewModal = new AddMessageWindowViewModal(); - var messageText = returnedViewModal.Message.Trim(); - if (string.IsNullOrEmpty(messageText)) - { - return; - } - - LoggingService.Log("Sending message..."); - if (CurrentTopic != null) - { - var connectionString = CurrentTopic.ServiceBus.ConnectionString; - await _topicHelper.SendMessage(connectionString, CurrentTopic.Name, messageText); - } + var returnedViewModal = + await ModalWindowHelper.ShowModalWindow(viewModal); - if (CurrentQueue != null) - { - var connectionString = CurrentQueue.ServiceBus.ConnectionString; - await _queueHelper.SendMessage(connectionString, CurrentQueue.Name, messageText); - } - LoggingService.Log("Message sent"); + if (returnedViewModal.Cancel) + { + return; } - public async void TransferDeadletterMessages() + var messageText = returnedViewModal.Message.Trim(); + if (string.IsNullOrEmpty(messageText)) { - string dlqPath = null; - string transferTo = null; - if (_currentSubscription != null) - { - transferTo = $"{_currentTopic.Name}/{_currentSubscription.Name}"; - dlqPath = $"{transferTo}/$DeadLetterQueue"; - } - - if (_currentQueue != null) - { - transferTo = $"{_currentQueue.Name}"; - dlqPath = $"{transferTo}/$DeadLetterQueue"; - } - - var buttonResult = await MessageBoxHelper.ShowConfirmation( - "Transferring messages from DLQ", - $"Are you sure you would like to transfer ALL the messages on {dlqPath} back to {transferTo}?"); + return; + } - // Because buttonResult can be None or No - if (buttonResult != ButtonResult.Yes) - { - CurrentMessage = null; - return; - } - - LoggingService.Log($"Transferring ALL messages in {dlqPath}... (might take some time)"); - long transferCount = -1; - if (CurrentSubscription != null) - { - var connectionString = CurrentSubscription.Topic.ServiceBus.ConnectionString; - transferCount = await _topicHelper.TransferDlqMessages(connectionString, _currentTopic.Name, - _currentSubscription.Name); - } - - if (CurrentQueue != null) - { - var connectionString = CurrentQueue.ServiceBus.ConnectionString; - transferCount = await _queueHelper.TransferDlqMessages(connectionString, _currentQueue.Name); - } - LoggingService.Log($"Transferred {transferCount} messages in {dlqPath}"); + LoggingService.Log("Sending message..."); + if (CurrentTopic != null) + { + var connectionString = CurrentTopic.ServiceBus.ConnectionString; + await _topicHelper.SendMessage(connectionString, CurrentTopic.Name, messageText); } - public async void PurgeMessages(string isDlqText) + if (CurrentQueue != null) { - var isDlq = Convert.ToBoolean(isDlqText); - string purgingPath = null; - if (_currentSubscription != null) - { - purgingPath = isDlq - ? $"{_currentTopic.Name}/{_currentSubscription.Name}/$DeadLetterQueue" - : $"{_currentTopic.Name}/{_currentSubscription.Name}"; - } - - if (_currentQueue != null) - { - purgingPath = isDlq - ? $"{_currentQueue.Name}/$DeadLetterQueue" - : $"{_currentQueue.Name}"; - } - - var buttonResult = await MessageBoxHelper.ShowConfirmation( - $"Purging messages from {purgingPath}", - $"Are you sure you would like to purge ALL the messages from {purgingPath}?"); - - // Because buttonResult can be None or No - if (buttonResult != ButtonResult.Yes) - { - CurrentMessage = null; - return; - } - - LoggingService.Log($"Purging ALL messages in {purgingPath}... (might take some time)"); - long purgedCount = -1; - if (CurrentSubscription != null) - { - var connectionString = CurrentSubscription.Topic.ServiceBus.ConnectionString; - purgedCount = await _topicHelper.PurgeMessages(connectionString, _currentTopic.Name, - _currentSubscription.Name, isDlq); - - if (!isDlq) - CurrentSubscription.ClearMessages(); - else - CurrentSubscription.ClearDlqMessages(); - } - - if (CurrentQueue != null) - { - var connectionString = CurrentQueue.ServiceBus.ConnectionString; - purgedCount = await _queueHelper.PurgeMessages(connectionString, _currentQueue.Name, isDlq); - - if (!isDlq) - CurrentQueue.ClearMessages(); - else - CurrentQueue.ClearDlqMessages(); - } - LoggingService.Log($"Purged {purgedCount} messages in {purgingPath}"); + var connectionString = CurrentQueue.ServiceBus.ConnectionString; + await _queueHelper.SendMessage(connectionString, CurrentQueue.Name, messageText); + } + LoggingService.Log("Message sent"); + } - // Refreshing messages - await FetchMessages(); + public async void TransferDeadletterMessages() + { + string dlqPath = null; + string transferTo = null; + if (_currentSubscription != null) + { + transferTo = $"{_currentTopic.Name}/{_currentSubscription.Name}"; + dlqPath = $"{transferTo}/$DeadLetterQueue"; } - public async Task Refresh() + if (_currentQueue != null) { - await RefreshConnectedServiceBuses(); - RefreshTabHeaders(); - await FetchMessages(); + transferTo = $"{_currentQueue.Name}"; + dlqPath = $"{transferTo}/$DeadLetterQueue"; } - - public async Task FetchMessages() + + var buttonResult = await MessageBoxHelper.ShowConfirmation( + "Transferring messages from DLQ", + $"Are you sure you would like to transfer ALL the messages on {dlqPath} back to {transferTo}?"); + + // Because buttonResult can be None or No + if (buttonResult != ButtonResult.Yes) { - LoggingService.Log("Fetching messages..."); - - await Task.WhenAll( - FetchSubscriptionMessages(), - FetchSubscriptionDlqMessages(), - FetchQueueMessages(), - FetchQueueDlqMessages() - ); + CurrentMessage = null; + return; + } - LoggingService.Log("Fetched messages"); + LoggingService.Log($"Transferring ALL messages in {dlqPath}... (might take some time)"); + long transferCount = -1; + if (CurrentSubscription != null) + { + var connectionString = CurrentSubscription.Topic.ServiceBus.ConnectionString; + transferCount = await _topicHelper.TransferDlqMessages(connectionString, _currentTopic.Name, + _currentSubscription.Name); } - public void SetSelectedSubscription(ServiceBusSubscription subscription) + if (CurrentQueue != null) { - CurrentSubscription = subscription; - CurrentTopic = subscription.Topic; - LoggingService.Log("Subscription selected: " + subscription.Name); + var connectionString = CurrentQueue.ServiceBus.ConnectionString; + transferCount = await _queueHelper.TransferDlqMessages(connectionString, _currentQueue.Name); } + LoggingService.Log($"Transferred {transferCount} messages in {dlqPath}"); + } - public void SetSelectedTopic(ServiceBusTopic selectedTopic) + public async void PurgeMessages(string isDlqText) + { + var isDlq = Convert.ToBoolean(isDlqText); + string purgingPath = null; + if (_currentSubscription != null) { - CurrentTopic = selectedTopic; - LoggingService.Log("Topic selected: " + selectedTopic.Name); + purgingPath = isDlq + ? $"{_currentTopic.Name}/{_currentSubscription.Name}/$DeadLetterQueue" + : $"{_currentTopic.Name}/{_currentSubscription.Name}"; } - public void SetSelectedMessage(Message message) + if (_currentQueue != null) { - CurrentMessage = message; - LoggingService.Log("Message selected: " + message.MessageId); + purgingPath = isDlq + ? $"{_currentQueue.Name}/$DeadLetterQueue" + : $"{_currentQueue.Name}"; } - public void SetSelectedQueue(ServiceBusQueue selectedQueue) + var buttonResult = await MessageBoxHelper.ShowConfirmation( + $"Purging messages from {purgingPath}", + $"Are you sure you would like to purge ALL the messages from {purgingPath}?"); + + // Because buttonResult can be None or No + if (buttonResult != ButtonResult.Yes) { - CurrentQueue = selectedQueue; - LoggingService.Log("Queue selected: " + selectedQueue.Name); + CurrentMessage = null; + return; } - public async Task ShowSettings() + LoggingService.Log($"Purging ALL messages in {purgingPath}... (might take some time)"); + long purgedCount = -1; + if (CurrentSubscription != null) { - await ModalWindowHelper.ShowModalWindow(_appState as AppState); + var connectionString = CurrentSubscription.Topic.ServiceBus.ConnectionString; + purgedCount = await _topicHelper.PurgeMessages(connectionString, _currentTopic.Name, + _currentSubscription.Name, isDlq); + + if (!isDlq) + CurrentSubscription.ClearMessages(); + else + CurrentSubscription.ClearDlqMessages(); } - - public void ClearAllSelections() + + if (CurrentQueue != null) { - CurrentSubscription = null; - CurrentTopic = null; - CurrentQueue = null; - CurrentMessage = null; - Messages.Clear(); - DlqMessages.Clear(); - RefreshTabHeaders(); + var connectionString = CurrentQueue.ServiceBus.ConnectionString; + purgedCount = await _queueHelper.PurgeMessages(connectionString, _currentQueue.Name, isDlq); + + if (!isDlq) + CurrentQueue.ClearMessages(); + else + CurrentQueue.ClearDlqMessages(); } + LoggingService.Log($"Purged {purgedCount} messages in {purgingPath}"); + + // Refreshing messages + await FetchMessages(); + } + + public async Task Refresh() + { + await RefreshConnectedServiceBuses(); + RefreshTabHeaders(); + await FetchMessages(); + } + + public async Task FetchMessages() + { + LoggingService.Log("Fetching messages..."); + + await Task.WhenAll( + FetchSubscriptionMessages(), + FetchSubscriptionDlqMessages(), + FetchQueueMessages(), + FetchQueueDlqMessages() + ); + + LoggingService.Log("Fetched messages"); + } + + public void SetSelectedSubscription(ServiceBusSubscription subscription) + { + CurrentSubscription = subscription; + CurrentTopic = subscription.Topic; + LoggingService.Log("Subscription selected: " + subscription.Name); + } + + public void SetSelectedTopic(ServiceBusTopic selectedTopic) + { + CurrentTopic = selectedTopic; + LoggingService.Log("Topic selected: " + selectedTopic.Name); + } + + public void SetSelectedMessage(Message message) + { + CurrentMessage = message; + LoggingService.Log("Message selected: " + message.MessageId); + } + + public void SetSelectedQueue(ServiceBusQueue selectedQueue) + { + CurrentQueue = selectedQueue; + LoggingService.Log("Queue selected: " + selectedQueue.Name); + } + + public async Task ShowSettings() + { + await ModalWindowHelper.ShowModalWindow(_appState as AppState); + } + + public void ClearAllSelections() + { + CurrentSubscription = null; + CurrentTopic = null; + CurrentQueue = null; + CurrentMessage = null; + Messages.Clear(); + DlqMessages.Clear(); + RefreshTabHeaders(); } } \ No newline at end of file diff --git a/PurpleExplorer/ViewModels/MessageDetailsWindowViewModel.cs b/PurpleExplorer/ViewModels/MessageDetailsWindowViewModel.cs index b8e02a4..2cfd0ab 100644 --- a/PurpleExplorer/ViewModels/MessageDetailsWindowViewModel.cs +++ b/PurpleExplorer/ViewModels/MessageDetailsWindowViewModel.cs @@ -6,138 +6,137 @@ using PurpleExplorer.Services; using Splat; -namespace PurpleExplorer.ViewModels +namespace PurpleExplorer.ViewModels; + +public class MessageDetailsWindowViewModel : ViewModelBase { - public class MessageDetailsWindowViewModel : ViewModelBase + private readonly ITopicHelper _topicHelper; + private readonly IQueueHelper _queueHelper; + private readonly ILoggingService _loggingService; + + public Message Message { get; set; } + public ServiceBusSubscription Subscription { get; set; } + public ServiceBusQueue Queue { get; set; } + public ServiceBusConnectionString ConnectionString { get; set; } + + public MessageDetailsWindowViewModel(ITopicHelper topicHelper = null, + ILoggingService loggingService = null, + IQueueHelper queueHelper = null) + { + _loggingService = loggingService ?? Locator.Current.GetService(); + _topicHelper = topicHelper ?? Locator.Current.GetService(); + _queueHelper = queueHelper ?? Locator.Current.GetService(); + } + + public async void DeleteMessage(Window window) { - private readonly ITopicHelper _topicHelper; - private readonly IQueueHelper _queueHelper; - private readonly ILoggingService _loggingService; - - public Message Message { get; set; } - public ServiceBusSubscription Subscription { get; set; } - public ServiceBusQueue Queue { get; set; } - public ServiceBusConnectionString ConnectionString { get; set; } - - public MessageDetailsWindowViewModel(ITopicHelper topicHelper = null, - ILoggingService loggingService = null, - IQueueHelper queueHelper = null) + _loggingService.Log("DANGER NOTE: Deleting requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages"); + string deletingPath = null; + if (Subscription != null) { - _loggingService = loggingService ?? Locator.Current.GetService(); - _topicHelper = topicHelper ?? Locator.Current.GetService(); - _queueHelper = queueHelper ?? Locator.Current.GetService(); + deletingPath = Message.IsDlq + ? $"{Subscription.Topic.Name}/{Subscription.Name}/$DeadLetterQueue" + : $"{Subscription.Topic.Name}/{Subscription.Name}"; } - public async void DeleteMessage(Window window) + if (Queue != null) { - _loggingService.Log("DANGER NOTE: Deleting requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages"); - string deletingPath = null; - if (Subscription != null) - { - deletingPath = Message.IsDlq - ? $"{Subscription.Topic.Name}/{Subscription.Name}/$DeadLetterQueue" - : $"{Subscription.Topic.Name}/{Subscription.Name}"; - } - - if (Queue != null) - { - deletingPath = Message.IsDlq - ? $"{Queue.Name}/$DeadLetterQueue" - : $"{Queue.Name}"; - } + deletingPath = Message.IsDlq + ? $"{Queue.Name}/$DeadLetterQueue" + : $"{Queue.Name}"; + } - var buttonResult = await MessageBoxHelper.ShowConfirmation( - $"Deleting message from {deletingPath}", - $"DANGER!!! READ CAREFULLY \n" + - $"Deleting requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages. \n" + - $"There can be consequences to other messages in this subscription, Are you sure? \n \n" + - $"Are you sure you would like to delete the message with ID: {Message.MessageId} AND increase the delivery count of ALL the messages before it?"); - - // Because buttonResult can be None or No - if (buttonResult != ButtonResult.Yes) - { - return; - } - - _loggingService.Log($"User accepted to receive messages in order to delete message {Message.MessageId}. This is going to increases the DeliveryCount of the messages before it."); - _loggingService.Log($"Deleting message {Message.MessageId}... (might take some seconds)"); - - if (Subscription != null) - { - var connectionString = Subscription.Topic.ServiceBus.ConnectionString; - await _topicHelper.DeleteMessage(connectionString, Subscription.Topic.Name, Subscription.Name, - Message, Message.IsDlq); - - if(!Message.IsDlq) - Subscription.RemoveMessage(Message.MessageId); - else - Subscription.RemoveDlqMessage(Message.MessageId); - } - - if (Queue != null) - { - var connectionString = Queue.ServiceBus.ConnectionString; - await _queueHelper.DeleteMessage(connectionString, Queue.Name, Message, Message.IsDlq); + var buttonResult = await MessageBoxHelper.ShowConfirmation( + $"Deleting message from {deletingPath}", + $"DANGER!!! READ CAREFULLY \n" + + $"Deleting requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages. \n" + + $"There can be consequences to other messages in this subscription, Are you sure? \n \n" + + $"Are you sure you would like to delete the message with ID: {Message.MessageId} AND increase the delivery count of ALL the messages before it?"); + + // Because buttonResult can be None or No + if (buttonResult != ButtonResult.Yes) + { + return; + } + + _loggingService.Log($"User accepted to receive messages in order to delete message {Message.MessageId}. This is going to increases the DeliveryCount of the messages before it."); + _loggingService.Log($"Deleting message {Message.MessageId}... (might take some seconds)"); + + if (Subscription != null) + { + var connectionString = Subscription.Topic.ServiceBus.ConnectionString; + await _topicHelper.DeleteMessage(connectionString, Subscription.Topic.Name, Subscription.Name, + Message, Message.IsDlq); - if(!Message.IsDlq) - Queue.RemoveMessage(Message.MessageId); - else - Queue.RemoveDlqMessage(Message.MessageId); - } - - _loggingService.Log($"Message deleted, MessageId: {Message.MessageId}"); - window.Close(); + if(!Message.IsDlq) + Subscription.RemoveMessage(Message.MessageId); + else + Subscription.RemoveDlqMessage(Message.MessageId); } - public async Task ResubmitMessage() + if (Queue != null) { - _loggingService.Log($"Resending DLQ message: {Message.MessageId}"); + var connectionString = Queue.ServiceBus.ConnectionString; + await _queueHelper.DeleteMessage(connectionString, Queue.Name, Message, Message.IsDlq); + + if(!Message.IsDlq) + Queue.RemoveMessage(Message.MessageId); + else + Queue.RemoveDlqMessage(Message.MessageId); + } + + _loggingService.Log($"Message deleted, MessageId: {Message.MessageId}"); + window.Close(); + } - if (Subscription != null) - { - await _topicHelper.ResubmitDlqMessage(ConnectionString, Subscription.Topic.Name, Subscription.Name, - Message); - } + public async Task ResubmitMessage() + { + _loggingService.Log($"Resending DLQ message: {Message.MessageId}"); - if (Queue != null) - { - await _queueHelper.ResubmitDlqMessage(ConnectionString, Queue.Name, Message); - } + if (Subscription != null) + { + await _topicHelper.ResubmitDlqMessage(ConnectionString, Subscription.Topic.Name, Subscription.Name, + Message); + } - _loggingService.Log($"Resent DLQ message: {Message.MessageId}"); + if (Queue != null) + { + await _queueHelper.ResubmitDlqMessage(ConnectionString, Queue.Name, Message); } + + _loggingService.Log($"Resent DLQ message: {Message.MessageId}"); + } - public async Task DeadletterMessage() + public async Task DeadletterMessage() + { + _loggingService.Log("DANGER NOTE: Sending to dead-letter requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages"); + var buttonResult = await MessageBoxHelper.ShowConfirmation( + $"Sending message to dead-letter", + $"DANGER!!! READ CAREFULLY \n" + + $"Sending to dead-letter requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages. \n" + + $"There can be consequences to other messages in this subscription, Are you sure? \n \n" + + $"Are you sure you would like to send the message {Message.MessageId} AND increase the delivery count of ALL the messages before it?"); + + // Because buttonResult can be None or No + if (buttonResult != ButtonResult.Yes) { - _loggingService.Log("DANGER NOTE: Sending to dead-letter requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages"); - var buttonResult = await MessageBoxHelper.ShowConfirmation( - $"Sending message to dead-letter", - $"DANGER!!! READ CAREFULLY \n" + - $"Sending to dead-letter requires receiving all the messages up to the selected message to perform this action and this increases the DeliveryCount of the messages. \n" + - $"There can be consequences to other messages in this subscription, Are you sure? \n \n" + - $"Are you sure you would like to send the message {Message.MessageId} AND increase the delivery count of ALL the messages before it?"); - - // Because buttonResult can be None or No - if (buttonResult != ButtonResult.Yes) - { - return; - } + return; + } - _loggingService.Log($"User accepted to receive messages in order to send message {Message.MessageId} to dead-letter. This is going to increases the DeliveryCount of the messages before it."); - _loggingService.Log($"Sending message: {Message.MessageId} to dead-letter"); + _loggingService.Log($"User accepted to receive messages in order to send message {Message.MessageId} to dead-letter. This is going to increases the DeliveryCount of the messages before it."); + _loggingService.Log($"Sending message: {Message.MessageId} to dead-letter"); - if (Subscription != null) - { - await _topicHelper.DeadletterMessage(ConnectionString, Subscription.Topic.Name, Subscription.Name, - Message); - } - - if (Queue != null) - { - await _queueHelper.DeadletterMessage(ConnectionString, Queue.Name, Message); - } + if (Subscription != null) + { + await _topicHelper.DeadletterMessage(ConnectionString, Subscription.Topic.Name, Subscription.Name, + Message); + } - _loggingService.Log($"Sent message: {Message.MessageId} to dead-letter"); + if (Queue != null) + { + await _queueHelper.DeadletterMessage(ConnectionString, Queue.Name, Message); } + + _loggingService.Log($"Sent message: {Message.MessageId} to dead-letter"); } } \ No newline at end of file diff --git a/PurpleExplorer/ViewModels/ViewModelBase.cs b/PurpleExplorer/ViewModels/ViewModelBase.cs index d9154de..a18928a 100644 --- a/PurpleExplorer/ViewModels/ViewModelBase.cs +++ b/PurpleExplorer/ViewModels/ViewModelBase.cs @@ -1,11 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Text; -using ReactiveUI; +using ReactiveUI; -namespace PurpleExplorer.ViewModels +namespace PurpleExplorer.ViewModels; + +public class ViewModelBase : ReactiveObject { - public class ViewModelBase : ReactiveObject - { - } } \ No newline at end of file diff --git a/PurpleExplorer/Views/AddMessageWindow.xaml.cs b/PurpleExplorer/Views/AddMessageWindow.xaml.cs index fee3ea6..14a8fe5 100644 --- a/PurpleExplorer/Views/AddMessageWindow.xaml.cs +++ b/PurpleExplorer/Views/AddMessageWindow.xaml.cs @@ -5,46 +5,45 @@ using PurpleExplorer.Models; using PurpleExplorer.ViewModels; -namespace PurpleExplorer.Views +namespace PurpleExplorer.Views; + +public class AddMessageWindow : Window { - public class AddMessageWindow : Window + public AddMessageWindow() { - public AddMessageWindow() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void InitializeComponent() - { - AvaloniaXamlLoader.Load(this); - } + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + } - public async void btnAddClick(object sender, RoutedEventArgs e) + public async void btnAddClick(object sender, RoutedEventArgs e) + { + var dataContext = DataContext as AddMessageWindowViewModal; + if (string.IsNullOrEmpty(dataContext.Message)) + await MessageBoxHelper.ShowError("Please enter a message to be sent"); + else { - var dataContext = DataContext as AddMessageWindowViewModal; - if (string.IsNullOrEmpty(dataContext.Message)) - await MessageBoxHelper.ShowError("Please enter a message to be sent"); - else - { - dataContext.Cancel = false; - Close(); - } + dataContext.Cancel = false; + Close(); } + } - public void btnDeleteMessage(object sender, RoutedEventArgs e) - { - var dataContext = DataContext as AddMessageWindowViewModal; - var dataGrid = this.FindControl("dgSavedMessages"); - dataContext.SavedMessages.Remove(dataGrid.SelectedItem as SavedMessage); - } + public void btnDeleteMessage(object sender, RoutedEventArgs e) + { + var dataContext = DataContext as AddMessageWindowViewModal; + var dataGrid = this.FindControl("dgSavedMessages"); + dataContext.SavedMessages.Remove(dataGrid.SelectedItem as SavedMessage); + } - public void messageSelectionChanged(object sender, SelectionChangedEventArgs e) - { - var dataContext = DataContext as AddMessageWindowViewModal; - var dataGrid = sender as DataGrid; - var selectedMessage = dataGrid.SelectedItem as SavedMessage; - dataContext.Message = selectedMessage?.Message; - dataContext.Title = selectedMessage?.Title; - } + public void messageSelectionChanged(object sender, SelectionChangedEventArgs e) + { + var dataContext = DataContext as AddMessageWindowViewModal; + var dataGrid = sender as DataGrid; + var selectedMessage = dataGrid.SelectedItem as SavedMessage; + dataContext.Message = selectedMessage?.Message; + dataContext.Title = selectedMessage?.Title; } } \ No newline at end of file diff --git a/PurpleExplorer/Views/AppSettingsWindow.axaml.cs b/PurpleExplorer/Views/AppSettingsWindow.axaml.cs index 1b75774..56e1866 100644 --- a/PurpleExplorer/Views/AppSettingsWindow.axaml.cs +++ b/PurpleExplorer/Views/AppSettingsWindow.axaml.cs @@ -1,8 +1,6 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; -using PurpleExplorer.Models; -using Splat; namespace PurpleExplorer.Views; diff --git a/PurpleExplorer/Views/ConnectionStringWindow.xaml b/PurpleExplorer/Views/ConnectionStringWindow.xaml index 5e3bfea..696762a 100644 --- a/PurpleExplorer/Views/ConnectionStringWindow.xaml +++ b/PurpleExplorer/Views/ConnectionStringWindow.xaml @@ -5,47 +5,50 @@ mc:Ignorable="d" d:DesignWidth="610" d:DesignHeight="480" x:Class="PurpleExplorer.Views.ConnectionStringWindow" xmlns:vm="clr-namespace:PurpleExplorer.ViewModels;assembly=PurpleExplorer" + xmlns:i="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia" + x:DataType="vm:ConnectionStringWindowViewModel" Title="Connect to Service Bus" Icon="/Assets/avalonia-logo.ico" - Width="610" Height="480" + Width="610" Height="510" WindowStartupLocation="CenterOwner"> - - - - - - - - - + + + - Managed Identity + Use Managed Identity - - - - - - + - - - - + + + + + + + @@ -55,9 +58,14 @@ - \ No newline at end of file diff --git a/PurpleExplorer/Views/ConnectionStringWindow.xaml.cs b/PurpleExplorer/Views/ConnectionStringWindow.xaml.cs index 218dc29..73c178b 100644 --- a/PurpleExplorer/Views/ConnectionStringWindow.xaml.cs +++ b/PurpleExplorer/Views/ConnectionStringWindow.xaml.cs @@ -1,68 +1,66 @@ using Avalonia.Controls; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; -using DynamicData; using PurpleExplorer.Helpers; using PurpleExplorer.ViewModels; using System.Linq; using Avalonia; -namespace PurpleExplorer.Views +namespace PurpleExplorer.Views; + +public class ConnectionStringWindow : Window { - public class ConnectionStringWindow : Window + public ConnectionStringWindow() { - public ConnectionStringWindow() - { - InitializeComponent(); + InitializeComponent(); #if DEBUG - this.AttachDevTools(); + this.AttachDevTools(); #endif - } + } - private void InitializeComponent() - { - AvaloniaXamlLoader.Load(this); - } - public async void btnSendClick(object sender, RoutedEventArgs e) + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + } + public async void btnSendClick(object sender, RoutedEventArgs e) + { + var dataContext = DataContext as ConnectionStringWindowViewModel; + if (string.IsNullOrEmpty(dataContext.ConnectionString)) + await MessageBoxHelper.ShowError("Please enter a service bus connection string."); + else { - var dataContext = this.DataContext as ConnectionStringWindowViewModel; - if (string.IsNullOrEmpty(dataContext.ConnectionString)) - await MessageBoxHelper.ShowError("Please enter a service bus connection string."); - else - { - dataContext.Cancel = false; - this.Close(); - } + dataContext.Cancel = false; + Close(); } + } - public async void btnSaveConnectionString(object sender, RoutedEventArgs e) - { - var dataContext = this.DataContext as ConnectionStringWindowViewModel; + public async void btnSaveConnectionString(object sender, RoutedEventArgs e) + { + var dataContext = DataContext as ConnectionStringWindowViewModel; - if (dataContext.SavedConnectionStrings.FirstOrDefault(x => x.ConnectionString == dataContext.ConnectionString && x.UseManagedIdentity == dataContext.UseManagedIdentity) != null) - await MessageBoxHelper.ShowMessage("Duplicate connection string", "This connection string is already saved."); - else - dataContext.SavedConnectionStrings.Add(new Models.ServiceBusConnectionString - { - ConnectionString = dataContext.ConnectionString, - UseManagedIdentity = dataContext.UseManagedIdentity - }); - } + if (dataContext.SavedConnectionStrings.FirstOrDefault(x => x.ConnectionString == dataContext.ConnectionString && x.UseManagedIdentity == dataContext.UseManagedIdentity) != null) + await MessageBoxHelper.ShowMessage("Duplicate connection string", "This connection string is already saved."); + else + dataContext.SavedConnectionStrings.Add(new Models.ServiceBusConnectionString + { + ConnectionString = dataContext.ConnectionString, + UseManagedIdentity = dataContext.UseManagedIdentity + }); + } - private void lsbConnectionStringSelectionChanged(object sender, SelectionChangedEventArgs e) - { - ListBox box = sender as ListBox; - var dataContext = this.DataContext as ConnectionStringWindowViewModel; - var serviceBusConnectionString = box.SelectedItem as Models.ServiceBusConnectionString; - dataContext.ConnectionString = serviceBusConnectionString.ConnectionString; - dataContext.UseManagedIdentity = serviceBusConnectionString.UseManagedIdentity; - } + private void lsbConnectionStringSelectionChanged(object sender, SelectionChangedEventArgs e) + { + var box = sender as ListBox; + var dataContext = DataContext as ConnectionStringWindowViewModel; + var serviceBusConnectionString = box.SelectedItem as Models.ServiceBusConnectionString; + dataContext.ConnectionString = serviceBusConnectionString.ConnectionString; + dataContext.UseManagedIdentity = serviceBusConnectionString.UseManagedIdentity; + } - public void btnDeleteConnectionString(object sender, RoutedEventArgs e) - { - var dataContext = this.DataContext as ConnectionStringWindowViewModel; - var listBox = this.FindControl("lsbSavedConnectionString"); - dataContext.SavedConnectionStrings.Remove(listBox.SelectedItem as Models.ServiceBusConnectionString); - } + public void btnDeleteConnectionString(object sender, RoutedEventArgs e) + { + var dataContext = DataContext as ConnectionStringWindowViewModel; + var listBox = this.FindControl("lsbSavedConnectionString"); + dataContext.SavedConnectionStrings.Remove(listBox.SelectedItem as Models.ServiceBusConnectionString); } -} +} \ No newline at end of file diff --git a/PurpleExplorer/Views/MainWindow.xaml b/PurpleExplorer/Views/MainWindow.xaml index 559c030..b6b928b 100644 --- a/PurpleExplorer/Views/MainWindow.xaml +++ b/PurpleExplorer/Views/MainWindow.xaml @@ -16,7 +16,7 @@ - + diff --git a/PurpleExplorer/Views/MainWindow.xaml.cs b/PurpleExplorer/Views/MainWindow.xaml.cs index 48deda3..f549cb6 100644 --- a/PurpleExplorer/Views/MainWindow.xaml.cs +++ b/PurpleExplorer/Views/MainWindow.xaml.cs @@ -6,92 +6,96 @@ using PurpleExplorer.Models; using PurpleExplorer.ViewModels; -namespace PurpleExplorer.Views +namespace PurpleExplorer.Views; + +public class MainWindow : Window { - public class MainWindow : Window + public MainWindow() { - public MainWindow() - { - InitializeComponent(); + InitializeComponent(); #if DEBUG - this.AttachDevTools(); + this.AttachDevTools(); #endif - } + } + + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + } - private void InitializeComponent() + private async void MessagesGrid_DoubleTapped(object sender, RoutedEventArgs e) + { + var grid = sender as DataGrid; + var mainWindowViewModel = DataContext as MainWindowViewModel; + + if (grid?.SelectedItem == null) { - AvaloniaXamlLoader.Load(this); + return; } - private async void MessagesGrid_DoubleTapped(object sender, RoutedEventArgs e) + var viewModal = new MessageDetailsWindowViewModel { - var grid = sender as DataGrid; - var mainWindowViewModel = DataContext as MainWindowViewModel; + Message = grid.SelectedItem as Message, + ConnectionString = mainWindowViewModel.ConnectionString, + Subscription = mainWindowViewModel.CurrentSubscription, + Queue = mainWindowViewModel.CurrentQueue + }; - var viewModal = new MessageDetailsWindowViewModel - { - Message = grid.SelectedItem as Message, - ConnectionString = mainWindowViewModel.ConnectionString, - Subscription = mainWindowViewModel.CurrentSubscription, - Queue = mainWindowViewModel.CurrentQueue - }; + await ModalWindowHelper.ShowModalWindow(viewModal); + } - await ModalWindowHelper.ShowModalWindow(viewModal); - } + private void MessagesGrid_Tapped(object sender, RoutedEventArgs e) + { + var grid = sender as DataGrid; + var mainWindowViewModel = DataContext as MainWindowViewModel; - private void MessagesGrid_Tapped(object sender, RoutedEventArgs e) + if (grid.SelectedItem is Message message) { - var grid = sender as DataGrid; - var mainWindowViewModel = DataContext as MainWindowViewModel; - - if (grid.SelectedItem is Message message) - { - mainWindowViewModel.SetSelectedMessage(message); - } + mainWindowViewModel.SetSelectedMessage(message); } + } - private async void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - var mainWindowViewModel = DataContext as MainWindowViewModel; - var treeView = sender as TreeView; + private async void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + var mainWindowViewModel = DataContext as MainWindowViewModel; + var treeView = sender as TreeView; - ClearOtherSelections(treeView); - mainWindowViewModel.ClearAllSelections(); + ClearOtherSelections(treeView); + mainWindowViewModel.ClearAllSelections(); - var selectedItem = treeView.SelectedItems.Count > 0 ? treeView.SelectedItems[0] : null; - if (selectedItem is ServiceBusSubscription selectedSubscription) - { - mainWindowViewModel.SetSelectedSubscription(selectedSubscription); - await mainWindowViewModel.FetchMessages(); - mainWindowViewModel.RefreshTabHeaders(); - } + var selectedItem = treeView.SelectedItems.Count > 0 ? treeView.SelectedItems[0] : null; + if (selectedItem is ServiceBusSubscription selectedSubscription) + { + mainWindowViewModel.SetSelectedSubscription(selectedSubscription); + await mainWindowViewModel.FetchMessages(); + mainWindowViewModel.RefreshTabHeaders(); + } - if (selectedItem is ServiceBusTopic selectedTopic) - { - mainWindowViewModel.SetSelectedTopic(selectedTopic); - } + if (selectedItem is ServiceBusTopic selectedTopic) + { + mainWindowViewModel.SetSelectedTopic(selectedTopic); + } - if (selectedItem is ServiceBusQueue selectedQueue) - { - mainWindowViewModel.SetSelectedQueue(selectedQueue); - await mainWindowViewModel.FetchMessages(); - mainWindowViewModel.RefreshTabHeaders(); - } + if (selectedItem is ServiceBusQueue selectedQueue) + { + mainWindowViewModel.SetSelectedQueue(selectedQueue); + await mainWindowViewModel.FetchMessages(); + mainWindowViewModel.RefreshTabHeaders(); } + } - private void ClearOtherSelections(TreeView currentTreeView) + private void ClearOtherSelections(TreeView currentTreeView) + { + var tvQueues = this.FindControl("tvQueues"); + var tvTopics = this.FindControl("tvTopics"); + if (currentTreeView == tvQueues) { - var tvQueues = this.FindControl("tvQueues"); - var tvTopics = this.FindControl("tvTopics"); - if (currentTreeView == tvQueues) - { - tvTopics.UnselectAll(); - } + tvTopics.UnselectAll(); + } - if (currentTreeView == tvTopics) - { - tvQueues.UnselectAll(); - } + if (currentTreeView == tvTopics) + { + tvQueues.UnselectAll(); } } } \ No newline at end of file diff --git a/PurpleExplorer/Views/MessageDetailsWindow.xaml.cs b/PurpleExplorer/Views/MessageDetailsWindow.xaml.cs index a4a9b47..5150a11 100644 --- a/PurpleExplorer/Views/MessageDetailsWindow.xaml.cs +++ b/PurpleExplorer/Views/MessageDetailsWindow.xaml.cs @@ -2,21 +2,20 @@ using Avalonia.Controls; using Avalonia.Markup.Xaml; -namespace PurpleExplorer.Views +namespace PurpleExplorer.Views; + +public class MessageDetailsWindow : Window { - public class MessageDetailsWindow : Window + public MessageDetailsWindow() { - public MessageDetailsWindow() - { - InitializeComponent(); + InitializeComponent(); #if DEBUG - this.AttachDevTools(); + this.AttachDevTools(); #endif - } + } - private void InitializeComponent() - { - AvaloniaXamlLoader.Load(this); - } + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); } -} +} \ No newline at end of file