Xamarin Forms MVVMCross how to pass parameter when closing the viewmodel - xamarin.forms

I have a Xamarin Forms using MVVMCross. One of my view models loads a new ViewModel like this:
public class ViewModelMainForm: BaseViewModel, IMvxViewModel<string>
{
..... some code here .....
public void Prepare(String parameters)
{
// should get incidentId HERE****
}
public async void OnShowIncidentForm()
{
var result = await _navigation.Navigate(typeof(ViewModelIncidentForm), _selectedItem.EmployeeId);
}
}
Then the new view appears perfect and I can receive the EmployeeId in the Prepare method.
public class ViewModelIncidentForm : BaseViewModel, IMvxViewModel<string>
{
..... some code here .....
public void Prepare(String parameters)
{
employeeId = parameters.ToString();
GetEmployeeData(employeeId);
}
public void CloseView(int incidentId)
{
_navigation.Close(this, incidentId);
}
}
All this works perfect, the problem is that when I close the ViewModel to pop to the previous ViewModel I don't know how to get the parameter "incidentId".
In my main form ViewModel, I already placed a breakpoint into the Prepare method but is not triggered.
Any clue on how to get the parameter sent in the navigation.Close() method in my main ViewModel?

Related

SqliteConnection Xamarin forms Exception Unhandled?

When i try to run the project, i am getting this kind of error: "System.NullReferenceException: Object reference not set to an instance of an object"
pointing in this code:
sqliteconnection = DependencyService.Get().GetConnection();
This is my Class for DB actions:
namespace DevoApp.DevoAppFinal.Helpers
{
public class DatabaseHelper
{
static SQLiteConnection sqliteconnection;
public const string DbFileName = "Devotion.db";
public DatabaseHelper()
{
sqliteconnection = DependencyService.Get<ISQLite>().GetConnection();
sqliteconnection.CreateTable<Devotion>();
}
// Get All Contact data
public List<Devotion> GetAllDevotionsData()
{
return (from data in sqliteconnection.Table<Devotion>() select data).ToList();
}
//Get Specific Contact data
public Devotion GetDevotionData(int id)
{
return sqliteconnection.Table<Devotion>().FirstOrDefault(t => t.devotionalId == id);
}
// Delete all Contacts Data
public void DeleteAllDevotions()
{
sqliteconnection.DeleteAll<Devotion>();
}
// Delete Specific Contact
public void DeleteDevotion(int id)
{
sqliteconnection.Delete<Devotion>(id);
}
// Insert new Contact to DB
public void InsertDevotion(Devotion contact)
{
sqliteconnection.Insert(contact);
}
// Update Contact Data
public void UpdateDevotion(Devotion contact)
{
sqliteconnection.Update(contact);
}
}
}
When using the DependencyService, you have to implement the interface in each targeted platform project.
In this case, you should have the ISQLite interface implemented on the platforms you're targeting, i.e. iOS and Android.
To make Xamarin find it at runtime, you will have to register the implementation with the Dependency attribute above the namespace. Observe the following example based on a few assumptions of your project.
In your shared library you have declared the interface:
public interface ISQLite
{
// Members here
}
Nothing fancy going on there. Then for each platform, you want to run the app on, do something like this:
[assembly: Xamarin.Forms.Dependency (typeof (SQLiteImplementation_iOS))]
namespace DevoApp.DevoAppFinal.iOS
{
public class SQLiteImplementation_iOS : ISQLite
{
// ... Your code
}
}
From the error, it looks like you forgot to add the attribute

Xamarin Forms with Prism: Remove a page from the stack

When I navigate from page A to page B, I need to remove page A.
How can I do this with Prism's navigation service in Xamarin Forms?
There are a few scenarios that people run into on this one.
As a common example say you have a LoginPage, and once the user successfully logs in you want to Navigate to the MainPage. Your code might look something like the following:
public class App : PrismApplication
{
protected override async void OnInitialized()
{
await NavigationService.NavigateAsync("LoginPage");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<LoginPage>();
Container.RegisterTypeForNavigation<MainPage>();
}
}
public class LoginPageViewModel : BindableBase
{
public DelegateCommand LoginCommand { get; }
private async void OnLoginCommandExecuted()
{
// Do some validation
// Notice the Absolute URI which will reset the navigation stack
// to start with MainPage
await _navigationService.NavigateAsync("/MainPage");
}
}
Now if what you're looking for is some flow where your navigation stack looks like MainPage/ViewA and what you want is MainPage/ViewB and you don't want to reinitialize MainPage, then this is something that we are currently evaluating and wanting to improve this so you could do something like _navigationService.NavigateAsync("../ViewB"). In the mean time what I might suggest is something like this:
public class ViewAViewModel : BindableBase
{
public DelegateCommand ViewBCommand { get; }
private async void OnViewBCommandExecuted()
{
var parameters = new NavigationParameters
{
{ "navigateTo", "ViewB" }
};
await _navigationService.GoBackAsync(parameters);
}
}
public class MainPageViewModel : BindableBase, INavigatedAware
{
public async void OnNavigatingTo(NavigationParameters parameters)
{
if(parameters. GetNavigationMode() == NavigationMode.Back &&
parameters.TryGetValue("navigateTo", out string navigateTo))
{
await _navigationService.NavigateAsync(navigateTo);
return;
}
}
}
Given: "NavigationPage/ViewA/ViewB/ViewC/ViewD"
Navigate from ViewD with:
NavigationService.NavigateAsync("../../../ViewE");
Results in: "NavigationPage/ViewA/ViewE"
Referred from here
Need Prism >= 7.0
Another approach would be to have your page implement INavigationAware and in the OnNavigatedFrom, call Navigatin.RemovePage(this).
I do it that way, it's simpler.
navigationService.NavigateAsync("../PageB");
I am using Prims 7.0.0.396.

Is there a way to get the current controller instance in ASP.NET 5?

Is there a way to do this using DI? I tried IScopedInstance<Controller> but this gives me null. Poked around aspnet's source code but didn't win. Any ideas?
I have a controller that accepts different IPaymentMethods. The IPaymentMethod can be a ViewComponent that can render Views. If the IPaymentMethod is a ViewComponent, I want it to use MVC's built-in model binding on post back.
public class XController : Controller
{
// ctor, props, ...
public IActionResult Checkout()
{
return View(new Model
{
PaymentMethodId = 1,
PaymentMethodType = typeof(MyPaymentMethod) // The razor file will use this type to render it as a ViewComponent
});
}
[HttpPost]
public IActionResult Checkout(Model model)
{
var paymentMethod = _paymentService.GetPaymentMethodById(model.PaymentMethodId);
paymentMethod.ProcessPayment();
// ..
}
}
This is where I need the controller to be injected. I wanted to make use of the built-in MVC validation and model binding.
public class MyPaymentMethod : IPaymentMethod
{
private Controller _currentController;
public MyPaymentMethod(IScopedInstance<Controller> controller)
{
_currentController = controller.Value;
}
public void ProcessPayment()
{
var model = new PaymentModel();
_currentController.TryUpdateModel(model, typeof(PaymentModel), null);
if (!_currentController.ModelState.IsValid)
{
return; // or exception
}
// Process Payment using model
}
public Task<IViewComponentResult> InvokeAsync()
{
// returns View
}
}
public interface IPaymentMethod
{
void ProcessPayment();
}
Since the model instance is required in the ProcessPayment method, why not simply pass it as a parameter?
[HttpPost]
public IActionResult Checkout(PaymentModel model)
{
var paymentMethod = _paymentService.GetPaymentMethodById(model.PaymentMethodId);
if (!ModelState.IsValid)
{
return; // or exception
}
paymentMethod.ProcessPayment(model);
// ..
}
public void ProcessPayment(PaymentModel model)
{
// Process Payment using model
}
Your service is taking on responsibilities that belong to the controller - namely checking ModelState.IsValid.
public interface IPaymentMethod
{
void ProcessPayment(PaymentModel model);
}
You may wish to also pass just the properties that are needed from the payment model, or you may wish to make an IPaymentModel interface to decouple your model from your PaymentService. In that case, your IPaymentModel would go into a shared layer.
public interface IPaymentMethod
{
void ProcessPayment(IPaymentModel model);
}
This no longer works with beta7
At this time of writing (beta6), this probably isn't supported and there is a good reason for it: Controllers in ASP.NET 5 does not need to inherit from the Controller class. I have, however, found a way for this to work using ActionFilters.
public class ScopeControllerActionFilterAttribute : ActionFilterAttribute
{
private readonly IScopedInstance<Controller> _controller;
public ScopeControllerActionFilterAttribute(IScopedInstance<Controller> controller)
{
_controller = controller;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
if (_controller.Value == null)
{
_controller.Value = context.Controller as Controller;
}
}
}
Note that depending on the stage of the http request lifecycle, the Value of IScopedInstance<Controller> may still be empty.

How to properly MVC this task?

My task is to upload file.
class FileUploadController : Controller {
public ActionResult Index(HttpPostedFileBase postedFile) {
// When and how to validate it and return appropriate view and model data
// How to store the file in database and appropriately return view and model data
}
}
Validation requires to check if filename already exists(database access) and if file extension(database access) is supported.
So far I architected it like this:
class FileUploadController : Controller {
public ActionResult Index(HttpPostedFileBase postedFile) {
FileUploadModel model=new FileUploadModel();
model.UploadedFile = postedFile;
FileUploadService service = new FileUploadService();
bool valid = service.Validate(postedFile);
if (valid) {
FileUploadViewModel viewModel = service.Save(postedFile);
return View("some_view", viewModel);
}
else {
return View("some_view", service.ViewModel);
}
}
}
public class FileUploadModel
{
public HttpPostedFileBase UploadedFile { get; set; }
}
class FileUploadViewModel {
public ModelState ModelState;
public String Filename;
}
public class FileUploadService
{
private FileUploadViewModel viewModel = new FileUploadViewModel();
public FileUploadViewModel Save(FileUploadModel fileUploadModel)
{
// here i will just save it to the database
// and return viewModel with valid state
}
public bool Validate(FileUploadModel fileUploadModel)
{
// I do the filename, size, etc validation here together with database validation if the file exists and appropriately attach errors to viewModel.ModelState so views can render the error
}
}
As you can see my validate method populates viewModel.ModelState and my Save method returns new FileUploadViewModel. I really can't make up my mind how to design this so it can grow.
My questions are:
- If suddenly update action is added and my service serve update method, I will need to return different data as ViewModel and the validation would be different, should I create new ViewModel class and new Validation..?
- Does my validation occur at valid place?

problem in xbap mvvm implementation

I am trying to implement a mvvm design pattern for xbap application But unable to carry out simple text binding.
Following is the definition of my DemoViewModel.cs,
class DemoViewModel : INotifyPropertyChanged
{
string name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("Name");
}
}
public DemoViewModel()
{
Name = "test";
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I am binding the view to viewmodel using code behind of view,
public DemoView()
{
InitializeComponent();
DataContext = new DemoViewModel();
}
Following is the binding definition for text box present in view,
I appears that you have everything hooked up correctly. During execution, take a look at you 'Output' window and see if it gives you any warnings on you Binding. Also, try to simplify your xaml a bit to the following and see if this helps:
<TextBox Text="{Binding Name, Mode=TwoWay}"/>
Based on your comment, to JSPrang's answer, I know whats wrong =)
XBAP is missing permissions to use reflection, and can therefore only bind to public classes, unless run in full trust.

Resources