unable to chain up to base constructor requiring arguments - oop

public class Font : SDLTTF.Font {
public Font (string _filename, int _size) {
}
public void draw () {
}
}
That's my code. When I try to build it, I get:
Font.vala:4.5-4.15: error: unable to chain up to base constructor requiring arguments
public Font (string _filename, int _size) {
^^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)
I thought I needed to override the constructor, so I tried to public override it, but now I get:
Font.vala:4.5-4.24: error: abstract, virtual, and override modifiers are not applicable to creation methods
public override Font (string _filename, int _size) {
^^^^^^^^^^^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)
Any ideas on how to fix this? I'm trying to inherit the SDLTTF.Font class.

Have you tried putting
base(_filename, _size);
in your constructor?
EDIT:
This worked for me. Note however that SDLTTF.Font is defined in the vapi as a compact class, meaning that when you derive it, you're only allowed to define new functions for your subclass, but no instance data (member variables, etc.). If you require this, I'd recommend you go with apmasell's suggestion and create a wrapper class deriving from (G)Object.

SDLTTF is not managed by GObject, so Vala cannot create a derived class. Vala can only create derived classes if they make use of GObject, as is typical in GLib, GTK+, Pango, ATK, and many GNOME libraries.
Depending on what you want to do, you could create a new class that contains an instance of SDLTFF.Font and proxy the appropriate requests.

Related

Setting value of inherited trivial property in the constructor triggers Code Analysis Warning CA2214

I define an interface containing a trivial/simple property and an implementing class that sets the property in its constructor:
interface class IMyInterface
{
public:
property System::String^ MyName;
};
ref class MyImplementingClass : public IMyInterface
{
public:
virtual property System::String^ MyName;
MyImplementingClass()
{
MyName = "Test Name";
}
};
This doesn't seem too contentious, but when I run Code Analysis in Visual Studio 2019 using the default 'Microsoft Mixed (C++/CLR) Recommended Rules' ruleset it triggers warning CA2214:
warning CA2214: Microsoft.Usage : 'MyImplementingClass::MyImplementingClass(void)' contains a call chain that results in a call to a virtual method defined by the class. Review the following call stack for unintended consequences:
warning CA2214: MyImplementingClass..ctor()
warning CA2214: MyImplementingClass.set_MyName(String):Void
So I think it's complaining because setting this property involves calling the automatically implemented method set_MyName() and since that method is virtual it is considered a violation to call it from a constructor.
Does that mean this whole pattern is invalid?
What is the correct way to set the value of an inherited property at construction time?

When I subclass a class using ByteBuddy in certain situations I get IllegalAccessErrors. Why?

(I am a new ByteBuddy user. I'm using ByteBuddy version 1.10.8 and JDK 11 without the module path or any other part of the module system.)
I have a nested class declared like this:
public static class Frob {
protected Frob() {
super();
}
public String sayHello() {
return "Hello!";
}
}
(Its containing class is foo.bar.TestExplorations.)
When I create a dynamic subclass of Frob named foo.bar.Crap like the following, everything works OK as I would expect:
final String className = "foo.bar.Crap";
final DynamicType.Unloaded<?> dynamicTypeUnloaded = new ByteBuddy()
.subclass(Frob.class)
.name(className)
.make();
final Class<?> mySubclass = dynamicTypeUnloaded
.load(this.getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertNotNull(mySubclass);
assertEquals(className, mySubclass.getName());
final Object frobSubclass = mySubclass.newInstance();
assertTrue(frobSubclass instanceof Frob);
But if I change Frob's constructor so that it is package private, I get the following error from the final assertion:
java.lang.IllegalAccessError: class foo.bar.Crap tried to access method 'void foo.bar.TestExplorations$Frob.<init>()' (foo.bar.Crap is in unnamed module of loader net.bytebuddy.dynamic.loading.ByteArrayClassLoader #5e3d57c7; foo.bar.TestExplorations$Frob is in unnamed module of loader 'app')
For some reason, Crap's constructor cannot call super(), even though Crap and Frob are in the same package, and Frob() is defined as package-private.
I have a sense the JDK module system is to blame here, even though I am deliberately (very, very deliberately) not using it. I know the module system does not like split packages, which is what it looks like to me is going on here. Is there a constructor strategy or other mechanism to work around this problem?
In Java, a package is only equal to another package if it has the same name and is loaded by the same class loader (the same as it is with classes). If you are using the WRAPPER strategy, you cannot access package-private members of any super class. Byte Buddy does not forbid the generation as it would be legal to do in javac but you would need to use the INJECTION strategy to do what you want to make sure that classes are loaded by the same class loader. Mind that it uses internal API, therefore, from Java 9, you'd rather use a ForLookup class loading strategy.

Changing IoC provider on an Caliburn Micro WPF Application

I've an existing WPF application based on caliburn micro MVVM pattern which was using Ideablade/cocktail for accessing to database. Now I've switched to servicestack and I was keeping on cocktail just for the composition pattern. Since I've noticed it takes quite a bit long to start the application I've done some test and Ninject performs better.
I find extremly usefull the MEF approach of defining the Export/ImportingConstrucor approach but and I was wondering how I can have it with Ninject... is it possible?
In my current implementation I've something as
[Export(typeof(IMyInterface))]
[Export(typeof(MyFirstViewModel))]
public class MyFirstViewModel:IMyInterface
{
[ImportingConstructor]
public MyFirstViewModel(IEventAggregator eventAggregator)ù
{
}
}
I've seend that in ninject I've to define something as
mKernel.Bind<MyFirstViewModel>().To<MyFirstViewModel>();
mKernel.Bind<MyFirstViewModel>().To<MyFirstViewModel>();
Can it be automatic?
Can I also define a funct to resolve when not found?
Thanks
StackTrace :
at Caliburn.Micro.IoC.<.cctor>b__0(Type service, String key) in c:\Users\Rob\Documents \CodePlex\caliburnmicro\src\Caliburn.Micro.Silverlight\IoC.cs:line 13
at Caliburn.Micro.IoC.Get[T](String key) in c:\Users\Rob\Documents\CodePlex\caliburnmicro\src\Caliburn.Micro.Silverlight\IoC.cs:line 32
at myApp.Modules.Core.Framework.ViewModels.myAppScreenBase`1..ctor() in c:\Projects\myApp\branches\myApp-branch-20140526\myApp\Core\Framework\ViewModels\myAppScreenBase.cs:line 44
at myApp.Modules.Core.Framework.ViewModels.myAppSimpleScreen`1..ctor() in c:\Projects\myApp\branches\myApp-branch-20140526\myApp\Core\Framework\ViewModels\myAppSimpleScreen.cs:line 8
at myApp.Modules.AdE.ViewModels.CMATCLIDDelegheViewModel..ctor(IAdERepository repository, IDialogManager dialogManager, ICommonRepository commonRepository) in c:\Projects\myApp\branches\myApp-branch-20140526\myApp\Modules.AdE\ViewModels\CMATCLIDDelegheViewModel.cs:line 56
at DynamicInjector1033b54d439c44dbaa064db1c7e82f18(Object[] )
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
RepositoryExport :
public class RepositoryBindingGenerator : IBindingGenerator
{
public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
{
foreach (var attribute in type.GetCustomAttributes(typeof(RepositoryAttribute), false)
.OfType<RepositoryAttribute>())
{
yield return bindingRoot
.Bind(attribute.ContractType ?? type)
.To(type).InSingletonScope();
}
}
}
but I got this compile error
Error 19 Cannot implicitly convert type 'Ninject.Syntax.IBindingNamedWithOrOnSyntax' to 'Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax'. An explicit conversion exists (are you missing a cast?)
Depending on the configuration of ninject (by default its enabled) you don't need to bind a type to itself, ninject will resolve it automatically. So mKernel.Bind<MyFirstViewModel>().To<MyFirstViewModel>(); is superfluous. Remark: Creating the binding anyway also works.
However, if you want to bind Bar to IFoo or Foo to IFoo you need to bind it.
With it you can tell ninject to look for all types with an [Export] attribute and bind these.
Here comes the ninject conventions extension to the rescue. Get the ninject.extensions.conventions nuget package.
Then create a convention binding:
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses()
.WithAttribute<ExportAttribute>()
.BindWith<ExportBindingGenerator>());
public class ExportBindingGenerator : IBindingGenerator
{
public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
{
foreach (var attribute in type.GetCustomAttributes<ExportAttribute>())
{
yield return bindingRoot
.Bind(attribute.ContractType)
.To(type);
}
}
}
Things get a bit more complicated when you need to also use the [ImportingConstructor] attribute to tell ninject which constructor to use. But i would suppose that you don't need it, since Ninject's auto-constructor-selection. What you can do however is replace all [ImportingConstructor] attributes with Ninject's [Inject] attribute which does exactly the same.
Notes:
You may need to use another method than .FromThisAssembly() to specify all the assemblies which contain the implementation types.
If the implementation types are not public, you need to add IncludeNonePublicTypes() to the convention.

Problems about java syntax [duplicate]

This question already has answers here:
Can a java file have more than one class?
(18 answers)
Closed 8 years ago.
Here's the code :
public class EmployeeTest
{
public static void main(String args[]){
//System.out.println("hello world");
Employee aEmployee = new Employee("David",1000);
System.out.println(aEmployee.getName() + aEmployee.getSalary());
}
}
class Employee // **why can't I put a "public" here**
{
// Constructor
public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
// Methods
public String getName()
{
return this.name;
}
public double getSalary()
{
return this.salary;
}
// instance field
private String name;
private double salary;
}
My question is : in the second class definition's first line, why can't I put a "public" to define it ?
What's the exactly meaning of "public" when using it defines a class ?
This is language feature. There must be only one top-level public class per .java file and public class name must match the source java file name.
Basically, non-public types are not accessible outside the package so if you wish to allow type to be used anywhere then make it public.
Never create a type in default package. (Always use package)
Employee.java
package com.abc.model;
public class Employee{..}
EmployeeTest.java
package com.abc.test;
public class EmployeeTest{ ... }
Because a Java source file can have at most one top-level public class or interface, and the name of the source file must be the same as the name of that class or interface.
That's a rule that the Java compiler of Oracle's JDK imposes.
In Java, there can only be a single public top level class per source file and it needs to be named the same as the file.
This is useful for the compiler when it needs to locate a class definition from outside the package, since it knows the type name, it knows which class file to find the class in. For example. since a jar file is in essence a zip file with class files, this prevents the compiler from having to unzip the entire jar to find a class definition.
The Java language specification §7.6 specifies this as an optional restriction;
If and only if packages are stored in a file system (§7.2), the host
system may choose to enforce the restriction that it is a compile-time
error if a type is not found in a file under a name composed of the
type name plus an extension (such as .java or .jav) if either of the
following is true:
The type is referred to by code in other compilation units of the
package in which the type is declared.
The type is declared public (and therefore is potentially accessible
from code in other packages).
you can define a public class inside a public class which is legal.
public class EmployeeTest
{
public class Employee {
}
}

Property chaining in RhinoMocks

I have a class TxRx with a property called Common. Common then has a property called LastMod. I want to write a RhinoMock expectation to show that LastMod has been set with something. So I tried:
var txRx = MockRepository.GenerateMock<TxRx>();
var common = MockRepository.GenerateMock<Common>();
txRx.Expect(t => t.Common).Return(common);
txRx.Expect(t => t.Common.LastMod).SetPropertyAndIgnoreArgument();
But I get the following exception:
System.InvalidOperationException: Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.RhinoMocksExtensions.Expect[T,R](T mock, Function`2 action)
at ...
I presume this means Common needs to be virtual, but as it is a property on a LinqToSql generated class I can't make it virtual (other than hacking the autogen code which is not really an option).
Is there any way around this?
One possibility is to wrap TxRx in a mockable class (i.e. one that has overridable methods and properties which you wish to mock out or implements an interface which defines the properties or methods that you're interested in) and then pass around the wrapper rather than the LinqToSQL class itself.
Perhaps something like the following:
public class TxRxWrapper : ITxRxWrapper
{
private TxRx m_txrx;
public object LastMod
{
get { return m_txrx.Common.LastMod; }
}
...
}
public interface ITxRxWrapper
{
public object LastMod { get; }
...
}
Not ideal (i.e. it can get somewhat cumbersome to pass wrappers around just for mockability!) but that's the only way you can get RhinoMocks to mock properties/methods for you.
The other option is to use TypeMock instead which I believe uses a different mechanism to mock stuff out. I don't think it's free, though.
You would need to replace your second expectation with
txRx.Expect(() => common.LastMod).SetPropertyAndIgnoreArgument();
But the Common property itself needs to be virtual for this to work.