C++ CLI KeyDown::raise Error error C3767 candidate function(s) not accessible - winforms

I have a scenario with three entities:
An interface with one method stub
A class that inherits from `System::Windows::Forms::NativeWindow` and implements the interface
A wrapper class that has a private member of the class type and a public property of the interface type. This class also has a `KeyDown` event member that's to be invoked/raised from the window class
These are the files I'm using:
INativeWindow.h
#pragma once
public interface class INativeWindow
{
void Nothing();
};
CLINativeWindow.h
#pragma once
ref class NWHolder;
public ref class CLINativeWindow : System::Windows::Forms::NativeWindow, INativeWindow
{
public:
NWHolder^ Parent;
virtual void Nothing() sealed;
void DoIt();
};
CLINativeWindow.cpp
#include "stdafx.h"
#include "CLINativeWindow.h"
void CLINativeWindow::Nothing()
{
Console::Write("None");
}
void CLINativeWindow::DoIt()
{
Parent->KeyDown(this, nullptr);
};
NWHolder.h
#pragma once
#include "INativeWindow.h"
#include "CLINativeWindow.h"
public ref class NWHolder
{
internal:
event System::Windows::Forms::KeyEventHandler^ KeyDown;
public:
virtual property INativeWindow^ OwnNativeWindow
{
INativeWindow^ __clrcall get() sealed;
void __clrcall set(INativeWindow^ value) sealed;
}
private:
CLINativeWindow^ nativeWindow_;
};
NWHolder.cpp
#include "stdafx.h"
#include "NWHolder.h"
INativeWindow^ NWHolder::OwnNativeWindow::get()
{
return nativeWindow_;
}
void NWHolder::OwnNativeWindow::set(INativeWindow^ value)
{
nativeWindow_ = dynamic_cast<CLINativeWindow^>(value);
}
At compile time, I get this error:
Error 1 error C3767: 'NWHolder::KeyDown::raise': candidate function(s) not accessible ..\NativeWindows\CLINativeWindow.cpp 10
Is there anything that can be done? I tried even #pragma make_public(System::Windows::Forms::KeyEventHandler) but it failed.

The 'raise' inner method of a C++/CLI event is always declared protected. Add a method on NWHolder named "FireKeyDownEvent", and give it whatever accessibility you like.

Related

testng how to dynamically set groups from Factory?

Before I setup a test class like the code below:
1. the Factory and test Dataprovider both used excel as the dataprovider.
2. In the Factory dataprovider table, it has a list of url
3. Each time, it will find one of the url in the factory dataprovider table, and run the test in each test methods..
public class Test {
WebDriver driver;
private String hostName;
private String url;
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url) {
this.hostName = hostName;
this.url = url;
}
#BeforeMethod
#Parameters("browser")
public void start(String browser) throws Exception {
driver = new FirefoxDriver();
driver.get(url);
Thread.sleep(1000);
}
#Test(priority = 10, dataProvider = "dataprovider Test A", dataProviderClass = xxx.class)
public void TestA(Variable1,
Variable2,Variable3) throws Exception {
some test here...
}
#Test(priority = 20, dataProvider = "dataprovider Test B", dataProviderClass = xxx.class)
public void TestB(Variable1,
Variable2,Variable3)
throws Exception {
some test here...
}
#AfterMethod
public void tearDown() {
driver.quit();
}
Now I want to dynamically assign different group for each test for different url. I am thinking add a variable 'flag' in the #Factory dataprovider:
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url, String flag) {
this.hostName = hostName;
this.url = url;
this.flag = flag;
}
That when flag.equals("A"), it will only run test cases in test groups={"A"}.
When flag.equals("B"), it will only run test cases in test groups ={"B"},
When flag.equals("A,B"), it will only run test cases in test groups ={"A","B"}
Is there any way I can do that?
Thank you!
TestNG groups provides "flexibility in how you partition your tests" but it isn't for conditional test sets. For that you simply use plain old Java.
You can use inheritance or composition (I recommend the latter, see Item 16: Favor composition over inheritance from Effective Java).
Either way the general idea is the same: use a Factory to create your test class instances dynamically creating the appropriate class type with the appropriate test annotations and/or methods that you want to run.
Examples:
Inheritance
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
/**
* Base test class with code for both A-tests and B-tests.
*
* Note that none of these test methods are annotated as tests so that
* subclasses may pick which ones to annotate.
*/
public static abstract class BaseTest {
protected void testA() {
// test something specific to flavor A
}
protected void testB() {
// test something specific to flavor B
}
}
// extend base but only annotate A-tests
public static class FlavorATest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
}
// extend base but only annotate B-tests
public static class FlavorBTest extends BaseTest {
#Test
#Override
public void testB() {
super.testB();
}
}
// extend base and annotate both A-tests and B-tests
public static class FlavorABTest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
#Test
#Override
public void testB() {
super.testB();
}
}
}
Composition
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
private static void testA() {
// test something specific to flavor A
}
private static void testB() {
// test something specific to flavor B
}
// only create A-test methods and delegate to shared code above
public static class FlavorATest {
#Test
public void testA() {
DemoTest.testA();
}
}
// only create B-test methods and delegate to shared code above
public static class FlavorBTest {
#Test
public void testB() {
DemoTest.testB();
}
}
// create A-test and B-test methods and delegate to shared code above
public static class FlavorABTest {
#Test
public void testA() {
DemoTest.testA();
}
#Test
public void testB() {
DemoTest.testB();
}
}
}
Your factory methods won't be as simple as you'll need to use your "flag" from your test data to switch off of and create instances of the appropriate test classes.

Java: how to "restart" a static class?

I have a static class (Foo) and a main class (Main)
See Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(Foo.i); // 0
Foo.i++;
System.out.println(Foo.i); // 1
// restart Foo here
System.out.println(Foo.i); // 1 again...I need 0
}
}
See Foo.java:
public class Foo {
public static int i = 0;
}
Is there any way to restart or reset a static class?
Note: I need this because I'm testing a static class with jUnit and I need to clean parameters before second test.
EDIT
ALMOST SOLUTION:
Using StanMax answer, I can to this:
Main.java
public class Main {
public static void main(String[] args) throws Exception {
test();
test();
}
public static void test() throws Exception {
System.out.println("\ntest()");
MyClassLoader myClassLoader = new MyClassLoader();
Class<?> fooClass = myClassLoader.loadClass(Foo.class.getCanonicalName());
Object foo = fooClass.newInstance();
System.out.println("Checking classloader: " + foo.getClass().getClassLoader());
System.out.println("GC called!");
System.gc();
}
}
MyClassLoader.java
public class MyClassLoader {
private URLClassLoader urlClassLoader;
public MyClassLoader() {
try {
URL url = new File(System.getProperty("user.dir") + "/bin/").toURL();
URL[] urlArray = {url};
urlClassLoader = new URLClassLoader(urlArray, null);
} catch (Exception e) {
}
}
public Class<?> loadClass(String name) {
try {
return (Class<?>) urlClassLoader.loadClass(name);
} catch (Exception e) {
}
return null;
}
#Override
protected void finalize() throws Throwable {
System.out.println("MyClassLoader - End.");
}
}
Foo.java
public class Foo {
public static int i = 0;
static {
System.out.println("Foo - BEGIN ---------------------------------");
}
public void finalize() throws Throwable {
System.out.println("Foo - End.");
}
}
OUTPUT
test()
Foo - BEGIN ---------------------------------
Checking classloader: java.net.URLClassLoader#ec160c9
GC called!
MyClassLoader - End.
Foo - End.
test()
Foo - BEGIN ---------------------------------
Checking classloader: java.net.URLClassLoader#ec3fb9b
GC called!
MyClassLoader - End.
Foo - End.
PROBLEM: if I do the cast bellow:
Foo foo = (Foo) fooClass.newInstance();
I get error:
java.lang.ClassCastException
Only if you can unload class, get it re-loaded, as class static code gets executed when class is loaded.
But you can just directly modify the value:
Foo.i = 0;
(or create equivalent method for doing it, esp. if static member is not public)
Create a static method that sets the class variables to their initial values, then call it when you need it.
Avoid static.
It is well known that static is not testable and should thus be avoided. For example, avoiding static is one of the key motivations behind dependency injection. If you need one instance only at runtime, use the singleton pattern instead. And create a new instance for each test run.
You can try this.
Main MainObject = new Main;
MainObject.main(args);
It will restart the class again and again until you stop the class.

How can I turn binding errors into runtime exceptions?

Just as there is "treat warning as errors" set in our projects to catch early possible problems, I would love to have a runtime exception to catch them early.
I have recently been bit by this problem and I would have been glad to have this.
Can it be done? And if yes, how?
You could hook into the PresentationTraceSources collection with your own listener:
public class BindingErrorListener : TraceListener
{
private Action<string> logAction;
public static void Listen(Action<string> logAction)
{
PresentationTraceSources.DataBindingSource.Listeners
.Add(new BindingErrorListener() { logAction = logAction });
}
public override void Write(string message) { }
public override void WriteLine(string message)
{
logAction(message);
}
}
and then hook it up in code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
BindingErrorListener.Listen(m => MessageBox.Show(m));
InitializeComponent();
DataContext = new string[] { "hello" };
}
}
Here is the XAML with a binding error
<Grid>
<TextBlock Text="{Binding BadBinding}" />
</Grid>
I implemented a solution very similar to the one proposed by Dean Chalk:
Derived a TraceListener that throws instead of logging
Added that listener to PresentationTraceSources.DataBindingSource
Please see the complete solution on GitHub, it includes a demo application and a unit test project.
First add this class to your project:
using System.Diagnostics;
namespace WpfTestApp
{
public class BindingErrorListener : TraceListener
{
public static void Register()
{
PresentationTraceSources.DataBindingSource.Listeners.Add(new BindingErrorListener());
}
public override void Write(string message)
{
}
public override void WriteLine(string message)
{
#if DEBUG
throw new System.Exception(message);
#endif
}
}
}
Then call the Register method in your App.xaml.cs class:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
BindingErrorListener.Register();
// ...
}
}
This way, (by throwing an exception) if you have any binding errors then you will be aware of those errors in the first place, that is, as soon as you start (F5) your application. If you wish, you can log those by injecting your logger object in the BindingErrorListener constructor.

Parameterized Tests with VS2010 Test Tools

Is it possible to write parameterized tests using VS2010 Test Tools for Silverlight?
In a regular NUnit test this would be done using TestCase attributes...
[Test]
[TestCase("myParam1")]
[TestCase("myParam2")]
[TestCase("myParam3")]
public void TestSomethingWithParameters(string myParam)
{
// ...some tests using myParam
}
Is this possible using VS2010 Test Tools?
No, this is not possible. The next best thing is to use data driven tests e.g.
http://callumhibbert.blogspot.com/2009/07/data-driven-tests-with-mstest.html
Check out the MSDN documentation also.
You can create a base class with the test method and the parameters as virtual properties.
When you inherit from this class you only need to override the properties with the desired values.
Please see the sample code:
public class Operation
{
public static int Add(int x, int y)
{
return x + y;
}
}
[TestClass]
public class AddTests : WorkItemTest
{
protected virtual int First{get { return 0; }}
protected virtual int Second{get { return 0; }}
[TestInitialize]
public virtual void Init()
{
//Init code
}
[TestCleanup]
public virtual void Clean()
{
//Clean code
}
[TestMethod]
[Description("x+y = y+x")]
public virtual void Test_operation_commutativity()
{
Assert.AreEqual(Operation.Add(Second, First), Operation.Add(First, Second));
}
}
[TestClass]
public class AddPositiveTest : AddTests
{
protected override int First { get { return 1; } }
protected override int Second { get { return 2; } }
}
[TestClass]
public class AddNegativeTest : AddTests
{
protected override int First { get { return -1; } }
protected override int Second { get { return -2; } }
}

JNA: How to access array of struct in struct?

I'm trying to access an array of struct inside a struct. This is the relevant C code reduced to the problem:
typedef struct {
int a;
int b;
} fileinfo_t;
typedef struct {
fileinfo_t **file;
int max_files;
} project_t;
In C accessing the array is as easy as this:
int var_a_of_file_0 = project.file[0].a;
int var_b_of_file_1 = project.file[1].b;
How do I implement this in Java? I'm asking this question because I'm new to JNA. So far I read the JNA documentation and tried every example which is somehow related to my problem but with no luck...
I used JNAerator for converting the header file. I don't know for shure if the result is correct:
package test;
import com.ochafik.lang.jnaerator.runtime.LibraryExtractor;
import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper;
import com.ochafik.lang.jnaerator.runtime.Structure;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.ptr.PointerByReference;
/**
* JNA Wrapper for library <b>test</b><br>
* This file was autogenerated by JNAerator,<br>
* a tool written by Olivier Chafik that uses a few opensource projects..<br>
* For help, please visit NativeLibs4Java , Rococoa, or JNA.
*/
public interface TestLibrary extends Library {
public static final java.lang.String JNA_LIBRARY_NAME = LibraryExtractor.getLibraryPath("test", true, test.TestLibrary.class);
public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance(test.TestLibrary.JNA_LIBRARY_NAME, com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper.DEFAULT_OPTIONS);
public static final TestLibrary INSTANCE = (TestLibrary)Native.loadLibrary(test.TestLibrary.JNA_LIBRARY_NAME, test.TestLibrary.class, com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper.DEFAULT_OPTIONS);
public static class fileinfo_t extends Structure<fileinfo_t, fileinfo_t.ByValue, fileinfo_t.ByReference > {
public int a;
public int b;
public fileinfo_t() {
super();
}
public fileinfo_t(int a, int b) {
super();
this.a = a;
this.b = b;
}
protected ByReference newByReference() { return new ByReference(); }
protected ByValue newByValue() { return new ByValue(); }
protected fileinfo_t newInstance() { return new fileinfo_t(); }
public static fileinfo_t[] newArray(int arrayLength) {
return Structure.newArray(fileinfo_t.class, arrayLength);
}
public static class ByReference extends fileinfo_t implements Structure.ByReference {
};
public static class ByValue extends fileinfo_t implements Structure.ByValue {
};
};
public static class project_t extends Structure<project_t, project_t.ByValue, project_t.ByReference > {
/// C type : fileinfo_t**
public PointerByReference file;
public int max_files;
public project_t() {
super();
}
/// #param file C type : fileinfo_t**
public project_t(PointerByReference file, int max_files) {
super();
this.file = file;
this.max_files = max_files;
}
protected ByReference newByReference() { return new ByReference(); }
protected ByValue newByValue() { return new ByValue(); }
protected project_t newInstance() { return new project_t(); }
public static project_t[] newArray(int arrayLength) {
return Structure.newArray(project_t.class, arrayLength);
}
public static class ByReference extends project_t implements Structure.ByReference {
};
public static class ByValue extends project_t implements Structure.ByValue {
};
};
}
Any help would be appreciated.
Since the array of structs does not overlay the containing struct's memory, you need a Pointer or equivalent type for that field. You can then manually derive the structure you need from the base pointer.
I don't think your usage example is valid, however.
Once you index with "[0]", you have a pointer to fileinfo_t, so you would have to use the following (have you actually compiled your example in C?):
int var_a_of_file_0 = project.file[0]->a;
int var_b_of_file_1 = project.file[1]->b;
Ultimately how you extract the actual structures depends on how they are laid out in memory, which is ambiguous in your current explanation.

Resources