Xamarin Android Global Session Variables - Error No constructor found (System.IntPtr, Android.Runtime.JniHandleOwnership) - variables

I'm working with Xamarin Android on Xamarin Studio 5.5.3, Im trying to create a global session state using the sample on this link:
Login Session - Activities
My code is pretty similar as the one on the link.
My Application Class:
namespace MyApp.Library.Droid
{
public class SessionApplication : Application
{
private static int _userID;
private static string _email;
private static string _firstName;
private static string _lastName;
public override void OnCreate() {
base.OnCreate();
_userID=0;
_email=null;
_firstName = null;
_lastName = null;
}
public static int UserID
{
get { retu`enter code here`rn _userID; }
set { _userID=value; }
}
public static string Email
{
get { return _email; }
set { _email=value; }
}
public static string FirstName
{
get { return _firstName; }
set { _firstName=value; }
}
public static string LastName
{
get { return _lastName; }
set { _lastName=value; }
}
}
}
My Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="myapp.ui.droid">
<uses-sdk />
<application android:label="myapp.ui.droid" android:name="myapp.library.droid.SessionApplication">
</application>
</manifest>
my code compiles but then it runs throws this exception.
[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] System.NotSupportedException: Unable to activate instance of type MyApp.Library.Droid.SessionApplication from native handle a2600019 --->
System.MissingMethodException: No constructor found for MyApp.Library.Droid.SessionApplication::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership) --->
Java.Interop.JavaLocationException: Exception of type 'Java.Interop.JavaLocationException' was thrown.
I'll appreciate your help.

Congratulations, you've found one of the few cases where you need to provide an explicit constructor that handles when a Java object is exposed to managed (Mono) code.
From the docs:
There are two scenarios in which the (IntPtr, JniHandleOwnership) constructor must be manually provided on a Managed Callable Wrapper subclass:
1 - Android.App.Application is subclassed. Application is special; the default Applicaton constructor will never be invoked, and the (IntPtr, JniHandleOwnership) constructor must instead be provided .
Virtual method invocation from a base class constructor.
To fix this, provide a constructor with the (IntPtr handle, JniHandleOwnership transfer) signature.
[Application]
public class SessionApplication : Application
{
public SessionApplication(IntPtr javaReference, JniHandleOwnership transfer)
:base(javaReference, transfer)
{
}
// ...
}
Some background reading:
Android Callable Wrappers
Xamarin.Android Architecture (See Java Activation specifically).

Related

ASP.NET MVC Custom configuration GetSection returns null

I'm working on an inherited ASP.NET MVC 4 project using .net framework 4.5.
We've added a new configuration section files and relevant class files and from what we can tell (docs.Microsoft and other online guides) it's set up correctly.
The Problem
ConfigurationManager.GetSection() returns null.
According to the docs this returns null if the section doesn't exist. Troubleshooting this has been troublesome.
The Code
The website is an ASP.NET Web Application. Properties window sets assembly name to Client.Project.UI.Base (which is the DLL in the published bin). This is the assembly name used for the config types FQN and assembly in web.config.
NB: the config section SupportCaseConfiguration was originally in a separate file and the SupportTickets section just specified the configSource. This has been moved into the web.config to reduce the number of potential issues while troubleshooting.
web.config:
<configSections>
<!-- define type for new section -->
<section name="SupportTickets" type="Client.Project.UI.Base.Infrastructure.Services.SupportCaseConfigurationSection, Client.Project.UI.Base"/>
</configSections>
<!-- new config section -->
<SupportTickets>
<SupportCaseConfiguration>
<caseTypes>
<add name="tenant.TestCase" label="Test Case" recipient="email_here" ccList="" bccList="" />
</caseTypes>
</SupportCaseConfiguration>
</SupportTickets>
SupportCaseConfiguration.cs:
namespace Client.Project.UI.Base.Infrastructure.Services
{
using System.Configuration;
//Extend the ConfigurationSection class.
public class SupportCaseConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("caseTypes", IsDefaultCollection = true)]
public CaseTypeElementCollection CaseTypes
{
get { return (CaseTypeElementCollection)this["caseTypes"]; }
}
}
//Extend the ConfigurationElementCollection class.
[ConfigurationCollection(typeof(CaseTypeElement))]
public class CaseTypeElementCollection : ConfigurationElementCollection
{
public CaseTypeElement this[int index]
{
get { return (CaseTypeElement)BaseGet(index); }
set
{
if (BaseGet(index) != null)
BaseRemoveAt(index);
BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new CaseTypeElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((CaseTypeElement)element).Name;
}
}
//Extend the ConfigurationElement class. This class represents a single element in the collection.
public class CaseTypeElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("label", IsRequired = true)]
public string Label
{
get { return (string)this["label"]; }
set { this["label"] = value; }
}
[ConfigurationProperty("recipient", IsRequired = true)]
public string Recipient
{
get { return (string)this["recipient"]; }
set { this["recipient"] = value; }
}
[ConfigurationProperty("ccList", IsRequired = true)]
public string CcList
{
get { return (string)this["ccList"]; }
set { this["ccList"] = value; }
}
[ConfigurationProperty("bccList", IsRequired = true)]
public string BccList
{
get { return (string)this["bccList"]; }
set { this["bccList"] = value; }
}
}
}
Elsewhere, getting new config data:
SupportCaseConfigurationSection supportTicketsConfigurationSection = ConfigurationManager.GetSection("SupportCaseConfiguration") as SupportCaseConfigurationSection;
The site is being published locally, I can attach a debugger to ensure the latest versions of files are being used. I can see the config section in the published web.config.
I've been looking at this I can no longer see if anything is amiss. It all looks fine for me...
Any ideas, troubleshooting tips or even pointing out I'm being a muppet would be useful.
Cheers.
I can only assume the issue was something to do with the config classes in the site assembly.
Even after trying online examples, copypasting into the project, not even they worked.
As soon as I put the configuration section/element classes in a separate project (moved out of the website project) it started working.

How to access I18n Bean from inside a task

I am trying to create a plugin with a task, but I have trouble getting access to an instance of I18bean for retrieving internationalized message. Does anyone has a hint on how to do it ?
Found it. You need to add a constructor with a I18nBeanFactory parameter and use this one for retrieving an I18nBean
public class CreateFileTask implements TaskType {
public I18nBeanFactory i18nBeanFactory;
public CreateFileTask(I18nBeanFactory i18nBeanFactory) {
this.i18nBeanFactory=i18nBeanFactory;
}
#NotNull
#Override
public TaskResult execute(TaskContext taskContext) throws TaskException {
I18nBean i18nBean = i18nBeanFactory.getI18nBean();
i18Bean.getText(...);
}
}

Is it possible to inject dependencies into an NServiceBus Message Mutator?

I'd like to inject a dependency into an NServiceBus Message Mutator... since the lifetime of the Mutators is controlled by NServiceBus (and NSB wants a paramaterless constructor), constructor injection won't work...
any ideas?
UPDATE: Here is the code:
public class AddTransactionInformationToOutgoingHeaders :
IMutateOutgoingTransportMessages,
INeedInitialization
{
private readonly IProvideTransactionInformation transactionInformationProvider;
public void Init()
{
Configure.Instance.Configurer.ConfigureComponent<AddTransactionInformationToOutgoingHeaders>(DependencyLifecycle.InstancePerCall);
}
public AddTransactionInformationToOutgoingHeaders()
{
}
public AddTransactionInformationToOutgoingHeaders(IProvideTransactionInformation transactionInformationProvider)
{
this.transactionInformationProvider = transactionInformationProvider;
}
public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
{
...
}
}
}
If I take away the empty ctor, I get this error message thrown from my ConfigureBus() call in Global.asax:
"No parameterless constructor defined for this object."
To get around this, I just kept one empty constructor for NServiceBus and then created a overloaded constructor that took my dependency that is managed by Unity.
It works.
Didn't know that mutators could work like that. It was my first time trying to inject a dependency into one.
UPDATE:
I got around this by using property injection on the mutator instead:
public class AddTransactionInformationToOutgoingHeaders : IMutateOutgoingTransportMessages, INeedInitialization
{
public IProvideTransactionInformation TransactionInformationProvider { get; set; }
public void Init()
{
Configure.Instance.Configurer.ConfigureComponent<AddTransactionInformationToOutgoingHeaders>(DependencyLifecycle.InstancePerCall);
}
public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
{
...
}
}
Worked perfectly.
Pretty sure both constructor and property injection should work. What is the exception?

Can't get Ninject.Extensions.Interception working

I've been trying for ages to figure this our. when i try to bind my class with an interceptor i'm getting the following exception on the line
Kernel.Bind<MyClass>().ToSelf().Intercept().With<ILoggerAspect>();
Error loading Ninject component IAdviceFactory. No such component has been registered in the kernel's component container
I've tried with and without LoadExtensions, With about with using a Module to set up my bindings and my last attempt looks like this
internal class AppConfiguration
{
internal AppConfiguration( )
{
var settings = new NinjectSettings() { LoadExtensions = false };
Kernel = new StandardKernel(settings);
Load();
}
internal StandardKernel Kernel { get; set; }
public static AppConfiguration Instance
{
get { return _instance ?? (_instance = new AppConfiguration()); }
}
private static AppConfiguration _instance;
private void Load()
{
Kernel.Bind<ILoggerAspect>().To<Log4NetAspect>().InSingletonScope();
Kernel.Bind<MyClass>().ToSelf().Intercept().With<ILoggerAspect>();
}
internal static StandardKernel Resolver()
{
return Instance.Kernel;
}
}
My Logger Attribute looks like this
public class LogAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Context.Kernel.Get<ILoggerAspect>();
}
}
And my interceptor like this
public class Log4NetAspect : SimpleInterceptor, ILoggerAspect
{
protected override void BeforeInvoke(IInvocation invocation)
{
Debug.WriteLine("Running " + invocation.ReturnValue);
base.BeforeInvoke(invocation);
}
public new void Intercept(IInvocation invocation)
{
try
{
base.Intercept(invocation);
}
catch (Exception e)
{
Debug.WriteLine("Exception: " + e.Message);
}
}
protected override void AfterInvoke(IInvocation invocation)
{
Debug.WriteLine("After Method");
base.AfterInvoke(invocation);
}
}
Most likely you didn't deploy Ninject.Extensions.Interception.DynamicProxy or Ninject.Extensions.Interception.Linfu alongside your application [and Ninject.Extensions.Interception]. You have to pick exactly one of them.
With the code as you have it right now (LoadExtensions=false) it will fail to pick up the specific interception library - you should remove that and the normal extensions loading should wire the extension into the Kernel on creation for the interception bits to pick it up.
In addition to Remo Gloor's answer which pointed me toward adding the nuget package for Ninject.Extensions.Interception.DynamicProxy, I kept getting the same exception as the OP, until I manually loaded a DynamicProxyModule - the FuncModule is manually loaded as well, to work around a similar error involving the factory extension:
_kernel = new StandardKernel(
new NinjectSettings{LoadExtensions = true},
new FuncModule(),
new DynamicProxyModule()); // <~ this is what fixed it

Castle Windsor Fluent API: Define Array with Single item as Dependency

Given this XML configuration (which works)
<component type="X.Y.Z.ActivityService, X.Y.Z.Services" id="X.Y.Z.ActivityService" lifestyle="transient">
<parameters>
<Listeners>
<array>
<item>${DefaultActivityListener}</item>
</array>
</Listeners>
</parameters>
</component>
<component type="X.Y.Z.DefaultActivityListener, X.Y.Z.Services" id="DefaultActivityListener" lifestyle="transient" />
I have converted to use the fluent API as below (which doesn't work):
Container.Register(
Component.For<X.Y.Z.ActivityService>()
.ServiceOverrides(
ServiceOverride.ForKey("Listeners").Eq(typeof(X.Y.Z.DefaultActivityListener).Name))
.LifeStyle.Transient
);
Container.Register(
Component.For<X.Y.Z.DefaultActivityListener>()
.Named("DefaultActivityListener")
.LifeStyle.Transient
);
When I now attempt to resolve an instance of X.Y.Z.ActivityService Windsor throws a NotImplementedException in Castle.MicroKernel.SubSystems.Conversion.ArrayConverter.PerformConversion(String, Type).
The implementation of the PerformConversion method is:
public override object PerformConversion(String value, Type targetType)
{
throw new NotImplementedException();
}
I should add that if I remove the ServiceOverrides call, all behaves as expected. So there is specifically something wrong in the way I am wiring up the Listeners parameter. Listeners by the way is a property as opposed to a constructor parameter.
Seeing as the XML config works as expected how do I best use the fluent API (short of implementing the PerformConversion method) in order to achieve the same result?
I am using Release 2.0.
EDIT
I will extend the question to how would you achieve this configuration in code, with or without use of the fluent API.
UPDATE
It appears the problem occurs if you attempt to assign a single element to an array property. Unit tests provided below to illustrate issue.
namespace Components
{
public class A
{
public I[] I { get; set; }
}
public interface I
{
string Name { get; }
}
public class B : I
{
public string Name { get { return "B"; } }
}
public class C : I
{
public string Name { get { return "C"; } }
}
}
[TestMethod]
public void ArrayPropertyTestApi()
{
//PASSES
using (Castle.Windsor.WindsorContainer container = new Castle.Windsor.WindsorContainer())
{
container.Register(Component.For<Components.A>().ServiceOverrides(ServiceOverride.ForKey("I").Eq(typeof(Components.B).FullName, typeof(Components.C).FullName)));
container.Register(Component.For<Components.B>());
container.Register(Component.For<Components.C>());
Components.A svc = container.Resolve<Components.A>();
Assert.IsTrue(svc.I.Length == 2);
Assert.IsTrue(svc.I[0].Name == "B");
Assert.IsTrue(svc.I[1].Name == "C");
}
}
[TestMethod]
public void ArrayPropertyTestApi2()
{
//FAILS
using (Castle.Windsor.WindsorContainer container = new Castle.Windsor.WindsorContainer())
{
container.Register(Component.For<Components.A>().ServiceOverrides(ServiceOverride.ForKey("I").Eq(typeof(Components.B).FullName)));
container.Register(Component.For<Components.B>());
container.Register(Component.For<Components.C>());
Components.A svc = container.Resolve<Components.A>(); //Throws NotImplementedException
Assert.IsTrue(svc.I.Length == 1);
Assert.IsTrue(svc.I[0].Name == "B");
}
}
Question still stands.
Thanks.
[TestFixture]
public class WindsorTests {
[Test]
public void ArrayConfig() {
var container = new WindsorContainer();
container.Register(Component.For<Listener>().Named("listener"));
container.Register(Component.For<ActivityService>()
.ServiceOverrides(ServiceOverride.ForKey("listeners").Eq(new[] {"listener"})));
var service = container.Resolve<ActivityService>();
Assert.AreEqual(1, service.Listeners.Length);
}
}
public class Listener {}
public class ActivityService {
public Listener[] Listeners { get; set; }
}
The key part here is the new[] {"listener"}. The MicroKernel needs to know that the parameter listeners is an array, if you pass just "listener" it assumes that the parameter is scalar and throws because it can't convert a scalar to an array.