C
C#4mo ago
Mekasu0124

✅ JSON names collide? Avalonia

using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace Diary.Models;

public class UserSetting
{
[JsonPropertyName("default")]
public List<StyleModel> StyleModel { get; set; }

[JsonPropertyName("default")]
public List<SettingsModel> SettingsModel { get; set; }
}

public List<StyleModel> CheckForStyleFile(string username = "default")
{
var data = new UserSetting
{
StyleModel =
[
new StyleModel
{
Username = username,
FontName = "Times New Roman",
FontStyle = "regular",
FontSize = "12",
FontColor = "#CDCDCD",
FontUnderline = "none",
TextAlign = "left",
BackgroundColor = "#000000",
BorderColor = "#24de45",
}
],
SettingsModel =
[
new SettingsModel
{
Username = username,
AutoCorrect = false
}
]
};

if (!File.Exists(_stylesFile))
{
var json = JsonSerializer.Serialize(data);
File.AppendAllText(_stylesFile, json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
data = JsonSerializer.Deserialize<UserSetting>(jsonObject);
}

return data.StyleModel;
}
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace Diary.Models;

public class UserSetting
{
[JsonPropertyName("default")]
public List<StyleModel> StyleModel { get; set; }

[JsonPropertyName("default")]
public List<SettingsModel> SettingsModel { get; set; }
}

public List<StyleModel> CheckForStyleFile(string username = "default")
{
var data = new UserSetting
{
StyleModel =
[
new StyleModel
{
Username = username,
FontName = "Times New Roman",
FontStyle = "regular",
FontSize = "12",
FontColor = "#CDCDCD",
FontUnderline = "none",
TextAlign = "left",
BackgroundColor = "#000000",
BorderColor = "#24de45",
}
],
SettingsModel =
[
new SettingsModel
{
Username = username,
AutoCorrect = false
}
]
};

if (!File.Exists(_stylesFile))
{
var json = JsonSerializer.Serialize(data);
File.AppendAllText(_stylesFile, json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
data = JsonSerializer.Deserialize<UserSetting>(jsonObject);
}

return data.StyleModel;
}
Between the model class and the function I'm using it in, I have something wrong. I get the error The JSON property name for 'Diary.Models.UserSetting.default' collieds with another property. This is a new error to me. I tried looking at https://stackoverflow.com/questions/69448540/net-core-the-json-property-name-for-collides-with-another-property and https://stackoverflow.com/questions/24887705/json-net-conflicting-property-name-when-using-jsonpropertyattribute but I can't determine what I have wrong. Thanks.
57 Replies
Mekasu0124
Mekasu01244mo ago
should I remove the [JsonPropertyName("default")] from the class decorators?
Jimmacle
Jimmacle4mo ago
well, it's saying you have 2 property names that conflict and you're giving 2 properties identical names
Mekasu0124
Mekasu01244mo ago
I wasn't sure if they both needed the decorator
Jimmacle
Jimmacle4mo ago
the attribute is for specifying a non-conventional name, it's not required at all
Mekasu0124
Mekasu01244mo ago
attribute. not decorator that's what I meant lol
Jimmacle
Jimmacle4mo ago
if it's not present the serializer will name the property based on the CLR property name and whatever naming convention you set in the options
Mekasu0124
Mekasu01244mo ago
ok well the function is supposed to create a json file that looks like this
{
"Username Here": {
"styles": {
"fontName": "some font name",
...
},
"settings": {
"autoCorrect": false
},
}
}
{
"Username Here": {
"styles": {
"fontName": "some font name",
...
},
"settings": {
"autoCorrect": false
},
}
}
so that as the user changes their custom settings, it can be added to replaced or deleted.
Jimmacle
Jimmacle4mo ago
i don't see any properties named "default" there
Mekasu0124
Mekasu01244mo ago
"default" would be present if the file is just newly created in place of "Username here". In the function parameters, string username = "default" is there
Jimmacle
Jimmacle4mo ago
the attributes name the properties they're put on, not the parent
Mekasu0124
Mekasu01244mo ago
it'll also remain there too as it's the style for the loading screen and the login screen ok so how should I fix my current code to get my desired output?
Jimmacle
Jimmacle4mo ago
remove the attributes you're currently trying to name the "styles" and "settings" keys to both be "default" instead, which would produce invalid json
Mekasu0124
Mekasu01244mo ago
ok they're removed. is there anything else I should change?
Jimmacle
Jimmacle4mo ago
did that fix your problem?
Mekasu0124
Mekasu01244mo ago
{
"StyleModel": [
{
"Username": "default",
"FontName": "Times New Roman",
"FontStyle": "regular",
"FontSize": "12",
"FontColor": "#CDCDCD",
"FontUnderline": "none",
"TextAlign": "left",
"BackgroundColor": "#000000",
"BorderColor": "#24de45"
}
],
"SettingsModel": [
{
"Username": "default",
"AutoCorrect": false
}
]
}
{
"StyleModel": [
{
"Username": "default",
"FontName": "Times New Roman",
"FontStyle": "regular",
"FontSize": "12",
"FontColor": "#CDCDCD",
"FontUnderline": "none",
"TextAlign": "left",
"BackgroundColor": "#000000",
"BorderColor": "#24de45"
}
],
"SettingsModel": [
{
"Username": "default",
"AutoCorrect": false
}
]
}
it did, however, it's a dictionary within a list instead of just a dictionary wait I guess that's ok
Jimmacle
Jimmacle4mo ago
that json matches your UserSetting model
Mekasu0124
Mekasu01244mo ago
because doing it that way will allow multiple local users so like people living within the same house hold that share a computer can create new logins and have their own individual settings, but I'm not sure on how to access the information
Jimmacle
Jimmacle4mo ago
if you want a dictionary of these keyed on usernames you'll need to actually have a Dictionary<string, UserSetting> to serialize
Mekasu0124
Mekasu01244mo ago
- var json = JsonSerializer.Serialize(data);
+ var json = JsonSerializer.Serialize<Dictionary<string, UserSetting>(data);
- var json = JsonSerializer.Serialize(data);
+ var json = JsonSerializer.Serialize<Dictionary<string, UserSetting>(data);
so this instead of that?
Jimmacle
Jimmacle4mo ago
try it and see
Mekasu0124
Mekasu01244mo ago
var json = JsonSerializer.Serialize<Dictionary<string, UserSetting>>(data);
var json = JsonSerializer.Serialize<Dictionary<string, UserSetting>>(data);
Argument 1: cannot convert from 'Diary.Models.UserSEtting' to 'System.Collections.Generic.Dictionary<string, Diary.Models.UserSettings'>
Argument 1: cannot convert from 'Diary.Models.UserSEtting' to 'System.Collections.Generic.Dictionary<string, Diary.Models.UserSettings'>
Jimmacle
Jimmacle4mo ago
correct your data has to actually model the json you want to produce you can't force a UserSetting to be serialized as a Dictionary<string, UserSetting>
Mekasu0124
Mekasu01244mo ago
so first I need to change the function line from List<StyleModel> to Dictionary<string, StyleModel> right?
Jimmacle
Jimmacle4mo ago
start with the line you shared, var json = JsonSerializer.Serialize(data); data needs to be an instance of the type you want to serialize if you want it to be a dictionary you have to make it a dictionary
Mekasu0124
Mekasu01244mo ago
ok so far I have changed
public Dictionary<string, UserSetting> CheckForStyleFile(string username = "default")
{
Dictionary<string, UserSEtting> data = new UserSetting
{
StyleModel = [...],
SettingsModel = [...]
};

if (!File.Exists(_stylesFile))
{
var json = JsonSerializer.Serialize<Dictionary<string, UserSetting>>(data);
File.AppendAllText(_stylesFile,json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
data = JsonSerilzer.Deserialize<Dictionary<string, UserSetting>>(jsonObject);
}

return data;
}

public class UserSetting
{
public Dictionary<string, StyleModel> StyleModel { get; set; }
public Dictionary<string, SettingsModel> SettingsModel { get; set; }
public Dictionary<string, UserSetting> UserFullSettings => new() { StyleModel, SettingsModel };
}
public Dictionary<string, UserSetting> CheckForStyleFile(string username = "default")
{
Dictionary<string, UserSEtting> data = new UserSetting
{
StyleModel = [...],
SettingsModel = [...]
};

if (!File.Exists(_stylesFile))
{
var json = JsonSerializer.Serialize<Dictionary<string, UserSetting>>(data);
File.AppendAllText(_stylesFile,json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
data = JsonSerilzer.Deserialize<Dictionary<string, UserSetting>>(jsonObject);
}

return data;
}

public class UserSetting
{
public Dictionary<string, StyleModel> StyleModel { get; set; }
public Dictionary<string, SettingsModel> SettingsModel { get; set; }
public Dictionary<string, UserSetting> UserFullSettings => new() { StyleModel, SettingsModel };
}
and so far my errors are
1. There is no argument given that corresponds to the required parameer of 'value' of 'Dictionary<string, UserSetting>.Add(string, UserSetting)'
2. Cannot implicitly convert type 'Diary.Models.StyleModel' to 'System.Collections.Generic.KeyValuePair<string, Diary.Models.StyleModel>'
3. Cannot implicitly convert type ;Diary.Models.SettingsModel' to 'System.Collections.Generic.KeyValuePair<string, Diary.Models.SettingsModel>'
1. There is no argument given that corresponds to the required parameer of 'value' of 'Dictionary<string, UserSetting>.Add(string, UserSetting)'
2. Cannot implicitly convert type 'Diary.Models.StyleModel' to 'System.Collections.Generic.KeyValuePair<string, Diary.Models.StyleModel>'
3. Cannot implicitly convert type ;Diary.Models.SettingsModel' to 'System.Collections.Generic.KeyValuePair<string, Diary.Models.SettingsModel>'
I'm just going to put it back to being a dictionary within a list. I can deal with that. This is causing more errors than it's worth lol
Jimmacle
Jimmacle4mo ago
why did you add dictionaries inside your user settings model? and i mean, this Dictionary<string, UserSEtting> data = new UserSetting is obviously not going to work
Mekasu0124
Mekasu01244mo ago
{
"StyleModel": [
{
"Username": "default",
"FontName": "Times New Roman",
"FontStyle": "regular",
"FontSize": "12",
"FontColor": "#CDCDCD",
"FontUnderline": "none",
"TextAlign": "left",
"BackgroundColor": "#000000",
"BorderColor": "#24de45"
}
],
"SettingsModel": [
{
"Username": "default",
"AutoCorrect": false
}
]
}
{
"StyleModel": [
{
"Username": "default",
"FontName": "Times New Roman",
"FontStyle": "regular",
"FontSize": "12",
"FontColor": "#CDCDCD",
"FontUnderline": "none",
"TextAlign": "left",
"BackgroundColor": "#000000",
"BorderColor": "#24de45"
}
],
"SettingsModel": [
{
"Username": "default",
"AutoCorrect": false
}
]
}
ok so going to back to what I had shown above, when I go to pull the settings and styles by the default username, how would I do that?
Jimmacle
Jimmacle4mo ago
that is not a collection of user settings that's a single user settings object so you can't get anything by anything, because there's only one thing to get i'm confused why you're separating "style" and "settings" into 2 collections
Mekasu0124
Mekasu01244mo ago
I don't have to
Jimmacle
Jimmacle4mo ago
if the goal is to look up all a user's settings by name, then the optimal way to structure that is a dictionary where the keys are the usernames and the values are the users' settings
Mekasu0124
Mekasu01244mo ago
ok so let's go with the desired output of the json file to be
{
"username_here": {
"font_name": "",
"font_style": "",
"font_size": 0,
"font_color": "",
"font_underline": "",
"text_align": "",
"background_color": "",
"border_color": "",
"auto_correct": false
},
}
{
"username_here": {
"font_name": "",
"font_style": "",
"font_size": 0,
"font_color": "",
"font_underline": "",
"text_align": "",
"background_color": "",
"border_color": "",
"auto_correct": false
},
}
how would I need to structure my function and how it writes it to the json file? I'm pretty sure I can get rid of the UserSetting class
Jimmacle
Jimmacle4mo ago
you can't that models your users' settings
Mekasu0124
Mekasu01244mo ago
ok so question then
Jimmacle
Jimmacle4mo ago
take some time to really think about how this data is structured and how that would translate to C# classes/collections
Mekasu0124
Mekasu01244mo ago
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName => $"{FirstName} {LastName}";
}
public class UserSetting
{
public List<StyleModel> StyleModel { get; set; }
public List<SettingsModel> SettingsModel { get; set; }
}
public class StyleModel
{
public string Username { get; set; }
public string FontName { get; set; }
public string FontStyle { get; set; }
public string FontSize { get; set; }
public string FontColor { get; set; }
public string FontUnderline { get; set; }
public string TextAlign { get; set; }
public string BackgroundColor { get; set; }
public string BorderColor { get; set; }
}
public class SettingsModel
{
public string Username { get; set; }
public bool AutoCorrect { get; set; }
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName => $"{FirstName} {LastName}";
}
public class UserSetting
{
public List<StyleModel> StyleModel { get; set; }
public List<SettingsModel> SettingsModel { get; set; }
}
public class StyleModel
{
public string Username { get; set; }
public string FontName { get; set; }
public string FontStyle { get; set; }
public string FontSize { get; set; }
public string FontColor { get; set; }
public string FontUnderline { get; set; }
public string TextAlign { get; set; }
public string BackgroundColor { get; set; }
public string BorderColor { get; set; }
}
public class SettingsModel
{
public string Username { get; set; }
public bool AutoCorrect { get; set; }
}
take some time to really think about how this data is structured and how that would translate to C# classes/collections
I was trying to do that. The reason I said I could likely get rid of the SettingsModel and StyleModel (if I didn't say those specifically, apologies, they're what I meant) because I was going to restructure the user model to hold all the needed information, build all of the information into a user who's username is default and then just append the user to the json file
Jimmacle
Jimmacle4mo ago
right, you can restructure it to just hold the settings themselves and make that the value of the dictionary and they don't need the username inside them because that's going to be the key
Mekasu0124
Mekasu01244mo ago
ok so remove all the usernames from the 3 classes that aren't the User class
Jimmacle
Jimmacle4mo ago
yeah
Mekasu0124
Mekasu01244mo ago
done. ok so how would I restucture the user class (thinking outloud) brb let me see if I can get this right
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName => $"{FirstName} {LastName}";
public List<UserSetting> UserSettings { get; }
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName => $"{FirstName} {LastName}";
public List<UserSetting> UserSettings { get; }
}
ok so my logic is that the UserSetting model will already be holding the StyleModel and the SettingsModel information when called, and given that the UserSetting class holds two lists, I figured it needed to be a List<> itself so I made it a list too. How far off am I?
Jimmacle
Jimmacle4mo ago
but why does usersetting hold 2 lists? does one user have mulitple sets of settings?
Mekasu0124
Mekasu01244mo ago
public class UserSetting
{
public List<StyleModel> StyleModel { get; set; }
public List<SettingsModel> SettingsModel { get; set; }
}
public class UserSetting
{
public List<StyleModel> StyleModel { get; set; }
public List<SettingsModel> SettingsModel { get; set; }
}
that's how it's setup. I was trying to find the thread from the last two weeks range that someone helped me build this function because I wanted it as lists instead of dictionaries as they're easier to index, but after listening to a podcast, I learned that dictionaries are faster so now I want dictionaries lol I'm just hung up on trying to make the changes I'm presuming that they don't have to be lists since it's only going to be one user's settings not a list of user's and their settings ok so I made that change as it just felt right to do lol
public User CheckForStyleFile(string username = "default")
{
User user = new()
{
FirstName = "Default",
LastName = "User",
Email = "default_user@email.com",
Username = "defaultUser",
Password = "",
UserSettings = new UserSetting()
{
StylesModel = new StyleModel()
{
FontName = "Times New Roman",
FontStyle = "regular",
FontSize = "12",
FontColor = "#CDCDCD",
FontUnderline = "none",
TextAlign = "left",
BackgroundColor = "#000000",
BorderColor = "#24de45"
},
SettingsModel = new SettingModel()
{
AutoCorrect = false
}
}
};

if (!File.Exists(_stylesFile))
{
var json = JsonSerializer.Serialize<User>(user);
File.AppendAllText(_stylesFile, json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);

foreach (User userObject in data)
{
if (userObject.Username == username)
{
user = new()
{
FirstName = userObject.FirstName,
LastName = userObject.LastName,
Email = userObject.Email,
Username = userObject.Username,
Password = userObject.Password,
UserSettings = userObject.UserSettings
};
}
}
}

return user;
}
public User CheckForStyleFile(string username = "default")
{
User user = new()
{
FirstName = "Default",
LastName = "User",
Email = "default_user@email.com",
Username = "defaultUser",
Password = "",
UserSettings = new UserSetting()
{
StylesModel = new StyleModel()
{
FontName = "Times New Roman",
FontStyle = "regular",
FontSize = "12",
FontColor = "#CDCDCD",
FontUnderline = "none",
TextAlign = "left",
BackgroundColor = "#000000",
BorderColor = "#24de45"
},
SettingsModel = new SettingModel()
{
AutoCorrect = false
}
}
};

if (!File.Exists(_stylesFile))
{
var json = JsonSerializer.Serialize<User>(user);
File.AppendAllText(_stylesFile, json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);

foreach (User userObject in data)
{
if (userObject.Username == username)
{
user = new()
{
FirstName = userObject.FirstName,
LastName = userObject.LastName,
Email = userObject.Email,
Username = userObject.Username,
Password = userObject.Password,
UserSettings = userObject.UserSettings
};
}
}
}

return user;
}
ok so I've gone through all of my models and made them single-entity use. Now I'm back to working on the function and here's where I'm at so far.
{
"Id": 0,
"FirstName": "Default",
"LastName": "User",
"Email": "default_user@email.com",
"Username": "defaultUser",
"Password": "",
"FullName": "Default User",
"UserSettings": {
"StylesModel": {
"FontName": "Times New Roman",
"FontStyle": "regular",
"FontSize": "12",
"FontColor": "#CDCDCD",
"FontUnderline": "none",
"TextAlign": "left",
"BackgroundColor": "#000000",
"BorderColor": "#24de45"
},
"SettingsModel": {
"AutoCorrect": false
}
}
}
{
"Id": 0,
"FirstName": "Default",
"LastName": "User",
"Email": "default_user@email.com",
"Username": "defaultUser",
"Password": "",
"FullName": "Default User",
"UserSettings": {
"StylesModel": {
"FontName": "Times New Roman",
"FontStyle": "regular",
"FontSize": "12",
"FontColor": "#CDCDCD",
"FontUnderline": "none",
"TextAlign": "left",
"BackgroundColor": "#000000",
"BorderColor": "#24de45"
},
"SettingsModel": {
"AutoCorrect": false
}
}
}
so right now it writes the json file with no problems when the json file doesn't exist. However, when running the project a second time, I get the error
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);
System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.List
System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.List
is this where I would possibly use something like IObservableList<string>? I believe this is because it's not saved in the correct format. All the information about the user should be a dictionary as the value to the username key pair like
{
"defaultUser": {
"Id": 0,
"FirstName": "Default",
"..."
}
}
{
"defaultUser": {
"Id": 0,
"FirstName": "Default",
"..."
}
}
Jimmacle
Jimmacle4mo ago
JsonSerializer.Serialize<User>(user) vs. JsonSerializer.Deserialize<List<User>>(jsonObject)
Mekasu0124
Mekasu01244mo ago
I was trying to make it be a list of users in case there is more than one user in the household that makes more than one account
Jimmacle
Jimmacle4mo ago
also, it's not going to serialize into a dictionary if you don't literally use a dictionary in the correct place in your model
Mekasu0124
Mekasu01244mo ago
so like it would read the json file and then take each user in the json file and add them to the list of users oh. ok
Jimmacle
Jimmacle4mo ago
decide on whether you want a list or dictionary you can't have it both ways unless you want to do extra processing after deserializing
Mekasu0124
Mekasu01244mo ago
I'd rather have a dictionary like
{
"defaultUser": {
"Id": 0,
"FirstName": "Default",
...
}
}
{
"defaultUser": {
"Id": 0,
"FirstName": "Default",
...
}
}
I can change the code to iterate through .Keys() no problem
MODiX
MODiX4mo ago
Jimmacle
if you want a dictionary of these keyed on usernames you'll need to actually have a Dictionary<string, UserSetting> to serialize
Quoted by
React with ❌ to remove this embed.
Jimmacle
Jimmacle4mo ago
that JSON structure maps to a C# dictionary
Mekasu0124
Mekasu01244mo ago
var json = JsonSerializer.Serialize<Dictionary<string, User>>(user.Username, user);
var json = JsonSerializer.Serialize<Dictionary<string, User>>(user.Username, user);
Jimmacle
Jimmacle4mo ago
it's best to just put that code in your IDE and see if it's even valid (it's not) the json serializer de/serializes a single object into JSON if you want the output JSON to be a dictionary, the input object has to be a dictionary
Mekasu0124
Mekasu01244mo ago
Dictionary<string, User> toSerialize = new();
toSerialize.Add(user.Username, user);
var json = JsonSerializer.Serialize(toSerialize);
File.AppendAllText(_stylesFile, json);
Dictionary<string, User> toSerialize = new();
toSerialize.Add(user.Username, user);
var json = JsonSerializer.Serialize(toSerialize);
File.AppendAllText(_stylesFile, json);
Jimmacle
Jimmacle4mo ago
yes
Mekasu0124
Mekasu01244mo ago
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);

foreach (User userObject in data)
{
if (userObject.Username == username)
{
user = new()
{
FirstName = userObject.FirstName,
LastName = userObject.LastName,
Email = userObject.Email,
Username = userObject.Username,
Password = userObject.Password,
UserSettings = userObject.UserSettings
};
}
}
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);

foreach (User userObject in data)
{
if (userObject.Username == username)
{
user = new()
{
FirstName = userObject.FirstName,
LastName = userObject.LastName,
Email = userObject.Email,
Username = userObject.Username,
Password = userObject.Password,
UserSettings = userObject.UserSettings
};
}
}
ok so now the else statement. This is for when the styles file does exists. It's supposed to find the custom styles for the user and return the default styles if no custom settings exist under the current username
if (!File.Exists(_stylesFile))
{
Dictionary<string, User> toSerialize = new();
toSerialize.Add(user.Username, user);
var json = JsonSerializer.Serialize(toSerialize);
File.AppendAllText(_stylesFile, json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);

foreach (User userObject in data)
{
if (userObject.Username == username)
{
user = new()
{
FirstName = userObject.FirstName,
LastName = userObject.LastName,
Email = userObject.Email,
Username = userObject.Username,
Password = userObject.Password,
UserSettings = userObject.UserSettings
};
}
}
}

return user;
if (!File.Exists(_stylesFile))
{
Dictionary<string, User> toSerialize = new();
toSerialize.Add(user.Username, user);
var json = JsonSerializer.Serialize(toSerialize);
File.AppendAllText(_stylesFile, json);
}
else
{
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<List<User>>(jsonObject);

foreach (User userObject in data)
{
if (userObject.Username == username)
{
user = new()
{
FirstName = userObject.FirstName,
LastName = userObject.LastName,
Email = userObject.Email,
Username = userObject.Username,
Password = userObject.Password,
UserSettings = userObject.UserSettings
};
}
}
}

return user;
to clarify, this is the full if statement the return user at the bottom is outside of the if statement so that no matter how the if statement triggers, either user will be returned so I guess I have that taken care of
else
{
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<Dictionary<string, User>>(jsonObject);

foreach (var uName in data.Keys)
{
if (uName == username)
{
return new User()
{
FirstName = data[uName].FirstName,
LastName = data[uName].LastName,
Email = data[uName].Email,
Username = data[uName].Username,
Password = data[uName].Password,
UserSettings = data[uName].UserSettings
};
}
}
}

return user;
else
{
var jsonObject = File.ReadAllText(_stylesFile);
var data = JsonSerializer.Deserialize<Dictionary<string, User>>(jsonObject);

foreach (var uName in data.Keys)
{
if (uName == username)
{
return new User()
{
FirstName = data[uName].FirstName,
LastName = data[uName].LastName,
Email = data[uName].Email,
Username = data[uName].Username,
Password = data[uName].Password,
UserSettings = data[uName].UserSettings
};
}
}
}

return user;
forgot that I went back to dictionaries. Here's the updated code
Jimmacle
Jimmacle4mo ago
you're using a dictionary like a list you don't get the performance benefits that way a dictionary's main benefit is O(1) search, but you're iterating over the entire collection making the search O(n)
if (data.TryGetValue(username, out var user)
return user;

return <your default user>;
if (data.TryGetValue(username, out var user)
return user;

return <your default user>;
the shallow copy of the user in your code is also unnecessary also, when accessing a dictionary just look it up once and use that reference, you're doing a dictionary lookup 6 times for one object
Mekasu0124
Mekasu01244mo ago
public LoginViewModel(Database db, Helpers hp, User user)
{
_db = db;
_hp = hp;
_user = user;
_userStyles = User.UserSettings.StylesModel;
// obtaining styles
...

IObservable<bool> usernameOk = this.WhenAnyValue(
x => x.Username,
x => !string.IsNullOrEmpty(x) && CheckUsername());

IObservable<bool> passwordOk = this.WhenAnyValue(
x => x.Password,
x => !string.IsNullOrEmpty(x) && CheckPassword());
IObservable<bool> okEnabled = passwordOk
.Concat(usernameOk);

Login = ReactiveCommand.Create(ReturnUser, okEnabled);
Exit = ReactiveCommand.Create(() => { });
}
public LoginViewModel(Database db, Helpers hp, User user)
{
_db = db;
_hp = hp;
_user = user;
_userStyles = User.UserSettings.StylesModel;
// obtaining styles
...

IObservable<bool> usernameOk = this.WhenAnyValue(
x => x.Username,
x => !string.IsNullOrEmpty(x) && CheckUsername());

IObservable<bool> passwordOk = this.WhenAnyValue(
x => x.Password,
x => !string.IsNullOrEmpty(x) && CheckPassword());
IObservable<bool> okEnabled = passwordOk
.Concat(usernameOk);

Login = ReactiveCommand.Create(ReturnUser, okEnabled);
Exit = ReactiveCommand.Create(() => { });
}
ok so running into other problems while trying to get the program to run so that I can test things, my first issue is this is my LoginViewModel. It returns the user model back to the MainWindowViewModel to be pass on to whatever screen the user goes to. That is done like this
public void LoginScreen()
{
var vm = new LoginViewModel(_db, _hp, CurrentUser);

Observable.Merge(vm.Exit, vm.Login)
.Take(1)
.Subscribe(model =>
{
if (model == null)
{
Environment.Exit(0);
}

CurrentUser = model;
});

Content = vm;
}
public void LoginScreen()
{
var vm = new LoginViewModel(_db, _hp, CurrentUser);

Observable.Merge(vm.Exit, vm.Login)
.Take(1)
.Subscribe(model =>
{
if (model == null)
{
Environment.Exit(0);
}

CurrentUser = model;
});

Content = vm;
}
I'm currently getting the error on the .Merge part of the Observable that says `The type arguments for method 'Observable.Merge<TSource>(IObservable<IObservable<TSource>>, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly. nevermind I got it ifugred out. Thanks for all your help ❤️