Xamarin forms - Cannot get object from REST API to xaml page - rest

I am developing an Xamarin.Forms app in VS 2019. My REST API is hosted on GoDaddy.
When I call the api I get back my json converted object fine in my viewmodel. But the object is null
from my xaml page. See this code:
public class NewOrderViewModel : BaseViewModel
{
public NewOrderDetails NewOrderDetails { get; set; }
public ICommand OkCommand { get; private set;}
public ICommand CancelCommand { get; private set; }
readonly IPageService _pageService;
public NewOrderViewModel(IPageService pageService, int custId)
{
_pageService = pageService;
OkCommand = new Command(NewOrder);
CancelCommand = new Command(CancelOrder);
NewOrderDetails = new NewOrderDetails();
LoadNewOrderDetails(custId);
}
private async void LoadNewOrderDetails(int custId)
{
using (var client = new HttpClient(new System.Net.Http.HttpClientHandler()))
{
var response = await client.GetStringAsync("http://api.lates.com.au/api/Customers/" + custId.ToString());
var customer = JsonConvert.DeserializeObject<Customer>(response);
await _pageService.DisplayAlert("Value", customer.CustomerName, "OK"); //This confirms the correct customer is returned.
NewOrderDetails.CustomerName = customer.CustomerName;
foreach (var cd in customer.CustomerDepartments)
{
NewOrderDetails.CustomerDepartments.Add(cd);
}
NewOrderDetails.OrderDate = DateTime.Today;
NewOrderDetails.DeliveryDate = DateTime.Today;
NewOrderDetails.CustomerId = custId;
}
}
private void NewOrder()
{
_pageService.PopAsync();
_pageService.PushModalAsync(new CustomerOrder());
}
private void CancelOrder()
{
_pageService.PopAsync();
}
}
public partial class NewOrder : ContentPage
{
public NewOrder()
{
InitializeComponent();
imgAddIcon.Source = FileImageSource.FromFile("AddDocument64By64.png");
}
protected override void OnAppearing()
{
BindingContext = new NewOrderViewModel(new PageService(), 1);
//If i put a break point here the NewOrderDetails property of NewOrderViewModel is null - WHY???
}
}
It seems to be something to do with asynchronous timing. Let me know if you need more info.
Malcolm

If i put a break point here the NewOrderDetails property of
NewOrderViewModel is null - WHY???
At that time your break point hit, the data in NewOrderDetails has not be set because the httpRequest is still requesting and you have to await the request finish to get the data from Api.
To solve your problem, you have to implement INotifyPropertyChanged in both NewOrderDetails and NewOrderViewModel to notify the View update value after you get the data from Api. I will give you some code snippets:
In NewOrderDetails :
public class NewOrderDetails : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public NewOrderDetails()
{
}
public string CustomerName
{
set
{
if (customerName != value)
{
customerName = value;
OnPropertyChanged("CustomerName");
}
}
get
{
return customerName;
}
}
string customerName { get; set; }
}
In NewOrderViewModel :
public class NewOrderViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public NewOrderDetails NewOrderDetaila
{
set
{
if (newOrderDetails != value)
{
newOrderDetails = value;
OnPropertyChanged("NewOrderDetaila");
}
}
get
{
return newOrderDetails;
}
}
NewOrderDetails newOrderDetails { get; set; }
public NewOrderViewModel( int custId)
{
NewOrderDetaila = new NewOrderDetails();
LoadNewOrderDetails(custId);
}
private async void LoadNewOrderDetails(int custId)
{
//...
NewOrderDetaila.CustomerName = "133";
//...
}
}
And in Xaml binding:
<Label Text="{Binding NewOrderDetaila.CustomerName}"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
Try and let me know if it works for you.

One problem in your code is here:
using (var client = new HttpClient(new System.Net.Http.HttpClientHandler()))
{
var response = await client.GetStringAsync("http://api.lates.com.au/api/Customers/" + custId.ToString());
var customer = JsonConvert.DeserializeObject<Customer>(response);
await _pageService.DisplayAlert("Value", customer.CustomerName, "OK"); //This confirms the correct customer is returned.
NewOrderDetails.CustomerName = customer.CustomerName;
foreach (var cd in customer.CustomerDepartments)
{
NewOrderDetails.CustomerDepartments.Add(cd);
}
NewOrderDetails.OrderDate = DateTime.Today;
NewOrderDetails.DeliveryDate = DateTime.Today;
NewOrderDetails.CustomerId = custId;
}
HttpClient should be defined as static class, and reused during your application lifetime. Disposing and recreating HttpClient leads to socket errors. Your code is causing multiple requests. I suggest also move this method to Task, that returns the object.
Example method:
internal class SendData
{
private static HttpClient client = new HttpClient();
internal static async Task<string> MakeServerRequest(string url, string content)
{
try
{
var request = new StringContent(content, Encoding.UTF8, "application/json");
var result = await client.PostAsync(url, request);
var response = await result.Content.ReadAsStringAsync();
return response;
}
catch (Exception ex)
{
YOUR ADDITIONAL LOGIC HERE
return null;
}
}
}
This will return JSON string that you can serialize to object, and do whatever your app requires.

Related

Run method in viewmodel after receiving object in AppShell .NET MAUI

I am sending a Course object from DashboardViewModel as shown below
DashboardViewModel.cs
[RelayCommand]
async void GoToCourse(Course course)
{
if (course == null) return;
await Shell.Current.GoToAsync(nameof(TopicSelectionPage), true, new Dictionary<string, object>
{
{"courseSelected", course}
});
}
to TopicSelectionViewModel which is attached below
TopicSelectionViewModel.cs
[INotifyPropertyChanged]
[QueryProperty(nameof(CourseSelected), "courseSelected")]
public partial class TopicSelectionViewModel
{
CancellationTokenSource cancellationTokenSource = new();
[ObservableProperty]
private Course courseSelected;
public ObservableRangeCollection<Topic> Topics { get; set; } = new();
[ObservableProperty]
private bool isBusy;
[ObservableProperty]
private string title;
[ObservableProperty]
private string imageURL;
[RelayCommand]
async Task Refresh()
{
Topics.Clear();
IsBusy = true;
try
{
if (courseSelected is not null)
{
Title= courseSelected.Title;
ImageURL = courseSelected.ImageURL;
if (courseSelected.CourseRef.Equals("anat1"))
{
foreach (Topic item in Constants.GetAnatomyTopics)
{
Topics.Add(item);
}
}
else if (courseSelected.CourseRef.Equals("phys1"))
{
foreach (Topic item in Constants.GetPhysiologyTopics)
{
Topics.Add(item);
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
I want to run the RefreshCommand after receiving the Course object. I tried calling the RefreshCommand in the constructor but the command is called before receiving the Course object. How do I go about this?
How to add OnAppearing to your ViewModel:
<ContentPage.Behaviors>
<toolkit:EventToCommandBehavior
EventName="Appearing"
Command="{Binding AppearingCommand}" />
</ContentPage.Behaviors>
Where toolkit is:
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
How to use code when assigning:
public void ApplyQueryAttributes(IDictionary<string, object> query)
When, your ViewModel is implementing:
IQueryAttributable
Edit: Instead of doing this to your ViewModel:
[INotifyPropertyChanged]
[QueryProperty(nameof(CourseSelected), "courseSelected")]
You can do this:
public partial class TopicSelectionViewModel : ObservableObject, IQueryAttributable
And then add this method:
public void ApplyQueryAttributes(IDictionary<string, object> query)
And get your data with:
query["SomeKey"]

How to data bind class A{prop masterProp} to a class B{ bound prop to class A masterProp}

I am learning Xamarin forms.
I wanted to be able to bind some ViewModel to some values in a DataManager class (Singleton).
Say the Singleton is a BleManager and all ViewModel need to use it to get or set some information to or from the BLE device.
I Know how to bind my VM to the XAML view code.
But now I need to be able to get the viewModels to update local Data when the BLEManager updates some info, like battery level.
so for example (semi sudo-code).
public class BLEInterface: INotifyPropertyChanged
{
protected virtual void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public async Task<float> GetDeviceName()
{
await Task.Delay(1000);
return float.random(0f:100f)
}
}
public sealed class BLEManager: INotifyPropertyChanged
{
private static BLEManager shared;
private static object objectLockCheck = new Object();
private BLEInterface BleModel { get; set; }
private float batteryLevel;
public float BatteryLevel {
get => batteryLevel;
set {
batteryLevel = value;
OnNotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnNotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private BLEManager()
{
}
public async Task ConnectToBLE()
{
await Task.Delay(1000);
BleModel = new TestModel();
}
public async void GetBatteryLevel()
{
BatteryLevel = await bleModel.GetDeviceName();
}
public static BLEManager Shared
{
get
{
if(shared == null)
{
lock (objectLockCheck)
{
if(shared == null)
{
shared = new BLEManager();
}
}
}
return shared;
}
}
}
The Part I need to know is how can my viewModel hook on changes from the BleManager battery level property.

Xamarin.Forms MVVM How to load bindable Picker with data from async process in ViewModel?

In my ViewModel i want o load the Picker source RegionName data from an Azure Region table. I extract data from table in an async method but the Picker displays an empty List even after ObservableCollection or List has changed or crashes.
When using PropertyChanged on the ListRegion list itself the app crashes.
In my models:
public class Region
{
public string Id { get; set; }
public string RegionName { get; set; }
}
In my RegisterPage.xaml:
<Picker SelectedIndex="{Binding RegionsSelectedIndex, Mode=TwoWay}"
ItemsSource="{Binding Regions}"
Margin="0,15,0,0"
Title="Select a region">
</Picker>
in my RegisterPage.cs:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RegisterPage : ContentPage
{
RegisterViewModel registerVM;
public RegisterPage ()
{
InitializeComponent ();
registerVM = new RegisterViewModel();
this.BindingContext = registerVM;
}
protected override void OnAppearing()
{
base.OnAppearing();
}
in my RegisterPageViewModel:
public class RegisterViewModel: INotifyPropertyChanged
{
ApiServices _apiServices = new ApiServices();
public RegisterViewModel()
{
initializePickerAsync();
}
async private void initializePickerAsync()
{
try
{
var regionsList = await App.MobileService.GetTable<Models.Region>().ToListAsync();
List<string> regionsStringList = new List<string>();
foreach (Models.Region reg in regionsList)
{
regionsStringList.Add(reg.RegionName);
}
Regions = regionsStringList;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/*
private RegisterViewModel (ObservableCollection<Models.Region> regionData)
{
ObservableCollection<string> regionDataAsStringList = new ObservableCollection<string>();
foreach (Models.Region r in regionData)
{
regionDataAsStringList.Add(r.RegionName);
}
this.Regions = regionDataAsStringList;
}
async public static Task<RegisterViewModel> BuildViewModelAsync()
{
ObservableCollection<Models.Region> tmpRegionData = new ObservableCollection<Models.Region>(await App.MobileService.GetTable<Models.Region>().ToListAsync());
return new RegisterViewModel(tmpRegionData);
}
*/
int regionsSelectedIndex = 0;
public int RegionsSelectedIndex
{
get
{
return regionsSelectedIndex;
}
set
{
if (regionsSelectedIndex != value)
{
regionsSelectedIndex = value;
OnPropertyChanged(nameof(RegionsSelectedIndex));
if (regionsSelectedIndex >= 0)
{
Region = Regions[regionsSelectedIndex];
}
}
}
}
// public ObservableCollection<Region> Regions {get;set}
public List<string> Regions
{
get
{
return Regions;
}
set
{
if (Regions != value)
{
Regions = value;
OnPropertyChanged(nameof(Regions));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
you seem to be doing a lot of unnecessary creating and assigning of different lists of data. You should be able to create your ObservableCollection ONCE and then add your data to it, something like this
in your ViewModel
ObservableCollection<Region> Regions { get; set; }
public RegisterViewModel()
{
Regions = new ObservableCollection<Region>();
}
public async void GetData()
{
var regionsList = await App.MobileService.GetTable<Models.Region>().ToListAsync();
foreach (Models.Region reg in regionsList)
{
Regions.Add(reg);
}
}
in your page
protected async override void OnAppearing()
{
base.OnAppearing();
await registerVM.GetData();
}

Prism proper handling of viewmodel collections

I'm using the prism framework for my Xamarin.Forms application.
This is a common scenario, but it caused me headache.
MainPage
- MainPageViewModel
- ObserveableCollection<SomePageViewModel>
public class MainPageViewModel : BaseViewModel
{
private ObservableCollection<SomePageViewModel> viewModels;
public MainPageViewModel(INavigationService navigationService) : base(navigationService)
{
SomePageSelectedCommand = DelegateCommand.FromAsyncHandler(NavigateToSomePage);
}
public ICommand SomePageSelectedCommand { get; private set; }
public ObservableCollection<SomePageViewModel> ViewModels
{
get { return viewModels; }
set { SetProperty(ref viewModels, value); }
}
private async Task NavigateToSomePage(SomePageViewModel viewModel)
{
var navParams = new NavigationParameters
{
{viewModel.typeof(SomePageViewModel).Name, viewModel}
};
await Navigation.NavigateAsync(NavigationConstants.SomePageUri, navParams, false);
}
}
public class SomePageViewModel : BaseViewModel
{
protected SomeModel someModel;
public SomePageViewModel(INavigationService navigationService) : base(navigationService)
{
someModel = new SomeModel();
EditCommand = DelegateCommand.FromAsyncHandler(Edit);
}
public ICommand EditCommand { get; private set; }
public string Name
{
get { return SomeModel.Name; }
set { SetProperty(ref SomeModel.Name, value); }
}
public string Description
{
get { return SomeModel.Description; }
set { SetProperty(ref SomeModel.Description, value); }
}
public override void OnNavigatedTo(NavigationParameters parameters)
{
if (parameters.ContainsKey(typeof(SomePageViewModel).Name))
{
var viewModel = (SomePageViewModel)parameters[typeof(SomePageViewModel).Name];
Name = viewModel.Name;
Description = viewModel.Name;
}
}
private async Task Edit()
{
var navParams = new NavigationParameters
{
{viewModel.typeof(SomePageViewModel).Name, this}
};
await Navigation.NavigateAsync(NavigationConstants.SomePageEditUri, navParams, false);
}
}
public class SomePageEditViewModel : BaseViewModel
{
public SomePageEditViewModel(INavigationService navigationService) : base(navigationService)
{
SaveCommand = DelegateCommand.FromAsyncHandler(Save);
}
public ICommand SaveCommand { get; private set; }
private async Task Save()
{
App.ContentService.Save(someModel);
await Navigation.GoBackAsync();
}
}
So lets navigate from the MainPage to a SomePage. We want to edit it so we navigate to SomePageEdit afterwards and save finally.
What is a proper way to make the changes visible to the SomePage and the MainPage according mvvm/prsim? For the first one I could pass the changes as NavigationParameter into GoBackAsync. But what about the MainPage?
Well it appears you have a bit of a design problem. To properly architect your app you want something closer to:
Model
public class TodoItem : ObservableObject
{
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
private bool _done;
public bool Done
{
get { return _done; }
set { SetProperty(ref _done, value); }
}
}
Model Collection Page ViewModel
public class TodoItemListPageViewModel : BaseViewModel, INavigationAware
{
private INavigationService _navigationService { get; }
public TodoItemListViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
TodoItems = new ObservableRangeCollection<TodoItem>();
AddTodoItemCommand = new DelegateCommand(OnAddTodoItemCommandExecuted);
EditTodoItemCommand = new DelegateCommand<TodoItem>(OnEditTodoItemCommandExecuted);
}
public ObservableRangeCollection<TodoItem> TodoItems { get; }
public DelegateCommand AddTodoItemCommand { get; }
public DelegateCommand<TodoItem> EditTodoItemCommand { get; }
public void OnNavigatingTo(NavigationParameters parameters)
{
// Initialize your collection
}
public void OnNavigatedTo(NavigationParameters parameters)
{
if(parameters.GetValue<NavigationMode>(KnownNavigationParameters.NavigationMode) == NavigationMode.Back)
{
// Option 1
// Fetch an updated list of TodoItems from your data source
TodoItems.ReplaceRange(updatedTodoItems);
// Option 2
// Replace the updated item or add a new item
}
}
Edit Model Page ViewModel
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
private async void OnAddTodoItemCommandExecuted() =>
await _navigationService.NavigateAsync("AddTodoItemPage");
private async void OnEditTodoItemCommandExecuted(TodoItem item) =>
await _navigationService.NavigateAsync("EditTodoItemPage", new NavigationParameters { { "item", item } });
}
public class EditTodoItemPageViewModel : BaseViewModel
{
private INavigationService _navigationService { get; }
public EditTodoItemPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
SaveCommand = new DelegateCommand(OnSaveCommandExecuted, () => IsNotBusy)
.ObservesProperty(() => IsBusy);
}
private TodoItem _model;
public TodoItem Model
{
get { return _model; }
set { SetProperty(ref _model, value); }
}
public DelegateCommand SaveCommand { get; }
public void OnNavigatingTo(NavigationParameters parameters)
{
Model = parameters.GetValue<TodoItem>("item");
}
private async void OnSaveCommandExecuted()
{
IsBusy = true;
// Persist any changes
// Option 1
await _navigationService.GoBackAsync();
// Option 2
await _navigationService.GoBackAsync(new NavigationParameters { { "updatedItem", Model } });
IsBusy = false;
}
}
The Why...
Your ObservableCollection should be where T : TModel not where T : TViewModel. Another issue you would have immediately is that the INavigationService is dependent on knowing what Page you're navigating to/from. So you cannot follow the pattern you're doing there.
Now a couple of notes here.
You'll notice this sample is actually using some helpers from the MvvmHelpers library. The BaseViewModel class from that library gives you the IsBusy/IsNotBusy property as well as a Title property and the ObservableRangeCollection.
ObservableRangeCollection vs ObservableCollection
The ObservableRangeCollection gives you a little better performance particularly when working with larger datasets. You may have noticed the Option 1 where we simply get the updated dataset and replace the entire dataset. This is where the ObservableRangeCollection really shines in my opinion since you're able to ensure you have an up to date dataset while minimizing the notifications to the UI resulting in fewer CPU cycles taken up.
Models, Views, ViewModels
I do not mean for this to an authoritative answer but to at least provide food for thought. From a high level overview of MVVM patterns you generally are working with a View which provides the UX, a ViewModel which provides the business logic for who/what/why/when/where/etc, and a Model which is the data we want to work with. In some cases it can become necessary to introduce a DTO which further abstracts our raw data from the Model we want to work with as a logical unit.

Custom Listener in Service Fabric + How to access from client?

Actually I am trying to learn Service fabric and its custom listener part. For this I have created a sample Service Fabric Stateful service which does nothing but returning a number 10 here.
internal sealed class StatefulService1 : StatefulService, INumber
{
protected override IEnumerable<ServiceReplicaListener>
CreateServiceReplicaListeners()
{
return new[] { new ServiceReplicaListener(context => new
HttpCommunicationListener(context), "HttpListener") };
}
public int GetNumber()
{
return 10;
}
}
I have created a custom Listener for this as below:
class HttpCommunicationListener : ICommunicationListener
{
StatefulServiceContext serviceContext;
string publishAddress;
public HttpCommunicationListener(StatefulServiceContext
serviceContext)
{
this.serviceContext = serviceContext;
}
public void Abort()
{
throw new NotImplementedException();
}
public Task CloseAsync(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<string> OpenAsync(CancellationToken cancellationToken)
{
var codePackageContext =
this.serviceContext.CodePackageActivationContext;
EndpointResourceDescription desc =
codePackageContext.GetEndpoint("ServiceEndpoint");
var port = desc.Port;
var address = string.Format("http://Address:{0}/", port);
this.publishAddress = address.Replace("Address",
FabricRuntime.GetNodeContext().IPAddressOrFQDN);
return Task.FromResult(publishAddress);
}
}
On the client side, I am struggling to access the GetNumber method using my listener,
My Client Side Implementation:
class CustomCommunicationClient : ICommunicationClient
{
public CustomCommunicationClient(ResolvedServicePartition partition)
{
this.ResolvedServicePartition = partition;
// this.Endpoint = partition.GetEndpoint();
}
public ResolvedServicePartition ResolvedServicePartition { get; set; }
public string ListenerName { get; set; }
public ResolvedServiceEndpoint Endpoint { get; set; }
}
Client Factory impl:
class CustomCommunicationClientFactory : CommunicationClientFactoryBase<CustomCommunicationClient>
{
ResolvedServicePartition partition;
public CustomCommunicationClientFactory(ResolvedServicePartition partition)
{
this.partition = partition;
}
protected override void AbortClient(CustomCommunicationClient client)
{
}
protected override Task<CustomCommunicationClient> CreateClientAsync(string endpoint, CancellationToken cancellationToken)
{
return Task.FromResult(new CustomCommunicationClient(this.partition));
}
protected override bool ValidateClient(CustomCommunicationClient client)
{
return true;
}
protected override bool ValidateClient(string endpoint, CustomCommunicationClient client)
{
return true;
}
}
Main.cs
class Program
{
private static string ServiceName = "fabric:/CustomCommunication.StatefulService/StatefulService1";
static void Main(string[] args)
{
var servicePartition = GetServicePartitionAsync();
var clientFactory = new CustomCommunicationClientFactory(servicePartition.Result);
var partition = new ServicePartitionKey(1);
var myServicePartitionClient = new ServicePartitionClient<CustomCommunicationClient>(clientFactory,
new Uri(ServiceName), partition);
Console.WriteLine("Running request client...");
//var result =
// myServicePartitionClient.InvokeWithRetryAsync(client => client., CancellationToken.None).Result;
Console.ReadKey();
}
private static Task<ResolvedServicePartition> GetServicePartitionAsync()
{
ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault();
Task<ResolvedServicePartition> partition = resolver.ResolveAsync(new Uri(ServiceName),
new ServicePartitionKey(1), CancellationToken.None);
return partition;
}
}
Can someone please guide me on how to do it? It would be great if someone provide me a code for this.