/// <summary> /// Exporting representation state /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task ExportRepresentation(CommandContextContainer commandContext) { using (var dbFactory = RepositoryFactory.CreateInstance()) { var guildId = dbFactory.GetRepository <GuildRepository>() .GetQuery() .Where(obj => obj.DiscordServerId == commandContext.Guild.Id) .Select(obj => obj.GuildId) .FirstOrDefault(); var entries = await dbFactory.GetRepository <AccountRepository>() .GetQuery() .Select(obj => new { obj.Name, DiscordAccountId = obj.User .DiscordAccounts .Select(obj2 => obj2.Id) .FirstOrDefault(), obj.ApiKey }) .ToListAsync() .ConfigureAwait(false); var accounts = new List <(string User, string AccountName, int Characters, int?Representation)>(); foreach (var entry in entries) { DiscordMember user = null; try { user = await commandContext.Guild .GetMemberAsync(entry.DiscordAccountId) .ConfigureAwait(false); } catch { } if (user != null) { var connector = new GuidWars2ApiConnector(entry.ApiKey); await using (connector.ConfigureAwait(false)) { var characters = await connector.GetCharactersAsync() .ConfigureAwait(false); accounts.Add((user.TryGetDisplayName(), entry.Name, characters?.Count ?? 0, characters?.Count(obj => obj.Guild == guildId) ?? 0)); } } } var memoryStream = new MemoryStream(); await using (memoryStream.ConfigureAwait(false)) { var writer = new StreamWriter(memoryStream); await using (writer.ConfigureAwait(false)) { await writer.WriteLineAsync("User;AccountName;Characters;Representation;Percentage") .ConfigureAwait(false); foreach (var(user, accountName, characters, representation) in accounts.OrderBy(obj => obj.User) .ThenBy(obj => obj.AccountName)) { await writer.WriteLineAsync($"{user};{accountName};{characters};{representation};{(characters != 0 ? representation / (double)characters : 0)}") .ConfigureAwait(false); } await writer.FlushAsync() .ConfigureAwait(false); memoryStream.Position = 0; await commandContext.Channel .SendMessageAsync(new DiscordMessageBuilder().WithFile("representation.csv", memoryStream)) .ConfigureAwait(false); } } } }