Can powershell call subclasses from external C# dll - powershell

I have some simple code from:
https://www.codeguru.com/csharp/csharp/cs_misc/dllsandexecutables/article.php/c4239/Creating-and-Using-C-DLLs.htm
which generates a dll to do some simple math. I wanted to add a subclass
namespace MathFunctions
{
public class Add : MultiClass
{
public static int MultiplyAndAdd(int a, int b, int c)
{
return (a * b) + c;
}
}
}
Then call it from powershell.
Running powershell against the master classes returns data back without an issue
Import-module("C:\temp\MathFunctions.dll")
[MathFunctions.MultiClass]::Multiply(10, 2)
returns 20 as expected, but I can't figure the format to access the subclass. I've tried variations on:
[MathFunctions.MultiClass.Add]::MultiplyAndAdd(10, 2, 3)
[MathFunctions.MultiClass+Add]::MultiplyAndAdd(10, 2, 3)
[MathFunctions.MultiClass]:Add:MultiplyAndAdd(10, 2, 3)
[MathFunctions.MultiClass]::Add.MultiplyAndAdd(10, 2, 3)
but I always get variations on
Unable to find type [MathFunctions.MultiClass.Add]
I've also looked for the method in powershell via:
[MathFunctions.MultiClass] | get-member -MemberType method
but my subclass isn't listed.
I know I'm accessing it incorrectly. I can't figure out how to access the subclass from powershell.
I'm fairly sure subclasses can be accessed, as the closest example is:
PowerShell IComparable with subclasses
but I don't see how he aliased it.
Thanks

Thank you bluuf who pointed me in the right direction.
I ended up using dotPeek to take the dll apart (now it was public [blush]).
Code is as above and the powershell method is just the subclass name:
[MathFunctions.Add]::MultiplyAndAdd(5,2,3)
which gave an answer - not an error

To explain the confusion in more detail:
You mistakenly thought that class-inheritance relationships must be reflected in a given class' full (namespace-qualified) type name, so you thought that because class Add derives from class MultiClass, MultiClass too must be reflected in the full type name.
In reality, a class' derivation is irrelevant with respect to its full name; all that matter is the namespace in which it is placed.
In other words: to form the full type name for any type (class), use <EnclosingNamespace>.<TypeName>[1], which in your case means:
MathFunctions.Add
Using that as a PowerShell type literal - [MathFunctions.Add] - allows you to access the static MultiplyAndAdd() method via ::, the static-member access operator, as shown in your own answer.
Also, remember that tab-completion can be helpful here, because it works with type names too; in your case, typing [Add<tab> will expand to [MathFunctions.Add, yielding the full type name.
(If multiple available (public) type names start with Add, you may to have to press the tab key repeatedly to cycle through the matches.)
[1] A variation is required to access a nested class, i.e., a class embedded in another class:
<EnclosingNamespace>.<EnclosingTypeName>+<NestedTypeName>, e.g., if your Add class had a nested class named Inner: MathFunctions.Add+Inner

Related

Add a method to Matlab table class

I wish to add a method called nansubset to the table class. Essentially it allows you to call T(r,c) where r and c are real positive integer vectors possibly containing NaN's.
Stubbed code for nansubset.m could be:
function T = nansubset(T, r, c)
T = T(r,c);
end
I am following the instructions here, which detail how to add a new method to the cell class. Basically, in a folder on my Matlab path, I create a folder called #table, and within this folder, create a file called nansubset.m.
I am getting the following problems:
>> tmpT = table(); nansubset(tmpT, 1, 1)
Undefined function 'nansubset' for input arguments of type 'table'.
and
>> doc #table/nansubset
Your search - #table/nansubset - did not match any documents.
However:
edit nansubset
and
edit #table/nansubset
both open the method file in my editor.
Further, I followed the instructions in the above link to add the plus method to the cell class and find that it works perfectly.
Can someone please explain to me how I can add this additional method to the table class?
With the release of Matlab R2012b (version 8), the class folder behavior changed (emphasis is mine):
In MATLAB Versions 5 through 7, class folders do not shadow other class folders having the same name, but residing in later path folders. Instead, the class the combination of methods from all class folders having the same name define the class. This is no longer true.
For backward compatibility, classes defined in class folders always take precedence over functions and scripts having the same name, even those that come before them on the path.
The combination of the two bold statements explains the behavior:
cell is a built-in Matlab function that predates the new OOP rules that returns an instance of its class. And before R2012b, adding methods to a class folder called #cell added the methods to the object returned from the cell function (which isn't defined with a classdef nor a class folder); this ability was retained for compatibility with legacy user code.
table was added after R2012b, is defined via a class folder, and is Sealed. Since it is Sealed, it cannot be subclassed. And with the new rules, any #table folder without an associated classdef file will not register as a class folder nor will its methods be composed into the existing class unless it is part of the legacy system (like cell).
I can see three workarounds listed in the order I think is best:
Have a function on the Matlab path, just like the one you have, and always call the "method" using function notation instead of dot notation. If you need more "methods" group them in a folder or package (if good namespacing is desired) on the path. Since table is a value class, this option doesn't seem bad.
Create a wrapper class like the one below. It is cumbersome but automatically encapsulates the additional functions.
classdef MyTable < handle
properties
tab;
end
methods
function mytab = MyTable(varargin)
mytab.tab = table(varargin{:});
end
function tabnan = nansubset(mytab,r,c)
tabnan = mytab.tab(r,c);
end
end
end
Create a local copy of [matlabroot,'\toolbox\matlab\datatypes\#table\*'] and add the methods directly. I can't think of any huge drawbacks to this per se, but it feels weird copying internals like this.

Different field instances in class and parent/Call super constructor with method

I am trying to call the super constructor from a class using a method. The whole setup looks like this:
class Straight(hand: Hand) extends Combination(Straight.makeHandAceLowIfNeeded(hand), 5)
object Straight {
private def makeHandAceLowIfNeeded(hand: Hand): Hand = {
...
}
}
While this does compile, it has some rather odd runtime behaviour. While debugging, I noticed that the Straight instances have the "hand" property defined twice. Can somebody tell me what is going on, and what the proper way is to call the super constructor with different arguments?
In my use case, I want to call the super constructor with a modified hand in which I replaced a card compared to the original constructor argument.
Debugger screenshot with duplicate field:
.
It's a perfectly fine way to call the superclass constructor. These are two private fields and they don't conflict, though you can rename one of them to avoid confusion during debugging (or if you want to access the superclass' value from the subclass). However, the field should only be generated for a class parameter if it's used outside a constructor, and in your case it doesn't appear to be. Did you simplify the definition of Straight?

Hierarchy in Python 3.4 [duplicate]

I know, there are no 'real' private/protected methods in Python. This approach isn't meant to hide anything; I just want to understand what Python does.
class Parent(object):
def _protected(self):
pass
def __private(self):
pass
class Child(Parent):
def foo(self):
self._protected() # This works
def bar(self):
self.__private() # This doesn't work, I get a AttributeError:
# 'Child' object has no attribute '_Child__private'
So, does this behaviour mean, that 'protected' methods will be inherited but 'private' won't at all?
Or did I miss anything?
Python has no privacy model, there are no access modifiers like in C++, C# or Java. There are no truly 'protected' or 'private' attributes.
Names with a leading double underscore and no trailing double underscore are mangled to protect them from clashes when inherited. Subclasses can define their own __private() method and these will not interfere with the same name on the parent class. Such names are considered class private; they are still accessible from outside the class but are far less likely to accidentally clash.
Mangling is done by prepending any such name with an extra underscore and the class name (regardless of how the name is used or if it exists), effectively giving them a namespace. In the Parent class, any __private identifier is replaced (at compilation time) by the name _Parent__private, while in the Child class the identifier is replaced by _Child__private, everywhere in the class definition.
The following will work:
class Child(Parent):
def foo(self):
self._protected()
def bar(self):
self._Parent__private()
See Reserved classes of identifiers in the lexical analysis documentation:
__*
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes.
and the referenced documentation on names:
Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used.
Don't use class-private names unless you specifically want to avoid having to tell developers that want to subclass your class that they can't use certain names or risk breaking your class. Outside of published frameworks and libraries, there is little use for this feature.
The PEP 8 Python Style Guide has this to say about private name mangling:
If your class is intended to be subclassed, and you have attributes
that you do not want subclasses to use, consider naming them with
double leading underscores and no trailing underscores. This invokes
Python's name mangling algorithm, where the name of the class is
mangled into the attribute name. This helps avoid attribute name
collisions should subclasses inadvertently contain attributes with the
same name.
Note 1: Note that only the simple class name is used in the mangled
name, so if a subclass chooses both the same class name and attribute
name, you can still get name collisions.
Note 2: Name mangling can make certain uses, such as debugging and
__getattr__(), less convenient. However the name mangling algorithm
is well documented and easy to perform manually.
Note 3: Not everyone likes name mangling. Try to balance the need to
avoid accidental name clashes with potential use by advanced callers.
The double __ attribute is changed to _ClassName__method_name which makes it more private than the semantic privacy implied by _method_name.
You can technically still get at it if you'd really like to, but presumably no one is going to do that, so for maintenance of code abstraction reasons, the method might as well be private at that point.
class Parent(object):
def _protected(self):
pass
def __private(self):
print("Is it really private?")
class Child(Parent):
def foo(self):
self._protected()
def bar(self):
self.__private()
c = Child()
c._Parent__private()
This has the additional upside (or some would say primary upside) of allowing a method to not collide with child class method names.
By declaring your data member private :
__private()
you simply can't access it from outside the class
Python supports a technique called name mangling.
This feature turns class member prefixed with two underscores into:
_className.memberName
if you want to access it from Child() you can use: self._Parent__private()
Also PEP8 says
Use one leading underscore only for non-public methods and instance
variables.
To avoid name clashes with subclasses, use two leading underscores to
invoke Python's name mangling rules.
Python mangles these names with the class name: if class Foo has an
attribute named __a, it cannot be accessed by Foo.__a. (An insistent
user could still gain access by calling Foo._Foo__a.) Generally,
double leading underscores should be used only to avoid name conflicts
with attributes in classes designed to be subclassed.
You should stay away from _such_methods too, by convention. I mean you should treat them as private
Although this is an old question, I encountered it and found a nice workaround.
In the case you name mangled on the parent class because you wanted to mimic a protected function, but still wanted to access the function in an easy manner on the child class.
parent_class_private_func_list = [func for func in dir(Child) if func.startswith ('_Parent__')]
for parent_private_func in parent_class_private_func_list:
setattr(self, parent_private_func.replace("_Parent__", "_Child"), getattr(self, parent_private_func))
The idea is manually replacing the parents function name into one fitting to the current namespace.
After adding this in the init function of the child class, you can call the function in an easy manner.
self.__private()
AFAIK, in the second case Python perform "name mangling", so the name of the __private method of the parent class is really:
_Parent__private
And you cannot use it in child in this form neither

Scala parameters for access modifiers?

What is the difference between
class Test {
private[this] val foo = 0
}
vs
class Test {
private val foo = 0
}
What all can go inside the []? Also, what should I search for when I want to look up the specs of this? I tried Googling various combinations of "scala access modifier arguments/parametrized scala access modifier" and nothing came up.
what should I search for when I want to look up the specs of this?
In The Scala Language Specification it is defined as "access modifier" and "access qualifier" (see BNF in §5.2).
What is the difference between
...
What all can go inside the []?
You can put class name, package name or this there. Here is a relevant quote from language specs that explains this (see §5.2 for more details):
The modifier can be qualified with an identifier C (e.g. private[C ]) that must
denote a class or package enclosing the definition. Members labeled with
such a modifier are accessible respectively only from code inside the package
C or only from code inside the class C and its companion module (§5.4).
An different form of qualification is private[this]. A member M marked
with this modifier is called object-protected; it can be accessed only from
within the object in which it is defined. That is, a selection p.M is only legal if the prefix is this or O.this, for some class O enclosing the reference. In
addition, the restrictions for unqualified private apply.
The first one is private for instance class, second is for class. If you use second version you have access from another instance of Test class (it's usefull for equals method or similiar).

Help with the Moles syntax for testing private method with generics

I've got a signature for a method that looks like this:
private IEnumerable BuildCustomerUpdatePlan(List localCacheChangedCustomers, List crmChangedCustomers){}
When I look at the moled object, the syntax (IntelliSense) of how to call the method and test itis absolutely confusing to me and every time I give it a shot, I get compilation errors. I've looked through the basic tutorials provided on MSFT's site, but I simply don't get how to test a private method using Moles or how to deal with the return type and multiple parameters.
Unfortuantely I've been unable to find other good HOWTO's or threads demonstrating a more complex sample than just working with a simple Add() method that spits out an INT and accepts an INT. :(
Tips?
In your testing project, first make sure you add a Moles assembly corresponding to the assembly-under-test. You'll also want to add an using statement of the assembly-under-test with .Moles appended so you can use the moled assembly.
Moles changes the names of the classes and methods to the form M[Original Class Name].[Original Method Name][typeof param1][typeof param2].... In your case a detour for that method could look like MClass.BuildCustomerUpdatePlanListList = (List x, List y) => { [code]};. That defines an anonymous method that takes two Lists as parameters and you'd put whatever code wanted in the function. Just make sure that you return an IEnumerable in that anonymous method.
Here's an example using Moles to detour Directory.GetFiles:
using System.IO.Moles;
[assembly: MoledType(typeof(System.IO.Directory))]
...
MDirectory.GetFilesStringString = (string x, string y) => new string[0];
Since the Directory class is a member of System.IO I use using System.IO.Moles; to specify that I want to use moled members of the assembly.
Moles requires you to specify the types Moled: [assembly: MoledType(typeof(System.IO.Directory))] does the job.
Finally, Directory.GetFiles takes two strings as parameters and returns a string array. To detour the method into returning the equivalent of no files found, the moled method just returns new string[0]. Curly braces are needed if you want multiple lines in the anonymous method and, if not detouring a void method, a return statement that matches the type the original method would return.