Use the new Csharp 8 features (pattern matching and using assignments) and cleanup some insignificant resparper complaints

This commit is contained in:
runebaas 2020-02-08 15:58:17 +01:00
parent 21f813d342
commit 3568b61f38
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
27 changed files with 217 additions and 250 deletions

View file

@ -35,7 +35,7 @@ namespace Geekbot.net.Commands.Admin
try
{
var userRepo = _userRepository.Get(user.Id);
if (userRepo != null && userRepo.UsedNames != null)
if (userRepo?.UsedNames != null)
{
var sb = new StringBuilder();
sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:");
@ -50,7 +50,7 @@ namespace Geekbot.net.Commands.Admin
catch (Exception e)
{
await _errorHandler.HandleCommandException(e, Context,
$"I don't have enough permissions do that");
"I don't have enough permissions do that");
}
}
}

View file

@ -41,9 +41,11 @@ namespace Geekbot.net.Commands.Integrations
return;
}
var eb = new EmbedBuilder();
eb.Title = card.Name;
eb.Description = card.Type;
var eb = new EmbedBuilder
{
Title = card.Name,
Description = card.Type
};
if (card.Colors != null) eb.WithColor(GetColor(card.Colors));
@ -74,21 +76,15 @@ namespace Geekbot.net.Commands.Integrations
private Color GetColor(IEnumerable<string> colors)
{
var color = colors.FirstOrDefault();
switch (color)
return color switch
{
case "Black":
return new Color(203, 194, 191);
case "White":
return new Color(255, 251, 213);
case "Blue":
return new Color(170, 224, 250);
case "Red":
return new Color(250, 170, 143);
case "Green":
return new Color(155, 211, 174);
default:
return new Color(204, 194, 212);
}
"Black" => new Color(203, 194, 191),
"White" => new Color(255, 251, 213),
"Blue" => new Color(170, 224, 250),
"Red" => new Color(250, 170, 143),
"Green" => new Color(155, 211, 174),
_ => new Color(204, 194, 212)
};
}
}
}

View file

@ -25,43 +25,43 @@ namespace Geekbot.net.Commands.Integrations.UbranDictionary
{
try
{
using (var client = new HttpClient())
using var client = new HttpClient
{
client.BaseAddress = new Uri("https://api.urbandictionary.com");
var response = await client.GetAsync($"/v0/define?term={word}");
response.EnsureSuccessStatusCode();
BaseAddress = new Uri("https://api.urbandictionary.com")
};
var response = await client.GetAsync($"/v0/define?term={word}");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var definitions = JsonConvert.DeserializeObject<UrbanResponseDto>(stringResponse);
if (definitions.List.Count == 0)
{
await ReplyAsync("That word hasn't been defined...");
return;
}
var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example));
var description = definition.Definition;
if (description.Length > 1801)
{
description = description.Substring(0, 1800) + " [...]";
}
var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder
{
Name = definition.Word,
Url = definition.Permalink
});
eb.WithColor(new Color(239, 255, 0));
if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = description;
if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)");
if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp);
if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown);
if (definitions.Tags?.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags));
await ReplyAsync("", false, eb.Build());
var stringResponse = await response.Content.ReadAsStringAsync();
var definitions = JsonConvert.DeserializeObject<UrbanResponseDto>(stringResponse);
if (definitions.List.Count == 0)
{
await ReplyAsync("That word hasn't been defined...");
return;
}
var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example));
var description = definition.Definition;
if (description.Length > 1801)
{
description = description.Substring(0, 1800) + " [...]";
}
var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder
{
Name = definition.Word,
Url = definition.Permalink
});
eb.WithColor(new Color(239, 255, 0));
if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = description;
if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)");
if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp);
if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown);
if (definitions.Tags?.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags));
await ReplyAsync("", false, eb.Build());
}
catch (Exception e)
{

View file

@ -23,24 +23,27 @@ namespace Geekbot.net.Commands.Randomness.Cat
{
try
{
using (var client = new HttpClient())
try
{
try
using var client = new HttpClient
{
client.BaseAddress = new Uri("https://aws.random.cat");
var response = await client.GetAsync("/meow");
response.EnsureSuccessStatusCode();
BaseAddress = new Uri("https://aws.random.cat")
};
var response = await client.GetAsync("/meow");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var catFile = JsonConvert.DeserializeObject<CatResponseDto>(stringResponse);
var eb = new EmbedBuilder();
eb.ImageUrl = catFile.File;
await ReplyAsync("", false, eb.Build());
}
catch
var stringResponse = await response.Content.ReadAsStringAsync();
var catFile = JsonConvert.DeserializeObject<CatResponseDto>(stringResponse);
var eb = new EmbedBuilder
{
await ReplyAsync("Seems like the dog cought the cat (error occured)");
}
ImageUrl = catFile.File
};
await ReplyAsync("", false, eb.Build());
}
catch
{
await ReplyAsync("Seems like the dog cought the cat (error occured)");
}
}
catch (Exception e)

View file

@ -61,7 +61,7 @@ namespace Geekbot.net.Commands.Randomness
while (num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
num /= 10;
}
listOfInts.Reverse();

View file

@ -23,23 +23,21 @@ namespace Geekbot.net.Commands.Randomness.Chuck
{
try
{
using (var client = new HttpClient())
try
{
try
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var response = await client.GetAsync("https://api.chucknorris.io/jokes/random");
response.EnsureSuccessStatusCode();
using var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var response = await client.GetAsync("https://api.chucknorris.io/jokes/random");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ChuckNorrisJokeResponseDto>(stringResponse);
await ReplyAsync(data.Value);
}
catch (HttpRequestException)
{
await ReplyAsync("Api down...");
}
var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ChuckNorrisJokeResponseDto>(stringResponse);
await ReplyAsync(data.Value);
}
catch (HttpRequestException)
{
await ReplyAsync("Api down...");
}
}
catch (Exception e)

View file

@ -23,23 +23,21 @@ namespace Geekbot.net.Commands.Randomness.Dad
{
try
{
using (var client = new HttpClient())
try
{
try
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var response = await client.GetAsync("https://icanhazdadjoke.com/");
response.EnsureSuccessStatusCode();
using var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var response = await client.GetAsync("https://icanhazdadjoke.com/");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<DadJokeResponseDto>(stringResponse);
await ReplyAsync(data.Joke);
}
catch (HttpRequestException)
{
await ReplyAsync("Api down...");
}
var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<DadJokeResponseDto>(stringResponse);
await ReplyAsync(data.Joke);
}
catch (HttpRequestException)
{
await ReplyAsync("Api down...");
}
}
catch (Exception e)

View file

@ -23,24 +23,26 @@ namespace Geekbot.net.Commands.Randomness.Dog
{
try
{
using (var client = new HttpClient())
try
{
try
using var client = new HttpClient
{
client.BaseAddress = new Uri("http://random.dog");
var response = await client.GetAsync("/woof.json");
response.EnsureSuccessStatusCode();
BaseAddress = new Uri("http://random.dog")
};
var response = await client.GetAsync("/woof.json");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var dogFile = JsonConvert.DeserializeObject<DogResponseDto>(stringResponse);
var eb = new EmbedBuilder();
eb.ImageUrl = dogFile.Url;
await ReplyAsync("", false, eb.Build());
}
catch (HttpRequestException e)
var stringResponse = await response.Content.ReadAsStringAsync();
var dogFile = JsonConvert.DeserializeObject<DogResponseDto>(stringResponse);
var eb = new EmbedBuilder
{
await ReplyAsync($"Seems like the dog got lost (error occured)\r\n{e.Message}");
}
ImageUrl = dogFile.Url
};
await ReplyAsync("", false, eb.Build());
}
catch (HttpRequestException e)
{
await ReplyAsync($"Seems like the dog got lost (error occured)\r\n{e.Message}");
}
}
catch (Exception e)

View file

@ -21,13 +21,11 @@ namespace Geekbot.net.Commands.Randomness
{
try
{
using (var client = new WebClient())
{
var url = new Uri("http://taskinoz.com/gdq/api/");
var response = client.DownloadString(url);
using var client = new WebClient();
var url = new Uri("http://taskinoz.com/gdq/api/");
var response = client.DownloadString(url);
await ReplyAsync(response);
}
await ReplyAsync(response);
}
catch (Exception e)
{

View file

@ -23,23 +23,21 @@ namespace Geekbot.net.Commands.Randomness.Kanye
{
try
{
using (var client = new HttpClient())
try
{
try
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var response = await client.GetAsync("https://api.kanye.rest/");
response.EnsureSuccessStatusCode();
using var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var response = await client.GetAsync("https://api.kanye.rest/");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<KanyeResponseDto>(stringResponse);
await ReplyAsync(data.Quote);
}
catch (HttpRequestException)
{
await ReplyAsync("Api down...");
}
var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<KanyeResponseDto>(stringResponse);
await ReplyAsync(data.Quote);
}
catch (HttpRequestException)
{
await ReplyAsync("Api down...");
}
}
catch (Exception e)

View file

@ -56,8 +56,8 @@ namespace Geekbot.net.Commands.Randomness
}
var reply = ":heartpulse: **Matchmaking** :heartpulse:\r\n";
reply = reply + $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n";
reply = reply + $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}";
reply += $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n";
reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}";
await ReplyAsync(reply);
}
catch (Exception e)
@ -87,13 +87,13 @@ namespace Geekbot.net.Commands.Randomness
for (var i = 1; i <= 10; i++)
if (i <= amount)
{
blocks = blocks + ":white_medium_small_square:";
blocks += ":white_medium_small_square:";
if (i == amount)
blocks = blocks + $" {rate}% ";
blocks += $" {rate}% ";
}
else
{
blocks = blocks + ":black_medium_small_square:";
blocks += ":black_medium_small_square:";
}
return blocks;

View file

@ -46,7 +46,7 @@ namespace Geekbot.net.Commands.User
else
{
var target = await GetUser(user.Id);
target.Karma = target.Karma + 1;
target.Karma += 1;
SetUser(target);
actor.TimeOut = DateTimeOffset.Now;
@ -93,7 +93,7 @@ namespace Geekbot.net.Commands.User
else
{
var target = await GetUser(user.Id);
target.Karma = target.Karma - 1;
target.Karma -= 1;
SetUser(target);
actor.TimeOut = DateTimeOffset.Now;

View file

@ -74,7 +74,7 @@ namespace Geekbot.net.Commands.User.Ranking
return;
}
int guildMessages = 0;
var guildMessages = 0;
if (type == HighscoreTypes.messages)
{
guildMessages = _database.Messages
@ -99,7 +99,7 @@ namespace Geekbot.net.Commands.User.Ranking
: $"**{user.Key.Id}**");
replyBuilder.Append(type == HighscoreTypes.messages
? $" - {user.Value} {type} - {Math.Round((double) (100 * user.Value) / guildMessages, digits: 2)}%\n"
? $" - {user.Value} {type} - {Math.Round((double) (100 * user.Value) / guildMessages, 2)}%\n"
: $" - {user.Value} {type}\n");
highscorePlace++;

View file

@ -51,7 +51,7 @@ namespace Geekbot.net.Commands.User
var level = _levelCalc.GetLevel(messages);
var percent = Math.Round((double) (100 * messages) / guildMessages, digits: 2);
var percent = Math.Round((double) (100 * messages) / guildMessages, 2);
var cookies = _database.Cookies
?.FirstOrDefault(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.UserId.Equals(userInfo.Id.AsLong()))

View file

@ -29,34 +29,34 @@ namespace Geekbot.net.Commands.Utils.Changelog
{
try
{
using (var client = new HttpClient())
using var client = new HttpClient
{
client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent",
"http://developer.github.com/v3/#user-agent-required");
var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits");
response.EnsureSuccessStatusCode();
BaseAddress = new Uri("https://api.github.com")
};
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent",
"http://developer.github.com/v3/#user-agent-required");
var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var commits = JsonConvert.DeserializeObject<List<CommitDto>>(stringResponse);
var eb = new EmbedBuilder();
eb.WithColor(new Color(143, 165, 102));
eb.WithAuthor(new EmbedAuthorBuilder
{
IconUrl = _client.CurrentUser.GetAvatarUrl(),
Name = "Latest Updates",
Url = "https://geekbot.pizzaandcoffee.rocks/updates"
});
var sb = new StringBuilder();
foreach (var commit in commits.Take(10))
sb.AppendLine($"- {commit.Commit.Message} ({commit.Commit.Author.Date:yyyy-MM-dd})");
eb.Description = sb.ToString();
eb.WithFooter(new EmbedFooterBuilder
{
Text = $"List generated from github commits on {DateTime.Now:yyyy-MM-dd}"
});
await ReplyAsync("", false, eb.Build());
}
var stringResponse = await response.Content.ReadAsStringAsync();
var commits = JsonConvert.DeserializeObject<List<CommitDto>>(stringResponse);
var eb = new EmbedBuilder();
eb.WithColor(new Color(143, 165, 102));
eb.WithAuthor(new EmbedAuthorBuilder
{
IconUrl = _client.CurrentUser.GetAvatarUrl(),
Name = "Latest Updates",
Url = "https://geekbot.pizzaandcoffee.rocks/updates"
});
var sb = new StringBuilder();
foreach (var commit in commits.Take(10))
sb.AppendLine($"- {commit.Commit.Message} ({commit.Commit.Author.Date:yyyy-MM-dd})");
eb.Description = sb.ToString();
eb.WithFooter(new EmbedFooterBuilder
{
Text = $"List generated from github commits on {DateTime.Now:yyyy-MM-dd}"
});
await ReplyAsync("", false, eb.Build());
}
catch (Exception e)
{

View file

@ -46,7 +46,7 @@ namespace Geekbot.net.Commands.Utils.Quote
return;
}
var random = _randomNumberGenerator.Next(0, s.Count());
var random = _randomNumberGenerator.Next(0, s.Count);
var quote = s[random];
var embed = QuoteBuilder(quote);
@ -238,7 +238,7 @@ namespace Geekbot.net.Commands.Utils.Quote
var last = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong()))
.OrderByDescending(e => e.InternalId).FirstOrDefault();
int internalId = 1;
var internalId = 1;
if (last != null) internalId = last.InternalId + 1;
return new QuoteModel()
{