from VBS to WPF via COM - wpf

we have a nasty (or maybe a trivial?) issue.
There is a WPF control. It has 2 interfaces, the main and one for automated testing purpose. Defined this way:
[ComVisible(true)]
[Guid("xxx")]
public interface IXXXXXTest
{
[DispId(1)]
void Test1(int index);
}
[ComVisible(true)]
public interface IXXXXX
{
void Main1(index);
}
[ComVisible(true)]
[Guid("xxx")]
ClassInterface(ClassInterfaceType.None)]
public partial class XXXXX_WPF_CONTROL : UserControl,
IXXXXX,
IXXXXXTest
{
...
}
Now we are trying to reach it from VBS.
Try 1)
Set Ctrl = GetControl(...) <---- this is ok
Ctrl.Test1(0) <---- Object doesn't support this property or method: 'Ctrl.Test1'
Set Ctrl = GetControl(...) <---- this is ok
Ctrl.Main1(0) <---- this is ok
So it works fine for the "main" interface but for the test interface.
This seems ok(?), because as far as I know VBS reaches the "main" interface only via IDispatch if there is no IDispatchEx. So I added a property to the IXXXXX to get the test interface.
[ComVisible(true)]
public interface IXXXXX
{
void Main1(index);
IXXXXXTest Test { get;}
}
....
public IXXXXXTest Test
{
get { return this as IXXXXXTest; }
}
Great, so now I can reach this IXXXXTest interface via the "main" interface.
Try 2)
VBS:
Set Ctrl = GetControl(...) <---- this is ok
Set CtrlTest = Ctrl.Test <----- this is ok
CtrlTest.Test1(0) <---- Object doesn't support this property or method: 'CtrlTest.Test1'
:(
Note that, for an other .NET control of us the "Try1" works, without any trick!
So probably due to the WPF something different?
Also, changing the
ClassInterface(ClassInterfaceType.None)]
into anything else (AutoDispatch / AutoDual), or leaving it makes the WPF control unusable.
Besides that this is also how it should be by this article: Is it possible to package WPF window as COM Object
Do you have any idea what could be the problem?
Thank much in advance!

Scripting languages can only use the default interface on a class. You've got more than one so at least one of them will not be usable. And method names may be renamed if they conflict with other declarations. I'd assume you obfuscated the real names in your question so hard to diagnose such a renaming happening from what you posted.
Best thing to do is to temporarily apply the [InterfaceType(ComInterfaceType.InterfaceIsDual)] attribute on your interface types. Which allows you to generate a type library with Tlbexp.exe which you can then view with the OleView.exe utility, File + View Typelib command. You'll see the exact names of the methods and you'll see which interface is the [default] one on the coclass. From there you should have little trouble modifying your declarations so they'll work in a scripting language.

Related

NUnit: How can I set name of test depending on parametr in [TestFixture(typeof(param))]

I'm using NUnit + Webdriver + C#. Setup class has next stucture:
[TestFixture(typeof(InternetExplorerDriver))]
[TestFixture(typeof(ChromeDriver))]
public partial class SetupBase<TWebDriver> where TWebDriver : IWebDriver, new()
{
public IWebDriver _driver;
[OneTimeSetUp]
public void OneTimeSetUp()
{
Init();
}
}
How can I set name of tests to include methode name, arguments and name of browser?
I tried with capabilities but it didn't help
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("Name", String.Format ("{0}_Chrome", TestContext.CurrentContext.Test.Name), true);
Also tried to use next code but was not able to find way how to pass driver type to NameAttribute
public class NameAttribute : NUnitAttribute, IApplyToTest
{
public NameAttribute(string name)
{
Name = String.Format("{0} {1}", name);
}
public string Name { get; set; }
public void ApplyToTest(Test test)
{
test.Properties.Add("Name", Name);
}
}
Can you help me please. Maybe need to update base class structure somehow?
This is how I use in tests
public class _001_General<TWebDriver> : SetupBase<TWebDriver> where TWebDriver : IWebDriver, new()
{
[OneTimeSetUp]
public void OneTimeSetupTest ()
{
//somework
}
[Test]
public void Test ()
{
//somework
}
}
Also SetupBase class contains functions that are used in tests
In NUnit, test cases, test methods, test fixtures and generic test fixture classes are all "tests" even though we sometimes talk loosely about "tests" as meaning test cases.
In your example, the following names are created:
_001_General<TWebDriver> (or maybe _001_General<>)
_001_General<InternetExplorerDriver>
Test
_001_General<ChromeDriver>
Test
Tests also have "fullnames", similar to that for a type or method. For example
_001_General<ChromeDriver>.Test
(Note: the fullname would also include a namespace, which I haven't shown.)
If you are using a runner that displays fullnames, like the NUnit 3 Console Runner, then there is no problem. So, I assume you are not. :-)
Some runners, like the NUnit 3 Visual Studio Test Adapter use simple test case names. So you would end up with a bunch of tests displayed with the name "Test."
Is that your problem? If so, this is not much of an answer. :-) However, I'll leave it as partial and add to it after hearing what runner you want to use and what you would like to see displayed in it.
UPDATE:
Based on your comment, what you really want to see is the test FullName - just as it is displayed by the NUnit 3 Console runner that TC runs for you. You'd like to see them in the VS IDE using the NUnit 3 VS Adapter.
Unfortunately, you can't right now. :-) More on that below. Meanwhile, here are some workarounds:
Use the console runner on your desktop. It's not as visual but works quite well. It's how I frequently work. Steps:
Install the console runner. I recommend using Chocolatey to install it globally, allowign you to use it with all your projects.
Set up your project to run the console runner with any options you like.
Make sure you use an external console window so you get the color display options that make the console runner easier to use.
Size your windows so you can see everything (if you have enough screen space) or just let the console run pop up on top of VS.
Try to trick VS by setting the test name in a way that includes the driver parameters. That's what you are already doing and it sounds as if you have already gotten almost all you can out of this option, i.e. class name without class parameters. You could try to take it a step further by creating separate classes for each driver. This would multiply the number of classes you have, obviously, but doesn't have to duplicate the code. You could use inheritance from the generic classes to create a new class with only a header in each place where it's needed. Like...
public class TestXYZDriver : TestDriver ...
This might be a lot of work, so it really depends on how important it is to you to get visual results that include fixture parameters right now.
For the future, you could request that the NUnit 3 Adapter project give an option of listing tests by their full names. I haven't worked on that project for a few years, so I'm not sure if it's actually possible. It may not be entirely in the control of the adapter, since VS controls what is displayed.

WPF two-way binding with internal setter

I'm using WPF's two-way binding on a CLR property, which implements INotifyPropertyChanged.
The set for the property is internal, while the get is public.
Unfortunately, I get the following error:
System.Windows.Markup.XamlParseException was unhandled
Message: An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: A TwoWay or OneWayToSource binding cannot work on the read-only property 'Name' of type 'MyType'.
Is this the expected behavior? I would have thought that internal setters should work just fine...
Note that the CLR-type is defined in another assembly, and are visible in the current assembly, with the [assembly: InternalsVisibleTo("MyAssembly")] attribute.
Does anyone have workarounds/suggestions? The declaring assembly is a class library, so it's not an option for me to change the set to public.
You can create your own NEW public wraper property and use getter and setter of it to interact with your internal property
internal string _SideTabHeader;
public string SideTabHeader
{
get { return _SideTabHeader; }
set
{
if( value<0)
{
do nothing
}
else
{
_SideTabHeader=value;
};
}
}
Oh my... I just found out, WPF bindings don't work with internal properties. Oh, Microsoft... Whatever were you thinking?
Update:
Here's what I've understood so far (Thank you, #Grx70):
WPF is not a native part of the .NET framework, it's just a "plug-in" framework that happens to be also written by Microsoft. That is why it can't access the internal members of your assembly.
Microsoft could have allowed WPF to respect the [assembly: InternalsVisibleTo("XXX")] attribute, but as of right now, WPF ignores it - which unfortunately does not leave one with any easy workarounds.
Note: I tested using InternalVisibleTo - both Signed and Unsigned, with PresentationFramework, PresentationCore, and a whole bunch of other DLLs with no luck.
The only workaround I can think of right now is to create a "Proxy" class which can expose all required members as public. This is quite a PITA (I have a LOT of classes, and I hate the maintenance nightmare that comes with creating an equal number of "Proxy" classes) - so I might look into using PostSharp, or Fody or some kind of weaver to auto-create these "Proxy" classes if I can.
All the best to anyone else facing this issue.
This is very late and not solving the initial question, but as very related it may help someone else which very similar problem...
If your internal property is of type Enum else skip
In my case I was trying to do a WPF xaml binding to a property of type inherited from a WCF service. The easy way to solve that simple case was to use int.
public Dictionary<int, string> ProductsList => EnumExtensions.ProductsList;
public int ProductType
{
get { return (int)_DeliveryProduct.ProductType; }
set
{
if (value.Equals(ProductType)) return;
_DeliveryProduct.ProductType = (ProductEnum)value;
RaisePropertyChanged(() => ProductType);
}
}
_DeliveryProduct is my reference to my domain object for which the property ProductType is an enum but in my viewmodel that property is an int.
... Note that ProductEnum is autogenerated from the API and can't be changed to public.
internal static Dictionary<int, string> ProductsList => new Dictionary<int, string>
{
{(int)ProductEnum.Regular, ProductEnum.Regular.GetDisplayName()},
{(int)ProductEnum.Intermediate, ProductEnum.Intermediate.GetDisplayName()},
{(int)ProductEnum.Super, ProductEnum.Super.GetDisplayName()},
{(int)ProductEnum.Diesel, ProductEnum.Diesel.GetDisplayName()}
};

Handling Kinect in Main Window and passing this reference to UserControls

I have a project in WPF with a lot of UserControls, some user controls uses Kinect KinectColorViewer.xaml
I want to handle the sensor discovering and setup (conect, disconect, etc) in main window and serve it to my UserControls, how is the best way to do it?
Here is the project that explains my question.
If you prefer, here are the github link.
From your example code,
Assuming you want to maintain as much of the already available code from Microsoft, you will want to set up a reference to the KinectSensorManager on initializing your application. My constructor normally looks something like this:
private readonly KinectSensorChooser sensorChooser = new KinectSensorChooser();
public KinectSensorManager KinectSensorManager { get; private set; }
public MainViewModel()
{
// initialize the Kinect sensor manager
KinectSensorManager = new KinectSensorManager();
KinectSensorManager.KinectSensorChanged += this.KinectSensorChanged;
// locate an available sensor
sensorChooser.Start();
// bind chooser's sensor value to the local sensor manager
var kinectSensorBinding = new Binding("Kinect") { Source = this.sensorChooser };
BindingOperations.SetBinding(this.KinectSensorManager, KinectSensorManager.KinectSensorProperty, kinectSensorBinding);
}
The KinectSensorManager is just a helper class. You can rewrite code to easily avoid using it, but it doesn't do anything bad (does a lot of nice stuff for you) so I've just keep using it. Also, since I'm assuming you want to re-use as much code as possible, we want to maintain its usage.
For your control, you can extend KinectControl which will set up a bunch of helpful items for you. So...
public partial class KinectUserControl : KinectControl
{
...
}
This will give your control access to a lot of override-able functions that listen in to various events (like KinectSensorChanged). Check our the KinectColorViewer code and you can see how it overrides this function, which allows it to automatically start displaying new data if you swap Kinects.
When declaring your control in the XAML you can now add a reference to the KinectSensorManager:
<my:KinectUserControl KinectSensorManager="{Binding KinectSensorManager}" />
Because your control now has a KinectSensorManager property, it should pass through to your KinectColorViewer control as well.

Error Application cast in WPF

i have 2 projects in my solution (main is A.WPF and secondary is B.WPF)
when i'm trying to access variables inside my App.xaml.cs in B.WPF:
filename = ((App)Application.Current).ErrorLogFileName;
i get the following error:
Unable to cast object of type 'A.App' to type 'B.App'.
i also tried the following:
filename = ((B.App)Application.Current).ErrorLogFileName;
but still the same error...
the definition in B.App is:
private string _errorLogFileName = "error log.xml";
public string ErrorLogFileName
{
get { return _errorLogFileName; }
}
please assist...
Looks like you need to do:
filename = ((A.App)Application.Current).ErrorLogFileName;
The error is saying the type is A.App, yet in both cases you are trying to cast to B.App.
There can only be one current application also.
Application.Current refers to the current application. The only way to be allowed to cast the current App to another App-type is when the other App-type is a base class of the current App-type.
Are A.App and B.App siblings or is B.App a base class of A.App?
If you don't want B to have a reference to A (or can't as you want A to reference B and that would cause a circular reference), then you need a common type defined in a third assembly that both A and B reference. In our implementation we tend to have a ConfigurationData type that is in a separate project referenced by both Wpf projects, e.g.
public static class ConfigurationData
{
private static string _errorLogFileName = "error log.xml";
public string ErrorLogFileName
{
get { return _errorLogFileName; }
}
}
Another approach would be to define an Interface for your ErrorLogFileName property in a 3rd assembly that both A and B reference, and then implement that interface on your Wpf Application class - A and B would then both be able to cast to that type. If you wanted your A project to set the values on that at runtime, you could make the ErrorLogFileName a read-write property instead and initialize it in your application startup.
I personally prefer using a separate ConfigurationData type from the Wpf app object for this kind of stuff (ErrorLogFileName etc.) as it can then also be used for code that might execute in a unit test and therefore might not be running under a Wpf application - it also avoids having to do casts all over the place (ConfigurationData.ErrorLogFileName instead of ((IAppConfigurationData)Application.Current).ErrorLogFileName.
BTW, if you have an Application object in both assemblies it sounds like you might have both assemblies configured to build as Output type: Windows Application in your project properties. You should only really have one assembly that is configured as the Windows Application and the rest should be Class Library to avoid confusing numbers of Application classes being generated - only the one in the main EXE (and it's related resources) will get created at runtime.

Can someone explain the magic going on in Prism's resolve<> method?

I've got a CustomersModule.cs with the following Initialize() method:
public void Initialize()
{
container.RegisterType<ICustomersRepository, CustomersRepository>(new ContainerControlledLifetimeManager());
CustomersPresenter customersPresenter = this.container.Resolve<CustomersPresenter>();
}
The class I resolve from the container looks like this:
class CustomersPresenter
{
private CustomersView view;
private ICustomersRepository customersRespository;
public CustomersPresenter(CustomersView view,
ICustomersRepository customersRepository,
TestWhatever testWhatever)
{
this.view = view;
this.customersRespository = customersRepository;
}
}
The TestWhatever class is just a dummy class I created:
public class TestWhatever
{
public string Title { get; set; }
public TestWhatever()
{
Title = "this is the title";
}
}
Yet the container happily resolves CustomersPresenter even though I never registered it, and also the container somehow finds TestWhatever, instantiates it, and injects it into CustomersPresenter.
I was quite surprised to realize this since I couldn't find anywhere in the Prism documentation which explicitly stated that the container was so automatic.
So this is great, but it what else is the container doing that I don't know about i.e. what else can it do that I don't know about? For example, can I inject classes from other modules and if the modules happen to be loaded the container will inject them, and if not, it will inject a null?
There is nothing magical going on. You are specifying concrete types, so naturally they are resolvable, because if we have the Type object, we can call a constructor on it.
class Fred { };
Fred f1 = new Fred();
Type t = typeof(Fred);
Fred f2 = (Fred)t.GetConstructor(Type.EmptyTypes).Invoke(null);
The last line above is effectively what happens, the type t having been found by using typeof on the type parameter you give to Resolve.
If the type cannot be constructed by new (because it's in some unknown separate codebase) then you wouldn't be able to give it as a type parameter to Resolve.
In the second case, it is constructor injection, but it's still a known concrete constructable type. Via reflection, the Unity framework can get an array of all the Types of the parameters to the constructor. The type TestWhatever is constructable, so there is no ambiguity or difficulty over what to construct.
As to your concern about separate modules (assemblies), if you move TestWhatever to another assembly, that will not change the lines of code you've written; it will just mean that you have to add a reference to the other assembly to get this one to build. And then TestWhatever is still an unambiguously refeferenced constructable type, so it can be constructed by Unity.
In other words, if you can refer to the type in code, you can get a Type object, and so at runtime it will be directly constructable.
Response to comment:
If you delete the class TestWhatever, you will get a compile-time error, because you refer to that type in your code. So it won't be possible to get a runtime by doing that.
The decoupling is still in effect in this arrangement, because you could register a specific instance of TestWhatever, so every call to Resolve<TestWhatever>() will get the same instance, rather than constructing a new one.
The reason this works is because Unity is designed for it. When you Resolve with a concrete type, Unity looks to see if it can resolve from the container. If it cannot, then it just goes and instantiates the type resolving it's dependencies. It's really quite simple.

Resources