Ejemplo n.º 1
0
    def __setattr__(self, key, value):
        try:
            _type = self.get_type(key)
        except AttributeError:
            raise AttributeError(f"{key} is not a valid field of {self.db_name}")

        if not self.assignment_types_are_equal(_type, value):
            raise Exception(f"Trying to assign incorrect type to {key}")

        default_arguments = (self.data, getattr(self.api, key.upper()))

        error = None
        if _type == self.api.ADK_FIELD_TYPE.eChar:
            error = self.api.AdkSetStr(*default_arguments, String(f"{value}"))[0]
        elif _type == self.api.ADK_FIELD_TYPE.eDouble:
            error = self.api.AdkSetDouble(*default_arguments, Double(value))
        elif _type == self.api.ADK_FIELD_TYPE.eBool:
            error = self.api.AdkSetBool(*default_arguments, Boolean(value))
        elif _type == self.api.ADK_FIELD_TYPE.eDate:
            error = self.api.AdkSetDate(*default_arguments, self.to_date(value))

        if error and error.lRc != self.api.ADKE_OK:
            error_message = self.api.AdkGetErrorText(
                error, self.api.ADK_ERROR_TEXT_TYPE.elRc
            )
            raise Exception(error_message)
Ejemplo n.º 2
0
def test_correct_overload_selection():
    """Test correct overloading selection for common types."""
    from System import (String, Double, Single,
                        Int16, Int32, Int64)
    from System import Math

    substr = String("substring")
    assert substr.Substring(2) == substr.Substring.__overloads__[Int32](
        Int32(2))
    assert substr.Substring(2, 3) == substr.Substring.__overloads__[Int32, Int32](
        Int32(2), Int32(3))

    for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64],
                                     [1.0, 1.0, 1, 1, 1],
                                     [2.0, 0.5, 2, 0, -1]):
        assert Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(value1))
        assert Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(value1))
        assert Math.Max(atype(value1),
                        atype(value2)) == Math.Max.__overloads__[atype, atype](
            atype(value1), atype(value2))
        assert Math.Max(atype(value1),
                        value2) == Math.Max.__overloads__[atype, atype](
            atype(value1), atype(value2))

    clr.AddReference("System.Runtime.InteropServices")
    from System.Runtime.InteropServices import GCHandle, GCHandleType
    from System import Array, Byte
    cs_array = Array.CreateInstance(Byte, 1000)
    handler = GCHandle.Alloc(cs_array, GCHandleType.Pinned)
Ejemplo n.º 3
0
def print_strings(is_64_bits=False):

    strings = []

    print '[+] Importing System.String'
    import clr
    clr.AddReference('System')
    from System import String
    
    clr.AddReference('ObjectUtils')
    from ObjectUtils import Objects, Heap
    
    test_str = String('DEADBEEF')
    test_str_ptr    = Objects.GetObjectAddress(test_str)
    test_str_mt     = Objects.GetMTAddress(test_str_ptr)
    test_str_type   = Objects.GetTypeByName('System.String')
    
    for heap in ishtar.MANAGED_HEAPS:
        print 'Parsing heap: {2}; {0} - {1}'.format(*heap)
        
        heap_start = heap[0]
        heap_end = heap[1]
        heap_name = heap[2]
        
        if is_64_bits:
            strings.extend(Heap.FindObjectsByMTAddress64(heap_start, heap_end, test_str_mt, test_str_type))
        else:
            strings.extend(Heap.FindObjectsByMTAddress32(heap_start, heap_end, test_str_mt, test_str_type))
        
        
    print '[+] Done.'
    return strings
Ejemplo n.º 4
0
def CalculateMassPrecision(rawFile, scanNumber: int):

    # Get the scan from the RAW file
    scan = Scan.FromFile(rawFile, scanNumber)

    # Get the scan event and from the scan event get the analyzer type for this scan
    scanEvent = rawFile.GetScanEventForScanNumber(scanNumber)

    scanFilter = rawFile.GetFilterForScanNumber(scanNumber)

    print(scanFilter.MassAnalyzer)
    print(scanEvent)

    # Get the trailer extra data to get the ion time for this file
    logEntry = rawFile.GetTrailerExtraInformation(scanNumber)

    print(logEntry.Labels)

    trailerHeadings = List[String]()
    trailerValues = List[String]()
    for i in range(logEntry.Length):

        trailerHeadings.Add(String(logEntry.Labels[i]))
        trailerValues.Add(String(logEntry.Values[i]))

    # create the mass precision estimate object
    precisionEstimate = PrecisionEstimate()

    # Get the ion time from the trailer extra data values
    ionTime = precisionEstimate.GetIonTime(scanFilter.MassAnalyzer, scan,
                                           trailerHeadings, trailerValues)

    # Calculate the mass precision for the scan
    listResults = precisionEstimate.GetMassPrecisionEstimate(
        scan, scanFilter.MassAnalyzer, ionTime,
        rawFile.RunHeader.MassResolution)

    # Output the mass precision results
    if len(listResults) > 0:

        print("Mass Precision Results:")

        for result in listResults:

            print("Mass {}, mmu = {}, ppm = {}".format(
                result.Mass, result.MassAccuracyInMmu,
                result.MassAccuracyInPpm))
Ejemplo n.º 5
0
 def run_thread():
     for i in range(10):
         time.sleep(0.1)
         dprint("thread %s %d" % (thread.get_ident(), i))
         mstr = String("thread %s %d" % (thread.get_ident(), i))
         pstr = mstr.ToString()
         done.append(None)
         dprint("thread %s %d done" % (thread.get_ident(), i))
Ejemplo n.º 6
0
    def test_isinstance(self):
        from System import Object
        from System import String

        a = [str(x) for x in range(0, 1000)]
        b = [String(x) for x in a]

        for x in a:
            self.assertFalse(isinstance(x, Object))
            self.assertFalse(isinstance(x, String))

        for x in b:
            self.assertTrue(isinstance(x, Object))
            self.assertTrue(isinstance(x, String))
Ejemplo n.º 7
0
    def test_pythonnet(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")
        if sys.platform.startswith("win"):
            from src.ensae_teaching_cs.pythonnet import clr
            from System import String
            s = String("example")
            x = s.Replace("e", "j")
            assert "jxamplj" == x

            from System.Collections.Generic import Dictionary
            d = Dictionary[String, String]()
            d["un"] = "1"
            assert d.Count == 1
Ejemplo n.º 8
0
    def __getattr__(self, key):
        try:
            _type = self.get_type(key)
        except AttributeError:
            raise AttributeError(f"{key} is not a valid field of {self.db_name}")

        default_arguments = (self.data, getattr(self.api, key.upper()))

        if _type == self.api.ADK_FIELD_TYPE.eChar:
            return self.api.AdkGetStr(*default_arguments, String(""))[1]
        elif _type == self.api.ADK_FIELD_TYPE.eDouble:
            return self.api.AdkGetDouble(*default_arguments, Double(0.0))[1]
        elif _type == self.api.ADK_FIELD_TYPE.eBool:
            return self.api.AdkGetBool(*default_arguments, Boolean(0))[1]
        elif _type == self.api.ADK_FIELD_TYPE.eDate:
            return self.api.AdkGetDate(*default_arguments, DateTime())[1]
Ejemplo n.º 9
0
    def testCorrectOverloadSelection(self):
        """
        Test correct overloading selection for common types.
        """
        from System.Drawing import Font

        from System import (String, Double, Single, Int16, Int32, Int64)
        from System import Math

        substr = String("substring")
        self.assertTrue(
            substr.Substring(2) == substr.Substring.__overloads__[Int32](Int32(
                2)))
        self.assertTrue(
            substr.Substring(2, 3) == substr.Substring.__overloads__[
                Int32, Int32](Int32(2), Int32(3)))

        for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64],
                                         [1.0, 1.0, 1, 1, 1],
                                         [2.0, 0.5, 2, 0, -1]):
            self.assertTrue(
                Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(
                    value1)))
            self.assertTrue(
                Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(
                    value1)))
            self.assertTrue(
                Math.Max(atype(value1), atype(value2)) ==
                Math.Max.__overloads__[atype,
                                       atype](atype(value1), atype(value2)))
            if (atype is Int64) and six.PY2:
                value2 = long(value2)
            self.assertTrue(
                Math.Max(atype(value1), value2) == Math.Max.__overloads__[
                    atype, atype](atype(value1), atype(value2)))

        clr.AddReference("System.Runtime.InteropServices")
        from System.Runtime.InteropServices import GCHandle, GCHandleType
        from System import Array, Byte
        CSArray = Array.CreateInstance(Byte, 1000)
        handler = GCHandle.Alloc(CSArray, GCHandleType.Pinned)
Ejemplo n.º 10
0
def onClick(sender, event):
    print('Ouch! ' + __name__)


button.Click += onClick

clr.AddReference("DLT698_45.OOP")

from DLT698_45.OOP import *
from DLT698_45.OOP.DataType import DT_OAD, DT_OI, DT_LONG_UNSIGNED, DT_UNSIGNED
from DLT698_45.OOP.DataType import DT_Data, DT_OCTET_STRING
#from DLT698_45.OOP.APDUType import *
from DLT698_45.OOP.Frame import *

HData_remain = DT_OCTET_STRING('')
value = String("68170043050100000000001026F605010060120200001085166666")

frame1 = OOPFrame(DT_OCTET_STRING(value), HData_remain)

if frame1 != None:
    str = frame1.HValue
    print(str)
frame1.A.SA.Addr = '000000000002'
frame1.A.SA.AddrLogic = DT_UNSIGNED(System.Byte(1))  #DT_UNSIGNED('1')
frame1.A.CA = 16
oad = DT_OAD(DT_OCTET_STRING('60130200'))

frame1.UserDataRegion.UserData.APDUGetRequest.OAD = oad
frame1.UserDataRegion.UserData.APDUGetRequest.PIID.ServiceID = 1
str = frame1.HValue
print(str)
def test_pythonnetworks():
    import clr
    clr.AddReference("System")
    from System import String
    s = String("teststring")
    assert "teststring" == str(s)
Ejemplo n.º 12
0
# Have fun! ;-)
#

import msvcrt
import clr
import time
pltlayer = clr.AddReference("PLTLayer")

from System import String, Int32
from System.Collections.Generic import List

# variables/constants
sleepsecslong = 1.5
sleepsecsshort = 0.5

p = String("Welcome to PLTLayer Python Savi 700 Disco"
           )  # test that Python for .NET is working
print(p)

print(pltlayer.FullName)  # test we have the PLTLayer.dll Assembly loaded

from Plantronics.EZ.API import PLTLayer  # import the PLTLayer class

plt = PLTLayer.Instance  # get the PLYLayer singleton instance


# define an event handler for all Plantronics events:
def handler(source, args):
    print('PltEvent Occured! EventType=', args.EventType, '(',
          args.EventTypeStr, ')')
    if args.MyParams is not None:
        for item in args.MyParams:
Ejemplo n.º 13
0
clr.AddReference("C:\\Windows\\Microsoft.NET\\assembly\\GAC_64\\Newport.DLS.CommandInterface\\v4.0_1.0.0.4__90ac4f829985d2bf\\Newport.DLS.CommandInterface.dll")

from CommandInterfaceDLS import *
from System import String

# COM port
instrument="COM3"

# Create an instance DLS interface
myDLS = DLS()

# Open a socket
result = myDLS.OpenInstrument(instrument)

if result==0:
    print('Success')
else: 
    print('Fail')
    
# Dummy arguments of the expected type 
# https://stackoverflow.com/questions/54692267/python-net-call-c-sharp-method-which-has-a-return-value-and-an-out-parameter
dummy_out0 = String('')
dummy_out1 = String('')

# Call DLS functions. Here, VE is used.
result=myDLS.VE(dummy_out0,dummy_out1)

print("version:",result)

# Close DLS connection   
myDLS.CloseInstrument()
)

from CommandInterfaceDLS import *
from System import String, Double

# COM port
instrument = "COM3"

# Create an instance DLS interface
myDLS = DLS()

# Open a socket
result = myDLS.OpenInstrument(instrument)

if result == 0:
    print('Success')
else:
    print('Fail')

# Dummy arguments of the expected type
# https://stackoverflow.com/questions/54692267/python-net-call-c-sharp-method-which-has-a-return-value-and-an-out-parameter
dummy_out0 = Double(0.)
dummy_out1 = String('')

# Call DLS functions. Here, VE is used.
result = myDLS.TP(dummy_out0, dummy_out1)

print("current position:", result)

# Close DLS connection
myDLS.CloseInstrument()
Ejemplo n.º 15
0
# Changed by: Lewis Collins
#   Changes:
#     - Initial version
# ********************************************************************************
#
# Have fun! ;-)
#

import msvcrt
import clr
import time
pltlayer = clr.AddReference("PLTLayer")

from System import String, Int32
from System.Collections.Generic import List
p = String("Welcome to PLTLayer test")  # test that .NET is working
print(p)

print(pltlayer.FullName)

from Plantronics.EZ.API import PLTLayer, PltEventType

MY_APP_NAME = "PLTLayerPythonTest"


# 5. Handle events received from Plantronics
#
# This event handler method is called by PLTLayer whenever a
# Plantronics event occurs, e.g. device events, call state events etc.
#
# By examining the "args.EventType" and "args.MyParams" parameters, your
Ejemplo n.º 16
0
#   Changes:
#     - Initial version, demonstrates monitoring of Call State and Headset State change events
# ********************************************************************************
#
# Have fun! ;-)
#

import msvcrt
import clr
import time
clr.AddReference('System.Collections')
hubsdkconnector = clr.AddReference("ResilientPLTDemo")

from System import String, Int32
from System.Collections.Generic import List
p = String(
    "Welcome to ResilientPLTDemoPythonTest")  # test that .NET is working
print(p)

print(hubsdkconnector.FullName)

from ResilientPLTDemo import HubSDKConnector

MY_APP_NAME = "ResilientPLTDemoPythonTest"


def _hubSDK_SDKError(sender, args):
    print("_hubSDK_SDKError:")
    print("Event Type: ", args.EventType, ", Message: ", args.msg, "\r\n")


def _hubSDK_SDKInfo(sender, args):