示例#1
0
        private static T Cast(Java.Lang.Object javaObject)
        {
            if (typeof(T).IsGenericType)
            {
                if (typeof(T).GetGenericTypeDefinition().Equals(typeof(Paginator <>)) &&
                    javaObject.GetType().Equals(typeof(InternalPaginator)))
                {
                    Type            genericType = typeof(Paginator <>).MakeGenericType(typeof(T).GetGenericArguments());
                    ConstructorInfo constructor = genericType.GetConstructor(new Type[] { typeof(InternalPaginator) });
                    if (constructor == null)
                    {
                        throw new InvalidOperationException("Type " + genericType.Name + " does not contain an appropriate constructor");
                    }
                    return((T)constructor.Invoke(new object[] { Convert.ChangeType(javaObject, typeof(InternalPaginator)) }));
                }

                if (typeof(T).GetGenericTypeDefinition().Equals(typeof(IList <>)) &&
                    javaObject.GetType().Equals(typeof(Android.Runtime.JavaList)))
                {
                    Type genericType = typeof(Android.Runtime.JavaList <>).MakeGenericType(typeof(T).GetGenericArguments());
                    return((T)Activator.CreateInstance(genericType, javaObject.Handle, Android.Runtime.JniHandleOwnership.DoNotRegister));
                }
            }
            return((T)Convert.ChangeType(javaObject, typeof(T)));
        }
示例#2
0
 public void DbOperSuccess(int p0, Java.Lang.Object obj)
 {
     if (obj != null && obj.GetType().ToString() != "Java.Lang.Long" && obj.GetType().ToString() != "Java.Lang.Integer")
     {
         Java.Util.ArrayList lstJsonObj = (Java.Util.ArrayList)obj;
         for (int i = 0; i < lstJsonObj.Size(); i++)
         {
             JSONObject castedJObj = (JSONObject)lstJsonObj.Get(i);
             string     str        = castedJObj.GetString("username");
         }
     }
     Log.I("DB Oper", "Success " + p0);
 }
示例#3
0
        void TestTypeConversion()
        {
            // Sanity checking to ensure that our binding stays correct.
            var v = ServerSocketFactory.Default;

            Log.Info("HelloApp", "ServerSocketFactory.Default={0}", v);
            var egl = EGLContext.EGL;

            Log.Info("HelloApp", "EGLContext.EGL={0}", egl);
            IEGL10 egl10 = egl.JavaCast <IEGL10>();

            Log.Info("HelloApp", "(IEGL10) EGLContext.EGL={0}", egl10.GetType().FullName);

            IntPtr lref = JNIEnv.NewString("Hello, world!");

            using (Java.Lang.Object s = Java.Lang.Object.GetObject <Java.Lang.Object>(lref, JniHandleOwnership.TransferLocalRef)) {
                if (s.GetType() != typeof(Java.Lang.String))
                {
                    throw new InvalidOperationException("Object.GetObject<T>() needs to return a Java.Lang.String!");
                }
            }

            lref = JNIEnv.CreateInstance("android/gesture/Gesture", "()V");
            using (Java.Lang.Object g = Java.Lang.Object.GetObject <Java.Lang.Object>(lref, JniHandleOwnership.TransferLocalRef))
                if (g.GetType() != typeof(Android.Gestures.Gesture))
                {
                    throw new InvalidOperationException("Object.GetObject<T>() needs to return a Android.Gestures.Gesture!");
                }
        }
        public static object ConvertJavaObjectToSettingValue(Java.Lang.Object value)
        {
            if (value == null)
            {
                return(null);
            }

            try
            {
                //Haven't checked I guess types are only bool, int and string?
                if (value is Java.Lang.Boolean javaBoolean)
                {
                    return(Convert.ToBoolean(javaBoolean));
                }
                else if (value is Java.Lang.Integer javaInteger)
                {
                    return(Convert.ToInt32(javaInteger));
                }
                else if (value is Java.Lang.String javaString)
                {
                    return(Convert.ToString(javaString));
                }
            }
            catch { }

            throw new ArgumentException("Unsupported setting value type: " + value.GetType().FullName);
        }
示例#5
0
        private object ConvertToPOCO(Java.Lang.Object obj, Type convertTo)
        {
            var javaObj   = obj.GetType().GetProperty("Instance");
            var javaBlank = javaObj.GetValue(obj, null);

            return(Convert.ChangeType(javaBlank, convertTo));
        }
 public void OnLoadFinished(Loader loader, Java.Lang.Object data)
 {
     if (data.GetType() == typeof(LoaderResponse <ZXing.Result>))
     {
         LoaderResponse <ZXing.Result> loaderResponse = (LoaderResponse <ZXing.Result>)data;
         textViewResult.Text = loaderResponse.Response.Text;
     }
 }
示例#7
0
        private ARHitResult HitTest4Result(ARFrame frame, ARCamera camera, MotionEvent mEvent)
        {
            ARHitResult         hitResult      = null;
            IList <ARHitResult> hitTestResults = frame.HitTest(mEvent);

            for (int i = 0; i < hitTestResults.Count; i++)
            {
                // Determine whether the hit point is within the plane polygon.
                ARHitResult hitResultTemp = hitTestResults.ElementAt(i);
                if (hitResultTemp == null)
                {
                    continue;
                }
                IARTrackable trackable = hitResultTemp.Trackable;

                Java.Lang.Object PointOrPlane    = null;
                bool             isPlanHitJudge  = false;
                bool             isPointHitJudge = false;

                try
                {
                    PointOrPlane   = trackable.JavaCast <ARPlane>();
                    isPlanHitJudge =
                        PointOrPlane.GetType() == typeof(ARPlane) && ((ARPlane)PointOrPlane).IsPoseInPolygon(hitResultTemp.HitPose) &&
                        (CalculateDistanceToPlane(hitResultTemp.HitPose, camera.Pose) > 0);
                }
                catch (Exception e)
                {
                    PointOrPlane    = trackable.JavaCast <ARPoint>();
                    isPointHitJudge = PointOrPlane.GetType() == typeof(ARPoint) &&
                                      ((ARPoint)PointOrPlane).GetOrientationMode() == ARPoint.OrientationMode.EstimatedSurfaceNormal;
                };

                // Determine whether the point cloud is clicked and whether the point faces the camera.


                // Select points on the plane preferentially.
                if (isPlanHitJudge)
                {
                    hitResult = hitResultTemp;
                }
            }
            return(hitResult);
        }
        private static T Cast(Java.Lang.Object javaObject)
        {
            if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition().Equals(typeof(Paginator <>)) &&
                javaObject.GetType().Equals(typeof(InternalPaginator)))
            {
                return((T)(Activator.CreateInstance(typeof(T), Convert.ChangeType(javaObject, typeof(InternalPaginator)))));
            }

            if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition().Equals(typeof(IList <>)) &&
                typeof(T).GetGenericArguments().Length.Equals(1) &&
                javaObject.GetType().Equals(typeof(Android.Runtime.JavaList)))
            {
                Type genericArgument = typeof(T).GetGenericArguments()[0];
                Type genericType     = typeof(Android.Runtime.JavaList <>).MakeGenericType(genericArgument);
                return((T)Activator.CreateInstance(genericType, javaObject.Handle, Android.Runtime.JniHandleOwnership.DoNotRegister));
            }

            return((T)Convert.ChangeType(javaObject, typeof(T)));
        }
        public static bool IsLocationEnabled(Context context)
        {
            Java.Lang.Object obj = context.GetSystemService(Context.LocationService);
            if (!(obj.GetType() == typeof(LocationManager)))
            {
                return(false);
            }
            LocationManager locationManager = (LocationManager)obj;

            return(locationManager.IsProviderEnabled(LocationManager.GpsProvider));
        }
示例#10
0
        public void GetObject_ReturnsMostDerivedType()
        {
            IntPtr lref = JNIEnv.NewString("Hello, world!");

            using (Java.Lang.Object s = Java.Lang.Object.GetObject <Java.Lang.Object>(lref, JniHandleOwnership.TransferLocalRef)) {
                Assert.AreEqual(typeof(Java.Lang.String), s.GetType());
            }

            lref = JNIEnv.CreateInstance("android/gesture/Gesture", "()V");
            using (Java.Lang.Object g = Java.Lang.Object.GetObject <Java.Lang.Object>(lref, JniHandleOwnership.TransferLocalRef)) {
                Assert.AreEqual(typeof(global::Android.Gestures.Gesture), g.GetType());
            }
        }
示例#11
0
        public override bool Equals(Java.Lang.Object obj)
#endif
        {
            if ((obj == null) || !this.GetType().Equals(obj.GetType()))
            {
                return(false);
            }
            else
            {
                LocationData locData = (LocationData)obj;
                return(this.GetHashCode() == locData.GetHashCode());
            }
        }
示例#12
0
        private void DoWhenEventTypeSingleTap(ARHitResult hitResult)
        {
            // The hit results are sorted by distance. Only the nearest hit point is valid.
            // Set the number of stored objects to 10 to avoid the overload of rendering and AR Engine.
            if (mVirtualObjects.Count >= 16)
            {
                mVirtualObjects.ElementAt(0).GetAnchor().Detach();
                mVirtualObjects.RemoveAt(0);
            }

            IARTrackable currentTrackable = hitResult.Trackable;

            Java.Lang.Object PointOrPlane    = null;
            bool             isPlanHitJudge  = false;
            bool             isPointHitJudge = false;

            try
            {
                PointOrPlane   = currentTrackable.JavaCast <ARPlane>();
                isPlanHitJudge = PointOrPlane.GetType() == typeof(ARPlane);
            }
            catch (Exception e)
            {
                PointOrPlane    = currentTrackable.JavaCast <ARPoint>();
                isPointHitJudge = PointOrPlane.GetType() == typeof(ARPoint);
            };
            if (isPointHitJudge)
            {
                mVirtualObjects.Add(new VirtualObject(hitResult.CreateAnchor(), BLUE_COLORS));
            }
            else if (isPlanHitJudge)
            {
                mVirtualObjects.Add(new VirtualObject(hitResult.CreateAnchor(), GREEN_COLORS));
            }
            else
            {
                Log.Info(TAG, "Hit result is not plane or point.");
            }
        }
 protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.ListView> e)
 {
     base.OnElementChanged(e);
     if (Control != null)
     {
         CustomListView view = (CustomListView)e.NewElement;
         Control.ItemLongClick += (s, args) =>
         {
             Control.SetItemChecked(args.Position, true);
             Java.Lang.Object item = Control.GetItemAtPosition(args.Position);
             view.OnLongTapped(item.GetType().GetProperty("Instance").GetValue(item));
         };
     }
 }
示例#14
0
        void TestManualOverrides()
        {
            var adder = new Adder();

            Console.WriteLine("Adder Class: {0}", adder.Class);

            var managedAdder = new ManagedAdder();
            int result       = Adder.Add(managedAdder, 3, 4);

            if (result != 14)
            {
                throw new InvalidOperationException("ManagedAdder.Add(3, 4) != 14!");
            }

            var progress = new AdderProgress();
            int sum      = Adder.Sum(adder, progress, 1, 2, 3);

            if (sum != 6)
            {
                throw new InvalidOperationException("Adder.Sum(adder, 1, 2, 3) != 6! Was: " + sum + ".");
            }
            if (progress.AddInvocations != 3)
            {
                throw new InvalidOperationException("Adder.Sum(adder, 1, 2, 3) didn't invoke progress 3 times! Was: " + progress.AddInvocations + ".");
            }

            progress.AddInvocations = 0;
            sum = Adder.Sum(managedAdder, progress, 6, 7);
            if (sum != 38)
            {
                throw new InvalidOperationException("Adder.Sum(managedAdder, 6, 7) != 38! Was: " + sum + ".");
            }
            if (progress.AddInvocations != 2)
            {
                throw new InvalidOperationException("Adder.Sum(adder, 6, 7) didn't invoke progress 2 times! Was: " + progress.AddInvocations + ".");
            }

            IntPtr javaDefaultProgress = JNIEnv.CreateInstance("mono/android/test/Adder$DefaultProgress", "()V");
            var    progress2           = Java.Lang.Object.GetObject <IAdderProgress>(javaDefaultProgress, JniHandleOwnership.TransferLocalRef);

            Console.WriteLine("progress2 MCW: {0}", progress2.GetType().FullName);

            javaDefaultProgress = JNIEnv.CreateInstance("mono/android/test/Adder$DefaultProgress", "()V");
            var progress3 = new Java.Lang.Object(javaDefaultProgress, JniHandleOwnership.TransferLocalRef)
                            .JavaCast <IAdderProgress> ();

            Console.WriteLine("progress3 MCW: {0}", progress3.GetType().FullName);
        }
示例#15
0
        protected override void OnElementChanged(ElementChangedEventArgs <ListView> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                var view = (ScrollableListView)Element;


                this.Control.ItemLongClick += (s, args) =>
                {
                    this.Control.SetItemChecked(args.Position, true);
                    Java.Lang.Object item = this.Control.GetItemAtPosition(args.Position);
                    view.OnLongClicked(item.GetType().GetProperty("Instance").GetValue(item), args.Position);
                };
            }
        }
示例#16
0
        private Intent SetIntent(AdapterView.ItemClickEventArgs e)
        {
            Object weatherViewModel = _lv.GetItemAtPosition(e.Position);
            Intent setIntent        = new Intent(this, typeof(DetailsView));

            if (weatherViewModel != null)
            {
                var propertyInfo = weatherViewModel.GetType().GetProperty("Instance");
                var proertyValue = (WeatherViewModel)propertyInfo.GetValue(weatherViewModel, null);
                if (proertyValue != null)
                {
                    setIntent.PutExtra("city", proertyValue.City);
                    setIntent.PutExtra("temp", proertyValue.Temp);
                    setIntent.PutExtra("weather", proertyValue.Weather);
                    setIntent.PutExtra("tempmax", proertyValue.TempMax);
                    setIntent.PutExtra("tempmin", proertyValue.TempMin);
                    setIntent.PutExtra("weathericon", proertyValue.Url);
                }
            }
            return(setIntent);
        }
示例#17
0
        public static T EnumCast <T>(this Java.Lang.Object obj)
        {
            var propertyInfo = obj.GetType().GetProperty("Instance");

            return(propertyInfo == null ? default(T) : (T)propertyInfo.GetValue(obj, null));
        }
示例#18
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            int rowType = GetItemViewType(position);

            if (convertView == null)
            {
                int    padding  = 16;
                int    padding4 = 4;
                string txt      = "";

#pragma warning disable 0618
                switch (rowType)
                {
                case TypeHeader:
                    convertView = new TextView(_context);

                    ((TextView)convertView).SetTextAppearance(_context, Android.Resource.Style.TextAppearanceSmall);
                    convertView.SetPadding(padding, padding4, padding, padding4);

                    txt = GetItem(position).ToString();
                    ((TextView)convertView).SetText(txt, TextView.BufferType.Normal);

                    break;

                case TypeItem:
                    convertView = new TextView(_context);

                    ((TextView)convertView).SetTextAppearance(_context, Android.Resource.Style.TextAppearanceMedium);
                    convertView.SetPadding(32, padding, padding, padding);

                    txt = GetItem(position).ToString();
                    ((TextView)convertView).SetText(txt, TextView.BufferType.Normal);

                    break;

                case TypeImage:
                    convertView = new ImageView(_context);
                    ((ImageView)convertView).SetImageBitmap(GetItem(position) as Bitmap);
                    break;

                case TypeSerial:
                    convertView = new LinearLayout(_context);
                    (convertView as LinearLayout).Orientation = Android.Widget.Orientation.Vertical;

                    var serialScanningResults = (GetItem(position) as Java.Util.LinkedHashMap);

                    foreach (Java.Lang.Object scanningResult in serialScanningResults.KeySet())
                    {
                        LinearLayout llPluginContent = new LinearLayout(_context);
                        llPluginContent.Orientation = Android.Widget.Orientation.Vertical;
                        llPluginContent.SetPadding(15, 30, 15, 30);
                        LinearLayout.LayoutParams parameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.FillParent);
                        parameters.SetMargins(32, 5, 32, 5);
                        llPluginContent.LayoutParameters = parameters;

                        string keyPluginResult = scanningResult.ToString();
                        Java.Util.LinkedHashMap pluginResults = serialScanningResults.Get(scanningResult) as Java.Util.LinkedHashMap;

                        TextView tvPluginTitle = CreateTextView(pluginResults.Get("PluginId").ToString(), padding, padding4, padding, padding4, Android.Resource.Style.TextAppearanceLarge, Color.ParseColor("#007aff"), TypefaceStyle.Bold, TextAlignment.Center);
                        llPluginContent.AddView(tvPluginTitle);

                        foreach (var result in pluginResults.KeySet())
                        {
                            string resultKey = result.ToString();
                            if (resultKey.Equals("PluginId"))
                            {
                                continue;
                            }
                            Java.Lang.Object resultValue = pluginResults.Get(resultKey);

                            TextView tvTitle = CreateTextView(resultKey, padding, padding4, padding, padding4, Android.Resource.Style.TextAppearanceSmall, Color.Black, TypefaceStyle.Normal);
                            llPluginContent.AddView(tvTitle);

                            if (resultValue.GetType() == typeof(Bitmap))
                            {
                                ImageView ivContent = new ImageView(_context);
                                ivContent.SetPadding(20, 20, 20, 20);
                                ivContent.SetImageBitmap(resultValue as Bitmap);
                                llPluginContent.AddView(ivContent);
                            }
                            else
                            {
                                TextView tvValue = CreateTextView(resultValue.ToString(), 32, padding, padding, padding, Android.Resource.Style.TextAppearanceMedium, Color.Black, TypefaceStyle.Bold);
                                llPluginContent.AddView(tvValue);
                            }
                        }
                        (convertView as LinearLayout).AddView(llPluginContent);
                        (convertView as LinearLayout).AddView(CreateLayoutDivider());
                    }


                    break;
                }
            }
#pragma warning restore 0618

            return(convertView);
        }
示例#19
0
        private Dictionary <string, object> CreatePropertyList(Java.Lang.Object obj)
        {
            var dict = new Dictionary <string, object>();

            foreach (var prop in obj.GetType().GetProperties())
            {
                switch (prop.Name)
                {
                // filter out properties that we don't want to display
                case "JniPeerMembers":
                case "JniIdentityHashCode":
                case "Handle":
                case "PeerReference":
                case "Outline":
                case "Class":
                    break;

                default:

                    try
                    {
                        var value = prop.GetValue(obj, null);


                        // filter out deprecated fields
                        if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).ToArray().Length > 0)
                        {
                            continue;
                        }

                        if (value != null)
                        {
                            // TODO: iterate through every result and display them
                            //if(value is JavaList)
                            //{
                            //    var i = 0;
                            //    var resultList = (value as JavaList);
                            //    foreach (Java.Lang.Object v in resultList)
                            //    {
                            //        var sublist = CreatePropertyList(v);
                            //        sublist.ToList().ForEach(x => dict.Add(x.Key + $" ({i})", x.Value));
                            //        i++;
                            //    }
                            //}
                            if (value is AnylineImage)
                            {
                                var bitmap = (value as AnylineImage).Clone().Bitmap;

                                MemoryStream stream = new MemoryStream();
                                bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                                byte[] bitmapData = stream.ToArray();

                                dict.Add(prop.Name, bitmapData);
                            }
                            else if (value is ID)
                            {
                                var sublist = CreatePropertyList(value as ID);
                                sublist.ToList().ForEach(x => dict.Add(x.Key, x.Value));
                            }
                            else if (value is IDFieldConfidences)
                            {
                                var sublist = CreatePropertyList(value as IDFieldConfidences);
                                sublist.ToList().ForEach(x => dict.Add($"{x.Key} (field confidence)", x.Value));
                            }
                            else
                            {
                                var str = new Java.Lang.String(value.ToString()).ReplaceAll("\\\\n", "\\\n");
                                dict.Add(prop.Name, str);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("Exception: " + e.Message);
                    }
                    break;
                }
            }

            // quick hack to re-order the list so that the result will be presented first:
            MoveElementToIndex(dict, "Result", 0);

            return(dict);
        }
示例#20
0
 public static System.Object CastBack(this Java.Lang.Object obj)
 {
     var propertyInfo = obj.GetType().GetProperty("Instance");
     return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as System.Object;
 }
示例#21
0
        public static T CastToNewMessage <T>(this Java.Lang.Object obj) where T : NewMessage
        {
            var propInfo = obj.GetType().GetProperty("Instance");

            return(propInfo?.GetValue(obj, null) as T);
        }
示例#22
0
        public static object ToFieldValue(this Java.Lang.Object fieldValue, Type type)
        {
            if (fieldValue == null)
            {
                return(null);
            }

            switch (fieldValue)
            {
            case Java.Lang.Boolean @bool:
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    type = type.GenericTypeArguments[0];
                }
                return(Convert.ChangeType((bool)@bool, type));

            case Java.Lang.Long @long:
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    type = type.GenericTypeArguments[0];
                }
                return(Convert.ChangeType((long)@long, type));

            case Java.Lang.Double @double:
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    type = type.GenericTypeArguments[0];
                }
                return(Convert.ChangeType((double)@double, type));

            case Java.Lang.String @string:
                return(fieldValue.ToString());

            case Firebase.Timestamp timestamp:
            {
                var time = new Timestamp(timestamp);
                if (type == typeof(DateTime) || type == typeof(DateTime?))
                {
                    return(time.ToDateTime());
                }
                if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
                {
                    return(time.ToDateTimeOffset());
                }
                return(time);
            }

            case Java.Util.Date date:
            {
                var time = new Timestamp(date);
                if (type == typeof(DateTime) || type == typeof(DateTime?))
                {
                    return(time.ToDateTime());
                }
                if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
                {
                    return(time.ToDateTimeOffset());
                }
                return(time);
            }

            case JavaList javaList:
            {
                IList list;
                if (type.GetInterfaces().Contains(typeof(IList)))
                {
                    list = (IList)Activator.CreateInstance(type);
                }
                else if (type.IsGenericType)
                {
                    var listType = typeof(List <>).MakeGenericType(type.GenericTypeArguments[0]);
                    list = (IList)Activator.CreateInstance(listType);
                }
                else
                {
                    list = new List <object>();
                }

                var genericType = typeof(object);
                if (type.IsGenericType)
                {
                    genericType = type.GenericTypeArguments[0];
                }

                foreach (var data in javaList)
                {
                    var value = data;
                    if (value is Java.Lang.Object javaObject)
                    {
                        value = javaObject.ToFieldValue(genericType);
                    }
                    else if (value != null && genericType != typeof(object))
                    {
                        if (genericType.IsGenericType && genericType.GetGenericTypeDefinition() == typeof(Nullable <>))
                        {
                            genericType = genericType.GenericTypeArguments[0];
                        }
                        value = Convert.ChangeType(value, genericType);
                    }
                    list.Add(value);
                }
                return(list);
            }

            case Java.Util.AbstractList javaList:
            {
                IList list;
                if (type.GetInterfaces().Contains(typeof(IList)))
                {
                    list = (IList)Activator.CreateInstance(type);
                }
                else if (type.IsGenericType)
                {
                    var listType = typeof(List <>).MakeGenericType(type.GenericTypeArguments[0]);
                    list = (IList)Activator.CreateInstance(listType);
                }
                else
                {
                    list = new List <object>();
                }

                var genericType = typeof(object);
                if (type.IsGenericType)
                {
                    genericType = type.GenericTypeArguments[0];
                }

                var iterator = javaList.Iterator();
                while (iterator.HasNext)
                {
                    object value = iterator.Next();
                    if (value is Java.Lang.Object javaObject)
                    {
                        value = javaObject.ToFieldValue(genericType);
                    }
                    else if (value != null && genericType != typeof(object))
                    {
                        if (genericType.IsGenericType && genericType.GetGenericTypeDefinition() == typeof(Nullable <>))
                        {
                            genericType = genericType.GenericTypeArguments[0];
                        }
                        value = Convert.ChangeType(value, genericType);
                    }
                    list.Add(value);
                }
                return(list);
            }

            case JavaDictionary dictionary:
            {
                object @object;
                if (type == typeof(object))
                {
                    @object = new Dictionary <string, object>();
                }
                else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary <,>))
                {
                    var dictionaryType = typeof(Dictionary <,>).MakeGenericType(type.GenericTypeArguments[0], type.GenericTypeArguments[1]);
                    @object = Activator.CreateInstance(dictionaryType);
                }
                else
                {
                    @object = Activator.CreateInstance(type);
                }

                if (@object is IDictionary dict)
                {
                    var genericType = typeof(object);
                    if (type.IsGenericType)
                    {
                        genericType = type.GenericTypeArguments[1];
                    }

                    foreach (var key in dictionary.Keys)
                    {
                        var value = dictionary[key];
                        if (value is Java.Lang.Object javaObject)
                        {
                            value = javaObject.ToFieldValue(genericType);
                        }
                        else if (value != null && genericType != typeof(object))
                        {
                            if (genericType.IsGenericType && genericType.GetGenericTypeDefinition() == typeof(Nullable <>))
                            {
                                genericType = genericType.GenericTypeArguments[0];
                            }
                            value = Convert.ChangeType(value, genericType);
                        }
                        dict.Add(key.ToString(), value);
                    }
                }
                else
                {
                    var properties       = type.GetProperties();
                    var mappedProperties = properties.Select(p => (Property: p, Attribute: Attribute.GetCustomAttribute(p, typeof(MapToAttribute)) as MapToAttribute))
                                           .Where(t => t.Attribute != null)
                                           .ToDictionary(t => t.Attribute.Mapping, t => t.Property);
                    var igonoredProperties = properties.Where(p => Attribute.GetCustomAttribute(p, typeof(IgnoredAttribute)) != null);

                    foreach (var key in dictionary.Keys)
                    {
                        PropertyInfo property;
                        if (mappedProperties.ContainsKey(key.ToString()))
                        {
                            property = mappedProperties[key.ToString()];
                        }
                        else
                        {
                            property = type.GetProperty(key.ToString());
                        }

                        if (property != null && !igonoredProperties.Contains(property))
                        {
                            var value = dictionary[key];
                            if (value is Java.Lang.Object javaObject)
                            {
                                value = javaObject.ToFieldValue(property.PropertyType);
                            }
                            else if (value != null)
                            {
                                var propertyType = property.PropertyType;
                                if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                                {
                                    propertyType = propertyType.GenericTypeArguments[0];
                                }
                                value = Convert.ChangeType(value, propertyType);
                            }
                            property.SetValue(@object, value);
                        }
                    }
                }
                return(@object);
            }

            case Java.Util.AbstractMap map:
            {
                object @object;
                if (type == typeof(object))
                {
                    @object = new Dictionary <string, object>();
                }
                else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary <,>))
                {
                    var dictionaryType = typeof(Dictionary <,>).MakeGenericType(type.GenericTypeArguments[0], type.GenericTypeArguments[1]);
                    @object = Activator.CreateInstance(dictionaryType);
                }
                else
                {
                    @object = Activator.CreateInstance(type);
                }

                if (@object is IDictionary dict)
                {
                    var genericType = typeof(object);
                    if (type.IsGenericType)
                    {
                        genericType = type.GenericTypeArguments[1];
                    }

                    foreach (var key in map.KeySet())
                    {
                        object value = map.Get(key.ToString());
                        if (value is Java.Lang.Object javaObject)
                        {
                            value = javaObject.ToFieldValue(genericType);
                        }
                        else if (value != null && genericType != typeof(object))
                        {
                            if (genericType.IsGenericType && genericType.GetGenericTypeDefinition() == typeof(Nullable <>))
                            {
                                genericType = genericType.GenericTypeArguments[0];
                            }
                            value = Convert.ChangeType(value, genericType);
                        }
                        dict.Add(key.ToString(), value);
                    }
                }
                else
                {
                    var properties       = type.GetProperties();
                    var mappedProperties = properties.Select(p => (Property: p, Attribute: Attribute.GetCustomAttribute(p, typeof(MapToAttribute)) as MapToAttribute))
                                           .Where(t => t.Attribute != null)
                                           .ToDictionary(t => t.Attribute.Mapping, t => t.Property);
                    var igonoredProperties = properties.Where(p => Attribute.GetCustomAttribute(p, typeof(IgnoredAttribute)) != null);

                    foreach (var key in map.KeySet())
                    {
                        PropertyInfo property;
                        if (mappedProperties.ContainsKey(key.ToString()))
                        {
                            property = mappedProperties[key.ToString()];
                        }
                        else
                        {
                            property = type.GetProperty(key.ToString());
                        }

                        if (property != null && !igonoredProperties.Contains(property))
                        {
                            object value = map.Get(key.ToString());
                            if (value is Java.Lang.Object javaObject)
                            {
                                value = javaObject.ToFieldValue(property.PropertyType);
                            }
                            else if (value != null)
                            {
                                var propertyType = property.PropertyType;
                                if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                                {
                                    propertyType = propertyType.GenericTypeArguments[0];
                                }
                                value = Convert.ChangeType(value, propertyType);
                            }
                            property.SetValue(@object, value);
                        }
                    }
                }
                return(@object);
            }

            case Firebase.Firestore.Blob blob:
                if (type == typeof(byte[]))
                {
                    return(blob.ToBytes());
                }
                return(new MemoryStream(blob.ToBytes()));

            case Firebase.Firestore.GeoPoint geoPoint:
                return(new GeoPoint(geoPoint));

            case Firebase.Firestore.DocumentReference documentReference:
                return(new DocumentReferenceWrapper(documentReference));

            default:
                throw new ArgumentOutOfRangeException($"{fieldValue.GetType().FullName} is not supported");
            }
        }
示例#23
0
        private Dictionary <string, Java.Lang.Object> CreatePropertyList(Java.Lang.Object obj)
        {
            var dict = new Dictionary <string, Java.Lang.Object>();
            int serialScanningIndex = 0;

            foreach (var prop in obj.GetType().GetProperties())
            {
                switch (prop.Name)
                {
                // filter out properties that we don't want to display
                case "JniPeerMembers":
                case "JniIdentityHashCode":
                case "Handle":
                case "PeerReference":
                case "Outline":
                case "Class":
                    break;

                default:

                    try
                    {
                        var value = prop.GetValue(obj, null);


                        // filter out deprecated fields
                        if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).ToArray().Length > 0)
                        {
                            continue;
                        }

                        Log.Debug(TAG, "{0}: {1}", prop.Name, value);
                        if (value != null)
                        {
                            // Iterate through a list for Serial Scanning
                            if (value is JavaList)
                            {
                                var indexResult = 0;

                                var mapResultsSerialScanning = new LinkedHashMap();
                                foreach (Java.Lang.Object result in (value as JavaList))
                                {
                                    var sublist          = CreatePropertyList(result);
                                    var mapPluginResults = new LinkedHashMap();
                                    foreach (KeyValuePair <string, Java.Lang.Object> item in sublist)
                                    {
                                        mapPluginResults.Put(item.Key, item.Value);
                                    }
                                    mapResultsSerialScanning.Put(indexResult, mapPluginResults);
                                    indexResult++;
                                }
                                dict.Add($"Composite {serialScanningIndex}", mapResultsSerialScanning);
                                serialScanningIndex++;
                            }
                            else if (value is AnylineImage)
                            {
                                var bitmap = (value as AnylineImage).Clone().Bitmap;
                                dict.Add(prop.Name, bitmap);
                            }
                            else if (value is ID)
                            {
                                var sublist = CreatePropertyList(value as ID);
                                sublist.ToList().ForEach(x => dict.Add(x.Key, x.Value));
                            }
                            else if (value is IDFieldConfidences)
                            {
                                var sublist = CreatePropertyList(value as IDFieldConfidences);
                                sublist.ToList().ForEach(x => dict.Add($"{x.Key} (field confidence)", x.Value));
                            }
                            else
                            {
                                var str = new Java.Lang.String(value.ToString()).ReplaceAll("\\\\n", "\\\n");
                                dict.Add(prop.Name, str);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("Exception: " + e.Message);
                    }
                    break;
                }
            }

            // quick hack to re-order the list so that the result will be presented first:
            dict.MoveElementToIndex("Result", 0);

            return(dict);
        }
示例#24
0
        private Dictionary <string, Java.Lang.Object> CreatePropertyList(Java.Lang.Object obj)
        {
            var dict = new Dictionary <string, Java.Lang.Object>();

            foreach (var prop in obj.GetType().GetProperties())
            {
                switch (prop.Name)
                {
                // filter out properties that we don't want to display
                case "JniPeerMembers":
                case "JniIdentityHashCode":
                case "Handle":
                case "PeerReference":
                case "Outline":
                case "Class":
                    break;

                default:

                    try
                    {
                        var value = prop.GetValue(obj, null);


                        // filter out deprecated fields
                        if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).ToArray().Length > 0)
                        {
                            continue;
                        }

                        Log.Debug(TAG, "{0}: {1}", prop.Name, value);
                        if (value != null)
                        {
                            if (value is AnylineImage)
                            {
                                var bitmap = (value as AnylineImage).Clone().Bitmap;
                                dict.Add(prop.Name, bitmap);
                            }
                            else if (value is ID)
                            {
                                var sublist = CreatePropertyList(value as ID);
                                sublist.ToList().ForEach(x => dict.Add(x.Key, x.Value));
                            }
                            else
                            {
                                var str = new Java.Lang.String(value.ToString()).ReplaceAll("\\\\n", "\\\n");
                                dict.Add(prop.Name, str);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("Exception: " + e.Message);
                    }
                    break;
                }
            }

            // quick hack to re-order the list so that the result will be presented first:
            dict.MoveElementToIndex("Result", 0);

            return(dict);
        }
示例#25
0
        public static T Cast <T>(this Java.Lang.Object obj) where T : class
        {
            var propertyInfo = obj.GetType().GetProperty("Instance");

            return(propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T);
        }
示例#26
0
        public static object ToObject(this Java.Lang.Object @this, Type targetType = null)
        {
            switch (@this)
            {
            case Java.Lang.ICharSequence x:
                return(x.ToString());

            case Java.Lang.Boolean x:
                return(x.BooleanValue());

            case Java.Lang.Integer x:
                return(x.IntValue());

            case Java.Lang.Double x:
                return(x.DoubleValue());

            case Java.Lang.Float x:
                return(x.FloatValue());

            case Java.Lang.Long x:
                return(x.LongValue());

            case Date x:
                return(x.ToDateTimeOffset());

            case NativeFirebase.Timestamp x:
                return(x.ToDate().ToDateTimeOffset());

            case IDictionary x:
                return(x.ToDictionaryObject(targetType));

            case JavaList x:
                return(x.ToList(targetType?.GenericTypeArguments[0]));

            case global::Firebase.Firestore.GeoPoint x:
                return(new GeoPoint(x.Latitude, x.Longitude));

            case DocumentReference x:
                return(new DocumentReferenceWrapper(x));

            default:
                throw new ArgumentException($"Could not convert Java.Lang.Object of type {@this.GetType()} to object");
            }
        }