Python clr.AddReference() Examples

The following are 30 code examples of clr.AddReference(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module clr , or try the search function .
Example #1
Source File: test_regressions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_cp23878(self):
        import clr
        clr.AddReference("rowantest.delegatedefinitions")
        clr.AddReference("rowantest.typesamples")
        from Merlin.Testing import Delegate, Flag
        from time import sleep

        cwtm = Delegate.ClassWithTargetMethods()
        vi32d = Delegate.VoidInt32Delegate(cwtm.MVoidInt32)
        ar = vi32d.BeginInvoke(32, None, None)
        is_complete = False
        for i in xrange(100):
            sleep(1)
            if ar.IsCompleted:
                is_complete = True
                break
        self.assertTrue(is_complete)
        self.assertEqual(Flag.Value, 32) 
Example #2
Source File: test_regressions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_indexing_value_types_cp20370(self):
        import clr
        if is_netcoreapp:
            clr.AddReference("System.Drawing.Primitives")
        else:
            clr.AddReference("System.Drawing")
        from System.Drawing import Point

        p = Point(1,2)
        l = [None]
        l[0] = p
        self.assertEqual(id(l[0]), id(p))
        self.assertEqual(id(l[0]), id(p))

        x = {}
        x[p] = p
        self.assertEqual(id(list(x.iterkeys())[0]), id(p))
        self.assertEqual(id(list(x.itervalues())[0]), id(p))

        self.load_iron_python_test()

        from IronPythonTest import StructIndexable
        a = StructIndexable()
        a[0] = 1
        self.assertEqual(a[0], 1) 
Example #3
Source File: test_superconsole.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_member_completion_com(self):
        superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')
        superConsole.SendKeys('import clr{ENTER}')
        superConsole.SendKeys('import System{ENTER}')
        superConsole.SendKeys('clr.AddReference{(}"Microsoft.Office.Interop.Word"{)}{ENTER}')
        superConsole.SendKeys('import Microsoft.Office.Interop.Word{ENTER}')
        superConsole.SendKeys('wordapp = Microsoft.Office.Interop.Word.ApplicationClass{(}{)}{ENTER}')
        sleep(10) #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24427
        superConsole.SendKeys('wordapp.Activ{TAB}{ENTER}')
        sleep(15) #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24427
        superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
        
        #Verification
        temp = getTestOutput()
        Assert(len(temp[0])==8, str(temp[0]))
        Assert(temp[0][6].startswith('<Microsoft.Scripting.ComInterop.DispCallable object at '), str(temp[0])) 
Example #4
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_a_override_patching(self):
        from IronPythonTest import TestHelpers

        if is_netcoreapp:
            clr.AddReference("System.Dynamic.Runtime")
            clr.AddReference("System.Linq.Expressions")
        else:
            clr.AddReference("System.Core")

        # derive from object
        class x(object):
            pass
        
        # force creation of GetHashCode built-in function
        TestHelpers.HashObject(x())

        # derive from a type which overrides GetHashCode
        from System.Dynamic import InvokeBinder
        from System.Dynamic import CallInfo
        
        class y(InvokeBinder):
            def GetHashCode(self): return super(InvokeBinder, self).GetHashCode()
        
        # now the super call should work & should include the InvokeBinder new type
        TestHelpers.HashObject(y(CallInfo(0))) 
Example #5
Source File: scriptpw.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test__3_registered_with_pia():
    run_tlbimp(scriptpw_path, "spwLib")
    run_register_com_component(scriptpw_path)
    clr.AddReference("spwLib.dll")
    
    from spwLib import PasswordClass    
    pc = PasswordClass()
        
    Assert('PasswordClass' in repr(pc))
    Assert('spwLib.PasswordClass' in pc.ToString())
    AreEqual(pc.__class__, PasswordClass)
        
    try: del pc.GetPassword
    except AttributeError: pass
    else: Fail("attribute 'GetPassword' of 'PasswordClass' object is read-only")
        
    _test_common_on_object(pc) 
Example #6
Source File: test_clrload.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_load_count(self):
        # verify loading an assembly updates the assembly-loaded count in the repr
        # if a new assembly gets loaded before this that contains System both numbers
        # need to be updated
        import clr, System
        before = repr(System)
        if is_netcoreapp:
            clr.AddReference('System.Drawing.Primitives')
        else:
            clr.AddReference('System.Drawing')
        after = repr(System)

        # Strip common substring from start and end
        start = 0; end = 1
        while before[start] == after[start]: start += 1
        while before[-end] == after[-end]: end += 1
        end -= 1;

        # what remains is an int - number of assemblies loaded.
        # The integer must have increased value by 1
        self.assertEqual(int(before[start:-end]) + 1, int(after[start:-end])) 
Example #7
Source File: process_util.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def run_tool(self, cmd, args=""):
        import clr
        import System
        if is_netcoreapp:
            clr.AddReference("System.Diagnostics.Process")
        process = System.Diagnostics.Process()
        process.StartInfo.FileName = cmd
        process.StartInfo.Arguments = args
        process.StartInfo.CreateNoWindow = True
        process.StartInfo.UseShellExecute = False
        process.StartInfo.RedirectStandardInput = False
        process.StartInfo.RedirectStandardOutput = False
        process.StartInfo.RedirectStandardError = False
        process.Start()
        process.WaitForExit()
        return process.ExitCode 
Example #8
Source File: run_compiled.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def main():
    if len(sys.argv) != 2:
        print "Usage: ipy run_compiled.py <testfile.py>"
        sys.exit(-1)
    
    testName = sys.argv[1]
    
    print "Compiling ", testName ,"..."
    clr.CompileModules("compiledTest.dll", testName)    
    File.Move(testName, testName+".bak")    
    try:
        print "Running test from compiled binary..."    
        clr.AddReference("compiledTest")    
        __import__(Path.GetFileNameWithoutExtension(testName))    
    finally:
        File.Move(testName+".bak" , testName)
    
#-------------------------------------------------------------------------------------- 
Example #9
Source File: test_clrload.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_load_count(self):
        # verify loading an assembly updates the assembly-loaded count in the repr
        # if a new assembly gets loaded before this that contains System both numbers
        # need to be updated
        import clr, System
        before = repr(System)
        if is_netcoreapp:
            clr.AddReference('System.Drawing.Primitives')
        else:
            clr.AddReference('System.Drawing')
        after = repr(System)

        # Strip common substring from start and end
        start = 0; end = 1
        while before[start] == after[start]: start += 1
        while before[-end] == after[-end]: end += 1
        end -= 1;

        # what remains is an int - number of assemblies loaded.
        # The integer must have increased value by 1
        self.assertEqual(int(before[start:-end]) + 1, int(after[start:-end])) 
Example #10
Source File: process_util.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def run_tool(self, cmd, args=""):
        import clr
        import System
        if is_netcoreapp:
            clr.AddReference("System.Diagnostics.Process")
        process = System.Diagnostics.Process()
        process.StartInfo.FileName = cmd
        process.StartInfo.Arguments = args
        process.StartInfo.CreateNoWindow = True
        process.StartInfo.UseShellExecute = False
        process.StartInfo.RedirectStandardInput = False
        process.StartInfo.RedirectStandardOutput = False
        process.StartInfo.RedirectStandardError = False
        process.Start()
        process.WaitForExit()
        return process.ExitCode 
Example #11
Source File: run_compiled.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def main():
    if len(sys.argv) != 2:
        print "Usage: ipy run_compiled.py <testfile.py>"
        sys.exit(-1)
    
    testName = sys.argv[1]
    
    print "Compiling ", testName ,"..."
    clr.CompileModules("compiledTest.dll", testName)    
    File.Move(testName, testName+".bak")    
    try:
        print "Running test from compiled binary..."    
        clr.AddReference("compiledTest")    
        __import__(Path.GetFileNameWithoutExtension(testName))    
    finally:
        File.Move(testName+".bak" , testName)
    
#-------------------------------------------------------------------------------------- 
Example #12
Source File: test_clrload.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_namespaceimport(self):
        import clr
        tmp = self.temporary_dir
        if tmp not in sys.path:
            sys.path.append(tmp)

        code1 = "namespace TestNamespace { public class Test1 {} }"
        code2 = "namespace TestNamespace { public class Test2 {} }"

        test1_cs, test1_dll = os.path.join(tmp, 'testns1.cs'), os.path.join(tmp, 'testns1.dll')
        test2_cs, test2_dll = os.path.join(tmp, 'testns2.cs'), os.path.join(tmp, 'testns2.dll')

        self.write_to_file(test1_cs, code1)
        self.write_to_file(test2_cs, code2)

        self.assertEqual(self.run_csc("/nologo /target:library /out:"+ test1_dll + ' ' + test1_cs), 0)
        self.assertEqual(self.run_csc("/nologo /target:library /out:"+ test2_dll + ' ' + test2_cs), 0)

        clr.AddReference('testns1')
        import TestNamespace
        self.assertEqual(dir(TestNamespace), ['Test1'])
        clr.AddReference('testns2')
        # verify that you don't need to import TestNamespace again to see Test2
        self.assertEqual(dir(TestNamespace), ['Test1', 'Test2']) 
Example #13
Source File: test_clrload.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_addreference_sanity(self):
        import clr
        # add reference directly to assembly
        clr.AddReference(''.GetType().Assembly)
        # add reference via partial name
        clr.AddReference('System.Xml')
        # add a reference via a fully qualified name
        clr.AddReference(''.GetType().Assembly.FullName) 
Example #14
Source File: test_exceptions_generated.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(ExceptionsGeneratedTest, self).setUp()
        import clr
        clr.AddReference("IronPython") 
Example #15
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_dir(self):
        # make sure you can do dir on everything in System which 
        # includes special types like ArgIterator and Func
        for attr in dir(System):
            if is_netcoreapp and attr in ["ArgIterator", "ReadOnlySpan"]: continue # TODO: https://github.com/IronLanguages/dlr/issues/74
            dir(getattr(System, attr))

        if is_netcoreapp:
            clr.AddReference("System.Collections")

        for x in [System.Collections.Generic.SortedList,
                    System.Collections.Generic.Dictionary,
                    ]:
            temp = dir(x) 
Example #16
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_scope_getvariable(self):
        import clr
        clr.AddReference('IronPython')
        clr.AddReference('Microsoft.Scripting')
        from IronPython.Hosting import Python
        from Microsoft.Scripting import ScopeVariable
        
        scope = Python.CreateEngine().CreateScope()
        var = scope.GetScopeVariable('foo')
        self.assertEqual(type(var), ScopeVariable) 
Example #17
Source File: test_ipye.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cp27547():
    import clr
    clr.AddReference('IronPython')
    clr.AddReference('Microsoft.Scripting')
    from IronPython.Hosting import Python
    from Microsoft.Scripting import SourceCodeKind, ScriptCodeParseResult
    engine = Python.CreateEngine()
    scope = engine.CreateScope()
    text = 'lambda'
    source = engine.CreateScriptSourceFromString(text, 'stdin',
    SourceCodeKind.InteractiveCode)
    result = source.GetCodeProperties()
    AreEqual(result, ScriptCodeParseResult.IncompleteToken) 
Example #18
Source File: wpf.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _():
    import sys
    if sys.implementation.name == 'ironpython':
        import clr
        try:
            clr.AddReference('IronPython.Wpf')
        except:
            pass 
Example #19
Source File: test_methoddispatch.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_system_drawing(self):
        import clr
        if is_netcoreapp:
            clr.AddReference("System.Drawing.Primitives")
        else:
            clr.AddReference("System.Drawing")
        from System.Drawing import Rectangle
        r = Rectangle(0, 0, 3, 7)
        s = Rectangle(3, 0, 8, 14)
        
        # calling the static method
        i = Rectangle.Intersect(r, s)
        self.assertEqual(i, Rectangle(3, 0, 0, 7))
        self.assertEqual(r, Rectangle(0, 0, 3, 7))
        self.assertEqual(s, Rectangle(3, 0, 8, 14))
        
        # calling the instance
        i = r.Intersect(s)
        self.assertEqual(i, None)
        self.assertEqual(r, Rectangle(3, 0, 0, 7))
        self.assertEqual(s, Rectangle(3, 0, 8, 14))
        
        # calling instance w/ StrongBox
        r = Rectangle(0, 0, 3, 7)
        box = clr.StrongBox[Rectangle](r)
        i = box.Intersect(s)
        self.assertEqual(i, None)
        self.assertEqual(box.Value, Rectangle(3, 0, 0, 7))
        self.assertEqual(s, Rectangle(3, 0, 8, 14))
        
        # should be able to access properties through the box
        self.assertEqual(box.X, 3)
        
        # multiple sites should produce the same function
        i = box.Intersect
        j = box.Intersect 
Example #20
Source File: test_methoddispatch.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_security_crypto(self):
        import System
        if is_netcoreapp:
            import clr
            clr.AddReference("System.Security.Cryptography.Algorithms")
            self.assertTrue(issubclass(type(System.Security.Cryptography.MD5.Create()),
                    System.Security.Cryptography.MD5))
        else:
            self.assertEqual(type(System.Security.Cryptography.MD5.Create("MD5")),
                    System.Security.Cryptography.MD5CryptoServiceProvider)
            self.assertEqual(type(System.Security.Cryptography.MD5.Create()),
                    System.Security.Cryptography.MD5CryptoServiceProvider) 
Example #21
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_generic_method_error(self):
        if is_netcoreapp:
            clr.AddReference("System.Linq.Queryable")
        else:
            clr.AddReference('System.Core')
        from System.Linq import Queryable
        self.assertRaisesMessage(TypeError, "The type arguments for method 'First' cannot be inferred from the usage. Try specifying the type arguments explicitly.", Queryable.First, []) 
Example #22
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_enum_repr(self):
        clr.AddReference('IronPython')
        from IronPython.Runtime import ModuleOptions
        self.assertEqual(repr(ModuleOptions.WithStatement), 'IronPython.Runtime.ModuleOptions.WithStatement')
        self.assertEqual(repr(ModuleOptions.WithStatement | ModuleOptions.TrueDivision), 
                '<enum IronPython.Runtime.ModuleOptions: TrueDivision, WithStatement>') 
Example #23
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_generic_getitem(self):
        if is_netcoreapp:
            clr.AddReference("System.Collections")

        # calling __getitem__ is the same as indexing
        self.assertEqual(System.Collections.Generic.Stack.__getitem__(int), System.Collections.Generic.Stack[int])
        
        # but __getitem__ on a type takes precedence
        self.assertRaises(TypeError, System.Collections.Generic.List.__getitem__, int)
        x = System.Collections.Generic.List[int]()
        x.Add(0)
        self.assertEqual(System.Collections.Generic.List[int].__getitem__(x, 0), 0)
        
        # but we can call type.__getitem__ with the instance    
        self.assertEqual(type.__getitem__(System.Collections.Generic.List, int), System.Collections.Generic.List[int]) 
Example #24
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_kw_construction_types(self):
        if is_netcoreapp:
            clr.AddReference("System.IO.FileSystem.Watcher")

        for val in [True, False]:
            x = System.IO.FileSystemWatcher('.', EnableRaisingEvents = val)
            self.assertEqual(x.EnableRaisingEvents, val) 
Example #25
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_property_get_set(self):
        if is_netcoreapp:
            clr.AddReference("System.Drawing.Primitives")
        else:
            clr.AddReference("System.Drawing")
        from System.Drawing import Size
        
        temp = Size()
        self.assertEqual(temp.Width, 0)
        temp.Width = 5
        self.assertEqual(temp.Width, 5)
            
        for i in xrange(5):
            temp.Width = i
            self.assertEqual(temp.Width, i) 
Example #26
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_dynamic_assembly_ref(self):
        # verify we can add a reference to a dynamic assembly, and
        # then create an instance of that type
        class foo(object): pass

        clr.AddReference(foo().GetType().Assembly)
        import IronPython.NewTypes.System
        for x in dir(IronPython.NewTypes.System):
            if x.startswith('Object_'):
                t = getattr(IronPython.NewTypes.System, x)            
                x = t(foo)
                break
        else:
            # we should have found our type
            self.fail('No type found!') 
Example #27
Source File: test_ironmath.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(IronMathTest, self).setUp()

        import clr
        from System import IFormatProvider
        class myFormatProvider(IFormatProvider):
            def ToString():pass

        self.p = myFormatProvider()

        clr.AddReference(long(1).GetType().Assembly)
        self.load_iron_python_test() 
Example #28
Source File: test_clrload.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_no_names_provided(self):
        import clr
        self.assertRaises(TypeError, clr.AddReference, None)
        self.assertRaises(TypeError, clr.AddReferenceToFile, None)
        self.assertRaises(TypeError, clr.AddReferenceByName, None)
        self.assertRaises(TypeError, clr.AddReferenceByPartialName, None)
        self.assertRaises(ValueError, clr.AddReference)
        self.assertRaises(ValueError, clr.AddReferenceToFile)
        self.assertRaises(ValueError, clr.AddReferenceByName)
        self.assertRaises(ValueError, clr.AddReferenceByPartialName)

    #TODO: @skip("multiple_execute") 
Example #29
Source File: test_regressions.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_cp23545(self):
        import clr
        clr.AddReference("rowantest.defaultmemberscs")
        from Merlin.Testing.DefaultMemberSample import ClassWithDefaultField
        self.assertEqual(repr(ClassWithDefaultField.Field),
                "<field# Field on ClassWithDefaultField>")
        try:
            ClassWithDefaultField.Field = 20
        except ValueError as e:
            self.assertEqual(e.args[0],
                    "assignment to instance field w/o instance")
        self.assertEqual(ClassWithDefaultField().Field, 10) 
Example #30
Source File: ipunittest.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _add_reference_to_dlr_core():
    if is_cli:
        clr.AddReference("System.Core")