C
C#17mo ago
thieved

`System.String` doesn't have the `Substring` method or something is weird about this string??

i've even tried this
description.Length > 2043 ? description[0 .. 2043] : description;
description.Length > 2043 ? description[0 .. 2043] : description;
but here's my substring operation:
description.Substring(0, 2043);
description.Substring(0, 2043);
it works for some returned strings but not all????
56 Replies
Angius
Angius17mo ago
There's only one string in C# It's not rust that has 163 different types
thieved
thieved17mo ago
LOL i meant though that some strings can be substringed but for others it erros errors let me try to catch the error since its not killing my code for some reason
thieved
thieved17mo ago
i see now
thieved
thieved17mo ago
C# is super strict about these things i guess should i just make a ternary to check if it needs to be substringed?
Angius
Angius17mo ago
Remember, that arrays in C# are 0-indexed
thieved
thieved17mo ago
well this sort of thing works in JS and lua i forgot these kind of languages enforce these operations
Angius
Angius17mo ago
So arr[..123] on an array that has .Length of length 123 won't work
thieved
thieved17mo ago
yea true so i guess i should just check if its over the length i need im used to js handling it regardless oh also i started using classes for web results and the standard serializer henkey helped me =D its not that bad
Angius
Angius17mo ago
description[..(Math.Min(description.Length - 1, 2043))]
description[..(Math.Min(description.Length - 1, 2043))]
This should work Or, yeah, a ternary
thieved
thieved17mo ago
how woulx this work? would*
Angius
Angius17mo ago
Math.Min(a, b) picks the lowest value So if the string is 2839746 chars long, and the max is 100, it will take a substring of length 100 If the string is 2 chars long, and the max is 100, it will take a substring of length 2, so the whole string There might be some off-by-one errors here, so you'd have to actually run this code and check lol
thieved
thieved17mo ago
oh that makes sense should i put 2042 if i want it to go to the 2043rd index lol
Angius
Angius17mo ago
2043rd item, that resides on the 2042nd index, yeah 0-indexed and all that
thieved
thieved17mo ago
worked! tysmmm ive never rlly used math functons that much functions besides rounding and randomization lol never really needed it could you possibly help me with one more thing?
Angius
Angius17mo ago
Shoot
thieved
thieved17mo ago
okay so i have a file of commands right
thieved
thieved17mo ago
and groups in other files, etc. u get the point but errors dont kill my code or throw in a fatal manner how do i get these errors to be recognized? so i can do debugging faster
Angius
Angius17mo ago
Do you have an async void method somewhere, by chance?
thieved
thieved17mo ago
uhh
Angius
Angius17mo ago
That will discard exceptions
thieved
thieved17mo ago
dont think so let me check let me send u all of the points where the cmd method is recognized
var newCommand = new ElfinCommand()
{
Name = commandName,
Aliases = aliases,
Usage = usage,
Description = description,
Respond = (ElfinClient elfin, ElfinCommandContext context) =>
{
method.Invoke(null, new object[] { elfin, context });
}
};
var newCommand = new ElfinCommand()
{
Name = commandName,
Aliases = aliases,
Usage = usage,
Description = description,
Respond = (ElfinClient elfin, ElfinCommandContext context) =>
{
method.Invoke(null, new object[] { elfin, context });
}
};
first when initiating the command then when checking for the command
public void HandlePossibleCommand(MessageCreateEventArgs packet)
{
var message = packet.Message;
var messageContent = message.Content;

if (!message.Author.IsBot && messageContent.StartsWith(this.Prefix))
{
var components = messageContent.Split(" ");
var commandName = components[0].Replace(this.Prefix, "").ToLower();
var command = this.GetCommand(commandName);

if (command != null && command.Enabled)
{
var context = new ElfinCommandContext()
{
Packet = packet,
Author = packet.Author,
Guild = packet.Guild,
Channel = packet.Channel,
Message = message,
Args = components[1..]
};

command.Respond!(this, context);
}
}
}
public void HandlePossibleCommand(MessageCreateEventArgs packet)
{
var message = packet.Message;
var messageContent = message.Content;

if (!message.Author.IsBot && messageContent.StartsWith(this.Prefix))
{
var components = messageContent.Split(" ");
var commandName = components[0].Replace(this.Prefix, "").ToLower();
var command = this.GetCommand(commandName);

if (command != null && command.Enabled)
{
var context = new ElfinCommandContext()
{
Packet = packet,
Author = packet.Author,
Guild = packet.Guild,
Channel = packet.Channel,
Message = message,
Args = components[1..]
};

command.Respond!(this, context);
}
}
}
is this because its a void?
Angius
Angius17mo ago
No, void alone is fine
thieved
thieved17mo ago
hm
Angius
Angius17mo ago
It's specifically async void that causes issues
thieved
thieved17mo ago
weird..
Angius
Angius17mo ago
Well, it can be something else Any try-catch blocks that discard the exception maybe?
thieved
thieved17mo ago
nope there are none they dont kill my program but they do stop the code from running at times
[ElfinCommand("helloworld")]
[ElfinAliases(new string[] { "hworld" })]
[ElfinUsage("[]")]
[ElfinDescription("Hello, world!")]
public static async Task HelloWorld(ElfinClient elfin, ElfinCommandContext context)
{
await context.Message.RespondAsync("Hello, world!");
}
[ElfinCommand("helloworld")]
[ElfinAliases(new string[] { "hworld" })]
[ElfinUsage("[]")]
[ElfinDescription("Hello, world!")]
public static async Task HelloWorld(ElfinClient elfin, ElfinCommandContext context)
{
await context.Message.RespondAsync("Hello, world!");
}
heres what one of the commands would look like i dont want to try catch all of the cmds lol
Angius
Angius17mo ago
Ah, wait, so this line
method.Invoke(null, new object[] { elfin, context });
method.Invoke(null, new object[] { elfin, context });
invokes an async method?
thieved
thieved17mo ago
ya i can't await it apparently its the only way i could think of to fetch command responses
Angius
Angius17mo ago
You can cast the return to a Task<T>
thieved
thieved17mo ago
elaborate
Angius
Angius17mo ago
Or, well, just Task in this case
thieved
thieved17mo ago
the return of which area ?
Angius
Angius17mo ago
await (Task)method.Invoke(null, new object[] { elfin, context });
await (Task)method.Invoke(null, new object[] { elfin, context });
thieved
thieved17mo ago
ohh i thought so i didnt think of that haha
await (Task)method.Invoke(null, new object[] { elfin, context })!;
await (Task)method.Invoke(null, new object[] { elfin, context })!;
seems fine?
Angius
Angius17mo ago
LGTM
thieved
thieved17mo ago
lol i learned abt the null-forgiving operator its so useful
Angius
Angius17mo ago
I prefer checking for null, but you do you
thieved
thieved17mo ago
public required Action<ElfinClient, ElfinCommandContext>? Respond { get; init; }
public required Action<ElfinClient, ElfinCommandContext>? Respond { get; init; }
how can i turn this async? since i need to await it in every context to get the errors
Angius
Angius17mo ago
Func<ElfinClient, ElfinCommandContext, Task>
thieved
thieved17mo ago
hmm
Angius
Angius17mo ago
Or use a delegate type
thieved
thieved17mo ago
ONE LAST QIOIUOIOIOEIOIOISOIOIOTIOIIOIOOIOIOINOIOIOQ sorry my macro oops
public record SafeBooruResponse(string Directory, string Image);
public record SafeBooruResponse(string Directory, string Image);
so im trying to create a serializeable type for a web response thats n array an* of objects but Directory and Image come out as null heres an example object
{"directory":"4086","hash":"2cb80939057d1e243ad7028871c17cf5","height":1500,"id":4271551,"image":"f176cb1ed31d18aa8e1b2373930ae58581e8946c.jpg","change":1677047429,"owner":"danbooru","parent_id":0,"rating":"general","sample":false,"sample_height":0,"sample_width":0,"score":null,"tags":"1girl ;d bangs blouse blue_skirt bocchi_the_rock! bow commentary green_eyes highres jj_(ssspulse) kita_ikuyo long_hair looking_at_viewer miniskirt one_eye_closed one_side_up open_mouth pleated_skirt red_bow redhead sailor_collar school_uniform serafuku shirt simple_background skirt smile solo sparkle standing translated w yellow_sailor_collar yellow_shirt","width":752}
{"directory":"4086","hash":"2cb80939057d1e243ad7028871c17cf5","height":1500,"id":4271551,"image":"f176cb1ed31d18aa8e1b2373930ae58581e8946c.jpg","change":1677047429,"owner":"danbooru","parent_id":0,"rating":"general","sample":false,"sample_height":0,"sample_width":0,"score":null,"tags":"1girl ;d bangs blouse blue_skirt bocchi_the_rock! bow commentary green_eyes highres jj_(ssspulse) kita_ikuyo long_hair looking_at_viewer miniskirt one_eye_closed one_side_up open_mouth pleated_skirt red_bow redhead sailor_collar school_uniform serafuku shirt simple_background skirt smile solo sparkle standing translated w yellow_sailor_collar yellow_shirt","width":752}
im not sure why it wouldnt work im trying to do this
var response = JsonSerializer.Deserialize<List<SafeBooruResponse>>(raw);
var random = new Random();
var pick = response!.ElementAt(random.Next(0, response!.Count));
var response = JsonSerializer.Deserialize<List<SafeBooruResponse>>(raw);
var random = new Random();
var pick = response!.ElementAt(random.Next(0, response!.Count));
but all of the values are appearing as null hmm oh i think its the json property name thats missing
Angius
Angius17mo ago
Or json serializer options To ignore the property name case
thieved
thieved17mo ago
that didnt work last time sadly henky said it was better to specify the name for each property
Angius
Angius17mo ago
Ugh, if you want a ton of work, sure
thieved
thieved17mo ago
yea ik the configuration didnt work for me for some reason
public record SafeBooruResponse
{
[JsonPropertyName("directory")]
public string Directory;
[JsonPropertyName("image")]
public string Image;
}
public record SafeBooruResponse
{
[JsonPropertyName("directory")]
public string Directory;
[JsonPropertyName("image")]
public string Image;
}
so i tried doing this and now all the objects are empty. u need .Count
MODiX
MODiX17mo ago
Angius#1586
REPL Result: Success
using System.Text.Json;

var json = """
[
{"directory":"4086","hash":"2cb80939057d1e243ad7028871c17cf5","height":1500,"id":4271551,"image":"f176cb1ed31d18aa8e1b2373930ae58581e8946c.jpg","change":1677047429,"owner":"danbooru","parent_id":0,"rating":"general","sample":false,"sample_height":0,"sample_width":0,"score":null,"tags":"1girl ;d bangs blouse blue_skirt bocchi_the_rock! bow commentary green_eyes highres jj_(ssspulse) kita_ikuyo long_hair looking_at_viewer miniskirt one_eye_closed one_side_up open_mouth pleated_skirt red_bow redhead sailor_collar school_uniform serafuku shirt simple_background skirt smile solo sparkle standing translated w yellow_sailor_collar yellow_shirt","width":752}
]
""";
record SafeBooruResponse(string Directory, string Image);
var response = JsonSerializer.Deserialize<List<SafeBooruResponse>>(json, new JsonSerializerOptions {
PropertyNameCaseInsensitive = true
});
var pick = response[Random.Shared.Next(0, response.Count)];

pick
using System.Text.Json;

var json = """
[
{"directory":"4086","hash":"2cb80939057d1e243ad7028871c17cf5","height":1500,"id":4271551,"image":"f176cb1ed31d18aa8e1b2373930ae58581e8946c.jpg","change":1677047429,"owner":"danbooru","parent_id":0,"rating":"general","sample":false,"sample_height":0,"sample_width":0,"score":null,"tags":"1girl ;d bangs blouse blue_skirt bocchi_the_rock! bow commentary green_eyes highres jj_(ssspulse) kita_ikuyo long_hair looking_at_viewer miniskirt one_eye_closed one_side_up open_mouth pleated_skirt red_bow redhead sailor_collar school_uniform serafuku shirt simple_background skirt smile solo sparkle standing translated w yellow_sailor_collar yellow_shirt","width":752}
]
""";
record SafeBooruResponse(string Directory, string Image);
var response = JsonSerializer.Deserialize<List<SafeBooruResponse>>(json, new JsonSerializerOptions {
PropertyNameCaseInsensitive = true
});
var pick = response[Random.Shared.Next(0, response.Count)];

pick
Result: SafeBooruResponse
{
"directory": "4086",
"image": "f176cb1ed31d18aa8e1b2373930ae58581e8946c.jpg"
}
{
"directory": "4086",
"image": "f176cb1ed31d18aa8e1b2373930ae58581e8946c.jpg"
}
Compile: 692.324ms | Execution: 91.639ms | React with ❌ to remove this embed.
Angius
Angius17mo ago
¯\_(ツ)_/¯
thieved
thieved17mo ago
idk why it doesnt work for me.. let me try hold on
Angius
Angius17mo ago
Are you sure the response you get from the API is just a straight array of objects?
thieved
thieved17mo ago
yes its an array of objects
Angius
Angius17mo ago
Give me a sample URL you're getting a response from?
thieved
thieved17mo ago
oh so NOW it wants to work 🙄 tysm for ur help forreal you have gotten me thru C# so fast already
Angius
Angius17mo ago
Anytime 👌
thieved
thieved17mo ago
❤️