PRISM Xamarin - Working with tabbed pages (IActiveAware) - xaml

I have tab pages implementing different views, but I cannot initialize each of the tabs when navigating.
<TabbedPage.Children>
<tabPages:Page1/>
<tabPages:Page2/>
<tabPages:Page3/>
</TabbedPage.Children>
So what I did was to use IActiveAware as prism documentation suggested to know which tab page is currently active. So I have this class:
public abstract class TabbedChildViewModelBase : BaseViewModel, IActiveAware, INavigationAware, IDestructible
protected bool IsInitalized { get; set; }
private bool _IsActive;
public bool IsActive
{
get
{
return _IsActive;
}
set
{
SetProperty(ref _IsActive, value, RaiseIsActiveChanged);
}
}
public event EventHandler IsActiveChanged;
public virtual void OnNavigatingTo(NavigationParameters parameters)
{
}
protected virtual void RaiseIsActiveChanged()
{
IsActiveChanged?.Invoke(this, EventArgs.Empty);
}
public virtual void Destroy()
{
}
}
So each child view models inherits the child view model base:
public class Page1 : TabbedChildViewModelBase
{
public CurrentSeaServiceViewModel()
{
IsActiveChanged += HandleIsActiveTrue;
IsActiveChanged += HandleIsActiveFalse;
}
private void HandleIsActiveTrue(object sender, EventArgs args)
{
if (IsActive == false)
{
TestLabelOnly = "Test";
}
// Handle Logic Here
}
private void HandleIsActiveFalse(object sender, EventArgs args)
{
if (IsActive == true) return;
// Handle Logic Here
}
public override void Destroy()
{
IsActiveChanged -= HandleIsActiveTrue;
IsActiveChanged -= HandleIsActiveFalse;
}
}
The problem is, the child vm isn't initializing. Is there something needed in order to implement IActiveAware properly nor launching the IsActive property

I still used IActiveAware unfortunately, to make the childtabbedviewmodel work you need to bind the page to its own view model.
So here's what I did:
<TabbedPage.Children>
<views:ChildPage1>
<views:ChildPage1.BindingContext>
<viewModels:ChildPage1ViewModel/>
</views:ChildPage1.BindingContext>
</views:ChildPage1>
<views:ChildPage2>
<views:ChildPage2.BindingContext>
<viewModels:ChildPage2ViewModel/>
</views:ChildPage2.BindingContext>
</views:ChildPage2>
</TabbedPage.Children>
I used the property BindingContext of my views and
using IActiveAware I would also know what tab is currently active. Hope anyone helps this who finds trouble binding the child pages of a tab.

Related

Action filter does not override controller action?

I have implemented an IAsyncAuthorizationFilter/IActionFilter filter and implemented TypeFilterAttribute for the filter. When I add the attribute to both the controller and action, the action filter does not appear to override the controller level filter.
public class MyAuthorizeAttribute : TypeFilterAttribute
{
public MyAuthorizeAttribute (bool redirectOnFailure = true)
: base(typeof(MyFilter))
{
Arguments = new object[]
{
redirectOnFailure
};
}
}
public class MyFilter: IAsyncAuthorizationFilter, IActionFilter
{
public bool RedirectOnFailure { get; set; }
public MyFilter(bool redirectOnFailure)
{
RedirectOnFailure = redirectOnFailure;
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.Controller is Controller controller)
{
// Do some work
if (true)
{
if (!RedirectOnFailure)
{
context.Result = new JsonResult("Your session has expired.");
}
else
{
context.Result = new RedirectResult("LoginUrl");
}
return;
}
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do nothing
}
public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
// Do work
}
}
The redirectOnFailure will be true for the Index action even though the filter specified false. In ASP.NET MVC, the action filter would override the controller filter. You could have a default for all actions but override specific actions with different properties/parameters. Can you not do this in Core?
[MyAuthorize]
public class HomeController : Controller
{
[MyAuthorize(redirectOnFailure: false)]
public IActionResult Index()
{
// Do work
}
}
As per the Microsoft website, filters do not override each other. They simply run one after the other in the order described in the cited document.
Just because the same attribute is put in both the controller and the action doesn't mean that ASP.net will say "ah, you probably want to override the class-level attribute". That's just not how it works.
If you want override logic, you need to write override logic.
Here's a sample made for .Net 6. The magic is done by the FindEffectivePolicy() method. This sample shows how to compare the current object against the effective one and only run the logic if the comparison matches.
public class MyFilter : IAsyncAuthorizationFilter
{
#region Properties
public string Name { get; }
#endregion
#region Constructors
public MyFilter(string name)
{
Name = name;
}
#endregion
#region IAsyncAuthorizationFilter
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var effectiveAtt = context.FindEffectivePolicy<MyFilter>();
System.Diagnostics.Debug.Print($"Effective filter's name: {effectiveAtt?.Name}");
System.Diagnostics.Debug.Print($"Am I the effective attribute? {this == effectiveAtt}");
if (this == effectiveAtt)
{
// Do stuff since this is the effective attribute (policy).
}
else
{
// ELSE part probably not needed. We just want the IF to make sure the code runs only once.
}
return Task.CompletedTask;
}
#endregion
}

Xamarin MVVM push user data to viewmodel

like the title says I want to give through the user information to my viewmodel, but the problem is that the viewmodel is registered as a dependency and I am binding its content to the xaml page itself. How do I send the user information to the viewmodel itself?
Thank you!
Xaml.cs part:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Calendar : ContentPage
{
public Calendar(User user)
{
InitializeComponent();
FileImageSource image = new FileImageSource
{
File = "calendar.png"
};
Icon = image;// push user information to the ICalendarViewModel
BindingContext = AppContainer.Container.Resolve<ICalendarViewModel>();
}
}
Interface:
public interface ICalendarViewModel : INotifyPropertyChanged
{
}
Bootstrap part registering dependencies:
public class Bootstrap
{
public IContainer CreateContainer()
{
var containerBuilder = new ContainerBuilder();
RegisterDependencies(containerBuilder);
return containerBuilder.Build();
}
protected virtual void RegisterDependencies(ContainerBuilder builder)
{
builder.RegisterType<CalendarViewModel>()
.As<ICalendarViewModel>()
.SingleInstance();
}
}
CalendarViewModel: I do not know if this will help
public class CalendarViewModel : ViewModelBase, ICalendarViewModel
{
public event PropertyChangedEventHandler PropertyChanged;
public string ErrorMessage { get; set; }
private CourseInformation _information;
private ICourseInformationRepository _repository;
public CalendarViewModel()
{
_repository = new CourseInformationRepository();
LoadData();
}
private ObservableCollection<CourseInformation> _courses;
public ObservableCollection<CourseInformation> Courses
{
get
{
return _courses;
}
set
{
_courses = value;
RaisePropertyChanged(nameof(Courses));
}
}
private void LoadData()
{
try
{
ObservableCollection<CourseInformation> CourseList = new ObservableCollection<CourseInformation>(_repository.GetAllCourseInformation());
Courses = new ObservableCollection<CourseInformation>();
DateTime date;
foreach (var course in CourseList)
{
string [] cour = course.Date.Split('/');
cour[2] = "20" + cour[2];
date = new DateTime(Convert.ToInt32(cour[2]), Convert.ToInt32(cour[1]), Convert.ToInt32(cour[0]));
if (date == DateTime.Now)//TESTING WITH TEST DATE, datetime.now
{
if (course.FromTime.Length < 4)
{
course.FromTime = "0" + course.FromTime;
}
if (course.UntilTime.Length < 4)
{
course.UntilTime = "0" + course.UntilTime;
}
course.FromTime = course.FromTime.Insert(2, ":");
course.UntilTime = course.UntilTime.Insert(2, ":");
Courses.Add(course);
}
}
}
catch (ServerUnavailableException e)
{
ErrorMessage = "Server is niet beschikbaar, ophalen van kalender is niet mogelijk.";
}
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Bootstrap binding in app.xaml.cs:
public partial class App : Application
{
public App()
{
InitializeComponent();
AppContainer.Container = new Bootstrap().CreateContainer();
MainPage = new LoginView();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
I wanted to comment (not enough reputation) on #LeRoy, use a framework. I would recommend FreshMVVM and you can pass objects into the ViewModel and even pass in Services. It makes it all nice and clean, and it just works.
Should not your CalendarViewModel viewModel contain BindableBase ?
public class CalendarViewModel : BindableBase, ViewModelBase, ICalendarViewModel
what framework are you using? prism, freshmvvm.
Your View and Viewmodel is normally automatically handled by the framework, all you need to do is register your page.
Container.RegisterTypeForNavigation<Views.CalendarPage>();

Xamarin Forms - Reference XAML from Android specific .cs file

I have a page called MapPage.xaml and a code behind called MapPage.xaml.cs. In my android project, I have another file called CustomMapRenderer.cs. In the CustomMapRenderer.cs file, I need to retrieve the item selected variable in a XAML picker found in my MapPage.xaml file, which changes when a user picks an option in my XAML picker.
How to I reference the picker from my CustomMapRenderer.cs?
In the CustomMapRenderer.cs file, I need to retrieve the item selected variable in a XAML picker found in my MapPage.xaml file, which changes when a user picks an option in my XAML picker.
If you followed the official doc Customizing a Map to create your CustomMapRenderer, then in PCL, there should be a class which inherits from Map, for example:
public class CustomMap : Map
{
}
Then, if your picker is another control in your MainPage, you can create a bindable property for your CustomMap, and override OnElementPropertyChanged in your renderer to get this property when it changed.
For example, in PCL:
public class MapWithMyZoomControl : Map
{
public ZoomState MyZoom
{
get { return (ZoomState)GetValue(MyZoomProperty); }
set { SetValue(MyZoomProperty, value); }
}
public static readonly BindableProperty MyZoomProperty =
BindableProperty.Create(
propertyName: "MyZoom",
returnType: typeof(ZoomState),
declaringType: typeof(MapWithMyZoomControl),
defaultValue: ZoomState.normal,
propertyChanged: OnZoomPropertyChanged);
public static void OnZoomPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
}
public enum ZoomState
{
normal,
zoomin,
zoomout
}
}
And in its renderer:
public class MapWithMyZoomControlRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap map;
public void OnMapReady(GoogleMap googleMap)
{
map = googleMap;
map.UiSettings.ZoomControlsEnabled = false;
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
}
if (e.NewElement != null)
{
var formsMap = (MapWithMyZoomControl)e.NewElement;
((MapView)Control).GetMapAsync(this);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var element = Element as MapWithMyZoomControl;
if (e.PropertyName == "MyZoom" && map != null)
{
if (element.MyZoom == MapWithMyZoomControl.ZoomState.zoomin)
{
map.AnimateCamera(CameraUpdateFactory.ZoomIn());
}
else if (element.MyZoom == MapWithMyZoomControl.ZoomState.zoomout)
{
map.AnimateCamera(CameraUpdateFactory.ZoomOut());
}
element.MyZoom = MapWithMyZoomControl.ZoomState.normal;
}
}
}
Out of this map control, I use buttons to control to zoom the map:
map.MyZoom = MapWithMyZoomControl.ZoomState.zoomin;
It'a a demo, but you can modify it to make property connected to your picker.

Application Menu with Security Trimming

I came from asp.net 2.0 webforms; where i just define my menu in Web.sitemap with all the trimming taken care off.
Is there any equivalent feature in asp.net-core-mvc for this seemingly easy task ?
You can create a custom TagHelper for it, inside this tag helper you can check whether user is in apporperiate role or not:
public class SecurityTrimmingTagHelper : TagHelper
{
[ViewContext]
public ViewContext Context { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = null;
if (!Context.HttpContext.User.Identity.IsAuthenticated)
{
output.SuppressOutput();
}
if (Context.HttpContext.User.IsInRole("Admin"))
{
return;
}
output.SuppressOutput();
}
}

Extend DropDownList to add ListSearchExtender

I want to extend DropDownList to add ListSearchExtender.
Using the code below, the control works well in runtime but in design time it give me this error:
SearchDropDownList - DdlTest There was an error rendering the
control. Page cannot be null. Please ensure that this operation is
being performed in the context of an ASP.NET request.
I'd like to understand the cause of this error.
[ToolboxData("<{0}:SearchDropDownList runat=\"server\"></{0}:SearchDropDownList>")]
public class SearchDropDownList : DropDownList
{
private ListSearchExtender listSearchExt = new ListSearchExtender();
protected override void OnInit(EventArgs e)
{
ReloadSettings();
}
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
listSearchExt.RenderControl(w);
}
public void ReloadSettings()
{
listSearchExt.TargetControlID = this.ID;
listSearchExt.ID = this.ID + "_CalendarExtender";
if (Controls.Count > 0)
{
foreach (Control item in Controls)
{
if (item.ID == listSearchExt.ID)
{
Controls.Remove(item);
}
}
}
Controls.Add(listSearchExt);
}
}
i got it by simple way i am not sure if it will make problem in future but for now it work well
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
if (!this.DesignMode)
{
listSearchExt.RenderControl(w);
}
}