C
C#2y 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
Angius2y ago
There's only one string in C# It's not rust that has 163 different types
thieved
thievedOP2y 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
thievedOP2y ago
i see now
thieved
thievedOP2y 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
Angius2y ago
Remember, that arrays in C# are 0-indexed
thieved
thievedOP2y ago
well this sort of thing works in JS and lua i forgot these kind of languages enforce these operations
Angius
Angius2y ago
So arr[..123] on an array that has .Length of length 123 won't work
thieved
thievedOP2y 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
Angius2y ago
description[..(Math.Min(description.Length - 1, 2043))]
description[..(Math.Min(description.Length - 1, 2043))]
This should work Or, yeah, a ternary
thieved
thievedOP2y ago
how woulx this work? would*
Angius
Angius2y 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
thievedOP2y ago
oh that makes sense should i put 2042 if i want it to go to the 2043rd index lol
Angius
Angius2y ago
2043rd item, that resides on the 2042nd index, yeah 0-indexed and all that
thieved
thievedOP2y 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
Angius2y ago
Shoot
thieved
thievedOP2y ago
okay so i have a file of commands right
thieved
thievedOP2y 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
Angius2y ago
Do you have an async void method somewhere, by chance?
thieved
thievedOP2y ago
uhh
Angius
Angius2y ago
That will discard exceptions
thieved
thievedOP2y 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
Angius2y ago
No, void alone is fine
thieved
thievedOP2y ago
hm
Angius
Angius2y ago
It's specifically async void that causes issues
thieved
thievedOP2y ago
weird..
Angius
Angius2y ago
Well, it can be something else Any try-catch blocks that discard the exception maybe?
thieved
thievedOP2y 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
Angius2y 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
thievedOP2y ago
ya i can't await it apparently its the only way i could think of to fetch command responses
Angius
Angius2y ago
You can cast the return to a Task<T>
thieved
thievedOP2y ago
elaborate
Angius
Angius2y ago
Or, well, just Task in this case
thieved
thievedOP2y ago
the return of which area ?
Angius
Angius2y ago
await (Task)method.Invoke(null, new object[] { elfin, context });
await (Task)method.Invoke(null, new object[] { elfin, context });
thieved
thievedOP2y 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
Angius2y ago
LGTM
thieved
thievedOP2y ago
lol i learned abt the null-forgiving operator its so useful
Angius
Angius2y ago
I prefer checking for null, but you do you
thieved
thievedOP2y 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
Angius2y ago
Func<ElfinClient, ElfinCommandContext, Task>
thieved
thievedOP2y ago
hmm
Angius
Angius2y ago
Or use a delegate type
thieved
thievedOP2y 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
Angius2y ago
Or json serializer options To ignore the property name case
thieved
thievedOP2y ago
that didnt work last time sadly henky said it was better to specify the name for each property
Angius
Angius2y ago
Ugh, if you want a ton of work, sure
thieved
thievedOP2y 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
MODiX2y 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
Angius2y ago
¯\_(ツ)_/¯
thieved
thievedOP2y ago
idk why it doesnt work for me.. let me try hold on
Angius
Angius2y ago
Are you sure the response you get from the API is just a straight array of objects?
thieved
thievedOP2y ago
yes its an array of objects
Angius
Angius2y ago
Give me a sample URL you're getting a response from?
thieved
thievedOP2y ago
oh so NOW it wants to work 🙄 tysm for ur help forreal you have gotten me thru C# so fast already
Angius
Angius2y ago
Anytime 👌
thieved
thievedOP2y ago
❤️
Want results from more Discord servers?
Add your server