How to add the OnShareTargetActivated() method manually in a windows 8 C# blank application? - windows-8

I have created a Windows8 blank xaml application.And now i want to make this application as a Share Target.I have followed the instructions at below link and able to make it as a Target app.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh973053
But where do i add the following method (OnShareTargetActivated) in my blank xaml application ?When i manually add this method in mainpage.xaml.cs , it shows the errors"
"Project.MainPage.OnShareTargetActivated(Windows.ApplicationModel.Activation.ShareTargetActivatedEventArgs)' is a new virtual member in sealed class "
"Project.MainPage.OnShareTargetActivated(Windows.ApplicationModel.Activation.ShareTargetActivatedEventArgs)': no suitable method found to override "
protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
// Code to handle activation goes here.
}

It goes in the class that inherits from Windows.UI.Xaml.Application. Typically App.cs.
E.g.
sealed partial class App : Application
{
public App()
{
this.InitializeComponent();
}
//...
protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
var rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), args.ShareOperation);
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
}

Related

.Net Maui Shell Navigation - Is it possible to pass a Query Parameter and Auto Populate a Page?

I need to auto populate a Page by passing a Shell Navigation Parameter to a ViewModel/Method and call a Service to return a single record from a Web Service. Essentially a drill-through page. My issue is that I need to call the data retrieveal command, "GetFieldPerformanceAsync" (note [ICommand] converts this to "GetFieldPerformanceCommand") from the "To" Page's code-behind from within OnNavigatedTo. This is required since the Shell Navigation Parameter is not set in the ViewModel until the Page is loaded. I'm currently unable to make the Command call from OnNavigatedTo and need advice on how to accomplish this.
Thanks!
Code behind the Page:
public partial class FieldPerformancePage : ContentPage
{
public FieldPerformancePage(FieldPerformanceViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
//works with parameter hard-coded in ViewModel
//viewModel.GetFieldPerformanceCommand.Execute(null);
}
FieldPerformanceViewModel viewModel;
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
//this does not work
viewModel.GetFieldPerformanceCommand.Execute(null);
}
}
ViewModel
namespace TrackMate.ViewModels;
[QueryProperty(nameof(FieldAssignedWbs), nameof(FieldAssignedWbs))]
public partial class FieldPerformanceViewModel : BaseViewModel
{
[ObservableProperty]
FieldAssignedWbs fieldAssignedWbs;
[ObservableProperty]
FieldPerformance fieldPerformance;
FieldPerformanceService fieldPerformanceService;
public FieldPerformanceViewModel(FieldPerformanceService fieldStatusService)
{
Title = "Status";
this.fieldPerformanceService = fieldStatusService;
}
[ICommand]
async Task GetFieldPerformanceAsync()
{
if (IsBusy)
return;
try
{
IsBusy = true;
int wbsId = fieldAssignedWbs.WbsId;
var fieldPerformanceList = await fieldPerformanceService.GetFieldPerformanceList(wbsId);
if (fieldPerformanceList.Count != 0)
FieldPerformance = fieldPerformanceList.First();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
await Shell.Current.DisplayAlert("Error!",
$"Undable to return records: {ex.Message}", "OK");
}
finally
{
IsBusy = false;
}
}
}
I believe I figured it out...
By adding ViewModel Binding within the OnNavigatedTo method in the "DetailsPage" Code Behind, a Command Call can be made to the Page's ViewModel to execute data retrieval method after the Shell Navigation Parameter (object in this scenario) passed from the "Main" Page has been set. Note a null is passed since the Query Parameter is sourced from the ViewModel. If you are new to .Net Maui, as I am, I recommend James Montemagno's video on .Net Maui Shell Navigation.
namespace TrackMate.Views;
public partial class FieldPerformancePage : ContentPage
{
public FieldPerformancePage(FieldPerformanceViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
FieldPerformanceViewModel viewModel = (FieldPerformanceViewModel)BindingContext;
viewModel.GetFieldPerformanceCommand.Execute(null);
base.OnNavigatedTo(args);
}
}
For me it only worked when the BindingContext assignment is before the component initialization and the method call after the base call in OnNavigatedTo
public partial class OccurrencePage : ContentPage
{
public OccurrencePage(OccurrenceViewModel model)
{
BindingContext = model;
InitializeComponent();
}
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
OccurrenceViewModel viewModel = (OccurrenceViewModel)BindingContext;
viewModel.GetFieldsCommand.Execute(null);
}
}
While overriding OnNavigatedTo works fine, there is one more simple technique to run something once your query param is set, given you do not need to run anything asynchronous inside the method: implementing partial method OnFieldAssignedWbsChanged, auto-generated for your convenience by mvvm toolkit
partial void OnFieldAssignedWbsChanged(FieldAssignedWbs value)
{
// run synchronous post query param set actions here
}
Less amount of code and less code-behind and viewModel dependencies, but works fine for non-async operations only.

Eclipse RCP 4 adds new tab/part in an IEventBroker handleEvent

In a normal command handler I can add new tab/part as this code:
#Execute
public void execute(Shell shell, EPartService partService, MApplication application,EModelService modelService) throws URISyntaxException{
MPart part = MBasicFactory.INSTANCE.createPart();
part.setLabel("New file ");
part.setCloseable(true);
part.setContributionURI("bundleclass://com.xxx.rcp.app.item_editor/com.xxx.rcp.app.item_editor.parts.ItemEditorPart");
List<MPartStack> stacks = modelService.findElements(application, "com.xxx.rcp.app.partstack.2", MPartStack.class, null);
stacks.get(0).getChildren().add(part);
partService.showPart(part, PartState.ACTIVATE);
}
Now I want to add new tab/part in one IEventBroker handleEvent.
First, I register the topic in the Activator:
#Override
public void start(BundleContext context) throws Exception {
IEclipseContext serviceContext = EclipseContextFactory.getServiceContext(context);
IEventBroker eventBroker = serviceContext.get(IEventBroker.class);
eventBroker.subscribe("MY_TOPIC", ContextInjectionFactory.make(OpenItemEditorHandler2.class, serviceContext));
}
Then, I add the tab/part in handleEvent:
public class OpenItemEditorHandler2 implements EventHandler {
// #Inject
// private IEclipseContext serviceContext;
// #Inject
// EPartService partService;
// #Inject
// MApplication application;
#Inject
IEclipseContext serviceContext;
// #Inject
// EModelService modelService;
// #Inject
// private ECommandService commandService;
//
// #Inject
// private EHandlerService handlerService;
#Override
public void handleEvent(Event event) {
MPart part = MBasicFactory.INSTANCE.createPart();
part.setLabel("New file ");
part.setCloseable(true);
part.setContributionURI("bundleclass://com.xxx.rcp.app.item_editor/com.xxx.rcp.app.item_editor.parts.ItemEditorPart");
// get the part stack and show created part
EModelService modelService = serviceContext.get(EModelService.class);
MApplication application = serviceContext.get(MApplication.class);
List<MPartStack> stacks = modelService.findElements(application, "com.xxx.rcp.app.partstack.2", MPartStack.class, null);
}
I cannot access or inject those services because of null all. Why? I have injected my object OpenItemEditorHandler2 in the Activator.
Or can you give some hints about other solutions to add new tab/part?
Thank you very much!
The context returned by EclipseContextFactory.getServiceContext only has OSGi services, it does not contain most of the normal e4 services so you can't use this to create your class. This means that the activator is not a suitable place to set up your subscribe.
You need to set up the subscribe somewhere where you have access to a proper eclipse context. An AddOn or the RCP LifeCycle might be suitable.
In an AddOn constructor you might have:
#Inject
public MyAddon(IEclipseContext context, IEventBroker eventBroker)
{
eventBroker.subscribe("MY_TOPIC", ContextInjectionFactory.make(OpenItemEditorHandler2.class, context));
}

Using Rg Plugins Popup with Xamarin Forms

I am very new to Xamarin Forms development and I need a popup dialog. I found exactly what I am looking for in https://github.com/rotorgames/Rg.Plugins.Popup, but I cannot for the life of me figure out how to use it. Could someone point me to a working example or provide some direction on use? The README.md on the site is not helping me much.
I want the the popup dialog to appear when a info button is clicked in the top navigation bar. All the popup needs is 1-2 buttons (and labels) for setting user settings.
This is for Xamarin.Forms: iOS and Android.
In simple steps:
Install the plugin in all the projects
Add the PopUp in your
Xaml
Use the methods they provide on the documentacion for Show/Hide the PopUp:
Task PushAsync(PopupPage page, bool animate = true)
Task PopAllAsync(bool animate = true)
They also provide a demo, check it:
https://github.com/rotorgames/Rg.Plugins.Popup/tree/master/src/Demo
Add a reference to the library, i.e. from nuget, to all projects.
Within your Android project, add this Rg.Plugins.Popup.Popup.Init(this, savedInstanceState); inside the MainActivity.cs OnCreate method, before Xamarin Forms Inits.
And the same for the iOS project, inside AppDelegate.cs FinishedLaunching method()
//Android
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Rg.Plugins.Popup.Popup.Init(this, savedInstanceState); /*Must add before the other Xamarin Inits*/
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
Xamarin.Forms.Forms.Init(this, savedInstanceState);
}
//iOS
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Rg.Plugins.Popup.Popup.Init(); /* place at the top*/
....
}
Add a new ContentPage (.xaml) to your Views directory.
<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations; assembly=Rg.Plugins.Popup"
x:Class="MyProjectName.Views.MyContentPageName">
<pages:PopupPage.Animation>
<animations:ScaleAnimation
PositionIn="Center"
PositionOut="Center"
ScaleIn="1.2"
ScaleOut="0.8"
DurationIn="400"
DurationOut="300"
EasingIn="SinOut"
EasingOut="SinIn"
HasBackgroundAnimation="True"/>
</pages:PopupPage.Animation>
<StackLayout HorizontalAlignment="FillAndExpand" VerticalAlignment="FillAndExpand">
<!-- place your layout content here ....fx a close popup button -->
<Button Clicked="CloseBtn_Clicked" Text="Close" />
</StackLayout>
</pages:PopupPage>
In the ContentPage (PopupPage) code behind file, add using Rg.Plugins.Popup.Services; and inherit from the following
using Rg.Plugins.Popup.Services;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyContentPageName: Rg.Plugins.Popup.Pages.PopupPage
{
public MyContentPageName()
{
InitializeComponent();
}
public void OnAnimationStarted(bool isPopAnimation)
{
// optional code here
}
public void OnAnimationFinished(bool isPopAnimation)
{
// optional code here
}
protected override bool OnBackButtonPressed()
{
// Return true if you don't want to close this popup page when a back button is pressed
return true;
}
// Invoked when background is clicked
protected override bool OnBackgroundClicked()
{
// Return false if you don't want to close this popup page when a background of the popup page is clicked
return false;
}
private async void CloseBtn_Clicked(object sender, EventArgs e)
{
await PopupNavigation.Instance.PopAsync(true);
}
}
From the .xaml.cs page, where you would like to open the popup, add this:
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Rg.Plugins.Popup.Contracts;
using Rg.Plugins.Popup.Services;
public partial class MyOtherPage : ContentPage
{
private IPopupNavigation _popup { get; set; }
private MyContentPageName _modalPage;
public MyOtherPage()
{
_popup = PopupNavigation.Instance;
_modalPage = new MyContentPageName();
}
protected override void OnAppearing()
{
base.OnAppearing();
_popup.Popped += Popup_Popped;
}
protected override void OnDisappearing()
{
base.OnDisappearing();
_popup.Popped -= Popup_Popped;
}
private async void Tapped_OpenModal(object sender, EventArgs e)
{
await _popup.PushAsync(_modalPage);
}
/// <summary> Triggered when the MyContentPageName popup is closed "PopAsync()" </summary>
private async void Popup_Popped(object sender, Rg.Plugins.Popup.Events.PopupNavigationEventArgs e)
{
/* add your logic here, if necessary */
}
}
*Note: If your modal simply displays static content, there is no need for a _popped event delegate within the OnAppearing()/OnDisappearing().

Pass data from android service to ContentPage in Xamarin Form based application

I am having one Application based on XamarinForms.
One background service I have created in Android project and that service would like to send data to ContentPage(which is in PCL) which is displayed to user.
How could I pass data to ContentPage(From xx.Droid project to PCL)?
One solution is:
To Create class in PCL with static variable(e.g. var TEMP_VAR), which will be accessed from xxx.Droid project.
Update value of that static variable(TEMP_VAR) from the service class from the xxx.Droid project.
Need to create Notifier on that static variable(TEMP_VAR)
Update the content page using MessageCenter Mechanism if require.
If there is any better solution, could you please provide me?
This can be achieved using the concept of C#
Dependency service
Event
Need to have 4 classes for such an implementation:
Interface in PCL(e.g. CurrentLocationService.cs) with event handlers defined in it.
namespace NAMESPACE
{
public interface CurrentLocationService
{
void start();
event EventHandler<PositionEventArgs> positionChanged;
}
}
Implementation of interface of PCL in xxx.Droid project (e.g. CurrentLocationService_Android.cs) using Dependency service
class CurrentLocationService_Android : CurrentLocationService
{
public static CurrentLocationService_Android mySelf;
public event EventHandler<PositionEventArgs> positionChanged;
public void start()
{
mySelf = this;
Forms.Context.StartService(new Intent(Forms.Context, typeof(MyService)));
}
public void receivedNewPosition(CustomPosition pos)
{
positionChanged(this, new PositionEventArgs(pos));
}
}
ContentPage in PCL - which will have object of implementation of interface.
Object can be obtained by
public CurrentLocationService LocationService
{
get
{
if(currentLocationService == null)
{
currentLocationService = DependencyService.Get<CurrentLocationService>();
currentLocationService.positionChanged += OnPositionChange;
}
return currentLocationService;
}
}
private void OnPositionChange(object sender, PositionEventArgs e)
{
Debug.WriteLine("Got the update in ContentPage from service ");
}
Background service in xxx.Droid project. This service will have reference of implementation of dependency service CurrentLocationService.cs
[Service]
public class MyService : Service
{
public string TAG = "MyService";
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug(TAG, TAG + " started");
doWork();
return StartCommandResult.Sticky;
}
public void doWork()
{
var t = new Thread(
() =>
{
Log.Debug(TAG, "Doing work");
Thread.Sleep(10000);
Log.Debug(TAG, "Work completed");
if(CurrentLocationService_Android.mySelf != null)
{
CustomPosition pos = new CustomPosition();
pos.update = "Finally value is updated";
CurrentLocationService_Android.mySelf.receivedNewPosition(pos);
}
StopSelf();
});
t.Start();
}
}
Note : PositionEventArgs class need to be created as per usage to pass on data between service and ContentPage.
This works for me like charm.
Hope so this would be helpful to you.

How configure LightInject in ASP.NET MVC?

I use SimpleInjector in mvc with this code
public static class SimpleInjectorInitializer
{
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
private static void InitializeContainer(Container container)
{
container.Register<IPersonRepository, PersonEntityRepository>();
}
}
but now I want to test LightInject Ioc in my mvc application but How ?
I wrote this code
[assembly: WebActivator.PostApplicationStartMethod(typeof(LightInjectInitializer), "InitializeLI")]
public static class LightInjectInitializer
{
public static void InitializeLI()
{
var container = new ServiceContainer();
InitializeContainer(container);
container.RegisterControllers(Assembly.GetExecutingAssembly());
container.EnableMvc();
}
private static void InitializeContainer(ServiceContainer container)
{
container.Register(typeof(PersonEntityRepository), typeof(IPersonRepository), new PerScopeLifetime());
}
}
but show me this error
No parameterless constructor defined for this object.
Can anyone help me for writing equivalent code that working in MVC ?
Sample Code : Download
I am the author of LightInject and would like to help you out.
This static initialize method? Where is it called from.
The reason that you get this error is probably because the initialize code did not execute.
If you would like further assistance, it would be valuable to see what you have in global.asax.cs.
This page also contains information about how to set this up.
http://www.lightinject.net/#mvc
Please change the controller registration line to:
container.RegisterControllers(typeof(MVCApplicationNamespace.Controllers.HomeController).Assembly);