MvvmCross Plugin Loading Issue in Windows Phone 8.1 - xamarin

I develop a Custom Plugin of MvvmCross for Windows Phone 8.1 and iOS
Its loading in iOS project but giving error in Windows Phone 8.1 at the manager.EnsurePlatformAdaptionLoaded();
public class PluginLoader : IMvxPluginLoader
{
public static readonly PluginLoader Instance = new PluginLoader();
public void EnsureLoaded()
{
var manager = Mvx.Resolve<IMvxPluginManager>();
manager.EnsurePlatformAdaptionLoaded<PluginLoader>();
}
}
Error is
An exception of type 'Cirrious.CrossCore.Exceptions.MvxException'
occurred in Cirrious.CrossCore.DLL but was not handled in user code
Additional information: could not load plugin assembly for type
Confiz.MvvmCross.Plugins.Timer.PluginLoader
I am loading my Plugin in Windows Phone 8.1 using the following code
public class TimerPluginBootstrap : MvxPluginBootstrapAction<Confiz.MvvmCross.Plugins.Timer.PluginLoader>
{
}
I am Using Windows Phone 8.1 and MvvmCross 3.2.1 and Following are the more info
Confiz.MvvmCross.Plugins.Timer(Portable)
ITimer.cs
public interface ITimer
{
void Start();
void Stop();
Action CallBackMethod { get; set; }
}
PluginLoader.cs
public class PluginLoader : IMvxPluginLoader
{
public static readonly PluginLoader Instance = new PluginLoader();
public void EnsureLoaded()
{
var manager = Mvx.Resolve<IMvxPluginManager>();
manager.EnsurePlatformAdaptionLoaded<PluginLoader>();
}
}
Confiz.MvvmCross.Plugins.Timer.WindowsPhone
MvxWindowsPhoneTimer.cs
public class MvxWindowsPhoneTimer : ITimer
{
private readonly DispatcherTimer timer;
public MvxWindowsPhoneTimer(double kronosApiRecallTimeInMinutes)
{
timer = new DispatcherTimer();
Timer.Interval = TimeSpan.FromSeconds(kronosApiRecallTimeInMinutes);
Timer.Tick += Timer_Tick;
}
void Timer_Tick(object sender, object e)
{
CallBackMethod.Invoke();
}
public DispatcherTimer Timer
{
get { return timer; }
}
public void Start()
{
Timer.Start();
}
public void Stop()
{
Timer.Stop();
}
public Action CallBackMethod { get; set; }
}
Plugin.cs
public class Plugin : IMvxPlugin
{
public void Load()
{
Mvx.RegisterSingleton<ITimer>(new MvxWindowsPhoneTimer(1));
}
}

The plugin extension name for Silverlight is WindowsPhone
For Jupiter Xaml Windows Phone apps, the extension name is WindowsCommon (if shared with Win81) and WindowsPhoneStore for Store only.
So Confiz.MvvmCross.Plugins.Timer.WindowsPhone.dll is for Silverlight
And Confiz.MvvmCross.Plugins.Timer.WindowsPhoneStore.dll is for Jupiter Xaml apps

Related

In AspNet Boilerplate DotNetCore Console App that uses a custom AppService it does not perform the dependency injection

I am trying to make a console app that uses a custom AppService by adapting from the example https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/AbpEfConsoleApp/AbpEfConsoleApp/Program.cs
It works for me to call the service, but when I try to use a IRepository gives me the following error
Castle.MicroKernel.Handlers.HandlerException: 'Can't create component 'VCloud.Rtdm.CashAudit.TestManager' as it has dependencies to be satisfied.
It's as if I didn't have the IRepository registered.
Program.cs
class Program
{
static void Main(string[] args)
{
TestUserReferencedService();
}
/// <summary>
/// Prueba de USAR un servicio de aspnetzero referenciando al proyecto. Spoiler: No funciona
/// </summary>
static async void TestUserReferencedService()
{
Clock.Provider = ClockProviders.Utc;
Console.WriteLine("Starting");
//Bootstrapping ABP system
using (var bootstrapper = AbpBootstrapper.Create<VCloudConsoleApplicationModule>())
{
bootstrapper.IocManager
.IocContainer
.AddFacility<LoggingFacility>(f => f.UseAbpLog4Net().WithConfig("log4net.config"));
bootstrapper.Initialize();
//Getting a Tester object from DI and running it
using (var tester = bootstrapper.IocManager.ResolveAsDisposable<TestAppService>())
{
var x = (await tester.Object.TestCount());
} //Disposes tester and all it's dependencies
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
VCloudConsoleApplicationModule.cs
[DependsOn(
typeof(VCloudApplicationSharedModule),
typeof(VCloudConsoleCoreModule),
typeof(AbpEntityFrameworkCoreModule),
typeof(AbpDapperModule),
typeof(AbpZeroCommonModule)
)]
public class VCloudConsoleApplicationModule : AbpModule
{
public override void PreInitialize()
{
//Adding authorization providers
Configuration.Authorization.Providers.Add<AppAuthorizationProvider>();
//Adding custom AutoMapper configuration
Configuration.Modules.AbpAutoMapper().Configurators.Add(CustomDtoMapper.CreateMappings);
Configuration.BackgroundJobs.IsJobExecutionEnabled = false;
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(VCloudConsoleApplicationModule).GetAssembly());
DapperExtensions.DapperExtensions.SetMappingAssemblies(new List<Assembly>
{typeof(VCloudConsoleApplicationModule).GetAssembly()});
DapperExtensions.DapperExtensions.SetMappingAssemblies(new List<Assembly>
{
typeof(VCloud.Dapper.Mappers.DapperMapper_RtdmOrder).GetAssembly(),
typeof(VCloud.Dapper.Mappers.DapperMapper_RtdmOrderItem).GetAssembly(),
typeof(VCloud.Dapper.Mappers.DapperMapper_RtdmCompany).GetAssembly(),
typeof(VCloud.Dapper.Mappers.DapperMapper_RtdmRestaurant).GetAssembly()
});
//DapperExtensions.DapperExtensions.Configure();
//Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
}
}
TestManager.cs
public class TestManager : VCloudDomainServiceBase, ITestManager
{
private IRepository<Invoice> _repository;
public TestManager(IRepository<Invoice> repository)
{
_repository = repository;
}
public async Task<int> GetCount()
{
return await _repository.CountAsync();
}
}
Your problem is not related to Dependeny Injection, the problem may be you forget to add the entity Invoice to the DbContext of your application in EntityFramework project.
Once you add it your problem will be solved.
public class VCloudApplicationDbContext : AbpZeroDbContext<Tenant, Role, User, VCloudApplicationDbContext>, IAbpPersistedGrantDbContext
{
public DbSet<Invoice> Invoice { get; set; }
}
I hope it could help you

ShouldDelayBannerRenderingListenerImplementor Error after Xamarin AdMob SDK 118.1.1 update

After a long wait for Admob SDK Update on Xamarin to implement Adaptive Banners and new Native Ads ,after upgrade to new Nuget package Sdk 118.1.1preview ,Visual Studio open a .Java File and mention the following error :
error: ShouldDelayBannerRenderingListenerImplementor is not abstract and does not override abstract method zzb(Runnable) in ShouldDelayBannerRenderingListener.
To take advantage of the new xamarin admob sdk (118.1.1 preview) , and overcome the JAVA error :
error: ShouldDelayBannerRenderingListenerImplementor is not abstract and does not override abstract method zzb(Runnable) in ShouldDelayBannerRenderingListener.
just put the following code on the java file poped-up and build solution :
#Override
public boolean zzb(Runnable runnable) {
return false;
}
or let this c# code (FileWatcher)keep running :
static void Main(string[] args)
{
var Javacode = File.ReadAllText(#"MyJavaFile.java");
while (true)
{
try
{
var JavaFilePah = #"C:\Project\Android\apps\AppName\obj\Debug\100\android\src\mono\com\google\android\gms\ads\formats\ShouldDelayBannerRenderingListenerImplementor.java";
DateTime LastFileChang = File.GetLastWriteTime(JavaFilePah);
if (LastFileChang != LastFileChangesave)
{
if (File.Exists(JavaFilePah) && File.ReadAllText(JavaFilePah).Contains("zzb") == false)
{
File.WriteAllText(JavaFilePah, Javacode);
Console.WriteLine("ok");
}
LastFileChangesave = LastFileChang;
}
Thread.Sleep(10);
}
catch (Exception e)
{
}
}
}
change JavaFilePah with path of ur android app.
MyJavaFile content is :
package mono.com.google.android.gms.ads.formats;
public class ShouldDelayBannerRenderingListenerImplementor
extends java.lang.Object
implements
mono.android.IGCUserPeer,
com.google.android.gms.ads.formats.ShouldDelayBannerRenderingListener
{
/** #hide */
public static final String __md_methods;
static {
__md_methods =
"";
mono.android.Runtime.register ("Android.Gms.Ads.Formats.IShouldDelayBannerRenderingListenerImplementor, Xamarin.GooglePlayServices.Ads.Lite", ShouldDelayBannerRenderingListenerImplementor.class, __md_methods);
}
public ShouldDelayBannerRenderingListenerImplementor ()
{
super ();
if (getClass () == ShouldDelayBannerRenderingListenerImplementor.class)
mono.android.TypeManager.Activate ("Android.Gms.Ads.Formats.IShouldDelayBannerRenderingListenerImplementor, Xamarin.GooglePlayServices.Ads.Lite", "", this, new java.lang.Object[] { });
}
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
#Override
public boolean zzb(Runnable runnable) {
return false;
}
}

How to load PDF in Xamarin Forms

I have a Xamarin Forms app where I want to open a locally stored PDF. I don't need to load them within the app, I'm fine with shelling out to the device's default document viewer for PDFs. How can I do this?
I tried sending a WebView to the PDF, but that didn't work, I just got a blank page.
I've recently done this in my own project using a custom renderer. First implement an empty Xamarin forms view such as (I've included a bindable FilePath attribute):
public class PdfViewer : View
{
public static readonly BindableProperty FilePathProperty =
BindableProperty.Create<DocumentViewer, string>(p => p.FilePath, null);
public string FilePath
{
get
{
return (string)this.GetValue(FilePathProperty);
}
set
{
this.SetValue(FilePathProperty, value);
}
}
}
Then create an iOS Renderer that will be registered for this control. This renderer can, as it is within an iOS project, use the Quick Look Preview Controller to delegate to the built in iOS pdf viewer:
[assembly: ExportRenderer(typeof(PdfViewer), typeof(DocumentViewRenderer))]
public class DocumentViewRenderer
: ViewRenderer<PdfViewer, UIView>
{
private QLPreviewController controller;
protected override void OnElementChanged(ElementChangedEventArgs<DocumentViewer> e)
{
base.OnElementChanged(e);
this.controller = new QLPreviewController();
this.controller.DataSource = new DocumentQLPreviewControllerDataSource(e.NewElement.FilePath);
SetNativeControl(this.controller.View);
}
private class DocumentQLPreviewControllerDataSource : QLPreviewControllerDataSource
{
private string fileName;
public DocumentQLPreviewControllerDataSource(string fileName)
{
this.fileName = fileName;
}
public override int PreviewItemCount(QLPreviewController controller)
{
return 1;
}
public override QLPreviewItem GetPreviewItem(QLPreviewController controller, int index)
{
var documents = NSBundle.MainBundle.BundlePath;
var library = Path.Combine(documents, this.fileName);
NSUrl url = NSUrl.FromFilename(library);
return new QlItem(string.Empty, url);
}
private class QlItem : QLPreviewItem
{
public QlItem(string title, NSUrl uri)
{
this.ItemTitle = title;
this.ItemUrl = uri;
}
public override string ItemTitle { get; private set; }
public override NSUrl ItemUrl { get; private set; }
}
}
}
I haven't compiled and run this as I've extracted it from my larger project but in general this should work.
I had to do something and solve it using a DependencyService . You can use it to open the pdf depending on each platform
I show you an example of how to solve it on Android :
IPdfCreator.cs:
public interface IPdfCreator
{
void ShowPdfFile();
}
MainPage.cs:
private void Button_OnClicked(object sender, EventArgs e)
{
DependencyService.Get<IPdfCreator>().ShowPdfFile();
}
PdfCreatorAndroid.cs
[assembly: Dependency(typeof(PdfCreatorAndroid))]
namespace Example.Droid.DependecyServices
{
public class PdfCreatorAndroid : IPdfCreator
{
public void ShowPdfFile()
{
var fileLocation = "/sdcard/Template.pdf";
var file = new File(fileLocation);
if (!file.Exists())
return;
var intent = DisplayPdf(file);
Forms.Context.StartActivity(intent);
}
public Intent DisplayPdf(File file)
{
var intent = new Intent(Intent.ActionView);
var filepath = Uri.FromFile(file);
intent.SetDataAndType(filepath, "application/pdf");
intent.SetFlags(ActivityFlags.ClearTop);
return intent;
}
}
}
Result:
http://i.stack.imgur.com/vrwzt.png
Here there is a good project that uses MuPDF Library in xamarin . I've tested it and it works properly.
With MuPDF you can zoom out , zoom in and even write some note on PDFs.

MvvmCross plugin for setting up Alarms

I want to write a cross mobile platform app that sets up the alarm by specifying the required parameters like Date and Time. I just want to set up only one time and not repeatedly.
I was unable to find any readily available plugin in mvvmcross or in Xamarin ?
Please help
Since there is no existing plugin within MVVMCross, you may want to write your own plugin. You can find the documentation here:
https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins
Because you'd like to specify a few parameters, you'd want to see the following section:
https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#writing-a-configurable-plugin
Overall this is what you might do:
General Interface
public interface IAlarm
{
void SetupAlarm();
}
public class PluginLoader
: IMvxPluginLoader
{
public static readonly PluginLoader Instance = new PluginLoader();
public void EnsureLoaded()
{
var manager = Mvx.Resolve<IMvxPluginManager>();
manager.EnsurePlatformAdaptionLoaded<PluginLoader>();
}
}
Android Implementation
public class DroidAlarmConfiguration
: IMvxPluginConfiguration
{
public AlarmLength { get; set;}
}
public class DroidAlarm : IAlarm
{
public TimeSpan AlarmLength { get; set; }
public void SetupAlarm()
{
//ALARM IMPLEMENTATION HERE. NOTE THIS IS SOME JAVA SYNTAX!!!!
var globals = Mvx.Resolve<Cirrious.CrossCore.Droid.IMvxAndroidGlobals>();
var alarm = globals.ApplicationContext
.GetSystemService(Context.ALARM_SERVICE)
as AlarmManager;
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
alarmLength, alarmIntent);
}
}
public class Plugin
: IMvxPlugin
{
private _alarmLength = **Your Value Here**;
public void Configure(IMvxPluginConfiguration configuration)
{
if (configuration == null)
return;
var droidConfiguration = (DroidAlarmConfiguration)configuration;
_alarmLength = droidConfiguration.AlarmLength;
}
public void Load()
{
var instance = new DroidAlarm();
instance.AlarmLength = _AlarmLength;
Mvx.RegisterSingleton<IAlarm>(instance);
}
}
Setup.cs - To set the values in one core place for all android/ios/windows
protected override IMvxPluginConfiguration GetPluginConfiguration(Type plugin)
{
if (plugin == typeof(Yours.Alarm.Droid.Plugin))
{
return new Yours.Alarm.Droid.DroidAlarmConfiguration()
{
AlarmLength = **YOUR VALUE HERE**
};
}
return null;
}
You would then follow the same Droid step for iOS and Windows Phone. I hope this helps!

NavigationService throws NullReferenceException

Using MVVM Light, I'm trying to develop a rather simple WP7 application. I've run into a problem using the navigation service. I can navigate to a page, but after pressing the back button I can't navigate to the same page again. NavigationService throws a NullReferenceException.
I have implemented my navigation using Messaging from the GalaSoft.MvvmLight.Messaging namespace. All my views inherits from a customized PhoneApplicationPage base class that registrers a listener on "NavigationRequest":
public class PhoneApplicationPage : Microsoft.Phone.Controls.PhoneApplicationPage
{
public PhoneApplicationPage() : base()
{
Messenger.Default.Register<Uri>(this, "NavigationRequest", (uri) => NavigationService.Navigate(uri));
}
}
From my view models I post Uri's to this listener:
SendNavigationRequestMessage(new Uri("/View/AppSettingsView.xaml", UriKind.Relative));
Like i said, this works except when navigating after pressing the Back button.
Why is this and how can I solve it?
Is there a better way to implement navigation using MVVM Light?
I'm using MVVM Light as well. I have a class called PageConductor, which is based on what John Papa (Silverlight MVP) from Microsoft uses. Here's the PageConductor Service I use
public class PageConductor : IPageConductor
{
protected Frame RootFrame { get; set; }
public PageConductor()
{
Messenger.Default.Register<Messages.FrameMessage>(this, OnReceiveFrameMessage);
}
public void DisplayError(string origin, Exception e, string details)
{
string description = string.Format("Error occured in {0}. {1} {2}", origin, details, e.Message);
var error = new Model.Error() { Description = description, Title = "Error Occurred" };
Messenger.Default.Send(new Messages.ErrorMessage() { Error = error });
}
public void DisplayError(string origin, Exception e)
{
DisplayError(origin, e, string.Empty);
}
private void OnReceiveFrameMessage(Messages.FrameMessage msg)
{
RootFrame = msg.RootFrame;
}
private void Go(string path, string sender)
{
RootFrame.Navigate(new Uri(path, UriKind.Relative));
}
public void GoBack()
{
RootFrame.GoBack();
}
}
In my MainPage.xaml.cs constructor, I have this, which creates an instance of my ContentFrame in my PageConductor service.:
Messenger.Default.Send(new Messages.FrameMessage() { RootFrame = ContentFrame });
I then use dependency injection to instantiate an instance of my PageConductor Service into my MainPage ViewModel. Here is my MainViewModel class:
protected Services.IPageConductor PageConductor { get; set; }
public RelayCommand<string> NavigateCommand { get; set; }
public MainViewModel(Services.IPageConductor pageConductor)
{
PageConductor = pageConductor;
RegisterCommands();
}
private void RegisterCommands()
{
NavigateCommand = new RelayCommand<string>(
(source) => OnNavigate(source));
}
private void OnNavigate(string sender)
{
PageConductor.GoToView(sender, "main");
}
Notice the instance of my PageConductorService as a parameter in my MainViewModel constructor method. I pass this in via my ViewModelLocator:
private readonly TSMVVM.Services.ServiceProviderBase _sp;
public ViewModelLocator()
{
_sp = Services.ServiceProviderBase.Instance;
CreateMain(_sp);
}
#region MainPageViewModel
public static MainViewModel MainStatic
{
get
{
Services.ServiceProviderBase SP = Services.ServiceProviderBase.Instance;
if (_main == null)
{
CreateMain(SP);
}
return _main;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainViewModel Main
{
get
{
return MainStatic;
}
}
public static void ClearMain()
{
_main.Cleanup();
_main = null;
}
public static void CreateMain(Services.ServiceProviderBase SP)
{
if (_main == null)
{
_main = new MainViewModel(SP.PageConductor);
}
}
#endregion
For further reference, my Messages.FrameMessage class is simply:
internal class FrameMessage
{
public Frame RootFrame { get; set; }
}
I've had no issues with forward/back buttons.

Resources