I am trying to override the OnLaunched() function in a Template 10 Windows Application, but the problem is that it is sealed in Template 10 BootStrapper class (which inherits from the Application class).
Here's my method:
using Windows.UI.Xaml;
...
namespace Sample {
...
sealed partial class App : Template10.Common.BootStrapper {
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
/*************** My stuff *****************
***********************************************/
}
...
}
I am using Template10 Blank app for this app, and the OnLaunched() method in BootStrapper class is this:
namespace Template10.Common
{
public abstract class BootStrapper : Application
{
...
protected sealed override void OnLaunched(LaunchActivatedEventArgs e);
...
}
...
}
I cannot remove the sealed modifier from OnLaunched() in BootStrapper (guess because it is "from metadata").
What's the point of including a sealed method in an abstract class?
Do we get some other method to override, like OnResume(), OnStartAsync(), etc, instead of OnLaunched()?
Update: For reference, here are all the members in BootStrapper:
public abstract class BootStrapper : Application
{
public const string DefaultTileID = "App";
protected BootStrapper();
public static BootStrapper Current { get; }
public TimeSpan CacheMaxDuration { get; set; }
public INavigationService NavigationService { get; }
public StateItems SessionState { get; set; }
public bool ShowShellBackButton { get; set; }
protected Func<SplashScreen, UserControl> SplashFactory { get; set; }
public event EventHandler<WindowCreatedEventArgs> WindowCreated;
public static AdditionalKinds DetermineStartCause(IActivatedEventArgs args);
public NavigationService NavigationServiceFactory(BackButton backButton, ExistingContent existingContent);
[AsyncStateMachine(typeof(<OnInitializeAsync>d__44))]
public virtual Task OnInitializeAsync(IActivatedEventArgs args);
public virtual void OnResuming(object s, object e);
public abstract Task OnStartAsync(StartKind startKind, IActivatedEventArgs args);
[AsyncStateMachine(typeof(<OnSuspendingAsync>d__45))]
public virtual Task OnSuspendingAsync(object s, SuspendingEventArgs e);
public Dictionary<T, Type> PageKeys<T>() where T : struct, IConvertible;
public virtual T Resolve<T>(Type type);
public virtual INavigable ResolveForPage(Type page, NavigationService navigationService);
public void UpdateShellBackButton();
[AsyncStateMachine(typeof(<OnActivated>d__26))]
protected sealed override void OnActivated(IActivatedEventArgs e);
[AsyncStateMachine(typeof(<OnCachedFileUpdaterActivated>d__27))]
protected sealed override void OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs args);
[AsyncStateMachine(typeof(<OnFileActivated>d__28))]
protected sealed override void OnFileActivated(FileActivatedEventArgs args);
[AsyncStateMachine(typeof(<OnFileOpenPickerActivated>d__29))]
protected sealed override void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args);
[AsyncStateMachine(typeof(<OnFileSavePickerActivated>d__30))]
protected sealed override void OnFileSavePickerActivated(FileSavePickerActivatedEventArgs args);
protected sealed override void OnLaunched(LaunchActivatedEventArgs e);
[AsyncStateMachine(typeof(<OnSearchActivated>d__31))]
protected sealed override void OnSearchActivated(SearchActivatedEventArgs args);
[AsyncStateMachine(typeof(<OnShareTargetActivated>d__32))]
protected sealed override void OnShareTargetActivated(ShareTargetActivatedEventArgs args);
protected sealed override void OnWindowCreated(WindowCreatedEventArgs args);
public enum AdditionalKinds
{
Primary,
Toast,
SecondaryTile,
Other
}
public enum BackButton
{
Attach,
Ignore
}
public enum ExistingContent
{
Include,
Exclude
}
public enum StartKind
{
Launch,
Activate
}
}
Please help :}
Template 10 does not allow us to override OnLaunched() method. Instead we can override the OnInitializeAsync() and OnStartAsync() methods for this purpose.
The reason is that Template 10 recommends us to use something called the Single Page Model, which is nothing but using a single instance of the Page class to put in the empty Frame provided by the Framework. How is that benefit to us? Well, if we need to put a menu, say a Hamburger menu, in our app, then we need to copy the code for the menu in each and every page we create in our app. This would lead to things like redundancy, inconsistency, WET code, etc. etc.
Therefore, template 10, initially, creates a Page, which they call the Shell, and then contents of each page is loaded into this Shell page, instead of creating new Pages.
We can override these methods in the following way:
sealed partial class App : BootStrapper
{
public App()
{
this.InitializeComponent();
}
public override Task OnInitializeAsync(IActivatedEventArgs args)
{
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
Window.Current.Content = new Views.Shell(nav);
return Task.FromResult<object>(null);
}
public override Task OnStartAsync(BootStrapper.StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(Views.MainPage));
return Task.FromResult<object>(null);
}
}
Here's where I figured the answer:
https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-HamburgerMenu
So, long story short, override OnInitializeAsync() or OnStartAsync(), instead of OnLaunched().
You're trying to override OnLaunched in MyPage.xaml.cs and I'm pretty safe to assume that your MyPage class does not inherit from Application. So it does not have OnLaunched() method (at least not with that signature). What you need to do is override it in App.xaml.cs, as it's Application.OnLaunched(). App class, which is in App.xaml.cs, inherits from Application.
By the way, this is the example from the blank app template, which you've mentioned:
Related
I'm trying to implement a generic abstract method with a type constraint, then Implement it multiple times using different specified types.
public abstract class Ability
{
public abstract void BindToStation<T>(T station) where T : Station;
}
public class DashAbility : Ability
{
public override void BindToStation<NavStation>(NavStation station){ }
public override void BindToStation<CannonStation>(CannonStation station){ }
}
But I get an error which says the method has already been defined with the same paramater types.
I'm guessing that the compiler treats any generic paramater as the same in terms of the method signature, so these two methods look the same to it.
Still though, I'm wondering if theres a way to have generic method overloading using specific types.. ?
You can't do exactly what you want, but you can try an approach like this:
interface IBindableTo<T> where T : Station
{
void BindToStation(T station);
}
abstract class Ability
{
public abstract void BindToStation<T>(T station) where T : Station;
}
class DashAbility : Ability, IBindableTo<NavStation>, IBindableTo<CannonStation>
{
public override void BindToStation<T>(T station)
{
if (this is IBindableTo<T> binnder)
{
binnder.BindToStation(station);
return;
}
throw new NotSupportedException();
}
void IBindableTo<NavStation>.BindToStation(NavStation station)
{
...
}
void IBindableTo<CannonStation>.BindToStation(CannonStation station)
{
...
}
}
Hope this helps.
C# doesn't support specialization in that way, and neither does C++ easily when you want to specialize on runtime type.
But you can use polymorphism, so you can use double-dispatch:
public abstract class Station {
internal abstract void DashBindToStation();
}
public class NavStation : Station {
internal override void DashBindToStation() {
throw new NotImplementedException();
}
}
public class CannonStation : Station {
internal override void DashBindToStation() {
throw new NotImplementedException();
}
}
public abstract class Ability {
public abstract void BindToStation(Station station);
}
public class DashAbility : Ability {
public override void BindToStation(Station station) {
station.DashBindToStation();
}
}
Another possibility with C# is to use runtime dispatching using dynamic:
public abstract class Station {
}
public class NavStation : Station {
}
public class CannonStation : Station {
}
public abstract class Ability {
public abstract void BindToStation(Station station);
}
public class DashAbility : Ability {
public void BindToStation(NavStation station) {
}
public void BindToStation(CannonStation station) {
}
public override void BindToStation(Station station) {
BindToStation((dynamic)station);
}
}
My goal is to have the Abstract class update on its own once Consume is called on one of the derived classes.
Imagine this:
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public virtual void Consume()
{
_consumed = true;
}
}
public class HealthyConsumable: AbstractConsumable
{
public override void Consume()
{
// Do something healthy and ...
base.Consume(); // Would like to avoid this...
}
}
public class PoisonousConsumable: AbstractConsumable
{
public override void Consume()
{
// Do something poisonous and ...
base.Consume(); // Would like to avoid this...
}
}
What I would like to achieve here is not having to call base.Consume() on the override methods, but still have the abstract class set _consumed once the derived classes call their Consume() methods.
You could make Consume none virtual and within it you called another protected virtual (or abstract method) that can contain code that be change by sub classes. Consumers of your class can only call the public Consume method but this will intern call the sub class implementation specific code
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public void Consume()
{
_consumed = true;
InternalConsumerBehaviour();
}
protected virtual void InternalConsumeBehaviour()
{
//default do nothing could potentially mark this method abstract rather than virtual its up to you
}
}
public class HealthyConsumable: AbstractConsumable
{
protected override void InternalConsumeBehaviour()
{
// Do something healthy and ...
}
}
public class PoisonousConsumable: AbstractConsumable
{
protected override void InternalConsumeBehaviour()
{
// Do something poisonous and ...
}
}
If I get what you're asking right you could do something like this:
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public abstract void ConsumeEffects();
public void Consume()
{
this.ConsumeEffects();
_consumed = true;
}
}
public class HealthyConsumable: AbstractConsumable
{
public override void ConsumeEffects()
{
// Do something healthy and ...
// Consume will get called in the base
}
}
public class PoisonousConsumable: AbstractConsumable
{
public override void ConsumeEffects()
{
// Do something poisonous and ...
// Consume will get called in the base
}
}
Is the setter injection supported in the Xamarin.forms?
I have a service injected in the bootstrapper like this
Container.RegisterType<ICommonService, CommonService>();
And inside a viewmodel, I want to have an instance injected to a property like this
[Dependency]
public ICommonService CommonService { get; set; }
But in the runtime, the property CommonService is always null.
The attribute I used is the Microsoft.Practices.Unity.DependencyAttribute, not Xamarin.Forms.DependencyAttribute
If I inject inside the constructor, it works
public LandingPageViewModel(INavigationService navigationService, ICommonService commonService)
Edited: added code snippet
public class Bootstrapper : UnityBootstrapper
{
protected override Page CreateMainPage()
{
try
{
return Container.Resolve<Views.LandingPage>();
}
catch (Exception exception)
{
//TODO: intent to get exception info
throw;
}
}
protected override void RegisterTypes()
{
DependencyResolver.Instance.Initialize(Container);
this.RegisterViews();
this.RegisterServices();
this.RegisterSingleton();
}
private void RegisterViews()
{
Container.RegisterTypeForNavigation<LandingPage>();
Container.RegisterTypeForNavigation<Page1>();
}
private void RegisterServices()
{
Container.RegisterType<ICommonService, CommonService>();
}
private void RegisterSingleton()
{
}
}
public partial class App : Application
{
public App()
{
InitializeComponent();
var bootstrapper = new Bootstrapper();
bootstrapper.Run(this);
}
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
}
}
Hmm they removed the DependencyAttribute injection feature since Prism 7.0, I think we should register it manually. (your code snippet should work)
Look: https://brianlagunas.com/whats-new-in-prism-for-xamarin-forms-7-0/
I need a programming pattern but I couldn't figure out what it will be. I am not even sure if what I want is possible or not. Lets say I have a Class A and 10 class inherited from A. What I want is call the same method Method Print() implemented differently on each inherited class, but all of them need to repeat a same method of Class A.
Class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
}
Class A_1 : A
{
public override void Print()
{
StartingProcedure();
/// class specific print operation
EndingProcedure();
}
}
Class A_2 : A
{
public override void Print()
{
StartingProcedure();
/// class specific print operation
EndingProcedure();
}
}
As you see I dont want to keep writing StartingProcedure(); on each overridden Print method. I want to automate that procedure, when I inherit a new class from A I don't want to mind the Starting and Ending procedures, i want to just write the class specific print operation. Is there any pattern that will provide me this kind of a class behaviour?
BTW I work with C#
Class A
{
public void Print()
{
StartingProcedure();
SpecificPrint();
EndingProcedure();
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
protected virtual SpecificPrint() // could possibly be abstract
{
}
}
Class A_1 : A
{
public override void SpecificPrint()
{
/// class specific print operation
}
}
Class A_2 : A
{
public override void SpecificPrint()
{
/// class specific print operation
}
}
The pattern you are looking for in this case is the Template Pattern by Gang of Four (GoF).
Class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
Print();
}
protected void EndingProcedure()
{
/// something
}
}
usually you'll add another method called the Template Method:
/// Template Method
protected void Run()
{
StartingProcedure();
Print();
EndingProcedure();
}
class A_1 : A
{
public override void Print()
{
/// class specific print operation
}
public A_1()
{
base.Run();
}
}
As an alternative to Rik's answer, if you can change the class hierarchy, and you really don't want to call the base methods in the derived methods, you can use composition instead of inheritance to accomplish this. By using the decorator pattern, you can specify a print method that wraps the derived functions.
class PrintDecorator : A
{
private A wrappedA;
public PrintDecorator(A a)
{
wrappedA = a;
}
public virtual void Print()
{
//wrap the derived logic with the pre- and post- processing
StartingProcedure();
wrappedA.Print();
EndingProcedure();
}
}
class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
}
class A_1 : A
{
public override void Print()
{
/// class specific print operation
}
}
class A_2 : A
{
public override void Print()
{
/// class specific print operation
}
}
Example usage:
A dec = new PrintDecorator(new A_1());
dec.Print();
I have two projects: ClientProj and ServerProj, which both share a SharedLibrary containing the basics of my game.
Inside this library I have the class GameObject which is the base class from which many other game items inherit.
Inside GameObject is a SetPosition() method.
Here's my problem: When I run SetPosition() on the client, I wish to add some additional code / override the method completely. The code I wish to add however relates to classes that are only present in the ClientProj namespace, which the SharedLibrary knows nothing about.
Is there any clean way to override or extend the library methods?
Updated: Note that the instances of GameObject and all things that inherit it are defined, contained and handled all within the SharedLibrary namespace. For the most part the ClientProj and ServerProj only handle networking, users and input/output.
You can use the Proxy pattern and have the game objects inherit from the proxy class instead of the real class:
SharedLibrary:
public class GameObject
{
public virtual void SetPosition() { ... }
}
public class DelegatingGameObject : GameObject
{
public GameObject Inner;
public override void SetPosition() { Inner.SetPosition(); }
}
public class Tree : DelegatingGameObject
{
}
ClientLibrary:
class ClientGameObject : GameObject
{
public override void SetPosition()
{
if (isMonday) base.SetPosition();
}
}
var tree = new Tree { Inner = new ClientGameObject() };
tree.SetPosition();
SharedLibrary:
public class GameObject
{
public virtual void SetPosition() { Console.WriteLine("GameObject.SetPosition"); }
public static event Func<GameObject> Factory;
internal static GameObject CreateBase() { var factory = Factory; return (factory != null) ? factory() : new GameObject(); }
}
internal class GameObjectBase : GameObject
{
private readonly GameObject baseGameObject;
protected GameObjectBase() { baseGameObject = GameObject.CreateBase(); }
public override void SetPosition() { baseGameObject.SetPosition(); }
}
internal class Tree : GameObjectBase
{
public override void SetPosition()
{
Console.WriteLine("Tree.SetPosition");
base.SetPosition();
}
}
public static class Game
{
public static void Start()
{
new Tree().SetPosition();
}
}
ClientLibrary:
internal class ClientGameObject : GameObject
{
public override void SetPosition()
{
Console.WriteLine("ClientGameObject.SetPosition Before");
base.SetPosition();
Console.WriteLine("ClientGameObject.SetPosition After");
}
}
internal static class Program
{
static void Main(string[] args)
{
GameObject.Factory += () => new ClientGameObject();
Game.Start();
}
}
Make SetPosition method virtual and use override keyword to override its behaviour in ClientProj.
You can do it virtual in base class, override in derived, and in overriden method call your methods and after base class method.
A psudocode can look like this:
public class GameObject
{
public virtual void SetPosition()
{
//do something here
}
}
public class Derived: GameObject
{
public override void SetPosition()
{
// do something specific to Derived
base.SetPosition(); // CALL BASE CLASS METHOD AFTER
}
}