private HttpWebResponse CreateMockedHttpWebResponse(int statusCode, string content, string[] headerNames, string[] headerValues)
        {
            byte[] contentBytes   = Encoding.UTF8.GetBytes(content);
            Stream responseStream = new MemoryStream();

            responseStream.Write(contentBytes, 0, contentBytes.Length);
            responseStream.Seek(0, SeekOrigin.Begin);

            WebHeaderCollection h = new WebHeaderCollection();

            if (headerNames != null)
            {
                for (int i = 0; i < headerNames.Length; i++)
                {
                    h.Add(headerNames[i], headerValues[i]);
                }
            }

            HttpWebResponse oNewResponse = (System.Net.HttpWebResponse)System.Activator.CreateInstance(typeof(HttpWebResponse));

            System.Reflection.PropertyInfo oInfo = oNewResponse.GetType().GetProperty("ResponseStream",
                                                                                      System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
            oInfo?.SetValue(oNewResponse, responseStream);
            System.Reflection.FieldInfo oFInfo = oNewResponse.GetType().GetField("m_HttpResponseHeaders",
                                                                                 System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
            oFInfo?.SetValue(oNewResponse, h);
            oFInfo = oNewResponse.GetType().GetField("m_StatusCode",
                                                     System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
            oFInfo?.SetValue(oNewResponse, statusCode);


            return(oNewResponse);
        }
Esempio n. 2
0
        static ObjectGroupingUtility()
        {
            System.Reflection.FieldInfo info = typeof(EditorApplication).GetField("globalEventHandler", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            EditorApplication.CallbackFunction value = (EditorApplication.CallbackFunction)info?.GetValue(null);

            value += EditorGlobalKeyPress;

            info?.SetValue(null, value);
        }
Esempio n. 3
0
        static void InvalidateOutAndError()
        {
            Type type = typeof(System.Console);

            System.Reflection.FieldInfo _out = type.GetField("_out",
                                                             System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            System.Reflection.FieldInfo _error = type.GetField("_error",
                                                               System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError",
                                                                                 System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            // Debug.Assert(_out != null);
            // Debug.Assert(_error != null);
            // Debug.Assert(_InitializeStdOutError != null);
            _out?.SetValue(null, null);
            _error?.SetValue(null, null);
            _InitializeStdOutError?.Invoke(null, new object[] { true });
        }
Esempio n. 4
0
            static public void SetDropLists(List <PickupIndex> givenTier1, List <PickupIndex> givenTier2, List <PickupIndex> givenTier3, List <PickupIndex> givenEquipment)
            {
                List <PickupIndex> none = new List <PickupIndex>()
                {
                    PickupIndex.none
                };
                List <List <PickupIndex> > availableItems = new List <List <PickupIndex> >()
                {
                    new List <PickupIndex>(), new List <PickupIndex>(), new List <PickupIndex>(), new List <PickupIndex>()
                };

                DuplicateDropList(givenTier1, availableItems[0]);
                DuplicateDropList(givenTier2, availableItems[1]);
                DuplicateDropList(givenTier3, availableItems[2]);
                DuplicateDropList(givenEquipment, availableItems[3]);
                for (int availableIndex = 0; availableIndex < 4; availableIndex++)
                {
                    if (availableItems[availableIndex].Count == 0)
                    {
                        availableItems[availableIndex] = none;
                    }
                }

                DuplicateDropList(Run.instance.availableTier1DropList, tier1DropListBackup);
                DuplicateDropList(Run.instance.availableTier2DropList, tier2DropListBackup);
                DuplicateDropList(Run.instance.availableTier3DropList, tier3DropListBackup);
                DuplicateDropList(Run.instance.availableEquipmentDropList, equipmentDropListBackup);
                System.Type type = typeof(RoR2.Run);
                System.Reflection.FieldInfo tier1     = type.GetField("availableTier1DropList", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                System.Reflection.FieldInfo tier2     = type.GetField("availableTier2DropList", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                System.Reflection.FieldInfo tier3     = type.GetField("availableTier3DropList", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                System.Reflection.FieldInfo equipment = type.GetField("availableEquipmentDropList", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                tier1.SetValue(RoR2.Run.instance, availableItems[0]);
                tier2.SetValue(RoR2.Run.instance, availableItems[1]);
                tier3.SetValue(RoR2.Run.instance, availableItems[2]);
                equipment.SetValue(RoR2.Run.instance, availableItems[3]);
            }
 void CheckFile()
 {
     lock (checkLock)
     {
         if (SuffixPattern == null)
         {
             SuffixPattern = ParseString("SuffixPattern", "_{0:yyyyMMdd}");
         }
         var dir          = Path.GetDirectoryName(_FileNameBasic);
         var nam          = Path.GetFileNameWithoutExtension(_FileNameBasic);
         var ext          = Path.GetExtension(_FileNameBasic);
         var pathPattern  = Path.Combine(dir, nam + SuffixPattern + ext);
         var expandedPath = Environment.ExpandEnvironmentVariables(pathPattern);
         var path         = string.Format(expandedPath, DateTime.Now);
         var writer       = (StreamWriter)writerField.GetValue(this);
         // If file is missing or name changed then...
         if (writer == null || !path.Equals(((FileStream)writer.BaseStream).Name, StringComparison.OrdinalIgnoreCase))
         {
             if (writer != null)
             {
                 writer.Close();
             }
             // Cleanup old files.
             WipeOldLogFiles(expandedPath);
             var fi = new System.IO.FileInfo(path);
             if (!fi.Directory.Exists)
             {
                 fi.Directory.Create();
             }
             // create a new file stream and a new stream writer and pass it to the listener
             var stream = new FileStream(path, FileMode.OpenOrCreate);
             writer = new StreamWriter(stream);
             stream.Seek(0, SeekOrigin.End);
             writerField.SetValue(this, writer);
         }
     }
 }
Esempio n. 6
0
        bool HandleOpenTags(string tag, string val)
        {
            System.Reflection.FieldInfo fieldInfo = typeof(Attribute).GetField(tag);
            string fieldName = fieldInfo.FieldType.Name;
            object newValue;

            if (fieldName == typeof(bool).Name)
            {
                val      = val.ToLower();
                newValue = val == "" | val == "true" || val != "0" || val == "yes" || val == "on";
            }
            else if (fieldName == typeof(string).Name)
            {
                newValue = val != "" ? val : fieldInfo.GetValue(layout.attr);
            }
            else if (fieldName == typeof(int).Name)
            {
                int def = (int)fieldInfo.GetValue(layout.defalutAttribute), resl;
                newValue = val != "" && int.TryParse(val, out resl) ? resl : def;
            }
            else if (fieldName == typeof(float).Name)
            {
                float def = (float)fieldInfo.GetValue(layout.defalutAttribute), resl;
                newValue = val != "" && float.TryParse(val, out resl) ? resl : def;
            }
            else
            {
                Warning("uncoded for type '" + fieldName + "', the field may be newly.");
                return(false);
            }

            situated.status.push(tag, fieldInfo.GetValue(layout.attr));
            fieldInfo.SetValue(layout.attr, newValue);

            RouteTags(tag);
            return(true);
        }
Esempio n. 7
0
        } // End Function FlexibleChangeType

        public static Setter_t <T> GetSetter <T>(string fieldName)
        {
            System.Type t = typeof(T);

            System.Reflection.FieldInfo fi = t.GetField(fieldName, System.Reflection.BindingFlags.IgnoreCase
                                                        | System.Reflection.BindingFlags.Public
                                                        | System.Reflection.BindingFlags.Instance
                                                        );

            if (fi != null)
            {
                return delegate(T obj, object value)
                       {
                           fi.SetValue(obj, FlexibleChangeType(value, fi.FieldType));
                       }
            }
            ;



            System.Reflection.PropertyInfo pi = t.GetProperty(fieldName, System.Reflection.BindingFlags.IgnoreCase
                                                              | System.Reflection.BindingFlags.Public
                                                              | System.Reflection.BindingFlags.Instance
                                                              );

            if (pi != null)
            {
                return delegate(T obj, object value)
                       {
                           pi.SetValue(obj, FlexibleChangeType(value, pi.PropertyType), null);
                       }
            }
            ;

            return(null);
        } // End Function GetSetter
Esempio n. 8
0
        /// <summary>
        /// 反射修改useUnsafeHeaderParsing
        /// </summary>
        /// <param name="useUnsafe">设置的参数值</param>
        /// <returns></returns>
        private bool SetAllowUnsafeHeaderParsing20(bool useUnsafe)
        {
            System.Reflection.Assembly aNetAssembly = System.Reflection.Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
            if (aNetAssembly != null)
            {
                Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
                if (aSettingsType != null)
                {
                    object anInstance = aSettingsType.InvokeMember("Section",
                                                                   System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.NonPublic, null, null, new object[] { });

                    if (anInstance != null)
                    {
                        System.Reflection.FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        if (aUseUnsafeHeaderParsing != null)
                        {
                            aUseUnsafeHeaderParsing.SetValue(anInstance, useUnsafe);
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        private void RegisterExtension(Type extClass, int priority, System.Web.Services.Configuration.PriorityGroup group)
        {
            if (!extClass.IsSubclassOf(typeof(System.Web.Services.Protocols.SoapExtension)))
            {
                throw new ArgumentException("Type must be derived from SoapException.", "extClass");
            }

            if (priority < 1)
            {
                throw new ArgumentOutOfRangeException("priority", priority, "Priority must be greater or equal to 1.");
            }

            System.Web.Services.Configuration.WebServicesSection wsSection = System.Web.Services.Configuration.WebServicesSection.Current;

            foreach (System.Web.Services.Configuration.SoapExtensionTypeElement it in wsSection.SoapExtensionTypes)
            {
                if (it.Type == extClass)
                {
                    return; // already registered
                }
            }
            // make collection writable
            Type type = typeof(System.Configuration.ConfigurationElementCollection);

            System.Reflection.FieldInfo readOnly = type.GetField("bReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            readOnly.SetValue(wsSection.SoapExtensionTypes, false);

            // add extension
            wsSection.SoapExtensionTypes.Add(new System.Web.Services.Configuration.SoapExtensionTypeElement(extClass, priority, group));
            // restore original collection state
            type = typeof(System.Configuration.ConfigurationElement);
            System.Reflection.MethodInfo method = type.GetMethod("ResetModified", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            method.Invoke(wsSection.SoapExtensionTypes, null);
            method = type.GetMethod("SetReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            method.Invoke(wsSection.SoapExtensionTypes, null);
        }
Esempio n. 10
0
        public void ReInitializeDriverRepository()
        {
            System.Reflection.FieldInfo fi0 = typeof(DriverRepository).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            Assert.IsNotNull(fi0);

            fi0.SetValue(null, null);

            System.Reflection.FieldInfo fi1 = typeof(TrackRepository).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            Assert.IsNotNull(fi1);

            fi1.SetValue(null, null);

            System.Reflection.FieldInfo fi2 = typeof(RaceRepository).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            Assert.IsNotNull(fi2);

            fi2.SetValue(null, null);



            driverRepository = DriverRepository.GetInstance();
            driverRepository.AddDriver(new Driver(16, "Charles", "Leclerc"));
            driverRepository.AddDriver(new Driver(5, "Sebastian", "Vettel"));
            driverRepository.AddDriver(new Driver(44, "Lewis", "Hamilton"));
            driverRepository.AddDriver(new Driver(77, "Valteri", "Bottas"));
            driverRepository.AddDriver(new Driver(3, "Max", "Verstapen"));
            driverRepository.AddDriver(new Driver(55, "Carlos", "Seinz"));

            trackRepository = TrackRepository.GetInstance();
            trackRepository.AddTrack(new Track(1, "Melbourne Grand Prix Circuit", "Australia", 5303000));
            trackRepository.AddTrack(new Track(2, "Bahrein International Circuit", "Bahrein", 5412000));
            trackRepository.AddTrack(new Track(3, "Spa-Francorchhamps", "Belgium", 7004000));
            trackRepository.AddTrack(new Track(4, "Shangai International Circuit", "China", 5451000));
        }
Esempio n. 11
0
        public void CounterStatusCheck()
        {
            //Für den ServiceProviderMock
            //Muss enthalten sein, damit der Mock nicht überschrieben wird
            IServiceProvider unused = ServiceManager.ServiceProvider;

            //Feld Infos holen
            System.Reflection.FieldInfo instance = typeof(ServiceManager).GetField("_serviceProvider", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            //Mocksaufsetzen
            //ServiceProvider
            Mock <IServiceProvider>        mockSingleton        = new Mock <IServiceProvider>();
            Mock <IActivityManager>        activityManagerMock  = new Mock <IActivityManager>();
            Mock <IServiceProvider>        activityProviderMock = new Mock <IServiceProvider>();
            Mock <AbstractStepActivity>    stepActivityMock     = new Mock <AbstractStepActivity>();
            Mock <AbstractRunningActivity> runningActivityMock  = new Mock <AbstractRunningActivity>();
            Mock <IEarablesConnection>     connectionMock       = new Mock <IEarablesConnection>();
            Mock <IPopUpService>           popUpMock            = new Mock <IPopUpService>();

            //ActivityManager
            activityManagerMock.Setup(x => x.ActitvityProvider).Returns(activityProviderMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractRunningActivity))).Returns(runningActivityMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractStepActivity))).Returns(stepActivityMock.Object);

            //IDataBaseConnection
            Mock <IDataBaseConnection> mockDataBase = new Mock <IDataBaseConnection>();
            List <DBEntry>             entries      = new List <DBEntry>();

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.GetMostRecentEntries(1)).Returns(entries);

            DateTime _dt       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            DBEntry  _entryNew = new DBEntry(_dt, 10, 0, 0);

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.SaveDBEntry(_entryNew)).Returns(1);

            //ServiceManager
            mockSingleton.Setup(x => x.GetService(typeof(IDataBaseConnection))).Returns(mockDataBase.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IActivityManager))).Returns(activityManagerMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IEarablesConnection))).Returns(connectionMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IPopUpService))).Returns(popUpMock.Object);

            //Connection
            ScanningPopUpViewModel.IsConnected = true;
            connectionMock.As <IEarablesConnection>().Setup(x => x.StartSampling());

            //ServiceProvider anlegen
            instance.SetValue(null, mockSingleton.Object);

            //Test
            StepModeViewModel viewModel = new StepModeViewModel();

            viewModel.StartActivity();
            Assert.Equal("--:--", viewModel.StepFrequency);
            viewModel.OnActivityDone(this, null);
            viewModel.OnActivityDone(this, null);
            viewModel.OnActivityDone(this, null);
            viewModel.OnRunningDone(this, new RunningEventArgs(true));
            Assert.Equal(3, viewModel.StepCounter);
            Assert.True(viewModel.IsRunning);
            Assert.NotNull(viewModel.StepFrequency);
            Assert.Equal("Du läufst!", viewModel.StatusDisplay);
            viewModel.OnRunningDone(this, new RunningEventArgs(false));
            Assert.False(viewModel.IsRunning);

            viewModel.StopActivity();
            Assert.Equal(3, viewModel.StepCounter);
            viewModel.StartActivity();
            Assert.Equal(0, viewModel.StepCounter);
            Assert.False(viewModel.IsRunning);
        }
Esempio n. 12
0
        /** Deserializes an object of type tp.
         * Will load all fields into the \a populate object if it is set (only works for classes).
         */
        System.Object Deserialize(Type tp, System.Object populate = null)
        {
            var tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp);

            if (tpInfo.IsEnum)
            {
                return(Enum.Parse(tp, EatField()));
            }
            else if (TryEat('n'))
            {
                Eat("ull");
                TryEat(',');
                return(null);
            }
            else if (Type.Equals(tp, typeof(float)))
            {
                return(float.Parse(EatField(), numberFormat));
            }
            else if (Type.Equals(tp, typeof(int)))
            {
                return(int.Parse(EatField(), numberFormat));
            }
            else if (Type.Equals(tp, typeof(uint)))
            {
                return(uint.Parse(EatField(), numberFormat));
            }
            else if (Type.Equals(tp, typeof(bool)))
            {
                return(bool.Parse(EatField()));
            }
            else if (Type.Equals(tp, typeof(string)))
            {
                return(EatField());
            }
            else if (Type.Equals(tp, typeof(Version)))
            {
                return(new Version(EatField()));
            }
            else if (Type.Equals(tp, typeof(Vector2)))
            {
                Eat("{");
                var result = new Vector2();
                EatField();
                result.x = float.Parse(EatField(), numberFormat);
                EatField();
                result.y = float.Parse(EatField(), numberFormat);
                Eat("}");
                return(result);
            }
            else if (Type.Equals(tp, typeof(Vector3)))
            {
                Eat("{");
                var result = new Vector3();
                EatField();
                result.x = float.Parse(EatField(), numberFormat);
                EatField();
                result.y = float.Parse(EatField(), numberFormat);
                EatField();
                result.z = float.Parse(EatField(), numberFormat);
                Eat("}");
                return(result);
            }
            else if (Type.Equals(tp, typeof(Guid)))
            {
                Eat("{");
                EatField();
                var result = Guid.Parse(EatField());
                Eat("}");
                return(result);
            }
            else if (Type.Equals(tp, typeof(List <string>)))
            {
                System.Collections.IList result = new List <string>();

                Eat("[");
                while (!TryEat(']'))
                {
                    result.Add(Deserialize(typeof(string)));
                    TryEat(',');
                }
                return(result);
            }
            else if (tpInfo.IsArray)
            {
                List <System.Object> ls = new List <System.Object>();
                Eat("[");
                while (!TryEat(']'))
                {
                    ls.Add(Deserialize(tp.GetElementType()));
                    TryEat(',');
                }
                var arr = Array.CreateInstance(tp.GetElementType(), ls.Count);
                ls.ToArray().CopyTo(arr, 0);
                return(arr);
            }
            else
            {
                var obj = populate ?? Activator.CreateInstance(tp);
                Eat("{");
                while (!TryEat('}'))
                {
                    var name    = EatField();
                    var tmpType = tp;
                    System.Reflection.FieldInfo field = null;
                    while (field == null && tmpType != null)
                    {
                        field   = tmpType.GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                        tmpType = tmpType.BaseType;
                    }

                    if (field == null)
                    {
                        SkipFieldData();
                    }
                    else
                    {
                        field.SetValue(obj, Deserialize(field.FieldType));
                    }
                    TryEat(',');
                }
                return(obj);
            }
        }
        public void ActivityListCheck()
        {
            //Für den ServiceProviderMock
            //Muss enthalten sein, damit der Mock nicht überschrieben wird
            IServiceProvider unused = ServiceManager.ServiceProvider;

            //Feld Infos holen
            System.Reflection.FieldInfo instance = typeof(ServiceManager).GetField("_serviceProvider",
                                                                                   System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            //Mocksaufsetzen
            //ServiceProvider
            Mock <IServiceProvider>       mockSingleton        = new Mock <IServiceProvider>();
            Mock <IActivityManager>       activityManagerMock  = new Mock <IActivityManager>();
            Mock <IServiceProvider>       activityProviderMock = new Mock <IServiceProvider>();
            Mock <AbstractSitUpActivity>  sitUpActivityMock    = new Mock <AbstractSitUpActivity>();
            Mock <AbstractPushUpActivity> pushUpActivityMock   = new Mock <AbstractPushUpActivity>();
            Mock <IEarablesConnection>    connectionMock       = new Mock <IEarablesConnection>();
            Mock <IPopUpService>          popUpMock            = new Mock <IPopUpService>();

            //ActivityManager
            activityManagerMock.Setup(x => x.ActitvityProvider).Returns(activityProviderMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractSitUpActivity)))
            .Returns(sitUpActivityMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractPushUpActivity)))
            .Returns(pushUpActivityMock.Object);

            //IDataBaseConnection
            Mock <IDataBaseConnection> mockDataBase = new Mock <IDataBaseConnection>();

            DateTime _dt       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            DBEntry  _entryNew = new DBEntry(_dt, 10, 0, 0);

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.SaveDBEntry(_entryNew)).Returns(1);

            //PopUpService
            popUpMock.SetupSequence(x =>
                                    x.ActionSheet("Wähle eine Aktivität:", "Abbruch", null, "Liegestütze", "Sit-ups", "Pause"))
            .Returns(Task.Run(() => { return("Liegestütze"); }))
            .Returns(Task.Run(() => { return("Liegestütze"); }));
            popUpMock.SetupSequence(x => x.DisplayPrompt("Liegestütze", "Gebe die Anzahl Wiederholungen an:", "Okay",
                                                         "Abbruch", "10", 3, Keyboard.Numeric))
            .Returns(Task.Run(() => { return("12"); }))
            .Returns(Task.Run(() => { return("12"); }));

            //ServiceManager
            mockSingleton.Setup(x => x.GetService(typeof(IDataBaseConnection))).Returns(mockDataBase.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IActivityManager))).Returns(activityManagerMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IPopUpService))).Returns(popUpMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IEarablesConnection))).Returns(connectionMock.Object);

            //Connection
            ScanningPopUpViewModel.IsConnected = true;
            connectionMock.As <IEarablesConnection>().Setup(x => x.StartSampling());

            //ServiceProvider anlegen
            instance.SetValue(null, mockSingleton.Object);

            //Test
            ListenAndPerformViewModel viewModel = new ListenAndPerformViewModel();

            viewModel.AddActivityCommand.Execute(3);             //4
            Assert.Equal(4, viewModel.ActivityList.Count);
            IEnumerator <ActivityWrapper> iterator = viewModel.ActivityList.GetEnumerator();

            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            Assert.Equal("Liegestütze", iterator.Current.Name);
            Assert.Equal(12, iterator.Current.Amount);

            viewModel.SelectedActivity = iterator.Current;
            viewModel.EditActivityCommand.Execute(null);
            iterator = viewModel.ActivityList.GetEnumerator();
            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            viewModel.SelectedActivity = iterator.Current;
            viewModel.RemoveActivityCommand.Execute(null);
            Assert.Equal(3, viewModel.ActivityList.Count);
        }
Esempio n. 14
0
        public virtual void DrawNodeInspectorGUI()
        {
            NodeComment = UnityEditor.EditorGUILayout.TextField("NodeComment", NodeComment);
            BTHelper.DrawSeparator();
            if (!AutoDrawNodeInspector)
            {
                return;
            }
            System.Reflection.FieldInfo[] fields = GetType().GetFields();
            for (int i = 0; i < fields.Length; i++)
            {
                System.Reflection.FieldInfo field = fields[i];
                if (field.IsDefined(typeof(NodeVariable), false))
                {
                    object v = field.GetValue(this);
                    Type   t = field.FieldType;

                    if (t.BaseType == typeof(Enum))
                    {
                        v = UnityEditor.EditorGUILayout.EnumPopup(field.Name, (Enum)v);
                    }
                    else if (t == typeof(int))
                    {
                        v = UnityEditor.EditorGUILayout.IntField(field.Name, (int)v);
                    }
                    else if (t == typeof(bool))
                    {
                        v = UnityEditor.EditorGUILayout.Toggle(field.Name, (bool)v);
                    }
                    else if (t == typeof(float))
                    {
                        v = UnityEditor.EditorGUILayout.FloatField(field.Name, (float)v);
                    }
                    else if (t == typeof(string))
                    {
                        v = UnityEditor.EditorGUILayout.TextField(field.Name, (string)v);
                    }
                    else if (t == typeof(UnityEngine.Object))
                    {
                        v = UnityEditor.EditorGUILayout.ObjectField(field.Name, (UnityEngine.Object)v, t, false);
                    }
                    else if (t == typeof(double))
                    {
                        v = UnityEditor.EditorGUILayout.DoubleField(field.Name, (double)v);
                    }
                    else if (t == typeof(Vector3))
                    {
                        v = UnityEditor.EditorGUILayout.Vector3Field(field.Name, (Vector3)v);
                    }
                    else if (t == typeof(Vector2))
                    {
                        v = UnityEditor.EditorGUILayout.Vector2Field(field.Name, (Vector2)v);
                    }
                    else if (t == typeof(AnimationCurve))
                    {
                        v = UnityEditor.EditorGUILayout.CurveField(field.Name, (AnimationCurve)v);
                    }
                    else if (t == typeof(Color))
                    {
                        v = UnityEditor.EditorGUILayout.ColorField(field.Name, (Color)v);
                    }
                    try
                    {
                        field.SetValue(this, v);
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError(ex.ToString());
                    }
                }
            }
        }
Esempio n. 15
0
 public void Set(object _this, object value)
 {
     info.SetValue(_this, value);
 }
Esempio n. 16
0
 private static void SetMyGraphics()
 {
     System.Reflection.FieldInfo fi = typeof(XPaint).GetField("graphics", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
     fi.SetValue(null, new MyXPaint());
 }
Esempio n. 17
0
        private GridEquipStats ComputeDisplayStats(DataEquipmentInformation equip)
        {
            ViewUpgradeModeComboIndex upgrade_type = (ViewUpgradeModeComboIndex)comboBoxUpgradeMode.SelectedIndex;

            RealmSynergy.SynergyValue synergy = RealmSynergy.Values.ElementAt(comboBoxSynergy.SelectedIndex);
            bool has_synergy = equip.SeriesId == synergy.GameSeries;

            DataCache.Items.Key cache_key = new DataCache.Items.Key {
                ItemId = equip.EquipmentId
            };
            DataCache.Items.Data cache_value;
            bool in_cache = FFRKProxy.Instance.Cache.Items.TryGetValue(cache_key, out cache_value);

            GridEquipStats result = new GridEquipStats();

            if (upgrade_type == ViewUpgradeModeComboIndex.CurrentUpgradeCurrentLevel)
            {
                result.Stats.Atk = (has_synergy) ? equip.SeriesAtk : equip.Atk;
                result.Stats.Mag = (has_synergy) ? equip.SeriesMag : equip.Mag;
                result.Stats.Acc = (has_synergy) ? equip.SeriesAcc : equip.Acc;
                result.Stats.Def = (has_synergy) ? equip.SeriesDef : equip.Def;
                result.Stats.Res = (has_synergy) ? equip.SeriesRes : equip.Res;
                result.Stats.Eva = (has_synergy) ? equip.SeriesEva : equip.Eva;
                result.Stats.Mnd = (has_synergy) ? equip.SeriesMnd : equip.Mnd;
                result.Level     = equip.Level;
                result.MaxLevel  = equip.LevelMax;
                if (equip.SeriesId == synergy.GameSeries)
                {
                    result.Level = StatCalculator.EffectiveLevelWithSynergy(result.Level);
                }
            }
            else
            {
                if (upgrade_type == ViewUpgradeModeComboIndex.CurrentUpgradeMaxLevel)
                {
                    result.MaxLevel = StatCalculator.MaxLevel(equip.Rarity);
                }
                else if (upgrade_type == ViewUpgradeModeComboIndex.MaxLevelThroughExistingCombine)
                {
                    // Valid candidates for combining items into this are only those items with matching
                    // equipment id and rarity LESS THAN OR EQUAL TO current item's rarity
                    int candidates = mEquipments.Count(x => x.EquipmentId == equip.EquipmentId && x.InstanceId != equip.InstanceId && x.Rarity <= equip.Rarity);
                    result.MaxLevel = StatCalculator.MaxLevel(StatCalculator.EvolveAsMuchAsPossible(equip.BaseRarity, equip.Rarity, candidates));
                }
                else
                {
                    result.MaxLevel = StatCalculator.MaxLevel(StatCalculator.Evolve(equip.BaseRarity, SchemaConstants.EvolutionLevel.PlusPlus));
                }
                result.Level = result.MaxLevel;
                if (has_synergy)
                {
                    result.Level = StatCalculator.EffectiveLevelWithSynergy(result.Level);
                }

                if (in_cache && cache_value.AreStatsValid)
                {
                    // Try to get the equipment stats from the database
                    result.Stats.Atk = StatCalculator.ComputeStatForLevel(equip.BaseRarity, cache_value.BaseStats.Atk, cache_value.MaxStats.Atk, result.Level);
                    result.Stats.Mag = StatCalculator.ComputeStatForLevel(equip.BaseRarity, cache_value.BaseStats.Mag, cache_value.MaxStats.Mag, result.Level);
                    result.Stats.Acc = StatCalculator.ComputeStatForLevel(equip.BaseRarity, cache_value.BaseStats.Acc, cache_value.MaxStats.Acc, result.Level);
                    result.Stats.Def = StatCalculator.ComputeStatForLevel(equip.BaseRarity, cache_value.BaseStats.Def, cache_value.MaxStats.Def, result.Level);
                    result.Stats.Res = StatCalculator.ComputeStatForLevel(equip.BaseRarity, cache_value.BaseStats.Res, cache_value.MaxStats.Res, result.Level);
                    result.Stats.Eva = StatCalculator.ComputeStatForLevel(equip.BaseRarity, cache_value.BaseStats.Eva, cache_value.MaxStats.Eva, result.Level);
                    result.Stats.Mnd = StatCalculator.ComputeStatForLevel(equip.BaseRarity, cache_value.BaseStats.Mnd, cache_value.MaxStats.Mnd, result.Level);
                }
                else
                {
                    // If they aren't there, fall back to trying to compute effective stats from the ifnormation in the JSON.  This will lead to some
                    // rounding error due to the fact that the values for Atk and SeriesAtk etc are all rounded, so the division will be less precise
                    // than doing it over the entire range of Max stats and base stats, but it's the best we can do in this case.
                    byte series_effective_level = StatCalculator.EffectiveLevelWithSynergy(equip.Level);
                    result.Stats.Atk = (result.MaxLevel == equip.Level) ? ((has_synergy) ? equip.SeriesAtk : equip.Atk) : StatCalculator.ComputeStatForLevel2(equip.Atk, equip.Level, equip.SeriesAtk, series_effective_level, result.Level);
                    result.Stats.Mag = (result.MaxLevel == equip.Level) ? ((has_synergy) ? equip.SeriesMag : equip.Mag) : StatCalculator.ComputeStatForLevel2(equip.Mag, equip.Level, equip.SeriesMag, series_effective_level, result.Level);
                    result.Stats.Acc = (result.MaxLevel == equip.Level) ? ((has_synergy) ? equip.SeriesAcc : equip.Acc) : StatCalculator.ComputeStatForLevel2(equip.Acc, equip.Level, equip.SeriesAcc, series_effective_level, result.Level);
                    result.Stats.Def = (result.MaxLevel == equip.Level) ? ((has_synergy) ? equip.SeriesDef : equip.Def) : StatCalculator.ComputeStatForLevel2(equip.Def, equip.Level, equip.SeriesDef, series_effective_level, result.Level);
                    result.Stats.Res = (result.MaxLevel == equip.Level) ? ((has_synergy) ? equip.SeriesRes : equip.Res) : StatCalculator.ComputeStatForLevel2(equip.Res, equip.Level, equip.SeriesRes, series_effective_level, result.Level);
                    result.Stats.Eva = (result.MaxLevel == equip.Level) ? ((has_synergy) ? equip.SeriesEva : equip.Eva) : StatCalculator.ComputeStatForLevel2(equip.Eva, equip.Level, equip.SeriesEva, series_effective_level, result.Level);
                    result.Stats.Mnd = (result.MaxLevel == equip.Level) ? ((has_synergy) ? equip.SeriesMnd : equip.Mnd) : StatCalculator.ComputeStatForLevel2(equip.Mnd, equip.Level, equip.SeriesMnd, series_effective_level, result.Level);
                }
            }

            if (equip.AugmentStat != null && equip.Augment > 0)
            {
                double bonus = (has_synergy) ? equip.Augment * 1.5 : (double)equip.Augment;

                System.Reflection.FieldInfo augmentField = typeof(EquipStats).GetField(equip.AugmentStat);
                short val = (short)augmentField.GetValue(result.Stats);
                augmentField.SetValue(result.Stats, (short)Math.Ceiling(val + bonus));
            }
            return(result);
        }
Esempio n. 18
0
        /// <summary>
        /// Uses a System.Reflection.FieldInfo to add a field
        /// Handles most built-in types and components
        /// includes automatic naming like the inspector does
        /// by default
        /// </summary>
        /// <param name="fieldInfo"></param>
        public static void FieldInfoField <T>(T instance, System.Reflection.FieldInfo fieldInfo)
        {
            string label = fieldInfo.Name.DeCamel();

            #region Built-in Data Types
            if (fieldInfo.FieldType == typeof(string))
            {
                var val = (string)fieldInfo.GetValue(instance);
                val = EditorGUILayout.TextField(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(int))
            {
                var val = (int)fieldInfo.GetValue(instance);
                val = EditorGUILayout.IntField(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(float))
            {
                var val = (float)fieldInfo.GetValue(instance);
                val = EditorGUILayout.FloatField(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(bool))
            {
                var val = (bool)fieldInfo.GetValue(instance);
                val = EditorGUILayout.Toggle(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            #endregion Built-in Data Types

            #region Basic Unity Types
            else if (fieldInfo.FieldType == typeof(GameObject))
            {
                var val = (GameObject)fieldInfo.GetValue(instance);
                val = ObjectField <GameObject>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(Transform))
            {
                var val = (Transform)fieldInfo.GetValue(instance);
                val = ObjectField <Transform>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(Rigidbody))
            {
                var val = (Rigidbody)fieldInfo.GetValue(instance);
                val = ObjectField <Rigidbody>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(Renderer))
            {
                var val = (Renderer)fieldInfo.GetValue(instance);
                val = ObjectField <Renderer>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(Mesh))
            {
                var val = (Mesh)fieldInfo.GetValue(instance);
                val = ObjectField <Mesh>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            #endregion Basic Unity Types

            #region Unity Collider Types
            else if (fieldInfo.FieldType == typeof(BoxCollider))
            {
                var val = (BoxCollider)fieldInfo.GetValue(instance);
                val = ObjectField <BoxCollider>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(SphereCollider))
            {
                var val = (SphereCollider)fieldInfo.GetValue(instance);
                val = ObjectField <SphereCollider>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(CapsuleCollider))
            {
                var val = (CapsuleCollider)fieldInfo.GetValue(instance);
                val = ObjectField <CapsuleCollider>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(MeshCollider))
            {
                var val = (MeshCollider)fieldInfo.GetValue(instance);
                val = ObjectField <MeshCollider>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            else if (fieldInfo.FieldType == typeof(WheelCollider))
            {
                var val = (WheelCollider)fieldInfo.GetValue(instance);
                val = ObjectField <WheelCollider>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            #endregion Unity Collider Types

            #region Other Unity Types
            else if (fieldInfo.FieldType == typeof(CharacterController))
            {
                var val = (CharacterController)fieldInfo.GetValue(instance);
                val = ObjectField <CharacterController>(label, val);
                fieldInfo.SetValue(instance, val);
                return;
            }
            #endregion Other Unity Types
        }
Esempio n. 19
0
        public void LoadLocalFile(string loname)
        {
            string filename = "./lang/" + loname + ".txt";

            if (!File.Exists(filename))
            {
                filename = AppDomain.CurrentDomain.BaseDirectory + "lang/" + loname + ".txt";
            }
            if (!File.Exists(filename))
            {
                return;
            }

            FileStream   fini = new FileStream(filename, FileMode.Open);
            StreamReader srini = new StreamReader(fini);
            string       sLine = "";
            string       sName = "", sPara = "";

            while (sLine != null)
            {
                sLine = srini.ReadLine();
                if
                (
                    sLine != null &&
                    sLine != "" &&
                    sLine.Substring(0, 1) != "-" &&
                    sLine.Substring(0, 1) != "%" &&
                    sLine.Substring(0, 1) != "'" &&
                    sLine.Substring(0, 1) != "/" &&
                    sLine.Substring(0, 1) != "!" &&
                    sLine.Substring(0, 1) != "[" &&
                    sLine.Substring(0, 1) != "#" &&
                    sLine.Contains("=") &&
                    !sLine.Substring(sLine.IndexOf("=") + 1).Contains("=")
                )
                {
                    sName = sLine.Substring(0, sLine.IndexOf("="));
                    sName = sName.Trim();
                    sPara = sLine.Substring(sLine.IndexOf("=") + 1);
                    sPara = sPara.Trim();
                    sPara = sPara.Trim('\"');

                    if (sName.StartsWith("ButtonNamePen"))
                    {
                        int penid = 0;
                        if (int.TryParse(sName.Substring(13, 1), out penid))
                        {
                            ButtonNamePen[penid] = sPara;
                        }
                    }

                    System.Reflection.FieldInfo fi = typeof(Local).GetField(sName);
                    if (fi != null)
                    {
                        fi.SetValue(this, sPara);
                    }
                }
            }
            fini.Close();

            CurrentLanguageFile = loname;
        }
Esempio n. 20
0
        /// <summary>
        /// Compile script
        /// </summary>
        /// <returns>Compiler ok or not</returns>
        public virtual bool Compile()
        {
            strRuntimeScriptText = null;
            strCompilerOutput    = null;
            myCompilerErrors     = null;
            if (bolClosedFlag)
            {
                return(false);
            }
            if (strScriptText == null || strScriptText.Trim().Length == 0)
            {
                return(false);
            }
            intScriptVersion++;
            bool bolResult = false;

            this.ScriptMethods.Clear();
            myAssembly        = null;
            bolScriptModified = false;

            // Generate integrated VB.NET source code

            string ModuleName       = "mdlXVBAScriptEngine";
            string globalModuleName = "mdlXVBAScriptGlobalValues";
            string nsName           = "NameSpaceXVBAScriptEngien";

            System.Text.StringBuilder mySource = new System.Text.StringBuilder();
            mySource.Append("Option Strict Off");
            foreach (string import in this.Options.ImportNamespaces)
            {
                mySource.Append("\r\nImports " + import);
            }
            mySource.Append("\r\nNamespace " + nsName);
            //System.Collections.Hashtable myGObjects = new Hashtable();
            // Generate source code for global objects
            if (myGlobalObjects != null && myGlobalObjects.Count > 0)
            {
                myVBCompilerImports.Add(nsName);

                //mySource.Append("\r\n<Microsoft.VisualBasic.CompilerServices.StandardModule>");
                mySource.Append("\r\nModule " + globalModuleName);
                mySource.Append("\r\n");
                mySource.Append("\r\n    Public myGlobalValues As Object");
                foreach (XVBAScriptGlobalObject item in myGlobalObjects)
                {
                    if (System.Xml.XmlReader.IsName(item.Name) == false)
                    {
                        if (this.ThrowException)
                        {
                            throw new ArgumentException("Script global object name:" + item.Name);
                        }
                        else
                        {
                            if (this.OutputDebug)
                            {
                                System.Diagnostics.Debug.WriteLine("Script global object name:" + item.Name);
                            }
                            continue;
                        }
                    }
                    if (item.ValueType.Equals(typeof(object)) || item.ValueType.IsPublic == false)
                    {
                        mySource.Append("\r\n    Public ReadOnly Property " + item.Name + "() As Object ");
                        mySource.Append("\r\n      Get");
                        mySource.Append("\r\n         Return myGlobalValues(\"" + item.Name + "\") ");
                        mySource.Append("\r\n      End Get");
                        mySource.Append("\r\n    End Property");
                    }
                    else
                    {
                        string typeName = item.ValueType.FullName;
                        typeName = typeName.Replace("+", ".");
                        mySource.Append("\r\n    Public ReadOnly Property " + item.Name + "() As " + typeName);
                        mySource.Append("\r\n      Get");
                        mySource.Append("\r\n         Return CType( myGlobalValues(\"" + item.Name + "\") , " + typeName + ")");
                        mySource.Append("\r\n      End Get");
                        mySource.Append("\r\n    End Property");
                    }
                }
                mySource.Append("\r\nEnd Module");
            }

            mySource.Append("\r\nModule " + ModuleName);
            mySource.Append("\r\n");
            mySource.Append(this.strScriptText);
            mySource.Append("\r\nEnd Module");
            mySource.Append("\r\nEnd Namespace");
            strRuntimeScriptText = mySource.ToString();

            myAssembly = null;
            if (myAssemblyBuffer != null)
            {
                // Check assembly buffer
                myAssembly = myAssemblyBuffer.GetAssembly(strRuntimeScriptText);
            }
            if (myAssembly == null)
            {
                // Use dynamic compile

                DynamicCompiler compiler = new DynamicCompiler();
                compiler.Language               = CompilerLanguage.VB;
                compiler.AppDomain              = myAppDomain;
                compiler.PreserveAssemblyFile   = false;
                compiler.OutputDebug            = this.OutputDebug;
                compiler.ThrowException         = this.ThrowException;
                compiler.SourceCode             = strRuntimeScriptText;
                compiler.AutoLoadResultAssembly = true;
                // add referenced assemblies
                DotNetAssemblyInfoList refs = this.Options.ReferenceAssemblies.Clone();
                refs.AddByType(this.GetType());
                if (this.GlobalObjects.Count > 0)
                {
                    foreach (XVBAScriptGlobalObject item in this.GlobalObjects)
                    {
                        refs.AddByType(item.ValueType);
                    }
                }
                foreach (string asm in this.Options.InnerReferenceAssemblies)
                {
                    refs.AddByName(asm);
                }

                foreach (DotNetAssemblyInfo asm in refs)
                {
                    if (asm.SourceStyle == AssemblySourceStyle.Standard)
                    {
                        compiler.ReferenceAssemblies.Add(System.IO.Path.GetFileName(asm.FileName));
                    }
                    else
                    {
                        compiler.ReferenceAssemblies.Add(asm.FileName);
                    }
                }

                foreach (string ns in this.VBCompilerImports)
                {
                    compiler.CompilerImports.Add(ns);
                }
                if (compiler.Compile())
                {
                    myAssembly = compiler.ResultAssembly;
                    if (myAssemblyBuffer != null)
                    {
                        myAssemblyBuffer.AddAssembly(
                            strRuntimeScriptText,
                            myAssembly,
                            compiler.ResultAssemblyBinary);
                    }
                    bolResult = true;
                }
                else
                {
                    myCompilerErrors = compiler.CompilerErrors;
                    foreach (CompilerError error in myCompilerErrors)
                    {
                        if (error.IsWarning == false)
                        {
                            // report error
                            if (this.Errors != null)
                            {
                                ScriptError err = new ScriptError(this, ScriptErrorStyle.Compile, null, null);
                                err.Message    = error.ErrorText;
                                err.ScriptText = error.ErrorText;
                                this.Errors.Add(err);
                            }
                            bolResult = false;
                            break;
                        }
                    }
                }
                strRuntimeScriptTextWithCompilerErrorMessage = compiler.SourceCodeWithCompilerErrorMessage;
            }
            if (this.myAssembly != null)
            {
                // set global object instance
                Type ModuleType = myAssembly.GetType(nsName + "." + globalModuleName);
                if (ModuleName != null)
                {
                    System.Reflection.FieldInfo gf = ModuleType.GetField("myGlobalValues");
                    gf.SetValue(null, this.GlobalObjects);
                }

                // analyze script method
                ModuleType = myAssembly.GetType(nsName + "." + ModuleName);
                if (ModuleType != null)
                {
                    System.Reflection.MethodInfo[] ms = ModuleType.GetMethods(
                        System.Reflection.BindingFlags.Public
                        | System.Reflection.BindingFlags.NonPublic
                        | System.Reflection.BindingFlags.Static);
                    foreach (System.Reflection.MethodInfo m in ms)
                    {
                        // generate script method information
                        ScriptMethodInfo info = new ScriptMethodInfo();
                        info.Assembly     = myAssembly;
                        info.MethodName   = m.Name;
                        info.MethodObject = m;
                        info.ModuleName   = ModuleType.Name;
                        info.ReturnType   = m.ReturnType;
                        info.ScriptText   = (string)myMethodSciptText[info.MethodName];
                        this.ScriptMethods.Add(info);
                        if (this.bolOutputDebug)
                        {
                            System.Diagnostics.Debug.WriteLine(
                                string.Format(ScriptStrings.AnalyseVBMethod_Name, m.Name));
                        }
                    } //foreach
                    bolResult = true;
                }     //if
            }
            return(bolResult);
        }
        /// <summary>
        /// Scans all classes deriving from any Mod type
        /// for a field called _ref
        /// and populates it, if it exists.
        /// </summary>
        private void LoadReferences()
        {
            foreach (Type type in Code.GetTypes())
            {
                if (type.IsAbstract)
                {
                    continue;
                }

                System.Reflection.FieldInfo field = type.GetField("_ref");
                if (field == null || !field.IsStatic)
                {
                    continue;
                }

                if (type.IsSubclassOf(typeof(ModItem)))
                {
                    if (field.FieldType == typeof(ModItem))
                    {
                        field.SetValue(null, GetItem(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModNPC)))
                {
                    if (field.FieldType == typeof(ModNPC))
                    {
                        field.SetValue(null, GetNPC(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModProjectile)))
                {
                    if (field.FieldType == typeof(ModProjectile))
                    {
                        field.SetValue(null, GetProjectile(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModDust)))
                {
                    if (field.FieldType == typeof(ModDust))
                    {
                        field.SetValue(null, GetDust(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModTile)))
                {
                    if (field.FieldType == typeof(ModTile))
                    {
                        field.SetValue(null, GetTile(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModWall)))
                {
                    if (field.FieldType == typeof(ModWall))
                    {
                        field.SetValue(null, GetWall(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModBuff)))
                {
                    if (field.FieldType == typeof(ModBuff))
                    {
                        field.SetValue(null, GetBuff(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModMountData)))
                {
                    if (field.FieldType == typeof(ModMountData))
                    {
                        field.SetValue(null, GetMount(type.Name));
                    }
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Copies the contents of the <see cref="FTBitmap"/> to a GDI+ <see cref="Bitmap"/>.
        /// </summary>
        /// <param name="color">The color of the text.</param>
        /// <returns>A GDI+ <see cref="Bitmap"/> containing this bitmap's data with a transparent background.</returns>
        public static Bitmap ToGdipBitmap(this FTBitmap b, Color color)
        {
            if (b.IsDisposed)
            {
                throw new ObjectDisposedException("FTBitmap", "Cannot access a disposed object.");
            }

            if (b.Width == 0 || b.Rows == 0)
            {
                throw new InvalidOperationException("Invalid image size - one or both dimensions are 0.");
            }

            //TODO deal with negative pitch
            switch (b.PixelMode)
            {
            case PixelMode.Mono:
            {
                Bitmap bmp    = new Bitmap(b.Width, b.Rows, PixelFormat.Format1bppIndexed);
                var    locked = bmp.LockBits(new Rectangle(0, 0, b.Width, b.Rows), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);

                for (int i = 0; i < b.Rows; i++)
                {
                    Copy(b.Buffer, i * b.Pitch, locked.Scan0, i * locked.Stride, locked.Stride);
                }

                bmp.UnlockBits(locked);

                ColorPalette palette = bmp.Palette;
                palette.Entries[0] = Color.FromArgb(0, color);
                palette.Entries[1] = Color.FromArgb(255, color);

                bmp.Palette = palette;
                return(bmp);
            }

            case PixelMode.Gray4:
            {
                Bitmap bmp    = new Bitmap(b.Width, b.Rows, PixelFormat.Format4bppIndexed);
                var    locked = bmp.LockBits(new Rectangle(0, 0, b.Width, b.Rows), ImageLockMode.ReadWrite, PixelFormat.Format4bppIndexed);

                for (int i = 0; i < b.Rows; i++)
                {
                    Copy(b.Buffer, i * b.Pitch, locked.Scan0, i * locked.Stride, locked.Stride);
                }

                bmp.UnlockBits(locked);

                ColorPalette palette = bmp.Palette;
                for (int i = 0; i < palette.Entries.Length; i++)
                {
                    float a = (i * 17) / 255f;
                    palette.Entries[i] = Color.FromArgb(i * 17, (int)(color.R * a), (int)(color.G * a), (int)(color.B * a));
                }

                bmp.Palette = palette;
                return(bmp);
            }

            case PixelMode.Gray:
            {
                Bitmap bmp    = new Bitmap(b.Width, b.Rows, PixelFormat.Format8bppIndexed);
                var    locked = bmp.LockBits(new Rectangle(0, 0, b.Width, b.Rows), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

                for (int i = 0; i < b.Rows; i++)
                {
                    Copy(b.Buffer, i * b.Pitch, locked.Scan0, i * locked.Stride, locked.Stride);
                }

                bmp.UnlockBits(locked);

                ColorPalette palette = bmp.Palette;
                for (int i = 0; i < palette.Entries.Length; i++)
                {
                    float a = i / 255f;
                    palette.Entries[i] = Color.FromArgb(i, (int)(color.R * a), (int)(color.G * a), (int)(color.B * a));
                }

                //HACK There's a bug in Mono's libgdiplus requiring the "PaletteHasAlpha" flag to be set for transparency to work properly
                //See https://github.com/Robmaister/SharpFont/issues/62
                if (!hasCheckedForMono)
                {
                    hasCheckedForMono = true;
                    isRunningOnMono   = Type.GetType("Mono.Runtime") != null;
                    if (isRunningOnMono)
                    {
                        monoPaletteFlagsField = typeof(ColorPalette).GetField("flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    }
                }

                if (isRunningOnMono)
                {
                    monoPaletteFlagsField.SetValue(palette, palette.Flags | 1);
                }

                bmp.Palette = palette;
                return(bmp);
            }

            case PixelMode.Lcd:
            {
                //TODO apply color
                int    bmpWidth = b.Width / 3;
                Bitmap bmp      = new Bitmap(bmpWidth, b.Rows, PixelFormat.Format24bppRgb);
                var    locked   = bmp.LockBits(new Rectangle(0, 0, bmpWidth, b.Rows), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

                for (int i = 0; i < b.Rows; i++)
                {
                    Copy(b.Buffer, i * b.Pitch, locked.Scan0, i * locked.Stride, locked.Stride);
                }

                bmp.UnlockBits(locked);

                return(bmp);
            }

            /*case PixelMode.VerticalLcd:
             * {
             *      int bmpHeight = b.Rows / 3;
             *      Bitmap bmp = new Bitmap(b.Width, bmpHeight, PixelFormat.Format24bppRgb);
             *      var locked = bmp.LockBits(new Rectangle(0, 0, b.Width, bmpHeight), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
             *      for (int i = 0; i < bmpHeight; i++)
             *              PInvokeHelper.Copy(Buffer, i * b.Pitch, locked.Scan0, i * locked.Stride, b.Width);
             *      bmp.UnlockBits(locked);
             *
             *      return bmp;
             * }*/

            default:
                throw new InvalidOperationException("System.Drawing.Bitmap does not support this pixel mode.");
            }
        }
Esempio n. 23
0
        public void StartProcess(SVGAsset asset)
        {
            if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            if (errors == null)
            {
                errors = new List <SVGError>();
            }
            else
            {
                errors.Clear();
            }
            _importingSVG = true;

            System.Reflection.FieldInfo _editor_runtimeMaterials = typeof(SVGAsset).GetField("_runtimeMaterials", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            _editor_runtimeMaterials.SetValue(asset, null);

            System.Reflection.FieldInfo _editor_runtimeMesh = typeof(SVGAsset).GetField("_runtimeMesh", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            _editor_runtimeMesh.SetValue(asset, null);

            UnityEditor.SerializedObject   svgAsset      = new UnityEditor.SerializedObject(asset);
            UnityEditor.SerializedProperty sharedMesh    = svgAsset.FindProperty("_sharedMesh");
            UnityEditor.SerializedProperty sharedShaders = svgAsset.FindProperty("_sharedShaders");

            Clear();
            SVGParser.Init();
            SVGGraphics.Init();
            atlasData = new SVGAtlasData();
            atlasData.Init(SVGAtlas.defaultAtlasTextureWidth * SVGAtlas.defaultAtlasTextureHeight);
            atlasData.AddGradient(SVGAtlasData.GetDefaultGradient());
            SVGElement _rootSVGElement = null;

#if IGNORE_EXCEPTIONS
            try {
#else
            Debug.LogWarning("Exceptions are turned on!");
#endif
                // Create new Asset
                CreateEmptySVGDocument();
                _rootSVGElement = this._svgDocument.rootElement;
#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                _rootSVGElement = null;
                errors.Add(SVGError.Syntax);
                Debug.LogError("SVG Document Exception: " + exception.Message, asset);
            }
#endif

                if (_rootSVGElement == null)
                {
                    Debug.LogError("SVG Document is corrupted! " + UnityEditor.AssetDatabase.GetAssetPath(asset), asset);
                    _importingSVG = false;
                    return;
                }

#if IGNORE_EXCEPTIONS
                try {
#endif
                _rootSVGElement.Render();

                Rect viewport = _rootSVGElement.paintable.viewport;
                viewport.x    *= SVGAssetImport.meshScale;
                viewport.y    *= SVGAssetImport.meshScale;
                viewport.size *= SVGAssetImport.meshScale;

                Vector2 offset;
                SVGGraphics.CorrectSVGLayers(SVGGraphics.layers, viewport, asset, out offset);

                // Handle gradients
                bool hasGradients = false;

                // Create actual Mesh
                Shader[] outputShaders;
                Mesh mesh = new Mesh();
                SVGMesh.CombineMeshes(SVGGraphics.layers.ToArray(), mesh, out outputShaders, useGradients, format, compressDepth, asset.antialiasing);
                if (mesh == null)
                {
                    return;
                }

                if (useGradients == SVGUseGradients.Always)
                {
                    if (outputShaders != null)
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            if (outputShaders[i] == null)
                            {
                                continue;
                            }
                            if (outputShaders[i].name == SVGShader.SolidColorOpaque.name)
                            {
                                outputShaders[i] = SVGShader.GradientColorOpaque;
                            }
                            else if (outputShaders[i].name == SVGShader.SolidColorAlphaBlended.name)
                            {
                                outputShaders[i] = SVGShader.GradientColorAlphaBlended;
                            }
                            else if (outputShaders[i].name == SVGShader.SolidColorAlphaBlendedAntialiased.name)
                            {
                                outputShaders[i] = SVGShader.GradientColorAlphaBlendedAntialiased;
                            }
                        }
                    }
                    hasGradients = true;
                }
                else
                {
                    if (outputShaders != null)
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            if (outputShaders[i] == null)
                            {
                                continue;
                            }
                            if (outputShaders[i].name == SVGShader.GradientColorOpaque.name ||
                                outputShaders[i].name == SVGShader.GradientColorAlphaBlended.name ||
                                outputShaders[i].name == SVGShader.GradientColorAlphaBlendedAntialiased.name ||
                                outputShaders[i].name == SVGShader.GradientColorAlphaBlendedAntialiasedCompressed.name)
                            {
                                hasGradients = true;
                                break;
                            }
                        }
                    }
                }

                if (!asset.useLayers)
                {
                    sharedMesh.objectReferenceValue = AddObjectToAsset <Mesh>(mesh, asset, HideFlags.HideInHierarchy);
                }

//                Material sharedMaterial;
                if (outputShaders != null && outputShaders.Length > 0)
                {
                    sharedShaders.arraySize = outputShaders.Length;
                    if (hasGradients)
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputShaders[i].name;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            if (outputShaders[i].name == SVGShader.GradientColorAlphaBlended.name)
                            {
                                outputShaders[i] = SVGShader.SolidColorAlphaBlended;
                            }
                            else if (outputShaders[i].name == SVGShader.GradientColorOpaque.name)
                            {
                                outputShaders[i] = SVGShader.SolidColorOpaque;
                            }
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputShaders[i].name;
                        }
                    }
                }

                // Serialize the Asset
                svgAsset.ApplyModifiedProperties();

                // Handle Canvas Rectangle
                System.Reflection.MethodInfo _editor_SetCanvasRectangle = typeof(SVGAsset).GetMethod("_editor_SetCanvasRectangle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetCanvasRectangle.Invoke(asset, new object[] { new Rect(viewport.x, viewport.y, viewport.size.x, viewport.size.y) });

                if (asset.generateCollider)
                {
                    // Create polygon contour
                    if (SVGGraphics.paths != null && SVGGraphics.paths.Count > 0)
                    {
                        List <List <Vector2> > polygons = new List <List <Vector2> >();
                        for (int i = 0; i < SVGGraphics.paths.Count; i++)
                        {
                            Vector2[] points = SVGGraphics.paths[i].points;
                            for (int j = 0; j < points.Length; j++)
                            {
                                points[j].x = points[j].x * SVGAssetImport.meshScale - offset.x;
                                points[j].y = (points[j].y * SVGAssetImport.meshScale + offset.y) * -1f;
                            }

                            polygons.Add(new List <Vector2>(points));
                        }

                        polygons = SVGGeom.MergePolygon(polygons);

                        SVGPath[] paths = new SVGPath[polygons.Count];
                        for (int i = 0; i < polygons.Count; i++)
                        {
                            paths[i] = new SVGPath(polygons[i].ToArray());
                        }

                        System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        if (paths != null && paths.Length > 0)
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { paths });
                        }
                        else
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { null });
                        }
                    }
                }
                else
                {
                    System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    _editor_SetColliderShape.Invoke(asset, new object[] { null });
                }

                System.Reflection.MethodInfo _editor_SetGradients = typeof(SVGAsset).GetMethod("_editor_SetGradients", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetGradients.Invoke(asset, new object[] { null });
                if (hasGradients)
                {
                    if (atlasData.gradientCache != null && atlasData.gradientCache.Count > 0)
                    {
                        int          gradientsCount = SVGAssetImport.atlasData.gradientCache.Count;
                        CCGradient[] gradients      = new CCGradient[gradientsCount];
                        int          i = 0;
                        foreach (KeyValuePair <string, CCGradient> entry in SVGAssetImport.atlasData.gradientCache)
                        {
                            gradients[i++] = entry.Value;
                        }
                        _editor_SetGradients.Invoke(asset, new object[] { gradients });
                    }
                }

                System.Reflection.MethodInfo _editor_SetLayers = typeof(SVGAsset).GetMethod("_editor_SetLayers", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetLayers.Invoke(asset, new object[] { null });
                if (asset.useLayers)
                {
                    if (SVGGraphics.layers != null && SVGGraphics.layers.Count > 0)
                    {
                        _editor_SetLayers.Invoke(asset, new object[] { SVGGraphics.layers.ToArray() });
                    }
                }

#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                Debug.LogWarning("Asset: " + UnityEditor.AssetDatabase.GetAssetPath(asset) + " Failed to import\n" + exception.Message, asset);
                errors.Add(SVGError.CorruptedFile);
            }
#endif
                if (_svgDocument != null)
                {
                    _svgDocument.Clear();
                    _svgDocument = null;
                }
                Clear();

                UnityEditor.EditorUtility.SetDirty(asset);
                _importingSVG = false;
            }
Esempio n. 24
0
 public void SetValue(System.Reflection.FieldInfo field, object value)
 {
     field.SetValue(this, value);
 }
Esempio n. 25
0
        /// <summary>
        /// Scans all classes deriving from any Mod type
        /// for a field called _ref
        /// and populates it, if it exists.
        /// </summary>
        private void LoadReferences()
        {
            foreach (Type type in Code.GetTypes())
            {
                if (type.IsAbstract)
                {
                    continue;
                }

                System.Reflection.FieldInfo _refField  = type.GetField("_ref");
                System.Reflection.FieldInfo _typeField = type.GetField("_type");
                bool isDefR  = _refField != null && _refField.IsStatic;
                bool isDefT  = _typeField != null && _typeField.IsStatic && _typeField.FieldType == typeof(int);
                bool modType = true;

                if (type.IsSubclassOf(typeof(ModItem)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModItem))
                    {
                        _refField.SetValue(null, GetItem(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, ItemType(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModNPC)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModNPC))
                    {
                        _refField.SetValue(null, GetNPC(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, NPCType(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModProjectile)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModProjectile))
                    {
                        _refField.SetValue(null, GetProjectile(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, ProjectileType(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModDust)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModDust))
                    {
                        _refField.SetValue(null, GetDust(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, DustType(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModTile)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModTile))
                    {
                        _refField.SetValue(null, GetTile(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, TileType(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModWall)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModWall))
                    {
                        _refField.SetValue(null, GetWall(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, WallType(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModBuff)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModBuff))
                    {
                        _refField.SetValue(null, GetBuff(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, BuffType(type.Name));
                    }
                }
                else if (type.IsSubclassOf(typeof(ModMountData)))
                {
                    if (isDefR && _refField.FieldType == typeof(ModMountData))
                    {
                        _refField.SetValue(null, GetMount(type.Name));
                    }
                    if (isDefT)
                    {
                        _typeField.SetValue(null, MountType(type.Name));
                    }
                }
                else
                {
                    modType = false;
                }

                if (Main.dedServ || !modType)
                {
                    continue;
                }

                System.Reflection.FieldInfo _texField = type.GetField("_textures");
                if (_texField == null || !_texField.IsStatic || _texField.FieldType != typeof(Texture2D[]))
                {
                    continue;
                }

                string path     = type.FullName.Substring(10).Replace('.', '/');             //Substring(10) removes "SpiritMod."
                int    texCount = 0;
                while (TextureExists(path + "_" + (texCount + 1)))
                {
                    texCount++;
                }
                Texture2D[] textures = new Texture2D[texCount + 1];
                if (TextureExists(path))
                {
                    textures[0] = GetTexture(path);
                }
                for (int i = 1; i <= texCount; i++)
                {
                    textures[i] = GetTexture(path + "_" + i);
                }
                _texField.SetValue(null, textures);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Deserializes an object of type tp.
        /// Will load all fields into the populate object if it is set (only works for classes).
        /// </summary>
        System.Object Deserialize(Type tp, System.Object populate = null)
        {
            var tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp);

            if (tpInfo.IsEnum)
            {
                return(Enum.Parse(tp, EatField()));
            }
            else if (TryEat('n'))
            {
                Eat("ull");
                TryEat(',');
                return(null);
            }
            else if (Type.Equals(tp, typeof(float)))
            {
                return(float.Parse(EatField(), numberFormat));
            }
            else if (Type.Equals(tp, typeof(int)))
            {
                return(int.Parse(EatField(), numberFormat));
            }
            else if (Type.Equals(tp, typeof(uint)))
            {
                return(uint.Parse(EatField(), numberFormat));
            }
            else if (Type.Equals(tp, typeof(bool)))
            {
                return(bool.Parse(EatField()));
            }
            else if (Type.Equals(tp, typeof(string)))
            {
                return(EatField());
            }
            else if (Type.Equals(tp, typeof(Version)))
            {
                return(new Version(EatField()));
            }
            else if (Type.Equals(tp, typeof(Vector2)))
            {
                Eat("{");
                var result = new Vector2();
                EatField();
                result.x = float.Parse(EatField(), numberFormat);
                EatField();
                result.y = float.Parse(EatField(), numberFormat);
                Eat("}");
                return(result);
            }
            else if (Type.Equals(tp, typeof(Vector3)))
            {
                Eat("{");
                var result = new Vector3();
                EatField();
                result.x = float.Parse(EatField(), numberFormat);
                EatField();
                result.y = float.Parse(EatField(), numberFormat);
                EatField();
                result.z = float.Parse(EatField(), numberFormat);
                Eat("}");
                return(result);
            }
            else if (Type.Equals(tp, typeof(Pathfinding.Util.Guid)))
            {
                Eat("{");
                EatField();
                var result = Pathfinding.Util.Guid.Parse(EatField());
                Eat("}");
                return(result);
            }
            else if (Type.Equals(tp, typeof(LayerMask)))
            {
                Eat("{");
                EatField();
                var result = (LayerMask)int.Parse(EatField());
                Eat("}");
                return(result);
            }
            else if (tp.IsGenericType && Type.Equals(tp.GetGenericTypeDefinition(), typeof(List <>)))
            {
                System.Collections.IList result = (System.Collections.IList)System.Activator.CreateInstance(tp);
                var elementType = tp.GetGenericArguments()[0];

                Eat("[");
                while (!TryEat(']'))
                {
                    result.Add(Deserialize(elementType));
                    TryEat(',');
                }
                return(result);
            }
            else if (tpInfo.IsArray)
            {
                List <System.Object> ls = new List <System.Object>();
                Eat("[");
                while (!TryEat(']'))
                {
                    ls.Add(Deserialize(tp.GetElementType()));
                    TryEat(',');
                }
                var arr = Array.CreateInstance(tp.GetElementType(), ls.Count);
                ls.ToArray().CopyTo(arr, 0);
                return(arr);
            }
            else if (Type.Equals(tp, typeof(Mesh)) || Type.Equals(tp, typeof(Texture2D)) || Type.Equals(tp, typeof(Transform)) || Type.Equals(tp, typeof(GameObject)))
            {
                return(DeserializeUnityObject());
            }
            else
            {
                Eat("{");

                if (tpInfo.GetCustomAttributes(typeof(JsonDynamicTypeAttribute), true).Length > 0)
                {
                    string name = EatField();
                    if (name != "@type")
                    {
                        throw new System.Exception("Expected field '@type' but found '" + name + "'" + "\n\nWhen trying to deserialize: " + fullTextDebug);
                    }

                    string typeName = EatField();
                    var    newType  = System.Type.GetType(typeName);
                    tp     = newType ?? throw new System.Exception("Could not find a type with the name '" + typeName + "'" + "\n\nWhen trying to deserialize: " + fullTextDebug);
                    tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp);
                }

                var obj = populate ?? Activator.CreateInstance(tp);
                while (!TryEat('}'))
                {
                    var name    = EatField();
                    var tmpType = tp;
                    System.Reflection.FieldInfo field = null;
                    while (field == null && tmpType != null)
                    {
                        field   = tmpType.GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                        tmpType = tmpType.BaseType;
                    }

                    if (field == null)
                    {
                        // Try a property instead
                        System.Reflection.PropertyInfo prop = null;
                        tmpType = tp;
                        while (prop == null && tmpType != null)
                        {
                            prop    = tmpType.GetProperty(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                            tmpType = tmpType.BaseType;
                        }

                        if (prop == null)
                        {
                            SkipFieldData();
                        }
                        else
                        {
                            prop.SetValue(obj, Deserialize(prop.PropertyType));
                        }
                    }
                    else
                    {
                        field.SetValue(obj, Deserialize(field.FieldType));
                    }
                    TryEat(',');
                }
                return(obj);
            }
        }
        private bool ProcessOptionWithMatchingField(string arg, string[] args, ref int index, string explicitArgument, ref System.Reflection.FieldInfo fi)
        {
            Type type   = fi.FieldType;
            bool isList = false;

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
            {
                isList = true;
                type   = type.GetGenericArguments()[0];
            }
            if (isList && explicitArgument == "!!")
            {
                // way to set list to empty
                System.Collections.IList listhandle = (System.Collections.IList)fi.GetValue(this);
                listhandle.Clear();
                return(true);
            }
            string argument = AdvanceArgumentIfNoExplicitArg(type, explicitArgument, args, ref index);

            if (isList)
            {
                if (argument == null)
                {
                    AddError("option -{0} requires an argument", arg);
                    return(true);
                }
                string[] listargs = argument.Split(';');
                for (int i = 0; i < listargs.Length; i++)
                {
                    if (listargs[i].Length == 0)
                    {
                        continue;                // skip empty values
                    }
                    bool   remove  = listargs[i][0] == '!';
                    string listarg = remove ? listargs[i].Substring(1) : listargs[i];
                    object value   = ParseValue(type, listarg, arg);
                    if (value != null)
                    {
                        if (remove)
                        {
                            this.GetListField(fi).Remove(value);
                        }
                        else
                        {
                            this.GetListField(fi).Add(value);
                        }
                    }
                }
            }
            else
            {
                object value = ParseValue(type, argument, arg);
                if (value != null)
                {
                    fi.SetValue(this, value);

                    string argname;
                    if (value is Int32 && HasOptionForAttribute(fi, out argname))
                    {
                        this.Parse(DerivedOptionFor(argname, (Int32)value).Split(' '));
                    }
                }
            }
            return(true);
        }
        public void ConstructorCheck()
        {
            //Für den ServiceProviderMock
            //Muss enthalten sein, damit der Mock nicht überschrieben wird
            IServiceProvider unused = ServiceManager.ServiceProvider;

            //Feld Infos holen
            System.Reflection.FieldInfo instance = typeof(ServiceManager).GetField("_serviceProvider",
                                                                                   System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            //Mocksaufsetzen
            //ServiceProvider
            Mock <IServiceProvider>       mockSingleton        = new Mock <IServiceProvider>();
            Mock <IActivityManager>       activityManagerMock  = new Mock <IActivityManager>();
            Mock <IServiceProvider>       activityProviderMock = new Mock <IServiceProvider>();
            Mock <AbstractSitUpActivity>  sitUpActivityMock    = new Mock <AbstractSitUpActivity>();
            Mock <AbstractPushUpActivity> pushUpActivityMock   = new Mock <AbstractPushUpActivity>();
            Mock <IEarablesConnection>    connectionMock       = new Mock <IEarablesConnection>();
            Mock <IPopUpService>          popUpMock            = new Mock <IPopUpService>();

            //ActivityManager
            activityManagerMock.Setup(x => x.ActitvityProvider).Returns(activityProviderMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractSitUpActivity)))
            .Returns(sitUpActivityMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractPushUpActivity)))
            .Returns(pushUpActivityMock.Object);

            //IDataBaseConnection
            Mock <IDataBaseConnection> mockDataBase = new Mock <IDataBaseConnection>();

            DateTime _dt       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            DBEntry  _entryNew = new DBEntry(_dt, 10, 0, 0);

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.SaveDBEntry(_entryNew)).Returns(1);

            //ServiceManager
            mockSingleton.Setup(x => x.GetService(typeof(IDataBaseConnection))).Returns(mockDataBase.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IActivityManager))).Returns(activityManagerMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IPopUpService))).Returns(popUpMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IEarablesConnection))).Returns(connectionMock.Object);

            //Connection
            ScanningPopUpViewModel.IsConnected = true;
            connectionMock.As <IEarablesConnection>().Setup(x => x.StartSampling());

            //ServiceProvider anlegen
            instance.SetValue(null, mockSingleton.Object);

            //Test
            ListenAndPerformViewModel     viewModel = new ListenAndPerformViewModel();
            IEnumerator <ActivityWrapper> iterator  = viewModel.ActivityList.GetEnumerator();

            Assert.Equal(3, viewModel.ActivityList.Count);
            iterator.MoveNext();
            Assert.Equal("Liegestütze", iterator.Current.Name);
            iterator.MoveNext();
            Assert.Equal("Pause", iterator.Current.Name);
            iterator.MoveNext();
            Assert.Equal("Sit-ups", iterator.Current.Name);
            viewModel.Milliseconds = "0";
            viewModel.Seconds      = "0";
            viewModel.Minutes      = "0";
            Assert.Equal("0", viewModel.Milliseconds);
            Assert.Equal("0", viewModel.Seconds);
            Assert.Equal("0", viewModel.Minutes);
        }
        } // End Function RenderControlToHtml

        private static void EnableFormat(Microsoft.Reporting.WebForms.ReportViewer viewer, string formatName)
        {
            const System.Reflection.BindingFlags Flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;

            System.Type tt = viewer.LocalReport.GetType();
            System.Reflection.FieldInfo m_previewService = tt.GetField("m_previewService", Flags);

            if (m_previewService == null)
            {
                m_previewService = tt.GetField("m_processingHost", Flags);
            }

            // Works only for v2005
            if (m_previewService != null)
            {
                System.Reflection.MethodInfo ListRenderingExtensions = m_previewService.FieldType.GetMethod
                                                                       (
                    "ListRenderingExtensions",
                    Flags
                                                                       );


                object previewServiceInstance = m_previewService.GetValue(viewer.LocalReport);

                System.Collections.IList extensions = ListRenderingExtensions.Invoke(previewServiceInstance, null) as System.Collections.IList;

                System.Reflection.PropertyInfo name = null;
                if (extensions.Count > 0)
                {
                    name = extensions[0].GetType().GetProperty("Name", Flags);
                }

                if (name == null)
                {
                    return;
                }

                foreach (object extension in extensions)
                {
                    string thisFormat = name.GetValue(extension, null).ToString();

                    //{
                    //    System.Reflection.FieldInfo m_isVisible = extension.GetType().GetField("m_isVisible", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    //    System.Reflection.FieldInfo m_isExposedExternally = extension.GetType().GetField("m_isExposedExternally", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

                    //    object valVisible = m_isVisible.GetValue(extension);
                    //    object valExposed = m_isExposedExternally.GetValue(extension);
                    //    System.Console.WriteLine(valVisible);
                    //    System.Console.WriteLine(valExposed);
                    //}

                    //if (string.Compare(thisFormat, formatName, true) == 0)
                    if (true)
                    {
                        System.Reflection.FieldInfo m_isVisible           = extension.GetType().GetField("m_isVisible", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        System.Reflection.FieldInfo m_isExposedExternally = extension.GetType().GetField("m_isExposedExternally", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        m_isVisible.SetValue(extension, true);
                        m_isExposedExternally.SetValue(extension, true);
                        //break;
                    } // End if (string.Compare(thisFormat, formatName, true) == 0)
                }     // Next extension
            }         // End if (m_previewService != null)
        }             // End Sub EnableFormat
Esempio n. 30
0
 public static GenericParameter Update(this GenericParameter param, int position, GenericParameterType type)
 {
     f_GenericParameter_position.SetValue(param, position);
     f_GenericParameter_type.SetValue(param, type);
     return(param);
 }