class class1(object): clr.AddReferenceToFile('Dapper.dll') import Dapper clr.ImportExtensions(Dapper) from Dapper import DynamicParameters, SqlMapper clr.AddReferenceToFile('MySql.Data.dll') import MySql.Data clr.AddReferenceToFile( 'App.dll' ) #custom .NET assembly used for when IronPython doesn't fit the need. import App.Core.Models as Models #get our "dumb" model objects from the projects assembly. cn = MySql.Data.MySqlClient.MySqlConnection("Server=localhost;Database=northwinddb;Uid=springqa;Pwd=springqa;" \ "Convert Zero Datetime=true;Allow Zero Datetime=false") cn.Open() params = DynamicParameters() params.Add('@in_CustomerId', 'ALFKI') procName = 'GetCustomerById' customer = cn.Query[Models.Customer]( procName, params, commandType=CommandType.StoredProcedure)[0] cn.Close() print customer.CustomerId print customer.ContactName print customer.ContactTitle
def take_snapshot(): """Use the DesignPerformanceViewer libraries to create a ModelSnapshot object """ clr.AddReferenceToFile('DpvApplication.dll') clr.AddReferenceToFile('DesignPerformanceViewer.dll') from DesignPerformanceViewer import DpvApplication dpv = DpvApplication.DpvApplication() doc = get_revit().ActiveUIDocument.Document return dpv.TakeSnapshot(doc)
def add_biodotnet_reference(dll_name): "Adds a Bio dll reference to the clr so that its contents can be imported." # An exception will be thrown if we're debugging in VS from the Python development dir, instead # of the standard non-dev method of running from the bin\Debug dir or an installation dir. If # we are debugging in VS, we just need to add bin\Debug to the path. try: clr.AddReferenceToFile(dll_name + ".dll") except: sys.path += [_solution_path + r"..\..\Build\Binaries\Debug"] print _solution_path clr.AddReferenceToFile(dll_name + ".dll")
def test_addreferencetofile_verification(): tmp = testpath.temporary_dir sys.path.append(tmp) code1 = """ using System; public class test1{ public static string Test1(){ test2 t2 = new test2(); return t2.DoSomething(); } public static string Test2(){ return "test1.test2"; } } """ code2 = """ using System; public class test2{ public string DoSomething(){ return "hello world"; } } """ test1_dll_along_with_ipy = path_combine(sys.prefix, 'test1.dll') # this dll is need for peverify # delete the old test1.dll if exists delete_files(test1_dll_along_with_ipy) test1_cs, test1_dll = path_combine(tmp, 'test1.cs'), path_combine(tmp, 'test1.dll') test2_cs, test2_dll = path_combine(tmp, 'test2.cs'), path_combine(tmp, 'test2.dll') write_to_file(test1_cs, code1) write_to_file(test2_cs, code2) AreEqual(run_csc("/nologo /target:library /out:"+ test2_dll + ' ' + test2_cs), 0) AreEqual(run_csc("/nologo /target:library /r:" + test2_dll + " /out:" + test1_dll + ' ' + test1_cs), 0) clr.AddReferenceToFile('test1') AreEqual(len([x for x in clr.References if x.FullName.startswith("test1")]), 1) # test 2 shouldn't be loaded yet... AreEqual(len([x for x in clr.References if x.FullName.startswith("test2")]), 0) import test1 # should create test1 (even though we're a top-level namespace) a = test1() AreEqual(a.Test2(), 'test1.test2') # should load test2 from path AreEqual(a.Test1(), 'hello world') AreEqual(len([x for x in clr.References if x.FullName.startswith("test2")]), 0) # this is to make peverify happy, apparently snippetx.dll referenced to test1 filecopy(test1_dll, test1_dll_along_with_ipy)
def parse(self, response): print("-----response.url: ", response.url) filename = response.url.split("/")[-2] + '.html' print("-----filename: ", filename) clr.AddReferenceToFile("./NetCrawler.dll") from NetCrawler import Test1 print(NetCrawler.Add(1 + 1), "********************") print(clr.red.bold('Hello world!'))
def __init__(self, title, url): clr.AddReferenceByPartialName("PresentationFramework") clr.AddReferenceByPartialName("PresentationCore") clr.AddReferenceToFile('CefSharp.Wpf.dll') import System.Windows from CefSharp.Wpf import ChromiumWebBrowser self.form = System.Windows.Window() browser = ChromiumWebBrowser() browser.Address = url self.form.Content = browser self.form.Title = title
# edm_init.py - sets up the IronPython environment ready for scripting # the edm control software. import clr import sys from System.IO import Path # Import the edm control software assemblies into IronPython sys.path.append(Path.GetFullPath("..\\EDMHardwareControl\\bin\\EDM\\")) clr.AddReferenceToFile("EDMHardwareControl.exe") clr.AddReferenceToFile("DAQ.dll") # Load some system assemblies that we'll need clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms") clr.AddReference("System.Xml") # code for IronPython remoting problem workaround class typedproxy(object): __slots__ = ['obj', 'proxyType'] def __init__(self, obj, proxyType): self.obj = obj self.proxyType = proxyType def __getattribute__(self, attr): proxyType = object.__getattribute__(self, 'proxyType') obj = object.__getattribute__(self, 'obj') return getattr(proxyType, attr).__get__(obj, proxyType)
"""An IronPython version of the Tentacle editor """ import sys import clr clr.AddReference("System") clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms") clr.AddReferenceToFile("./SinkWorld.dll") from SinkWorld import * from Pentacle import uiBase, Pentacle from System import * from System.Drawing import * from System.Text import * from System.Windows.Forms import * PrototypeRegistry.Init() RegisteredDecorations.Init() RegisteredLexers.Init() def BytesFromString(s): l = len(s) pd = Array.CreateInstance(Byte, l) for i in range(l): pd[i] = ord(s[i])
try: programfilesPath = os.environ['PROGRAMFILES'] masterApiBasePath = os.path.join(programfilesPath, r'Nordic Semiconductor\Master Emulator') dirsandfiles = os.listdir(masterApiBasePath) dirs = [] for element in dirsandfiles: if os.path.isdir(os.path.join(masterApiBasePath, element)): dirs.append(element) if len(dirs) == 0: raise Exception('Master Emulator directory not found.') dirs.sort() masterApiPath = os.path.join(masterApiBasePath, dirs[-1]) print masterApiPath sys.path.append(masterApiPath) clr.AddReferenceToFile("MasterEmulator.dll") except Exception, e: raise Exception("Cannot load MasterEmulator.dll") from dfu.ble_dfu import BleDfu def main(): parser = argparse.ArgumentParser( description='Send hex file over-the-air via BLE') parser.add_argument('--file', '-f', type=str, required=True, dest='file', help='Filename of Hex file.')
from __future__ import division import clr clr.AddReferenceToFile("OpenTK.dll") clr.AddReference("System.Drawing") import math import random import time import array from System import Array, Byte, Int32 from System.Drawing import Bitmap, Rectangle, Color from OpenTK import * from OpenTK.Graphics import * from OpenTK.Graphics.OpenGL import * from OpenTK.Input import * import threading class BlackProjectorWindow(GameWindow): def __new__(self, controller): self.controller = controller # try to use a second display (projector) display = DisplayDevice.GetDisplay(DisplayIndex.Second) if display is not None: display_width = 1280
self.proxyType = proxyType def __getattribute__(self, attr): proxyType = object.__getattribute__(self, 'proxyType') obj = object.__getattribute__(self, 'obj') return getattr(proxyType, attr).__get__(obj, proxyType) # Import the edm control software assemblies into IronPython #sys.path.append(Path.GetFullPath("C:\\Control Programs\\EDMSuite\\ScanMaster\\bin\\Decelerator\\")) #clr.AddReferenceToFile("ScanMaster.exe") sys.path.append( Path.GetFullPath("C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\")) clr.AddReferenceToFile("MOTMaster.exe") sys.path.append( Path.GetFullPath( "C:\\ControlPrograms\\EDMSuite\\MoleculeMOTHardwareControl\\bin\\CaF\\" )) clr.AddReferenceToFile("MoleculeMOTHardwareControl.exe") clr.AddReferenceToFile("DAQ.dll") clr.AddReferenceToFile("SharedCode.dll") # Load some system assemblies that we'll need clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms") clr.AddReference("System.Xml") # create connections to the control programs
# source code in any fashion, you are agreeing to be bound by the terms of # the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ############################################################################## import clr clr.AddReference("System.Windows.Forms") clr.AddReference("System.Drawing") from System.Drawing import Icon, Size from System.Windows.Forms import * clr.AddReferenceToFile("MapPointWebServiceProject.dll") from MapPointWebServiceProject import MapPointWebServiceHelper class FormV7(Form): def __init__(self): self.Text = "(" + __file__ + ")" # Create TableLayoutPanel and FlowLayoutPanel self._tableLayoutPanel1 = TableLayoutPanel(ColumnCount=1, Dock=DockStyle.Fill, RowCount=2) self._flowLayoutPanel1 = FlowLayoutPanel(Dock=DockStyle.Fill) # Create Controls self._pictureBox1 = PictureBox(Dock=DockStyle.Fill)
#// This code is licensed under the Microsoft Public License. #// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF #// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY #// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR #// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. #// ***************************************************************** import clr import sys import time # Adding the dll reference will throw an exception if we're debugging in VS from the Python # development dir, instead of the standard non-dev method of running from the bin\Debug dir or an # installation dir. try: clr.AddReferenceToFile("MBF.IronPython.dll") except: pass from MBFIronPython.Algorithms import * from MBFIronPython.IO import * from MBFIronPython.Util import * from MBFIronPython.Web import * from MBFIronPython.SequenceManipulationApplications import * from MBFIronPython.ListOr import * from MBFIronPython.MBFDemo import * again = "y" while "yY".find(again[0]) != -1: option = ""
import clr clr.AddReferenceToFile('MooseXLSReports') import MooseXLSReports import System from System import DateTime import reportoutput def build_ipy_writer(filename): xls_report = MooseXLSReports.XlsReport(filename) writer = reportoutput.ReportWriter(xls_report) return writer class ReportWriter(): def __init__(self, report_accessor): self.accessor = report_accessor def close(self): self.accessor.Dispose() def converttoDateTime(self, date, hours): day = DateTime(date.year, date.month, date.day, hours.hour, hours.minute, hours.second) return day def write(self, hours): if self.is_start_time_empty(hours): day = self.converttoDateTime(hours.date, hours.start) self.accessor.WriteStartTime(day)
# # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # [email protected]. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### # Task 1 import clr clr.AddReferenceToFile("csextend.dll") import Simple dir(Simple) s = Simple(10) print s # Task 2 import clr clr.AddReferenceToFile("csextend.dll") import Simple dir(Simple) s = Simple(10) for i in s: print i
# terms governing use, modification, and redistribution, is contained in * # the files COPYING and Copyright.html. COPYING can be found at the root * # of the source code distribution tree; Copyright.html can be found at the * # root level of an installed copy of the electronic HDF5 document set and * # is linked from the top-level documents page. It can also be found at * # http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * # access to either file, you may request a copy from [email protected]. * # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ # This example writes data to the HDF5 file. # Data conversion is performed during write operation. #=============================================================================== import clr clr.AddReferenceToFile('HDF5DotNet.dll') import HDF5DotNet from HDF5DotNet import * #=============================================================================== import System from System import Array, Int32, Int64 #=============================================================================== print '\nInitializing HDF5 library\n' status = H5.Open() shape = Array[Int64]((5, 6)) data = Array.CreateInstance(Int32, shape)
import ctypes # a = ctypes.cdll.LoadLibrary("libnodave.net.dll") # a.Read() import clr import System import sys clr.AddReferenceToFile("ClassLibrary1.dll") print(dir()) from ClassLibrary1 import sim print(dir()) client = sim() print(client.__str__()) a = client.Read('IP', 132, 0, 'int', 1, '192.168.18.17', 0) print(a)
import sys import unittest import clr import os sys.path.Add(os.getcwd() + '\\' + '..\\bin') # solution bin directory clr.AddReferenceToFile('Foo.dll') from Foo import * castle = PythonWindsor() #b = Bar() b = castle.GetBar() print('Hello world') print(b.Dork())
__author__ = 'DreTaX' import clr import sys """ This method has to be uncommented when you will use the plugin on your live server. """ #clr.AddReferenceByPartialName("Fougerite") """ The below method in the place where our Fougerite.dll is. This will define our IDE where to look for the functions In python we use double \\ when giving paths. Note: sys.path and clr.AddReferenceToFile is not required when running the plugin on a live server. When ever you are planning to try the plugin, please COMMENT these two lines. """ sys.path.Add("d:\\Python33\\Fougerite\\") """ As above, we have given our IDE the path where to look for the libraries. Now we define which dlls do we need. """ clr.AddReferenceToFile("Fougerite.dll") #This might show errors in your IDE, if it does, just hover your mouse on the red lamp and click to ignore reference. import Fougerite
import logging import argparse import fileinput import Interop.PTSControl as PTSControl import clr import System # to be able to find PTS interop assembly and ptsprojects module sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) import ptsprojects.ptstypes as ptstypes # load the PTS interop assembly clr.AddReferenceToFile("Interop.PTSControl.dll") log = logging.debug class PyPTSControl: """PTS control interface. This class contains cherry picked functionality from ptscontrol.PyPTS """ def __init__(self): self.pts = None # This is done to have valid pts in case client does not restart_pts # and uses other methods. Normally though, the client should
ghenv.Component.SubCategory = "1 || IO" try: ghenv.Component.AdditionalHelpFromDocStrings = "3" except: pass import scriptcontext as sc import os import sys import clr ##################Envimet INX#################### from System.Collections.Generic import * try: user_path = os.getenv("APPDATA") sys.path.append(os.path.join(user_path, "Morpho")) clr.AddReferenceToFile("MorphoReader.dll") clr.AddReferenceToFile("MorphoRhino.dll") from MorphoReader import GridOutput, BuildingOutput, Direction, Facade from MorphoRhino.RhinoAdapter import RhinoConvert except ImportError as e: raise ImportError( "\nFailed to import Morpho: {0}\n\nCheck your 'Morpho' folder in {1}". format(e, os.getenv("APPDATA"))) ################################################ ghenv.Component.Message = "1.0.1 2.5D/3D" def get_file_path(path): file, extension = os.path.splitext(path)
import clr clr.AddReferenceToFile("QuickGraph.Heap") import QuickGraph.Heap from QuickGraph.Heap import GcTypeHeap g = GcTypeHeap.Load("heap.xml", "eeheap.txt") g = g.Merge(20)
import clr clr.AddReference('System.Drawing') clr.AddReferenceToFile('CommonRules.dll') import System from System.Drawing import Color from System.Text.RegularExpressions import Regex from stej.Tools.UdpLogViewer.Core import ProcessingResult as PR from stej.Tools.UdpLogViewer.CommonRules import LogItemProcessor as LIP clr.AddReferenceToFile('Growl.Connector.dll') clr.AddReferenceToFile('Growl.CoreLibrary.dll') import Growl.Connector class ToGrowl(LIP): def __new__(cls, regex, connector, condition=None, regexOnLogger=False): inst = LIP.__new__(cls, regex, None, None, regexOnLogger) inst.connector = connector inst.condition = condition inst.Name = "To Growl" inst.DetailsInfo = "%s - %s" % (inst.Name, regex) return inst def Process(self, logItem, parameters): if self.Matches(logItem) and (self.condition == None or self.condition(logItem, parameters)): notification = Growl.Connector.Notification( 'UdpLogViewer', 'lv', System.DateTime.Now.Ticks.ToString(), 'Log item arrived', logItem.Message) notification.Priority = Growl.Connector.Priority.Emergency
import unittest import deviceAPIUtils import clr import json clr.AddReferenceToFileAndPath("DeviceDLL/DeviceDLL/bin/Debug/DeviceDLL.dll") clr.AddReferenceToFile("Newtonsoft.Json.dll") clr.AddReference("System") import api as devapi import System from System.Collections.Generic import List class deviceAPIUtilsTest(unittest.TestCase): def testCanBrightenNotCLR(self): self.assertFalse(deviceAPIUtils.canBrighten(10)) self.assertFalse(deviceAPIUtils.canBrighten('a string')) somePythonTypeObject = [ 'this is', 'a list of python strings', 'not a .NET class' ] self.assertFalse(deviceAPIUtils.canBrighten(somePythonTypeObject)) def testCanBrightenIsEnableable(self): someIEnableable = devapi.CeilingFan(None, None) self.assertFalse(deviceAPIUtils.canBrighten(someIEnableable)) def testCanBrightenWrongIReadable(self): wrongGenericIReadable = devapi.Thermostat(None, None) self.assertFalse(deviceAPIUtils.canBrighten(wrongGenericIReadable)) def testCanBrightenIsLight(self):
sys.path.append(r'..\..\PyTES') from PyTES import * sys.path.append(r'c:\Program Files\Python 2.7.5\Lib\site-packages') # path to common files sys.path.append(r'c:\python_programs\mics2') import watlowF4ipy import clr clr.AddReference("System") from System import * clr.AddReferenceToFile("Config.dll") import Config class WaitForDisconnectedEventState(IScriptExecState): def __init__(self, key, data): self.key = key self.data = data def doEntryAction(self, sm): sm.ICD.breakLink() return def processEvent(self, sm, ev): return type(ev)==DisconnectedEvent class sicdCalScript(PyScript):
def test_assembly_resolve_isolation(self): import clr, os clr.AddReference("IronPython") clr.AddReference("Microsoft.Scripting") from IronPython.Hosting import Python from Microsoft.Scripting import SourceCodeKind tmp = self.temporary_dir tmp1 = os.path.join(tmp, 'resolve1') tmp2 = os.path.join(tmp, 'resolve2') if not os.path.exists(tmp1): os.mkdir(tmp1) if not os.path.exists(tmp2): os.mkdir(tmp2) code1a = """ using System; public class ResolveTestA { public static string Test() { ResolveTestB test = new ResolveTestB(); return test.DoSomething(); } } """ code1b = """ using System; public class ResolveTestB { public string DoSomething() { return "resolve test 1"; } } """ code2a = """ using System; public class ResolveTestA { public static string Test() { ResolveTestB test = new ResolveTestB(); return test.DoSomething(); } } """ code2b = """ using System; public class ResolveTestB { public string DoSomething() { return "resolve test 2"; } } """ script_code = """import clr clr.AddReferenceToFile("ResolveTestA") from ResolveTestA import Test result = Test() """ test1a_cs, test1a_dll, test1b_cs, test1b_dll = map( lambda x: os.path.join(tmp1, x), ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll'] ) test2a_cs, test2a_dll, test2b_cs, test2b_dll = map( lambda x: os.path.join(tmp2, x), ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll'] ) self.write_to_file(test1a_cs, code1a) self.write_to_file(test1b_cs, code1b) self.write_to_file(test2a_cs, code2a) self.write_to_file(test2b_cs, code2b) self.assertEqual(self.run_csc("/nologo /target:library /out:" + test1b_dll + ' ' + test1b_cs), 0) self.assertEqual(self.run_csc("/nologo /target:library /r:" + test1b_dll + " /out:" + test1a_dll + ' ' + test1a_cs), 0) self.assertEqual(self.run_csc("/nologo /target:library /out:" + test2b_dll + ' ' + test2b_cs), 0) self.assertEqual(self.run_csc("/nologo /target:library /r:" + test2b_dll + " /out:" + test2a_dll + ' ' + test2a_cs), 0) engine1 = Python.CreateEngine() paths1 = engine1.GetSearchPaths() paths1.Add(tmp1) engine1.SetSearchPaths(paths1) scope1 = engine1.CreateScope() script1 = engine1.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements) script1.Execute(scope1) result1 = scope1.GetVariable("result") self.assertEqual(result1, "resolve test 1") engine2 = Python.CreateEngine() paths2 = engine2.GetSearchPaths() paths2.Add(tmp2) engine2.SetSearchPaths(paths2) scope2 = engine2.CreateScope() script2 = engine2.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements) script2.Execute(scope2) result2 = scope2.GetVariable("result") self.assertEqual(result2, "resolve test 2")
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # [email protected]. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### import clr clr.AddReferenceToFile("vbextend.dll") import Simple a = Simple(10) def X(i): return i + 100 a.Transform(X)
""" How to make and output Kangaroo2 goals. - Author: Anders Holden Deleuran Github: github.com/AndersDeleuran/KangarooGHPython Updated: 150429 """ import clr clr.AddReferenceToFile("KangarooSolver.dll") import KangarooSolver as ks import Rhino as rc from System.Collections.Generic import List # Convert Python points list to .NET type list ptsList = List[rc.Geometry.Point3d](Pts) # Make the OnPlane goal and output to GH P = ks.Goals.OnPlane(ptsList, rc.Geometry.Plane.WorldXY, 1.0)
# sm_init.py - sets up the IronPython environment ready for scripting # scan master. import clr import sys from System.IO import Path # Import the edm control software assemblies into IronPython sys.path.append(Path.GetFullPath("..\\ScanMaster\\bin\\EDM\\")) clr.AddReferenceToFile("ScanMaster.exe") sys.path.append(Path.GetFullPath("..\\EDMBlockHead\\bin\\EDM\\")) clr.AddReferenceToFile("EDMBlockHead.exe") sys.path.append(Path.GetFullPath("..\\EDMHardwareControl\\bin\\EDM\\")) clr.AddReferenceToFile("EDMHardwareControl.exe") clr.AddReferenceToFile("DAQ.dll") clr.AddReferenceToFile("SharedCode.dll") sys.path.append(Path.GetFullPath("..\\SirCachealot\\bin\\EDM\\")) clr.AddReferenceToFile("SirCachealot.exe") # Load some system assemblies that we'll need clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms") clr.AddReference("System.Xml") # code for IronPython remoting problem workaround class typedproxy(object): __slots__ = ['obj', 'proxyType'] def __init__(self, obj, proxyType): self.obj = obj
ghenv.Component.Category = "Morpho" ghenv.Component.SubCategory = "4 || Simulation" try: ghenv.Component.AdditionalHelpFromDocStrings = "2" except: pass import scriptcontext as sc import os import sys import clr ##################Envimet INX#################### try: user_path = os.getenv("APPDATA") sys.path.append(os.path.join(user_path, "Morpho")) clr.AddReferenceToFile("Morpho25.dll") from Morpho25.Settings import TThread, Active except ImportError as e: raise ImportError( "\nFailed to import Morpho: {0}\n\nCheck your 'Morpho' folder in {1}". format(e, os.getenv("APPDATA"))) ################################################ ghenv.Component.Message = "1.0.1 2.5D" def main(): if _active: t_thread = TThread(Active.YES)