Represents a standard Python list object. See the documentation at http://www.python.org/doc/current/api/listObjects.html for details.
Inheritance: PySequence
        private object _ToClr(PyList pyList)
        {
            var list = new List <T>();

            foreach (PyObject item in pyList)
            {
                var _item = this.Converter.ToClr <T>(item);
                list.Add(_item);
            }
            return(list);
        }
Beispiel #2
1
 public void TestOnPyList()
 {
     PyList list = new PyList();
     list.Append(new PyString("foo"));
     list.Append(new PyString("bar"));
     list.Append(new PyString("baz"));
     List<string> result = new List<string>();
     foreach (PyObject item in list)
         result.Add(item.ToString());
     Assert.AreEqual(3, result.Count);
     Assert.AreEqual("foo", result[0]);
     Assert.AreEqual("bar", result[1]);
     Assert.AreEqual("baz", result[2]);
 }
        public PyObject _ToPython(List <T> clrObj)
        {
            var pyList = new PyList();

            foreach (var item in clrObj)
            {
                PyObject _item = this.Converter.ToPython(item);
                pyList.Append(_item);
            }
            return(pyList);
        }
 public void TestMessage()
 {
     PyList list = new PyList();
     try
     {
         PyObject junk = list[0];
     }
     catch (PythonException e)
     {
         Assert.AreEqual("IndexError : list index out of range", e.Message);
     }
 }
Beispiel #5
0
        private static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType)
        {
            var cb = GetManagedObject(tp) as ClassBase;

            if (cb == null)
            {
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);
            }

            Runtime.XIncref(args);
            using (var argsObj = new PyList(args))
            {
                if (argsObj.Length() != 1)
                {
                    return(Exceptions.RaiseTypeError("Invalid parameter count"));
                }

                PyObject arg = argsObj[0];
                PyObject otherType;
                if (checkType)
                {
                    otherType = arg;
                }
                else
                {
                    otherType = arg.GetPythonType();
                }

                if (Runtime.PyObject_TYPE(otherType.Handle) != PyCLRMetaType)
                {
                    Runtime.XIncref(Runtime.PyFalse);
                    return(Runtime.PyFalse);
                }

                var otherCb = GetManagedObject(otherType.Handle) as ClassBase;
                if (otherCb == null)
                {
                    Runtime.XIncref(Runtime.PyFalse);
                    return(Runtime.PyFalse);
                }

                return(Converter.ToPython(cb.type.IsAssignableFrom(otherCb.type)));
            }
        }
Beispiel #6
0
        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return(handle);
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return(result);
            }

            if (value is IList && value.GetType().IsGenericType)
            {
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return(resultlist.Handle);
                }
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
#if NETSTANDARD || NETCOREAPP
                return(ClassDerivedObject.ToPython(pyderived));
#else
                // if object is remote don't do this
                if (!System.Runtime.Remoting.RemotingServices.IsTransparentProxy(pyderived))
                {
                    return(ClassDerivedObject.ToPython(pyderived));
                }
#endif
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                return(CLRObject.GetInstHandle(value, type));

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.XIncref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.Interop.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.Interop.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string ss = ((float)value).ToString(nfi);
                IntPtr ps = Runtime.PyString_FromString(ss);
                IntPtr op = Runtime.Interop.PyFloat_FromString(ps, IntPtr.Zero);
                Runtime.XDecref(ps);
                return(op);

            case TypeCode.Double:
                return(Runtime.Interop.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.Interop.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.Interop.PyLong_FromUnsignedLongLong((ulong)value));

            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o?.GetType())))
                            {
                                resultlist.Append(p);
                            }
                        }
                        Runtime.XIncref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }
Beispiel #7
0
        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return(handle);
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return(result);
            }

            if (Type.GetTypeCode(type) == TypeCode.Object && value.GetType() != typeof(object))
            {
                var encoded = PyObjectConversions.TryEncode(value, type);
                if (encoded != null)
                {
                    result = encoded.Handle;
                    Runtime.XIncref(result);
                    return(result);
                }
            }

            if (value is IList && !(value is INotifyPropertyChanged) && value.GetType().IsGenericType)
            {
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return(resultlist.Handle);
                }
            }

            if (type.IsInterface)
            {
                var ifaceObj = (InterfaceObject)ClassManager.GetClass(type);
                return(ifaceObj.WrapObject(value));
            }

            // We need to special case interface array handling to ensure we
            // produce the correct type. Value may be an array of some concrete
            // type (FooImpl[]), but we want access to go via the interface type
            // (IFoo[]).
            if (type.IsArray && type.GetElementType().IsInterface)
            {
                return(CLRObject.GetInstHandle(value, type));
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
                if (!IsTransparentProxy(pyderived))
                {
                    return(ClassDerivedObject.ToPython(pyderived));
                }
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                return(CLRObject.GetInstHandle(value, type));

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.XIncref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string ss = ((float)value).ToString(nfi);
                IntPtr ps = Runtime.PyString_FromString(ss);
                IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
                Runtime.XDecref(ps);
                return(op);

            case TypeCode.Double:
                return(Runtime.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.PyLong_FromUnsignedLongLong((ulong)value));

            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o?.GetType())))
                            {
                                resultlist.Append(p);
                            }
                        }
                        Runtime.XIncref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }
Beispiel #8
0
        static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType)
        {
            ClassBase cb = GetManagedObject(tp) as ClassBase;

            if (cb == null)
            {
                Runtime.XIncref(Runtime.PyFalse);
                return Runtime.PyFalse;
            }

            using (PyList argsObj = new PyList(args))
            {
                if (argsObj.Length() != 1)
                    return Exceptions.RaiseTypeError("Invalid parameter count");

                PyObject arg = argsObj[0];
                PyObject otherType;
                if (checkType)
                    otherType = arg;
                else
                    otherType = arg.GetPythonType();

                if (Runtime.PyObject_TYPE(otherType.Handle) != PyCLRMetaType)
                {
                    Runtime.XIncref(Runtime.PyFalse);
                    return Runtime.PyFalse;
                }

                ClassBase otherCb = GetManagedObject(otherType.Handle) as ClassBase;
                if (otherCb == null)
                {
                    Runtime.XIncref(Runtime.PyFalse);
                    return Runtime.PyFalse;
                }

                return Converter.ToPython(cb.type.IsAssignableFrom(otherCb.type));
            }
        }
Beispiel #9
0
        internal static IntPtr ToPython(Object value, Type type)
        {
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.Incref(result);
                return(result);
            }

            // it the type is a python subclass of a managed type then return the
            // underying python object rather than construct a new wrapper object.
            IPythonDerivedType pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
                return(ClassDerivedObject.ToPython(pyderived));
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                result = CLRObject.GetInstHandle(value, type);

                // XXX - hack to make sure we convert new-style class based
                // managed exception instances to wrappers ;(
                if (Runtime.wrap_exceptions)
                {
                    Exception e = value as Exception;
                    if (e != null)
                    {
                        return(Exceptions.GetExceptionInstanceWrapper(result));
                    }
                }

                return(result);

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.Incref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.Incref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string ss = ((float)value).ToString(nfi);
                IntPtr ps = Runtime.PyString_FromString(ss);
                IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
                Runtime.Decref(ps);
                return(op);

            case TypeCode.Double:
                return(Runtime.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.PyLong_FromUnsignedLongLong((ulong)value));

            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o.GetType())))
                                resultlist.Append(p);
                        }
                        Runtime.Incref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }
Beispiel #10
0
        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return(handle);
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return(result);
            }

            if (value is IList && value.GetType().IsGenericType)
            {
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return(resultlist.Handle);
                }
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
                return(ClassDerivedObject.ToPython(pyderived));
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                if (value is TimeSpan)
                {
                    var timespan = (TimeSpan)value;

                    IntPtr timeSpanArgs = Runtime.PyTuple_New(1);
                    Runtime.PyTuple_SetItem(timeSpanArgs, 0, Runtime.PyFloat_FromDouble(timespan.TotalDays));
                    return(Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs));
                }
                return(CLRObject.GetInstHandle(value, type));

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.XIncref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string ss = ((float)value).ToString(nfi);
                IntPtr ps = Runtime.PyString_FromString(ss);
                IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
                Runtime.XDecref(ps);
                return(op);

            case TypeCode.Double:
                return(Runtime.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.PyLong_FromUnsignedLongLong((ulong)value));

            case TypeCode.Decimal:
                string d2s         = ((decimal)value).ToString(nfi);
                IntPtr d2p         = Runtime.PyString_FromString(d2s);
                IntPtr decimalArgs = Runtime.PyTuple_New(1);
                Runtime.PyTuple_SetItem(decimalArgs, 0, d2p);

                return(Runtime.PyObject_CallObject(decimalCtor, decimalArgs));

            case TypeCode.DateTime:
                var datetime = (DateTime)value;

                IntPtr dateTimeArgs = Runtime.PyTuple_New(8);
                Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year));
                Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month));
                Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day));
                Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour));
                Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute));
                Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second));
                Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(1000 * datetime.Millisecond));
                Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind));

                return(Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs));

            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o?.GetType())))
                            {
                                resultlist.Append(p);
                            }
                        }
                        Runtime.XIncref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }
Beispiel #11
0
        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return(handle);
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return(result);
            }

            if (Type.GetTypeCode(type) == TypeCode.Object && value.GetType() != typeof(object))
            {
                var encoded = PyObjectConversions.TryEncode(value, type);
                if (encoded != null)
                {
                    result = encoded.Handle;
                    Runtime.XIncref(result);
                    return(result);
                }
            }

            if (value is IList && !(value is INotifyPropertyChanged) && value.GetType().IsGenericType)
            {
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return(resultlist.Handle);
                }
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
                if (!IsTransparentProxy(pyderived))
                {
                    return(ClassDerivedObject.ToPython(pyderived));
                }
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                if (value is TimeSpan)
                {
                    var timespan = (TimeSpan)value;

                    IntPtr timeSpanArgs = Runtime.PyTuple_New(1);
                    Runtime.PyTuple_SetItem(timeSpanArgs, 0, Runtime.PyFloat_FromDouble(timespan.TotalDays));
                    var returnTimeSpan = Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs);
                    // clean up
                    Runtime.XDecref(timeSpanArgs);
                    return(returnTimeSpan);
                }
                return(CLRObject.GetInstHandle(value, type));

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.XIncref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string       ss = ((float)value).ToString(nfi);
                IntPtr       ps = Runtime.PyString_FromString(ss);
                NewReference op = Runtime.PyFloat_FromString(new BorrowedReference(ps));;
                Runtime.XDecref(ps);
                return(op.DangerousMoveToPointerOrNull());

            case TypeCode.Double:
                return(Runtime.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.PyLong_FromUnsignedLongLong((ulong)value));

            case TypeCode.Decimal:
                // C# decimal to python decimal has a big impact on performance
                // so we will use C# double and python float
                return(Runtime.PyFloat_FromDouble(decimal.ToDouble((decimal)value)));

            case TypeCode.DateTime:
                var datetime = (DateTime)value;

                var size = datetime.Kind == DateTimeKind.Unspecified ? 7 : 8;

                IntPtr dateTimeArgs = Runtime.PyTuple_New(size);
                Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year));
                Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month));
                Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day));
                Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour));
                Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute));
                Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second));

                // datetime.datetime 6th argument represents micro seconds
                var totalSeconds = datetime.TimeOfDay.TotalSeconds;
                var microSeconds = Convert.ToInt32((totalSeconds - Math.Truncate(totalSeconds)) * 1000000);
                if (microSeconds == 1000000)
                {
                    microSeconds = 999999;
                }
                Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(microSeconds));

                if (size == 8)
                {
                    Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind));
                }

                var returnDateTime = Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs);
                // clean up
                Runtime.XDecref(dateTimeArgs);
                return(returnDateTime);


            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o?.GetType())))
                            {
                                resultlist.Append(p);
                            }
                        }
                        Runtime.XIncref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }
    public void UploadForecastsToGeoServer(Dictionary<DateTime, FileInfo> probabilities)
    {
        if (uploadResultsToGeoserver)
        {
            StartPythonSession();

            Console.WriteLine("Uploading results to the geoserver...\n");

            PyObject upload_files_to_geoserver = uploadToGeoserver.GetAttr("upload_files_to_geoserver");

            PyList files = new PyList();
            List<string> zippedFiles = new List<string>();

            foreach (var s in probabilities.Values)
            {

                //write projection file

                FileInfo prj = new FileInfo(s.FullName.Replace(s.Extension, ".prj"));
                FileInfo tfw = new FileInfo(s.FullName.Replace(s.Extension, ".tfw"));

                File.WriteAllText(prj.FullName, projection.ToUpper());
                string zippedFile = s.FullName.Replace(s.Extension, ".zip");
                zippedFiles.Add(zippedFile);

                using (FileStream fstream = File.Create(zippedFile))
                {

                    using (IWriter writer = WriterFactory.Open(fstream, SharpCompress.Common.ArchiveType.Zip, SharpCompress.Common.CompressionType.None))
                    {
                        writer.Write(s.Name, s.FullName);
                        writer.Write(prj.Name, prj.FullName);
                        writer.Write(tfw.Name, tfw.FullName);
                        writer.Dispose();
                    }

                    fstream.Close();
                    fstream.Dispose();
                }

                files.Append(new PyString(zippedFile));

                //files.Append(new PyString(s.FullName));
            }

            PyObject[] args = new PyObject[]
                {
                    files,
                    new PyString(geoServerURI),
                    new PyString(geoServerRestServiceEndpoint),
                    new PyString(geoServerWorkSpace),
                    new PyString(geoServerUserName),
                    new PyString(GeoServerPassword)
                };

            upload_files_to_geoserver.Invoke(args);
            files.Dispose();
            files = null;

            for (int i = 0; i < args.Length; i++)
            {
                args[i].Dispose();
                args[i] = null;
            }

            foreach (var zipped in zippedFiles)
            {
                if (File.Exists(zipped))
                {
                    try
                    {
                        File.Delete(zipped);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }

            Console.WriteLine("\nFinished uploading results to the geoserver!");

            EndPythonSession();
        }
    }
    private Dictionary<DateTime, List<string>> GetAvailableForecastListFromIrods()
    {
        Dictionary<DateTime, List<string>> forecasts = new Dictionary<DateTime, List<string>>();
        PyObject create_session = iRODSClientModule.GetAttr("create_session");

        PyObject[] sessionArgs = new PyObject[]
                                {
                                    new PyString(iRODShost),
                                    new PyString(iRODSuserName),
                                    new PyString(iRODSpassword),
                                    new PyString(iRODSzone),
                                    new PyInt(iRODSport)
                                };

        PyObject session = create_session.Invoke(sessionArgs);

        PyObject get_collection = iRODSClientModule.GetAttr("get_collection");
        PyObject get_all_data_objects_recursively = iRODSClientModule.GetAttr("get_all_data_objects_recursively");

        PyObject[] args = new PyObject[]
                                {
                                    session,
                                    new PyString(iRODScollection),
                                };

        PyObject headNodeCollection = get_collection.Invoke(args);

        for (int m = 0; m < args.Length; m++)
        {
            PyObject obj = args[m];
            obj.Dispose();
            obj = null;
        }

        args = new PyObject[]{                      headNodeCollection
                                };

        PyObject allFiles = get_all_data_objects_recursively.Invoke(args);

        PyList dataObjects = new PyList(allFiles);

        int value = dataObjects.Length();

        for (int i = 0; i < value; i++)
        {
            PyObject dataObject = dataObjects.GetItem(i);
            string path = dataObject.ToString();

            KeyValuePair<bool, DateTime> dateTime = GetiRODSDataObjectDate(path);

            if (dateTime.Key)
            {
                KeyValuePair<bool, string> ensembleid = GetiRODSDataObjectEnsembleID(path);

                if (ensembleid.Key)
                {
                    if (forecasts.ContainsKey(dateTime.Value))
                    {
                        forecasts[dateTime.Value].Add(path);
                    }
                    else
                    {
                        List<string> newstring = new List<string>();
                        newstring.Add(path);
                        forecasts.Add(dateTime.Value, newstring);
                    }

                }
                else
                {
                    dataObject.ToString();
                }
            }
            else
            {
                dataObject.ToString();
            }

            dataObject.Dispose();
            dataObject = null;
        }

        session.Dispose();
        session = null;
        create_session.Dispose();
        create_session = null;

        for (int m = 0; m < sessionArgs.Length; m++)
        {
            PyObject obj = sessionArgs[m];
            obj.Dispose();
            obj = null;
        }

        get_collection.Dispose();
        get_collection = null;

        get_all_data_objects_recursively.Dispose();
        get_all_data_objects_recursively = null;

        for (int m = 0; m < args.Length; m++)
        {
            PyObject obj = args[m];
            obj.Dispose();
            obj = null;
        }

        headNodeCollection.Dispose();
        headNodeCollection = null;

        allFiles.Dispose();
        allFiles = null;

        dataObjects.Dispose(); dataObjects = null;

        return forecasts;
    }
    private List<FileInfo> DownloadFromIrodsAndUnzipForecastsLocally(List<string> files)
    {
        //Remember to remove
        List<FileInfo> downloadedFiles = new List<FileInfo>();
        PyList server_paths = new PyList();
        PyList local_paths = new PyList();

        List<string> local_paths_ = new List<string>();

        for (int i = 0; i < files.Count; i++)
        {
        #if DEBUG
            if (i > 1)
                break;
        #endif
            string ipath = files[i];
            DateTime dateTime = GetiRODSDataObjectDate(ipath).Value;

            string saveAs = name + "_" + GetiRODSDataObjectEnsembleID(ipath).Value +
                 "_" + dateTime.Year.ToString("0000") + dateTime.Month.ToString("00") +
                 dateTime.Day.ToString("00") + "T" + dateTime.Hour.ToString("00") +
                 dateTime.Minute.ToString("00") + "Z" + "." + GetFileExtension(ipath);

            FileInfo saveAsFile = new FileInfo(localWorkspace + "\\" + saveAs);

            local_paths_.Add(saveAsFile.FullName);

            server_paths.Append(new PyString(ipath));
            local_paths.Append(new PyString(saveAsFile.FullName));

        }

        PyObject create_session = iRODSClientModule.GetAttr("create_session");

        PyObject[] sessionArgs = new PyObject[]
                                {
                                    new PyString(iRODShost),
                                    new PyString(iRODSuserName),
                                    new PyString(iRODSpassword),
                                    new PyString(iRODSzone),
                                    new PyInt(iRODSport)
                                };

        PyObject session = create_session.Invoke(sessionArgs);

        PyObject save_data_objects_locally = iRODSClientModule.GetAttr("save_data_objects_locally");

        PyObject[] args = new PyObject[]
                {
                    session,
                    server_paths,
                    local_paths
                };

        PyObject result = save_data_objects_locally.Invoke(args);
        result.Dispose();
        result = null;

        for (int m = 1; m < args.Length; m++)
        {
            PyObject obj = args[m];
            obj.Dispose();
            obj = null;
        }

        save_data_objects_locally.Dispose();
        save_data_objects_locally = null;

        session.Dispose();
        session = null;

        for (int m = 0; m < sessionArgs.Length; m++)
        {
            PyObject obj = sessionArgs[m];
            obj.Dispose();
            obj = null;
        }

        create_session.Dispose();
        create_session = null;

        foreach (var f in local_paths_)
        {
            if (File.Exists(f))
            {
                FileInfo saveAsFile = new FileInfo(f);

                Console.WriteLine("Decompressing  [" + f + "]\n");

                using (FileStream downloadedStream = new FileStream(saveAsFile.FullName, FileMode.Open))
                {
                    using (IReader reader = ReaderFactory.Open(downloadedStream))
                    {
                        FileInfo file = new FileInfo(saveAsFile.FullName.Replace(saveAsFile.Extension, ".nc"));

                        while (reader.MoveToNextEntry())
                        {
                            if (!reader.Entry.IsDirectory && reader.Entry.FilePath.ToLower().Contains(".nc"))
                            {
                                try
                                {
                                    reader.WriteEntryToFile(file.FullName);

                                    using (Microsoft.Research.Science.Data.DataSet dt = Microsoft.Research.Science.Data.DataSet.Open(file.FullName, ResourceOpenMode.ReadOnly))
                                    {

                                    }

                                    downloadedFiles.Add(file);
                                }
                                catch (Exception ex)
                                {

                                    Console.WriteLine(ex.Message);

                                }
                                break;
                            }
                        }

                        reader.Dispose();

                        Console.WriteLine("Finished Decompressing " + GetLocalFileDate(file).ToString("s") + " [" + file.FullName + "]\n");
                    }

                    downloadedStream.Close();
                    downloadedStream.Dispose();
                }

                try
                {
                    File.Delete(saveAsFile.FullName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\n" + ex.Message);
                }
            }
        }

        return downloadedFiles;
    }
Beispiel #15
0
        //====================================================================
        // Return a Python object for the given native object, converting
        // basic types (string, int, etc.) into equivalent Python objects.
        // This always returns a new reference. Note that the System.Decimal
        // type has no Python equivalent and converts to a managed instance.
        //====================================================================
        internal static IntPtr ToPython(Object value, Type type)
        {
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null) {
                result = Runtime.PyNone;
                Runtime.Incref(result);
                return result;
            }

            // it the type is a python subclass of a managed type then return the
            // underying python object rather than construct a new wrapper object.
            IPythonDerivedType pyderived = value as IPythonDerivedType;
            if (null != pyderived)
            {
                return ClassDerivedObject.ToPython(pyderived);
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch(tc) {

            case TypeCode.Object:
                result = CLRObject.GetInstHandle(value, type);

                // XXX - hack to make sure we convert new-style class based
                // managed exception instances to wrappers ;(
                if (Runtime.wrap_exceptions) {
                    Exception e = value as Exception;
                    if (e != null) {
                        return Exceptions.GetExceptionInstanceWrapper(result);
                    }
                }

                return result;

            case TypeCode.String:
                return Runtime.PyUnicode_FromString((string)value);

            case TypeCode.Int32:
                return Runtime.PyInt_FromInt32((int)value);

            case TypeCode.Boolean:
                if ((bool)value) {
                    Runtime.Incref(Runtime.PyTrue);
                    return Runtime.PyTrue;
                }
                Runtime.Incref(Runtime.PyFalse);
                return Runtime.PyFalse;

            case TypeCode.Byte:
                return Runtime.PyInt_FromInt32((int)((byte)value));

            case TypeCode.Char:
                return Runtime.PyUnicode_FromOrdinal((int)((char)value));

            case TypeCode.Int16:
                return Runtime.PyInt_FromInt32((int)((short)value));

            case TypeCode.Int64:
                return Runtime.PyLong_FromLongLong((long)value);

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string ss = ((float)value).ToString(nfi);
                IntPtr ps = Runtime.PyString_FromString(ss);
                IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
                Runtime.Decref(ps);
                return op;

            case TypeCode.Double:
                return Runtime.PyFloat_FromDouble((double)value);

            case TypeCode.SByte:
                return Runtime.PyInt_FromInt32((int)((sbyte)value));

            case TypeCode.UInt16:
                return Runtime.PyInt_FromInt32((int)((ushort)value));

            case TypeCode.UInt32:
                return Runtime.PyLong_FromUnsignedLong((uint)value);

            case TypeCode.UInt64:
                return Runtime.PyLong_FromUnsignedLongLong((ulong)value);

            default:
            if (value is IEnumerable)
                {
                    var resultlist = new PyList();
                    foreach (object o in (IEnumerable)value)
                    {
                        resultlist.Append(new PyObject(ToPython(o, o.GetType())));
                    }
                    return resultlist.Handle;
                }
                result = CLRObject.GetInstHandle(value, type);
                return result;
            }
        }