UnemployedNinja
UnemployedNinja
CC#
Created by UnemployedNinja on 11/7/2024 in #help
✅ Default interface methods - Am I using them wrong?
I'm trying to learn when/where to properly use interfaces, and I don't understand why my default method doesn't work. I have this:
c#
public interface IMyInterface {
string Name { get; set; }
string JobTitle { get; set; }

void Foo() { Console.WriteLine("Default Foo"); }
}

public class Person {
public string Name { get; set; }
}

public class Employee : Person, IMyInterface {
public string JobTitle { get; set; }
}
c#
public interface IMyInterface {
string Name { get; set; }
string JobTitle { get; set; }

void Foo() { Console.WriteLine("Default Foo"); }
}

public class Person {
public string Name { get; set; }
}

public class Employee : Person, IMyInterface {
public string JobTitle { get; set; }
}
Creating a new instance of Employee should give me access to employee.Foo(), but it doesn't. Maybe I'm just overlooking something simple, but I don't understand :/
10 replies
CC#
Created by UnemployedNinja on 10/18/2024 in #help
Best way to deserialize duplicate JSON API responses (Using Newtonsoft.JSON)
I'm using a HTTP client to contact an API, and then deserializing the JSON response into an instance of its respective object type. My issue is this - the API has two versions: - Version 1: The old API, but still active, however, it's not maintained and may be missing bits of data that are present in requests made to v2 of the API. - Version 2: The new API. Almost identical responses to v1, but all of the fields are obfuscated. So an API response for version 1 and 2 may look like this: Version 1:
{
"id": "1"
"name": "John"
"bleh": "Something else"
}
{
"id": "1"
"name": "John"
"bleh": "Something else"
}
Version 2:
{
"lLL": "1"
"llLLlLLl": "John"
"LLlLLllL": "Something else"
}
{
"lLL": "1"
"llLLlLLl": "John"
"LLlLLllL": "Something else"
}
If I were to to create a class for this response, it may look like this:
c#
public class Person {
[JsonProperty("id")]
public readonly int Id;

[JsonProperty("name")]
public readonly string Name;

[JsonProperty("bleh")]
public readonly string Bleh;

public Person() {}
}
c#
public class Person {
[JsonProperty("id")]
public readonly int Id;

[JsonProperty("name")]
public readonly string Name;

[JsonProperty("bleh")]
public readonly string Bleh;

public Person() {}
}
As you can see, this makes it difficult to reuse the same class type for v2 data. Is there a "clean" way I to achieve using only on class type for deserialization of both API versions?
73 replies
CC#
Created by UnemployedNinja on 3/19/2024 in #help
`args` used outside of the namespace
No description
4 replies
CC#
Created by UnemployedNinja on 3/19/2024 in #help
✅ Is this necessary?
If using disposes of everything inside of it, why is this still a thing?
using (HttpClient client = new HttpClient(handler, true))
using (HttpResponseMessage resp = await client.GetAsync()) {
}
using (HttpClient client = new HttpClient(handler, true))
using (HttpResponseMessage resp = await client.GetAsync()) {
}
Wont HttpResponseMessage be disposed of once the client is finished anyway? o.O Just wanting to understand it better, idk what other channels to use
7 replies
CC#
Created by UnemployedNinja on 3/15/2024 in #help
Thread.sleep in a constructor
Since you can't await in a constructor, I'm calling an async method and just sleeping the thread for 10ms while the task is incomplete:
private readonly string _Value;
public MyClass() { // Constructor
Task<string> task = GetMyValue(); // Makes an asynchronous Http request
while (!task.IsCompleted) Thread.Sleep(10);
_Value = task.Result;
}
private readonly string _Value;
public MyClass() { // Constructor
Task<string> task = GetMyValue(); // Makes an asynchronous Http request
while (!task.IsCompleted) Thread.Sleep(10);
_Value = task.Result;
}
Is this ok, or is there a better way to do this? ... or should I just be designing my code better in the first place? 😬
14 replies
CC#
Created by UnemployedNinja on 3/14/2024 in #help
Specify timeout for websocket connection
I'm using Marfusios' websocket-client and I'm trying to specify a timeout period for establishing the connection, but I'm unsure how, or if it's even possible. The GitHub demonstrates creating a factory for some client settings, but there are no options for specifying a timeout period
c#
// Param: Func<ClientWebSocket>? clientFactory

var factory = new Func<ClientWebSocket>(() => new ClientWebSocket
{
Options =
{
KeepAliveInterval = TimeSpan.FromSeconds(5),
Proxy = ...
ClientCertificates = ...
}
});
var client = new WebsocketClient(url, factory);
c#
// Param: Func<ClientWebSocket>? clientFactory

var factory = new Func<ClientWebSocket>(() => new ClientWebSocket
{
Options =
{
KeepAliveInterval = TimeSpan.FromSeconds(5),
Proxy = ...
ClientCertificates = ...
}
});
var client = new WebsocketClient(url, factory);
One client constructor gives the option for a connectionFactory, where a cancelation token can be provided, but I'm unure how to use it (I'm still pretty fresh to C#):
c#
Func<Uri, CancellationToken, Task<WebSocket>>? connectionFactory
c#
Func<Uri, CancellationToken, Task<WebSocket>>? connectionFactory
5 replies
CC#
Created by UnemployedNinja on 3/13/2024 in #help
Struggling with generic class... design?
I have BaseClass that other classes will extend from:
c#
public class BaseClass {
public BaseClass() { /* Constructor */ }
public static T? JsonDeserialiseAs<T>(string json) where T : BaseClass { /* Do stuff */ }
}

public class MyClassA : BaseClass {
public string? SomeProp { get; set; } // Some properties that BaseClass doesn't have
public MyClassA() : base() { /* Constructor */ }
}
c#
public class BaseClass {
public BaseClass() { /* Constructor */ }
public static T? JsonDeserialiseAs<T>(string json) where T : BaseClass { /* Do stuff */ }
}

public class MyClassA : BaseClass {
public string? SomeProp { get; set; } // Some properties that BaseClass doesn't have
public MyClassA() : base() { /* Constructor */ }
}
The extending classes will have properties that BaseClass doesn't have, do knowing the type is important for deserialization. Instead of using MyClassA.JsonDeserialiseAs<MyClassA>(json) every time, I'd like to be able to use MyClassA.JsonDeserialize(json) What's the best way I can achieve this?
4 replies
CC#
Created by UnemployedNinja on 3/10/2024 in #help
Why does this require a cast?
I have this method:
c#
public string JsonSerialize(bool? mini) {
mini = mini == null ? true : mini;
JsonSettings.Formatting = mini ? Formatting.None : Formatting.Indented;
return JsonConvert.SerializeObject(this, JsonSettings);
}
c#
public string JsonSerialize(bool? mini) {
mini = mini == null ? true : mini;
JsonSettings.Formatting = mini ? Formatting.None : Formatting.Indented;
return JsonConvert.SerializeObject(this, JsonSettings);
}
Even though I've null-checked mini, VS is still telling me that I need an explicit cast to bool on mini ? Formatting.None : Formatting.Indented Why?
23 replies
CC#
Created by UnemployedNinja on 3/8/2024 in #help
Generic type that extends bool
How can I make my generic type "extend" boolean?
c#
class MyClass<T> where T : bool {
}
c#
class MyClass<T> where T : bool {
}
9 replies
CC#
Created by UnemployedNinja on 3/7/2024 in #help
Check value type of extended class instance
I have BaseClass and MyClass : BaseClass. Using val is BaseClass will return true for any object that is, or extends BaseClass. How can I check if the object is of type MyClass, and not BaseClass?
13 replies
CC#
Created by UnemployedNinja on 3/6/2024 in #help
Custom Newtonsoft JSON deserialization
I have a dictionary where: - The key will always be a string - The value will be either: - string - an object of MyClass Normally, you would do something like:
c#
string jsonData = ""; // Some data...
Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
c#
string jsonData = ""; // Some data...
Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
However, this wont deserialize the non-string value into an instance of MyClass like it normally would. How can tell the deserializer how to deserialize a string vs an object?
21 replies
CC#
Created by UnemployedNinja on 3/5/2024 in #help
Different HttpClient headers
When I make an HTTP request in my browser (Chrome), I get different response headers than I do in my program using HttpClient with a HttpClientHandler I'm using all the exact same headers, including the same cookies, and making the request to the same URL - I also have redirects disabled Why could this be? Chrome shows me 11 headers, whereas C#'s HttpClient only shows me 6 headers from the exact same request
17 replies
CC#
Created by UnemployedNinja on 3/4/2024 in #help
Dynamically assign values to class instance properties / Indexing class instance properties
I have a class like:
c#
public class MyClass {
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public bool BoolProperty { get; set; }

private MyClass() {}

public static MyClass FromData(Dictionary<string, object?> data) {
MyClass newInstance = new MyClass();
foreach (var (key, val) in data) {

// Do some type checking, and then
// something like: newInstance[key] = (cast)val;

}
return newInstance;
}
}
c#
public class MyClass {
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public bool BoolProperty { get; set; }

private MyClass() {}

public static MyClass FromData(Dictionary<string, object?> data) {
MyClass newInstance = new MyClass();
foreach (var (key, val) in data) {

// Do some type checking, and then
// something like: newInstance[key] = (cast)val;

}
return newInstance;
}
}
Assuming I have a dictionary like:
c#
Dictionary<string, object> data = new Dictionary<string, object>(){
{"StringProperty", "My string"},
{"IntProperty", 21},
{"BoolProperty", true}
};
c#
Dictionary<string, object> data = new Dictionary<string, object>(){
{"StringProperty", "My string"},
{"IntProperty", 21},
{"BoolProperty", true}
};
Is it possible to do something like my method FromData? Where if it exists, each property will be assigned the value from the dictionary?
15 replies
CC#
Created by UnemployedNinja on 3/4/2024 in #help
Data with enums
I want to add some data with enums, but you can't do much more than bytes or ints in C#. To go around this, I've done this instead:
14 replies
CC#
Created by UnemployedNinja on 3/4/2024 in #help
Publishing/Building project with dependencies based on target .NET version
I have a project that requires an external library file, which I have different versions of, for different .NET versions. How can I tell Visual Studio to build my project with the right file?
3 replies
CC#
Created by UnemployedNinja on 2/29/2024 in #help
Comments Not Working
No description
25 replies
CC#
Created by UnemployedNinja on 2/27/2024 in #help
Packing an external DLL with my own DLL
I've written a library that also uses another external library, packed into a .dll file. When I build my library file, it doesn't pack the external dll in with it. How can I do this? Do I need the source?
29 replies
CC#
Created by UnemployedNinja on 2/27/2024 in #help
Reduce File Size
I have a very simple console application written in C#, barely more than a couple megabytes. When I publish my project to a self-contained single-file executable, the file comes out to about 50mb. What's the easiest way to remove unused dependencies and only publish with what it needs?
22 replies
CC#
Created by UnemployedNinja on 2/27/2024 in #help
Could not load type 'System.Web.HttpContext' from assembly
I'm trying to use an AMF3 library called FlourineFx. Sending a HTTP request works fine, but when trying to decode the AMF package from the request response, I get this error:
Unhandled exception. System.TypeLoadException: Could not load type 'System.Web.HttpContext' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Unhandled exception. System.TypeLoadException: Could not load type 'System.Web.HttpContext' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
25 replies
CC#
Created by UnemployedNinja on 2/25/2024 in #help
Check if an object is a Dictionary of any type
I'm trying to type-check a method parameter using if (dict.GetType() == typeof(Dictionary)). How can I check for all types of Dictionary without having to write them all out. Or am I wasting my time here, since the language has type-checking anyway?
30 replies