def get_idf(self, args, request, uiApplication):
        '''
        deserializes a ModelSnapshot from the POST and then uses the DPV
        idf writer to export the ModelSnapshot as an IDF file.
        '''
        clr.AddReference('DpvApplication')
        clr.AddReference('DesignPerformanceViewer')
        from DesignPerformanceViewer.Model import ModelSnapshotImporter
        from DesignPerformanceViewer.EnergyPlusCalculation import IdfWriter
        from System.IO import StreamReader
        from System.IO import MemoryStream
        from System.Text import Encoding

        if request.HttpMethod == 'POST':
            body = request.InputStream
            encoding = request.ContentEncoding
            reader = StreamReader(body, encoding)
            snapshot_xml = reader.ReadToEnd()

            snapshot = ModelSnapshotImporter().Import(snapshot_xml)
        elif request.HttpMethod == 'GET':
            snapshot = self.take_snapshot(uiApplication)
        else:
            return (404, 'text/plain',
                    'invalid HTTP method: ' + request.HttpMethod)
        ms = MemoryStream()
        writer = IdfWriter(ms, Encoding.UTF8)
        writer.Write(snapshot)
        ms.Position = 0
        idf = StreamReader(ms, Encoding.UTF8).ReadToEnd()
        print 'idf=', idf
        return (200, 'text/plain', idf)
Exemplo n.º 2
0
def prettify_string(rough_string):
    """Return an XML string with added whitespace for legibility,
    using .NET infrastructure.

    Parameters
    ----------
    rough_string : str
        XML string
    """
    mStream = MemoryStream()
    writer = XmlTextWriter(mStream, Encoding.UTF8)
    document = XmlDocument()

    document.LoadXml(rough_string)

    writer.Formatting = Formatting.Indented

    writer.WriteStartDocument()
    document.WriteContentTo(writer)
    writer.Flush()
    mStream.Flush()

    mStream.Position = 0

    sReader = StreamReader(mStream)

    formattedXml = sReader.ReadToEnd()

    return formattedXml
Exemplo n.º 3
0
    def _dotnet_decrypt(data, key):
        """Perform decrypting of provided encrypted data.

        If 'digest' is True data must be hex digest, otherwise data should be
        encrypted bytes.

        This function is symmetrical with encrypt function.
        """
        data = Array[Byte](map(Byte, map(ord, data)))
        key = Array[Byte](map(Byte, key))
        rm = RijndaelManaged()
        dec_transform = rm.CreateDecryptor(key, Array[Byte](_vector))

        mem = MemoryStream()
        cs = CryptoStream(mem, dec_transform, CryptoStreamMode.Write)
        cs.Write(data, 0, data.Length)
        cs.FlushFinalBlock()

        mem.Position = 0
        decrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(decrypted, 0, decrypted.Length)

        cs.Close()
        utfEncoder = UTF8Encoding()
        return utfEncoder.GetString(decrypted)
Exemplo n.º 4
0
def stream_bitmap(imagebytes):
    memoryStream = MemoryStream(imagebytes)
    memoryStream.Position = 0
    image = Imaging.BitmapImage()
    image.BeginInit()
    image.StreamSource = memoryStream
    image.CacheOption = Imaging.BitmapCacheOption.OnLoad
    image.EndInit()
    return image
Exemplo n.º 5
0
    def testWeCanBindToEncodingGetString(self):
        """Check that we can bind to the Encoding.GetString method with variables."""
        
        from System.Text import Encoding
        from System.IO import MemoryStream
        myBytes = Encoding.UTF8.GetBytes('Some testing string')
        stream = MemoryStream()
        stream.Write(myBytes, 0, myBytes.Length)
        stream.Position = 0
        
        buff = System.Array.CreateInstance(System.Byte, 3)
        buff.Initialize()
        data = []
        read = 1

        while read > 0:
            read, _ = stream.Read(buff, 0, buff.Length)
            temp = Encoding.UTF8.GetString(buff, 0, read)
            data.append(temp)

        data = ''.join(data)
        self.assertEqual(data, 'Some testing string')
Exemplo n.º 6
0
    def testWeCanBindToEncodingGetString(self):
        """Check that we can bind to the Encoding.GetString method with variables."""

        from System.Text import Encoding
        from System.IO import MemoryStream
        myBytes = Encoding.UTF8.GetBytes('Some testing string')
        stream = MemoryStream()
        stream.Write(myBytes, 0, myBytes.Length)
        stream.Position = 0

        buff = System.Array.CreateInstance(System.Byte, 3)
        buff.Initialize()
        data = []
        read = 1

        while read > 0:
            read, _ = stream.Read(buff, 0, buff.Length)
            temp = Encoding.UTF8.GetString(buff, 0, read)
            data.append(temp)

        data = ''.join(data)
        self.assertEqual(data, 'Some testing string')
Exemplo n.º 7
0
def test_we_can_bind_to_encoding_get_string():
    """Check that we can bind to the Encoding.GetString method
    with variables."""
    from System.Text import Encoding
    from System.IO import MemoryStream

    my_bytes = Encoding.UTF8.GetBytes('Some testing string')
    stream = MemoryStream()
    stream.Write(my_bytes, 0, my_bytes.Length)
    stream.Position = 0

    buff = System.Array.CreateInstance(System.Byte, 3)
    buff.Initialize()
    data = []
    read = 1

    while read > 0:
        read = stream.Read(buff, 0, buff.Length)
        temp = Encoding.UTF8.GetString(buff, 0, read)
        data.append(temp)

    data = ''.join(data)
    assert data == 'Some testing string'
Exemplo n.º 8
0
Arquivo: crypto.py Projeto: delicb/tea
    def _encrypt(text, key):
        """Performs crypting of provided text using AES algorithm.

        If 'digest' is True hex_digest will be returned, otherwise bytes of
        encrypted data will be returned.

        This function is symmetrical with decrypt function.
        """
        utfEncoder = UTF8Encoding()
        bytes_text = utfEncoder.GetBytes(text)
        rm = RijndaelManaged()
        key = Array[Byte](key)
        enc_transform = rm.CreateEncryptor(key, Array[Byte](_vector))
        mem = MemoryStream()

        cs = CryptoStream(mem, enc_transform, CryptoStreamMode.Write)
        cs.Write(bytes_text, 0, len(bytes_text))
        cs.FlushFinalBlock()
        mem.Position = 0
        encrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(encrypted, 0, mem.Length)
        cs.Close()

        return ''.join(map(chr, encrypted))
Exemplo n.º 9
0
    def _dotnet_decrypt(data, key):
        """Performs decrypting of provided encrypted data.
        If 'digest' is True data must be hex digest, otherwise data should be
        encrypted bytes.

        This function is symmetrical with encrypt function.
        """
        data = Array[Byte](map(Byte, map(ord, data)))
        key = Array[Byte](map(Byte, key))
        rm = RijndaelManaged()
        dec_transform = rm.CreateDecryptor(key, Array[Byte](_vector))

        mem = MemoryStream()
        cs = CryptoStream(mem, dec_transform, CryptoStreamMode.Write)
        cs.Write(data, 0, data.Length)
        cs.FlushFinalBlock()

        mem.Position = 0
        decrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(decrypted, 0, decrypted.Length)

        cs.Close()
        utfEncoder = UTF8Encoding()
        return utfEncoder.GetString(decrypted)
Exemplo n.º 10
0
    def _dotnet_encrypt(text, key):
        """Performs crypting of provided text using AES algorithm.

        If 'digest' is True hex_digest will be returned, otherwise bytes of
        encrypted data will be returned.

        This function is symmetrical with decrypt function.
        """
        utfEncoder = UTF8Encoding()
        bytes_text = utfEncoder.GetBytes(text)
        rm = RijndaelManaged()
        key = Array[Byte](key)
        enc_transform = rm.CreateEncryptor(key, Array[Byte](_vector))
        mem = MemoryStream()

        cs = CryptoStream(mem, enc_transform, CryptoStreamMode.Write)
        cs.Write(bytes_text, 0, len(bytes_text))
        cs.FlushFinalBlock()
        mem.Position = 0
        encrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(encrypted, 0, mem.Length)
        cs.Close()

        return ''.join(map(chr, encrypted))
    def SetupFields(self, newbook, oldbook, renamefile, count):

        self.win.FindName("RenameText").Text = self.RenameText + renamefile

        if type(newbook) != FileInfo:
            #oldbook can be either a ComicBook object or a FileInfo object
            self.win.FindName("NewSeries").Content = newbook.ShadowSeries
            self.win.FindName("NewVolume").Content = newbook.ShadowVolume
            self.win.FindName("NewNumber").Content = newbook.ShadowNumber
            self.win.FindName("NewPages").Content = newbook.PageCount
            self.win.FindName("NewFileSize").Content = newbook.FileSizeAsText
            self.win.FindName(
                "NewPublishedDate"
            ).Content = newbook.MonthAsText + ", " + newbook.YearAsText
            self.win.FindName("NewAddedDate").Content = newbook.AddedTime
            self.win.FindName("NewPath").Text = newbook.FilePath
            self.win.FindName("NewScanInfo").Content = newbook.ScanInformation

            #Load the new book cover
            ncs = MemoryStream()
            ComicRack.App.GetComicThumbnail(newbook,
                                            newbook.PreferredFrontCover).Save(
                                                ncs, ImageFormat.Png)
            ncs.Position = 0
            newcover = BitmapImage()
            newcover.BeginInit()
            newcover.StreamSource = ncs
            newcover.EndInit()
            self.win.FindName("NewCover").Source = newcover
        else:
            self.win.FindName("NewSeries").Content = "Comic not in Library"
            self.win.FindName("NewVolume").Content = ""
            self.win.FindName("NewNumber").Content = ""
            self.win.FindName("NewPages").Content = ""
            self.win.FindName("NewFileSize").Content = '%.2f MB' % (
                newbook.Length / 1048576.0)  #Calculate bytes to MB
            self.win.FindName("NewPublishedDate").Content = ""
            self.win.FindName("NewAddedDate").Content = ""
            self.win.FindName("NewScanInfo").Content = ""
            self.win.FindName("NewPath").Text = newbook.FullName
            self.win.FindName("NewCover").Source = None

        #old book, possible for it to be a FileInfo object
        if type(oldbook) != FileInfo:
            self.win.FindName("OldSeries").Content = oldbook.ShadowSeries
            self.win.FindName("OldVolume").Content = oldbook.ShadowVolume
            self.win.FindName("OldNumber").Content = oldbook.ShadowNumber
            self.win.FindName("OldPages").Content = oldbook.PageCount
            self.win.FindName("OldFileSize").Content = oldbook.FileSizeAsText
            self.win.FindName(
                "OldPublishedDate"
            ).Content = oldbook.MonthAsText + ", " + oldbook.YearAsText
            self.win.FindName("OldAddedDate").Content = oldbook.AddedTime
            self.win.FindName("OldScanInfo").Content = oldbook.ScanInformation
            self.win.FindName("OldPath").Text = oldbook.FilePath

            #cover
            ocs = MemoryStream()
            ComicRack.App.GetComicThumbnail(oldbook,
                                            oldbook.PreferredFrontCover).Save(
                                                ocs, ImageFormat.Png)
            ncs.Position = 0
            oldcover = BitmapImage()
            oldcover.BeginInit()
            oldcover.StreamSource = ocs
            oldcover.EndInit()
            self.win.FindName("OldCover").Source = oldcover

        else:
            self.win.FindName("OldSeries").Content = "Comic not in Library"
            self.win.FindName("OldVolume").Content = ""
            self.win.FindName("OldNumber").Content = ""
            self.win.FindName("OldPages").Content = ""
            self.win.FindName("OldFileSize").Content = '%.2f MB' % (
                oldbook.Length / 1048576.0)  #Calculate bytes to MB
            self.win.FindName("OldPublishedDate").Content = ""
            self.win.FindName("OldAddedDate").Content = ""
            self.win.FindName("OldScanInfo").Content = ""
            self.win.FindName("OldPath").Text = oldbook.FullName
            self.win.FindName("OldCover").Source = None

        if count > 1:
            self.win.FindName("DoAll").Visibility = Visibility.Visible
            self.win.FindName(
                "DoAll"
            ).Content = "Do this for all conficts (" + str(count) + ")"
        else:
            self.win.FindName("DoAll").Visibility = Visibility.Hidden
Exemplo n.º 12
0
        print("Parsed file with {} warnings.".format(errorHandler.warnings))

    errorHandler = ErrorHandler()
    tree.Validate(errorHandler)

    if (errorHandler.warnings == 0):
        print("Validated parsed data with no warnings.")
    else:
        print("Validated parsed data with {} warnings.".format(
            errorHandler.warnings))

    input("Press enter to serialise data.")

    tree.elements.Insert(0, comment)
    ms = MemoryStream()
    stream = StreamWriter(ms, UTF8Encoding(True))
    parser.Serialise(tree, stream)
    ms.Position = 0
    sr = StreamReader(ms)
    myStr = sr.ReadToEnd()
    print(myStr)

    # output to the file
    #f = codecs.open("testFileNew.a2l", 'w+', 'utf-8')
    #f.write(myStr)
    #f.close()

    input("Press enter to close...")
else:
    print("Parsing failed!")