I have a code that connects to the server and get's from it a list of contacts. Iv'e been trying to get it using this function.
public async Task<List<Contact>> GetContactsAsync()
{
try
{
// Send the GET_CONTACTS_COMMAND to the server
await comm.SendMessageAsync(JsonConvert.SerializeObject("GET_CONTACTS"));
// Wait for and handle the server's response
string contactsResponse = await comm.ReceiveMessageAsync();
// Process the server's response
if (!string.IsNullOrEmpty(contactsResponse))
{
// Parse the response to get the list of contacts
List<Contact> contacts = JsonConvert.DeserializeObject<List<Contact>>(contactsResponse);
return contacts;
}
else
{
MessageBox.Show("Failed to fetch contacts from the server");
return null; // or throw an exception
}
}
catch (Exception ex)
{
MessageBox.Show($"Error during contact loading: {ex.Message}");
return null; // or throw an exception
}
}
This is where I call it
public async Task LoadChat()
{
if (Chats == null)
{
Chats = new ObservableCollection<ChatListData>();
List<Contact> contacts = await GetContactsAsync();
MessageBox.Show("did");
Chats.Add(new ChatListData(contacts.ElementAt(0).Username, new Uri("/assets/5.jpg", UriKind.RelativeOrAbsolute), "hello", DateTime.Now, false));
OnPropertyChanged("Chats");
}
}
this is the decleration of Chats
public ObservableCollection<ChatListData> Chats { get; set; }
public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
this is the constructor and the init function
public ViewModel(Communicator communicator)
{
comm = communicator;
Initialize();
LoadChatConversation();
LoadStatusThumbs();
}
private void Initialize()
{
try
{
{
if (comm == null)
{
comm = new Communicator();
_ = comm.ConnectToServerAsync();
}
}
_ = LoadChat();
//await comm.ConnectToServerAsync();
}
catch (Exception ex)
{
MessageBox.Show($"Error during initialization: {ex.Message}");
}
}
I've tried to run the loadChat that way (to check if the problem might be with the getContacts functions, but it won't work.
public async Task LoadChat()
{
if (Chats == null)
{
Chats = new ObservableCollection<ChatListData>();
Chats.Add(new ChatListData("shelly", new Uri("/assets/5.jpg", UriKind.RelativeOrAbsolute), "hello", DateTime.Now, false));
OnPropertyChanged("Chats");
}
}
this is the relevant xaml
<ItemsControl
ItemsSource="{Binding Chats}"
ItemTemplate="{StaticResource ChatButtonItemTemplate}"
Padding="0,15">
<ItemsControl.DataContext>
<viewmodels:ViewModel/>
</ItemsControl.DataContext>
</ItemsControl>