ToString() public method

public ToString ( ) : string
return string
        /// <summary>
        /// Inserts in the circulare buffer to keep it ordered
        /// by timestamp.
        /// </summary>
        /// <returns>the index where the data was inserted timestamp.</returns>
        private int InsertByTimestamp(TrackingData data)
        {
            System.Type entryType = data.GetType();
            System.Type exitType;
            trackingDataBuffer.PushFront(data);
            int index = 0;

            for (int i = 1; i < trackingDataBuffer.Size; i++)
            {
                index = i - 1;
                if (trackingDataBuffer[i - 1].timestamp < trackingDataBuffer[i].timestamp)
                {
                    // Invert
                    TrackingData tempData = trackingDataBuffer[i];
                    trackingDataBuffer[i]     = trackingDataBuffer[i - 1];
                    trackingDataBuffer[i - 1] = tempData;
                }
                else
                {
                    exitType = trackingDataBuffer[i - 1].GetType();
                    if (entryType != exitType)
                    {
                        Debug.LogWarning("A. Entrype: " + entryType.ToString() + "  ExitType: " + exitType.ToString());
                    }
                    return(index);
                }
            }
            exitType = trackingDataBuffer[index].GetType();
            if (entryType != exitType)
            {
                Debug.LogWarning("B. Entrype: " + entryType.ToString() + "  ExitType: " + exitType.ToString() + "  Index: " + index.ToString());
            }
            return(index);
        }
        private void AddKid(object o, TreeNodeCollection tnc, string name, AST key)
        {
            TreeNode n = new TreeNode();

            tnc.Add(n);
            if (o == null)
            {
                n.Text = name + ": null";
            }
            else                        // o != null
            {
                System.Type t = o.GetType();
                if (o is CodeObject)
                {
                    CodeObject co  = (CodeObject)o;
                    AST        ast = (AST)co.UserData["AST"];
                    int        c   = co.UserData.Count;
                    if (ast != null && !o2n.Contains(ast))                              // incredibly bogus because CodeDom synthesizes its own nodes!!  void type of property setter...
                    {
                        o2n[ast] = n;
                    }
                    n.Tag = ast;
                    foreach (PropertyInfo pi in t.GetProperties())
                    {
                        if (pi.GetIndexParameters().Length == 0)
                        {
                            if (!(o is CodeObject) || pi.Name != "UserData")
                            {
                                object x = pi.GetValue(o, null);
                                AddKid(x, n.Nodes, pi.Name, ast);
                            }
                        }
                    }
                    n.Text = name + ": " + t.ToString();
                }
                else if (o is IList)
                {
                    IList a = (IList)o;
                    if (a.Count > 0)
                    {
                        for (int i = 0; i < a.Count; i++)
                        {
                            object x = a[i];
                            AddKid(x, n.Nodes, name + "[" + i.ToString() + "]", key);
                        }
                        n.Tag  = key;
                        n.Text = name + ": " + t.ToString() + "{" + a.Count + "}";
                    }
                    else
                    {
                        tnc.Remove(n);
                    }
                }
                else
                {
                    n.Tag  = key;
                    n.Text = name + ": " + t.ToString() + " = " + o.ToString();
                }
            }
        }
        public static void GetAttribute(Type t)
        {
            VersionAttribute att;

            att = (VersionAttribute)Attribute.GetCustomAttribute(t, typeof(VersionAttribute));

            if (att == null)
            {
                Console.WriteLine("No attribute in class {0}.\n", t.ToString());
            }
            else
            {
                Console.WriteLine("The version of the class {0} is {1}.{2}", t.ToString(), att.Major, att.Minor);
            }

            MemberInfo[] MyMemberInfo = t.GetMethods();

            for (int i = 0; i < MyMemberInfo.Length; i++)
            {
                att = (VersionAttribute)Attribute.GetCustomAttribute(MyMemberInfo[i], typeof(VersionAttribute));
                if (att == null)
                {
                    Console.WriteLine("No attribute in member function {0}.\n", MyMemberInfo[i].ToString());
                }
                else
                {
                    Console.WriteLine("The version of the method {0} is {1}.{2}",
                        MyMemberInfo[i].ToString(), att.Major, att.Minor);
                }
            }
        }
Esempio n. 4
0
        private bool VerifyInvalidReadValue(int iBufferSize, int iIndex, int iCount, Type exceptionType)
        {
            bool bPassed = false;
            Char[] buffer = new Char[iBufferSize];

            ReloadSource();
            DataReader.PositionOnElement(ST_TEST_NAME);
            DataReader.Read();
            if (!DataReader.CanReadValueChunk)
            {
                try
                {
                    DataReader.ReadValueChunk(buffer, 0, 5);
                    return bPassed;
                }
                catch (NotSupportedException)
                {
                    return true;
                }
            }
            try
            {
                DataReader.ReadValueChunk(buffer, iIndex, iCount);
            }
            catch (Exception e)
            {
                CError.WriteLine("Actual   exception:{0}", e.GetType().ToString());
                CError.WriteLine("Expected exception:{0}", exceptionType.ToString());
                bPassed = (e.GetType().ToString() == exceptionType.ToString());
            }

            return bPassed;
        }
Esempio n. 5
0
 public object ConvertBack(object value, Type sourceType, object parameter, CultureInfo culture)
 {
     if (value == null)
     {
         if (!DefaultValueConverter.AcceptsNull(sourceType))
         {
             CultureInfo invariantCulture = CultureInfo.InvariantCulture;
             string str = "ValueConverter can't convert Type {0}  to Type {1}";
             object[] objArray = new object[] { "'null'", sourceType.ToString() };
             throw new InvalidOperationException(string.Format(invariantCulture, str, objArray));
         }
         value = null;
     }
     else
     {
         Type type = value.GetType();
         this.EnsureConverter(sourceType, type);
         if (this.converter == null)
         {
             CultureInfo cultureInfo = CultureInfo.InvariantCulture;
             string str1 = "ValueConverter can't convert Type {0}  to Type {1}";
             object[] objArray1 = new object[] { type.ToString(), sourceType.ToString() };
             throw new InvalidOperationException(string.Format(cultureInfo, str1, objArray1));
         }
         value = this.converter.ConvertBack(value, sourceType, parameter, culture);
     }
     return value;
 }
Esempio n. 6
0
        /// <summary>
        /// Instantiates an object and passes in IObjectStore information
        /// If no constructor with IObjectStore data is available but there is
        /// an empty Constructor it will utilize that
        /// </summary>
        /// <param name="type"></param>
        /// <param name="constructor"></param>
        /// <returns></returns>
        public static T Instantiate <T>(this System.Type type, params IObjectStore[] constructor)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            try
            {
                if (constructor.Length > 0)
                {
                    var types = constructor.Select(x => x.GetType()).ToArray();
                    ShortLog.DebugFormat("type is {0}", type.ToString());
                    var matchConstructor = type.GetConstructor(types);

                    //Could not find a matching constructor, just try for an empty one
                    if (matchConstructor == null)
                    {
                        return((T)Activator.CreateInstance(type));
                    }
                }
                return((T)Activator.CreateInstance(type, constructor));
            }
            catch
            {
                ShortLog.ErrorFormat("Failed to created type: {0}", type.ToString());
                throw;
            }
        }
Esempio n. 7
0
        public static void AssertValidRdModel([NotNull] TypeInfo type)
        {
            var isDataModel = HasRdModelAttribute(type);

            Assertion.Assert(isDataModel, $"Error in {type.ToString(true)} model: no {nameof(RdModelAttribute)} attribute specified");

            Assertion.Assert(!type.IsValueType, $"Error in {type.ToString(true)} model: data model can't be ValueType");

            // No way to prevent serialization errors for intrinsic serializers, just skip for now
            if (HasIntrinsicMethods(type))
            {
                return;
            }

            foreach (var member in ReflectionSerializers.GetBindableMembers(type))
            {
                if (member is PropertyInfo || member is FieldInfo)
                {
                    AssertDataMemberDeclaration(member);
                }

                if (member is TypeInfo)
                {
                    // out scope for current validation
                }
                // methods events are allowed in model
            }
        }
Esempio n. 8
0
 public static void MyTrace(TraceLevel type, Type theClass, string controllerName, string actionName, string message, Exception e)
 {
     string messageToShow;
     log4net.ILog log;
     log = log4net.LogManager.GetLogger(theClass);
     if (e != null)
     {
         messageToShow = string.Format("\tClass={0} \r\n\tController= {1} \r\n\tAction= {2} \r\n\tMessage= {3} \r\n\tGetBaseException= {4}",
                     theClass.ToString(), controllerName, actionName, message, e.GetBaseException().ToString());
     }
     else
     {
         messageToShow = string.Format("\tClass={0} \r\n\tController= {1} \r\n\tAction= {2} \r\n\tMessage= {3}",
                     theClass.ToString(), controllerName, actionName, message);
     }
     switch (type)
     {
         case TraceLevel.Info:
             Trace.TraceInformation(messageToShow);
             log.Info(messageToShow);
             break;
         case TraceLevel.Error:
             Trace.TraceError(messageToShow);
             log.Error(messageToShow);
             break;
         case TraceLevel.Warning:
             Trace.TraceWarning(messageToShow);
             log.Warn(messageToShow);
             break;
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Add a nokia layer to the layers collection of the map.
        /// </summary>
        /// <param name="layers">The layers collection.</param>
        /// <param name="type">The basic map type.</param>
        /// <param name="scheme">The scheme of the map.</param>
        /// <param name="appId">The application id.</param>
        /// <param name="token">The token.</param>
        public static void AddNokiaLayer(this LayerCollection layers, Type type, Scheme scheme, string appId, string token)
        {
            // request schema is
            // http://SERVER-URL/maptile/2.1/TYPE/MAPID/SCHEME/ZOOM/COL/ROW/RESOLUTION/FORMAT?param=value&...

            string copyrightText = (scheme == Scheme.SatelliteDay) ? "© 2012 DigitalGlobe" : "© 2012 NAVTEQ";
            string schemeString = Regex.Replace(scheme.ToString(), "[a-z][A-Z]", m => m.Value[0] + "." + m.Value[1]).ToLower();
            string typeString = type.ToString().ToLower();
            string caption = (type == Type.StreetTile) ? "Streets" : (type == Type.LabelTile) ? "Labels" : "BaseMap";

            layers.Add(new TiledLayer("Nokia_" + type.ToString())
            {
                Caption = caption,
                IsLabelLayer = type == Type.LabelTile || type == Type.StreetTile,
                IsBaseMapLayer = type == Type.MapTile || type == Type.BaseTile,
                TiledProvider = new RemoteTiledProvider
                {
                    MinZoom = 0,
                    MaxZoom = 20,
                    RequestBuilderDelegate = (x, y, level) =>
                    string.Format("http://{0}.maps.nlp.nokia.com/maptile/2.1/{1}/newest/{2}/{3}/{4}/{5}/256/png8?app_id={6}&token={7}",
                    "1234"[(x ^ y) % 4], typeString, schemeString, level, x, y, appId, token)
                },
                Copyright = copyrightText,
            });
        }
Esempio n. 10
0
                private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
                {
                    bool bPassed = false;
                    byte[] buffer = new byte[iBufferSize];

                    XmlReader DataReader = GetReader(pBinHexXml);
                    PositionOnElement(DataReader, ST_ELEM_NAME1);
                    DataReader.Read();

                    if (!DataReader.CanReadBinaryContent) return true;
                    try
                    {
                        DataReader.ReadContentAsBinHex(buffer, iIndex, iCount);
                    }
                    catch (Exception e)
                    {
                        bPassed = (e.GetType().ToString() == exceptionType.ToString());
                        if (!bPassed)
                        {
                            TestLog.WriteLine("Actual   exception:{0}", e.GetType().ToString());
                            TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
                        }
                    }

                    return bPassed;
                }
Esempio n. 11
0
        /// <summary>
        /// convert from string to the appropriate type
        /// </summary>
        /// <param name="propertyValue">incoming string value</param>
        /// <param name="propertyType">type to convert to</param>
        /// <returns>converted value</returns>
        internal static object ChangeType(string propertyValue, Type propertyType)
        {
            Debug.Assert(null != propertyValue, "should never be passed null");

            PrimitiveType primitiveType;
            if (PrimitiveType.TryGetPrimitiveType(propertyType, out primitiveType) && primitiveType.TypeConverter != null)
            {
                try
                {
                    // functionality provided by type converter
                    return primitiveType.TypeConverter.Parse(propertyValue);
                }
                catch (FormatException ex)
                {
                    propertyValue = (0 == propertyValue.Length ? "String.Empty" : "String");
                    throw Error.InvalidOperation(Strings.Deserialize_Current(propertyType.ToString(), propertyValue), ex);
                }
                catch (OverflowException ex)
                {
                    propertyValue = (0 == propertyValue.Length ? "String.Empty" : "String");
                    throw Error.InvalidOperation(Strings.Deserialize_Current(propertyType.ToString(), propertyValue), ex);
                }
            }
            else
            {
                Debug.Assert(false, "new StorageType without update to knownTypes");
                return propertyValue;
            }
        }
Esempio n. 12
0
 public static SType FindBy(SType ifc)
 {
     lock (TYPES)
     {
         if (TYPES.ContainsKey(ifc.FullName))
         {
             return(TYPES[ifc.ToString()]);
         }
         foreach (SReflection.Assembly assembly in System.AppDomain.CurrentDomain.GetAssemblies())
         {
             foreach (SType type in assembly.GetTypes())
             {
                 foreach (SType i in type.GetInterfaces())
                 {
                     if (i.Equals(ifc))
                     {
                         TYPES.Add(ifc.ToString(), type);
                         return(type);
                     }
                 }
             }
         }
     }
     throw new DllNotFoundException("An Add'On Support DLL was not loaded. Missing Interface : " + ifc.FullName);
 }
Esempio n. 13
0
        private void RegisterEntity(string name, System.Type type, OnCacheUpdatedDelegate onupdated)
        {
            if (m_cacheEntities.ContainsKey(name))
            {
                DataCacheEntity entity = m_cacheEntities[name];
                if (entity.Type != type)
                {
                    EB.Debug.LogError("DataCacheManager.RegisterCacheEntity: exists {0} named {1} not match {2}",
                                      m_cacheEntities[name].ToString(), name, type.ToString());

                    return;
                }

                EB.Debug.LogWarning("DataCacheManager.RegisterCacheEntity: {0} named {1} already exists",
                                    type.ToString(), name);

                if (onupdated != null)
                {
                    entity.OnCacheUpdated += onupdated;
                }
            }
            else
            {
                DataCacheEntity entity = new DataCacheEntity();
                entity.Name = name;
                entity.Type = type;
                entity.Name = string.Empty;
                if (onupdated != null)
                {
                    entity.OnCacheUpdated += onupdated;
                }
                m_cacheEntities[name] = entity;
            }
        }
Esempio n. 14
0
        public static void AssertValidRdExt(TypeInfo type)
        {
            var isRdModel = HasRdExtAttribute(type);

            Assertion.Assert(isRdModel, $"Error in {type.ToString(true)} model: no {nameof(RdExtAttribute)} attribute specified");
            Assertion.Assert(!type.IsValueType, $"Error in {type.ToString(true)} model: can't be ValueType");
            Assertion.Assert(typeof(RdReflectionBindableBase).GetTypeInfo().IsAssignableFrom(type.AsType()), $"Error in {type.ToString(true)} model: should be inherited from {nameof(RdReflectionBindableBase)}");

            // actually, it is possible, but error-prone.
            // you may have non-rdmodel base class and several sealed derivatives from it.
            // commented sealed check to avoid annoying colleagues.
            // Assertion.Assert(type.IsSealed, $"Error in {type.ToString(true)} model: RdModels must be sealed.");

            foreach (var member in ReflectionSerializers.GetBindableMembers(type))
            {
                if (member is PropertyInfo || member is FieldInfo)
                {
                    AssertMemberDeclaration(member);
                }

                if (member is TypeInfo)
                {
                    // out scope for current validation
                }
                // methods and events are allowed in model
            }
        }
Esempio n. 15
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 static public object GetObject(Type type)
 {
     if (signalObjects.ContainsKey(type.ToString()))
     {
         return signalObjects[type.ToString()];
     }
     return null;
 }
Esempio n. 16
0
 /// <summary>
 /// 获取注册的键值
 /// </summary>
 /// <param name="intefaceType"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 private static string GetFullKey(System.Type intefaceType, string key = null)
 {
     if (key != null)
     {
         return(intefaceType.ToString() + "$" + key);
     }
     return(intefaceType.ToString() + "$");
 }
Esempio n. 17
0
 public static bool IsA(ActionInfo action, System.Type verbType, Observer perspective, float threashold = 0f)
 {
     if (m_instance.m_Verbs.ContainsKey(verbType.ToString()))
     {
         return(IsA(action, m_instance.m_Verbs[verbType.ToString()], perspective, threashold));
     }
     return(false);
 }
Esempio n. 18
0
 public static bool IsA(GameObject target, System.Type nounType, Observer perspective, float threashold = 0f)
 {
     if (m_instance.m_Nouns.ContainsKey(nounType.ToString()))
     {
         return(IsA(target, m_instance.m_Nouns[nounType.ToString()], perspective, threashold));
     }
     return(false);
 }
Esempio n. 19
0
        /// <summary>
        /// 类型匹配
        /// </summary>
        /// <param name="type"></param>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public static bool IsType(Type type, string typeName)
        {
            if (type.ToString() == typeName)
                return true;
            if (type.ToString() == "System.Object")
                return false;

            return IsType(type.BaseType, typeName);
        }
Esempio n. 20
0
        /// <summary>
        /// adds the current object to the static dictionary of signal items
        /// </summary>
        /// <param name="type"></param>
        static public void AddObject(Type type, ISignalBase obj)
        {
            if (signalObjects.ContainsKey(type.ToString()))
            {
                signalObjects.Remove(type.ToString());
            }

            signalObjects.Add(type.ToString(), obj);
        }
Esempio n. 21
0
        public void ApplyConfiguration(System.Type type, GameObject ob, int configVariant = 0)
        {
            //sanity
            if (ob == null)
            {
                Logger.Log(this, Logger.Level.Critical, "Object to bind to is null or empty. Why you do this?");
                return;
            }

            if (!_configDataDict.ContainsKey(type.ToString()))
            {
                Logger.Log(this, Logger.Level.Critical, "Configuration datum doest exist for type " + type.ToString());
                return;
            }

            string key = type.ToString();

            ConfigurationData data = _configDataDict[key];

            if (data == null || data.Data == null || data.Data.Count == 0)
            {
                Logger.Log(this, Logger.Level.Critical, "Configuration data is empty for type " + type.ToString());
                return;
            }

            if (!data.Data.ContainsKey(configVariant))
            {
                Logger.Log(this, Logger.Level.Critical, "Configuration datum for type " + type.ToString() + " and variant " + configVariant + " cannot be found.");
                return;
            }

            ConfigurationDatum datum = data.Data[configVariant];

            if (datum == null)
            {
                Logger.Log(this, Logger.Level.Critical, "Configuration datum for type " + type.ToString() + " and variant " + configVariant + " is null or empty.");
                return;
            }

            Transform goToModify = ob.transform.Find(datum.GameObjectHierarchy);

            if (goToModify == null)
            {
                Logger.Log(this, Logger.Level.Critical, "cannot find child at hierarchy " + datum.GameObjectHierarchy);
                return;
            }

            Component compToModify = goToModify.GetComponent(type);

            if (compToModify == null)
            {
                Logger.Log(this, Logger.Level.Critical, "cannot find component of type " + datum.TypeOfComponent + " at hierarchy " + datum.GameObjectHierarchy);
                return;
            }

            ApplyConfigurationInternal(compToModify, datum);
        }
Esempio n. 22
0
        public Propiedad CrearClasePropiedad(Type Tipo)
        {
            if (Tipo.ToString() == "GI.BR.Propiedades.Venta")
                return new Venta();

            else if (Tipo.ToString() == "GI.BR.Propiedades.Alquiler")
                return new Alquiler();

            return null;
        }
 public ExceptionNotThrownException(Type expectedException, Exception actualException)
 {
     if (actualException == null)
     {
         message = string.Format("{0} was not thrown", expectedException.ToString());
     }
     else
     {
         message = string.Format("{0} was not thrown, but {1} was", expectedException.ToString(),expectedException.GetType().ToString());
     }
 }
        public void Stop(Type service)
        {
            if (_services.ContainsKey(service.ToString()))
            {
                ServiceHost host = _services[service.ToString()];

                // Close the ServiceHost.
                host.Close();

                _services.Remove(service.ToString());
            }
        }
Esempio n. 25
0
        public FZ.Actor GetUsableActor(System.Type actorType)
        {
            if (!actorType.IsSubclassOf(typeof(FZ.Actor)) ||
                !_actors.ContainsKey(actorType.ToString()))
            {
                throw new UnityException("Actor's type is not correct.");
            }

            var preActor = _actors[actorType.ToString()];

            return(preActor);
        }
Esempio n. 26
0
        public async Task<Page> Build(Type pageType, object parameter)
        {
            ConstructorInfo constructor = null;
            object[] parameters = null;

            if (parameter == null)
            {
                constructor = pageType.GetTypeInfo()
                    .DeclaredConstructors
                    .FirstOrDefault(c => !c.GetParameters().Any());

                parameters = new object[] { };
            }
            else
            {
                constructor = pageType.GetTypeInfo()
                    .DeclaredConstructors
                    .FirstOrDefault(
                        c =>
                        {
                            var p = c.GetParameters();
                            return p.Count() == 1
                                   && p[0].ParameterType == parameter.GetType();
                        });

                parameters = new[]
                            {
                                        parameter
                                    };
            }

            if (constructor == null)
                throw new InvalidOperationException(
                    "No suitable constructor found for page " + pageType.ToString());

            var page = constructor.Invoke(parameters) as Page;

            // Assign Binding Context
            if (_pagesByType.ContainsKey(pageType))
            {
                page.BindingContext = GetBindingContext(pageType);

                // Pass parameter to view model
                var model = page.BindingContext as BaseViewModel;
                if (model != null)
                    await model.OnNavigated(parameter);
            }
            else
                throw new InvalidOperationException(
                    "No suitable view model found for page " + pageType.ToString());

            return page;
        }
Esempio n. 27
0
 public object this[Type type]
 {
     get
     {
         return this[type.ToString()];
     }
     set
     {
         string stuff = type.ToString();
         this[stuff] = value;
     }
 }
Esempio n. 28
0
        public void Load <U>(ref U loadObject)
        {
            StringBuilder nameSave = new StringBuilder();

            nameSave.Append(prefixSave);
            nameSave.Append(myType.ToString());
            nameSave.Append(SaveController.GetNumSave());
            if (PlayerPrefs.HasKey(nameSave.ToString()))
            {
                string serialized = PlayerPrefs.GetString(nameSave.ToString());
                loadObject = JsonUtility.FromJson <U>(serialized);
            }
        }
        /// <summary>
        /// Creates a new AggregateOrFunctionDoesNotExistException exception
        /// </summary>
		/// <param name="innerException">The exception that is the cause of the current exception, this parameter can be NULL.</param>
        public AggregateOrFunctionDoesNotExistException(Type myAggrOrFuncType, String myAggrOrFuncName, String myInfo, Exception innerException = null) : base(innerException)
        {
            Info = myInfo;
            AggrOrFuncType = myAggrOrFuncType;
            AggrOrFuncName = myAggrOrFuncName;
            
            if (InnerException != null)
            {
				if(InnerException.Message != null && !InnerException.Message.Equals(""))
					_msg = String.Format("Error during loading the aggregate plugin of type: [{0}] name: [{1}]\n\nInner Exception: {2}\n\n{3}", myAggrOrFuncType.ToString(), myAggrOrFuncName, InnerException.Message, myInfo);
                else
                    _msg = String.Format("Error during loading the aggregate plugin of type: [{0}] name: [{1}]\n\n{2}", myAggrOrFuncType.ToString(), myAggrOrFuncName, myInfo);
            }
        }
Esempio n. 30
0
        private static void AddCore(Type type, ProcessorAttribute att)
        {
            if (att == null)
            {
                att = new ProcessorAttribute();
            }

            CategoryItem item = new CategoryItem();
            item.Name = String.IsNullOrEmpty(att.Name) ? type.ToString() : att.Name;
            item.Introduce = String.IsNullOrEmpty(att.Introduce) ? type.ToString() : att.Introduce;
            item.Category = att.Category;
            item.Value = type;
            CategoryItems.Add(item);
        }
Esempio n. 31
0
    void OnGUI()
    {
        try
        {
            tran = Selection.GetTransforms(SelectionMode.TopLevel);
            if (tran != null)
            {
                for (int i = 0; i < tran.Length; i++)
                {
                    if (tran[i] == null)
                    {
                        continue;
                    }
                    System.Type type = tran[i].GetComponent <MonoBehaviour>().GetType();
                    if (type.ToString().Contains("UILabel"))
                    {
                        curType   = ComponentType.ENUM_LABEL;
                        curWidget = tran[i].GetComponent <UIWidget>();
                    }
                    else if (type.ToString().Contains("UISprite") ||
                             type.ToString().Contains("UISlicedSprite") ||
                             type.ToString().Contains("UITiledSprite"))
                    {
                        curType   = ComponentType.ENUM_SPRITE;
                        curWidget = tran[i].GetComponent <UIWidget>();
                    }
                    else
                    {
                        curType = ComponentType.ENUM_NON_DIFINE;
                    }
                }
            }

            GUILayout.BeginHorizontal();
            showColorType(curType);
            GUILayout.Space(20);
            ShowBtnUI();
            GUILayout.Space(30);
            GUI.color = ColorCopyNow;
            if (GUILayout.Button("点击应用此颜色\n" + ColorCopyNow.ToString(), GUILayout.Width(200), GUILayout.Height(100)))
            {
                SetColor(ColorCopyNow);
            }
            GUI.color = Color.white;
            GUILayout.EndHorizontal();
        }
        catch (System.Exception ex)
        {
        }
    }
Esempio n. 32
0
        public Cliente CrearClaseCliente(Type Tipo)
        {
            if (Tipo == null)
                return null;
            if (Tipo.ToString() == "GI.BR.Clientes.Propietario")
                return new Propietario();

            else if (Tipo.ToString() == "GI.BR.Clientes.Inquilino")
                return new Inquilino();

            else if (Tipo.ToString() == "GI.BR.Clientes.ClientePedido")
                return new ClientePedido();

            return null;
        }
Esempio n. 33
0
        /// <summary>Attempts to patch the given source method with the given prefix method.</summary>
        /// <param name="harmonyInstance">The Harmony instance to patch with.</param>
        /// <param name="sourceClass">The class the source method is part of.</param>
        /// <param name="sourceName">The name of the source method.</param>
        /// <param name="patchClass">The class the patch method is part of.</param>
        /// <param name="patchName">The name of the patch method.</param>
        /// <param name="sourceParameters">The source method's parameter list, when needed for disambiguation.</param>
        void patchPrefix(HarmonyInstance harmonyInstance, System.Type sourceClass, string sourceName, System.Type patchClass, string patchName, Type[] sourceParameters = null)
        {
            try
            {
                MethodBase    sourceMethod = AccessTools.Method(sourceClass, sourceName, sourceParameters);
                HarmonyMethod prefixPatch  = new HarmonyMethod(patchClass, patchName);

                if (sourceMethod != null && prefixPatch != null)
                {
                    harmonyInstance.Patch(sourceMethod, prefixPatch);
                }
                else
                {
                    if (sourceMethod == null)
                    {
                        Log("Warning: Source method (" + sourceClass.ToString() + "::" + sourceName + ") not found or ambiguous.");
                    }
                    if (prefixPatch == null)
                    {
                        Log("Warning: Patch method (" + patchClass.ToString() + "::" + patchName + ") not found.");
                    }
                }
            }
            catch (Exception e)
            {
                Log("Error in code patching: " + e.Message + Environment.NewLine + e.StackTrace);
            }
        }
Esempio n. 34
0
    //

    // --- Type ---
    public void Serialize(System.Type t)
    {
        // serialize type as string
        string typeStr = t.ToString();

        Serialize(typeStr);
    }
Esempio n. 35
0
 private static void CreateForm(Form mform, Type frmtype)
 {
     Assembly ass = Assembly.LoadFrom(frmtype.Module.Name);
     Form frm = (Form)ass.CreateInstance(frmtype.ToString());
     frm.MdiParent = mform;
     frm.Show();
 }
Esempio n. 36
0
        //"Assets/Bundle/Test" -> "Assets/Bundle/Test.prefab
        private string GetRealPath(string assetPath, System.Type type)
        {
            string assetName  = Path.GetFileName(assetPath);
            string searchName = assetName;

            if (type != null)
            {
                searchName += " t:" + Path.GetExtension(type.ToString()).TrimStart('.'); // UnityEngine.GameObject -> GameObject
            }
            tmpStrArr[0] = Path.GetDirectoryName(assetPath);
            var files = AssetDatabase.FindAssets(searchName, tmpStrArr);

            if (files.Length == 0)
            {
                return(assetPath);
            }
            else if (files.Length == 1)
            {
                return(AssetDatabase.GUIDToAssetPath(files[0]));
            }
            else
            {
                //相同文件夹下,多个文件名字有包含关系
                //Test.png,Test_1.png
                foreach (var guid in files)
                {
                    var path = AssetDatabase.GUIDToAssetPath(guid);
                    if (Path.GetFileNameWithoutExtension(path) == assetName)
                    {
                        return(path);
                    }
                }
            }
            return(assetPath);
        }
Esempio n. 37
0
    public string Register(System.Type classType, GameObject obj)
    {
        string classTypeString = classType.ToString();

        this[classTypeString][obj.transform.name] = obj;
        return("[\"" + classTypeString + "\"][\"" + obj.transform.name + "\"]");
    }
Esempio n. 38
0
 private int ReadField(Context context, FieldType field, int fieldIndex, ArrayList fieldValues, out object fieldValue, ref byte bitOffset)
 {
     fieldValue = null;
     System.Type type = field.GetType();
     if ((type == typeof(Integer)) || type.IsSubclassOf(typeof(Integer)))
     {
         return(this.ReadField(context, (Integer)field, out fieldValue));
     }
     if ((type == typeof(FloatingPoint)) || type.IsSubclassOf(typeof(FloatingPoint)))
     {
         return(this.ReadField(context, (FloatingPoint)field, out fieldValue));
     }
     if ((type == typeof(CharString)) || type.IsSubclassOf(typeof(CharString)))
     {
         return(this.ReadField(context, (CharString)field, fieldIndex, fieldValues, out fieldValue));
     }
     if ((type == typeof(BitString)) || type.IsSubclassOf(typeof(BitString)))
     {
         return(this.ReadField(context, (BitString)field, out fieldValue, ref bitOffset));
     }
     if (type != typeof(TypeReference))
     {
         throw new NotImplementedException("Fields of type '" + type.ToString() + "' are not implemented yet.");
     }
     return(this.ReadField(context, (TypeReference)field, out fieldValue));
 }
        private IEnumerable<Action<IComponentContext, object>> BuildLoggerInjectors(Type componentType) {
            // Look for settable properties of type "ILogger" 
            var loggerProperties = componentType
                .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
                .Select(p => new {
                    PropertyInfo = p,
                    p.PropertyType,
                    IndexParameters = p.GetIndexParameters(),
                    Accessors = p.GetAccessors(false)
                })
                .Where(x => x.PropertyType == typeof(ILogger)) // must be a logger
                .Where(x => x.IndexParameters.Count() == 0) // must not be an indexer
                .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)); //must have get/set, or only set

            // Return an array of actions that resolve a logger and assign the property
            foreach (var entry in loggerProperties) {
                var propertyInfo = entry.PropertyInfo;

                yield return (ctx, instance) => {
                    string component = componentType.ToString();
                    if (component != instance.GetType().ToString()) {
                        return;
                    }
                    var logger = _loggerCache.GetOrAdd(component, key => ctx.Resolve<ILogger>(new TypedParameter(typeof(Type), componentType)));
                    propertyInfo.SetValue(instance, logger, null);
                };
            }
        }
        private static string FormatMessage(string memberName, System.Type typeSearched, string addlInfo)
        {
            var addlStr  = string.IsNullOrEmpty(addlInfo) ? string.Empty : addlInfo.TrimEnd('.') + ". ";
            var typeName = (typeSearched != null) ? typeSearched.ToString() : "[Type Not Provided]";

            return(string.Format("{2}Could not find member named '{0}' in type '{1}'.", memberName, typeName, addlStr));
        }
        /// <summary>
        /// 指定されたビューモデルのインスタンスの IWindowCloseCommand インターフェイス の
        /// WindowClose メソッドを実行します。
        /// </summary>
        /// <returns></returns>
        public static void CloseViewModels(Type type)
        {
            if (!type.IsSubclassOf(typeof(ViewModelBase))) throw new ArgumentException(
                string.Format("引数の型が ViewModelBase の派生クラスになっていません(引数の型:{0})。", type.Name));
            if (Count(type) == 0) return;

            var list = GetViewModels(type);
            if (list.First() as IWindowCloseCommand == null)
            {
                throw new InvalidCastException(
                "オブジェクトは IWindowCloseCommand インターフェイスを実装していません。: " + type.ToString());
            }

            // ウィンドウが閉じることのできる状態か確認
            if (!isReadyCloseWindows(list))
            {
                throw new WindowPendingProcessException(
                    string.Format("ViewModel:{0} が閉じることの出来る状態にありません。", type.Name));
            }
            // ウィンドウを閉じる
            foreach (var n in list)
            {
                (n as IWindowCloseCommand).WindowClose();
            }
        }
        public object GetService(Type serviceType)
        {
            _log.Debug("VerboseDependencyResolver.GetService(Type serviceType), serviceType: " + serviceType.ToString());

            if(serviceType.Equals(typeof(IControllerFactory)))
            {
                // Cannot return controller here, as it is also set via
                // ControllerBuilder.Current.SetControllerFactory.
                //return new VerboseControllerFactory();
                _log.Debug("VerboseDependencyResolver.GetService(Type serviceType) returning null.");
                return null;
            }

            if (serviceType.Equals(typeof(IControllerActivator)))
            {
                _log.Debug("VerboseDependencyResolver.GetService(Type serviceType) returning null.");
                return null;
            }

            if (typeof(IController).IsAssignableFrom(serviceType))
            {
                _log.Debug("VerboseDependencyResolver.GetService(Type serviceType) returning instance of HomeController.");
                return new HomeController();
            }

            _log.Debug("VerboseDependencyResolver.GetService(Type serviceType) returning null.");
            return null;
        }
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            if (modelType.Name != "IPaymentMethod") return base.CreateModel(controllerContext, bindingContext, modelType);

            var paymentMethodType = bindingContext.ModelName + ".PaymentMethodType";

            var rawClassName = bindingContext.ValueProvider.GetValue(paymentMethodType);
            if (rawClassName == null || string.IsNullOrEmpty(rawClassName.ToString())) throw new Exception("You cannot model-bind to a property of type {0} without passing the desired model class name through a form field named '{1}'.".FormatWith(modelType.ToString(), paymentMethodType));

            var className = rawClassName.AttemptedValue.ToString();
            modelType = Type.GetType(className);

            if (modelType.Name == "String[]") throw new Exception("You cannot pass more than one form field named '{0}' when model-binding to IPaymentMethod.".FormatWith(paymentMethodType));

            if (modelType != null)
            {
                var instance = Activator.CreateInstance(modelType);
                bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, modelType);

                return instance;
            }
            else
            {
                return null;
            }
        }
Esempio n. 44
0
        /// <summary>
        /// Создает произвольный диалог для класса из доменной модели приложения.
        /// </summary>
        /// <returns>Виджет с интерфейсом ITdiDialog</returns>
        /// <param name="objectClass">Класс объекта для которого нужно создать диалог.</param>
        /// <param name="parameters">Параметры конструктора диалога.</param>
        public static ITdiDialog CreateObjectDialog(System.Type objectClass, params object[] parameters)
        {
            System.Type dlgType = GetDialogType(objectClass);
            if (dlgType == null)
            {
                InvalidOperationException ex = new InvalidOperationException(
                    String.Format("Для класса {0} нет привязанного диалога.", objectClass));
                logger.Error(ex);
                throw ex;
            }
            Type[] paramTypes = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                paramTypes[i] = parameters[i].GetType();
            }

            System.Reflection.ConstructorInfo ci = dlgType.GetConstructor(paramTypes);
            if (ci == null)
            {
                InvalidOperationException ex = new InvalidOperationException(
                    String.Format("Конструктор для диалога {0} с параметрами({1}) не найден.", dlgType.ToString(), NHibernate.Util.CollectionPrinter.ToString(paramTypes)));
                logger.Error(ex);
                throw ex;
            }
            logger.Debug("Вызываем конструктор диалога {0} c параметрами {1}.", dlgType.ToString(), NHibernate.Util.CollectionPrinter.ToString(paramTypes));
            return((ITdiDialog)ci.Invoke(parameters));
        }
Esempio n. 45
0
    private T AddComponentBasedOnPlatform <T> () where T : MonoBehaviour
    {
        System.Type _basicType    = typeof(T);
        string      _baseTypeName = _basicType.ToString();

        // Check if we have free version specific class
        string _platformSpecificTypeName = null;

#if UNITY_EDITOR
        _platformSpecificTypeName = _baseTypeName + "Editor";
#elif UNITY_IOS
        _platformSpecificTypeName = _baseTypeName + "IOS";
#elif UNITY_ANDROID
        _platformSpecificTypeName = _baseTypeName + "Android";
#endif

        if (!string.IsNullOrEmpty(_platformSpecificTypeName))
        {
#if !NETFX_CORE
            System.Type _platformSpecificClassType = _basicType.Assembly.GetType(_platformSpecificTypeName, false);
#else
            System.Type _platformSpecificClassType = _basicType;
#endif

            return(CachedGameObject.AddComponent(_platformSpecificClassType) as T);
        }

        return(CachedGameObject.AddComponent <T>());
    }
Esempio n. 46
0
 public void Static_LoadSettingsStorageProvider(string p, Type type)
 {
     ISettingsStorageProviderV30 prov = ProviderLoader.LoadSettingsStorageProvider(p);
     Assert.IsNotNull(prov, "Provider should not be null");
     // type == prov.GetType() seems to fail due to reflection
     Assert.AreEqual(type.ToString(), prov.GetType().FullName, "Wrong return type");
 }
 public void DoAddButton(ReorderableList list)
 {
     if (list.serializedProperty != null)
     {
         ++list.serializedProperty.arraySize;
         list.index = list.serializedProperty.arraySize - 1;
     }
     else
     {
         System.Type elementType = list.list.GetType().GetElementType();
         if ((object)elementType == (object)typeof(string))
         {
             list.index = list.list.Add((object)"");
         }
         else if ((object)elementType != null && (object)elementType.GetConstructor(System.Type.EmptyTypes) == null)
         {
             Debug.LogError((object)("Cannot add element. Type " + elementType.ToString() + " has no default constructor. Implement a default constructor or implement your own add behaviour."));
         }
         else if ((object)list.list.GetType().GetGenericArguments()[0] != null)
         {
             list.index = list.list.Add(Activator.CreateInstance(list.list.GetType().GetGenericArguments()[0]));
         }
         else if ((object)elementType != null)
         {
             list.index = list.list.Add(Activator.CreateInstance(elementType));
         }
         else
         {
             Debug.LogError((object)"Cannot add element of type Null.");
         }
     }
 }
        /// <summary>
        /// Gets the value of an Enum, based on it's Description Attribute or named value
        /// </summary>
        /// <param name="value">The Enum type</param>
        /// <param name="description">The description or name of the element</param>
        /// <returns>The value, or the passed in description, if it was not found</returns>
        public static object GetEnumValue(Type value, string description)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (description == null)
                throw new ArgumentNullException("description", "value was " + (value == null ? "null" : value.ToString()));

            FieldInfo[] fis = value.GetFields();
            foreach (FieldInfo fi in fis)
            {
                DescriptionAttribute[] attributes =
                    (DescriptionAttribute[]) fi.GetCustomAttributes(
                                                 typeof (DescriptionAttribute), false);
                if (attributes.Length > 0)
                {
                    if (attributes[0].Description == description)
                    {
                        return fi.GetValue(fi.Name);
                    }
                }
                if (fi.Name == description)
                {
                    return fi.GetValue(fi.Name);
                }
            }
            throw new ArgumentException("Unknown value for enum type " + value.FullName + ": " + description);
            //return description;
        }
Esempio n. 49
0
        //Methods
        public virtual void Add(string key, Element value)
        {
            if (!mModifiable)
            {
                throw new CollectionNotModifiableException("This collection is not modifiable.");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value", "Element parameter cannot be null reference.");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key", "Key may not be null.");
            }
            if (key == "")
            {
                throw new ArgumentException("Key may not be null string.", "key");
            }
            if (!mBaseType.IsInstanceOfType(value) && !value.GetType().IsSubclassOf(mBaseType))
            {
                throw new ArgumentException("Items added to this collection must be of or inherit from type '" + mBaseType.ToString());
            }

            //Key can be reset by removing and then readding to collection
            value.SetKey(key);
            Dictionary.Add(key, value);

            //Zordering now done outside the collection
            //Since multiple collections can contain the same reference eg layer
            OnInsert(key, value);
        }
Esempio n. 50
0
    public static IEnumerator DumpAssets(System.Type assetType)
    {
        yield return(Resources.UnloadUnusedAssets());

#if !UNITY_WEBPLAYER
        string filePath = Path.Combine(Application.persistentDataPath, assetType.ToString() + ".log");
        //ssLogger.Log(filePath);
        StreamWriter sw = File.CreateText(filePath);

        Object[] assetArray = Resources.FindObjectsOfTypeAll(assetType);
        int      len        = assetArray.Length;
        float    totalSize  = 0;
        System.Array.Sort(assetArray, SortBySize);
        for (int i = 0; i < len; ++i)
        {
            Object obj    = assetArray[i];
            float  sizeKB = Profiler.GetRuntimeMemorySize(obj) / 1024.0f;
            totalSize += sizeKB;
            sw.WriteLine(obj.name + "(" + obj.GetInstanceID() + ")" + ": " + sizeKB + " kB");
        }

        sw.WriteLine();

        sw.WriteLine("TotalCount: " + len);
        sw.WriteLine("TotalSize: " + totalSize + " kB");

        sw.WriteLine("Mono heap used size: " + mono_gc_get_used_size() / 1024.0f + " kB");
        sw.WriteLine("Mono heap size: " + mono_gc_get_heap_size() / 1024.0f + " kB");

        sw.Close();
#endif
    }
Esempio n. 51
0
            public static object CreateInstanceByInterface(SType iifc)
            {
                Log.debug("Looking for {0}", iifc.FullName);
                foreach (SReflection.Assembly assembly in System.AppDomain.CurrentDomain.GetAssemblies())
                {
                    foreach (SType type in assembly.GetTypes())
                    {
                        foreach (SType ifc in type.GetInterfaces())
                        {
                            Log.debug("Checking {0} {1} {2}", assembly, type, ifc);

                            /*
                             * This caught me with my pants down!
                             * (typeof(Interface).Equals(ifc.GetType())) and (typeof(Interface) == ifc.GetType()) does not work!
                             */
                            if (iifc.ToString() == ifc.ToString())                             // Don't ask. This works...
                            {
                                Log.debug("Found one! {0}", ifc);
                                return(CreateInstance(type));
                            }
                        }
                    }
                }
                return(null);
            }
Esempio n. 52
0
 // Token: 0x060003EE RID: 1006 RVA: 0x0000B1B0 File Offset: 0x0000A1B0
 private int WriteField(Context context, FieldType field, int fieldIndex, ComplexValue[] fieldValues, object fieldValue, ref byte bitOffset)
 {
     System.Type type = field.GetType();
     if (type == typeof(Integer) || type.IsSubclassOf(typeof(Integer)))
     {
         return(this.WriteField(context, (Integer)field, fieldValue));
     }
     if (type == typeof(FloatingPoint) || type.IsSubclassOf(typeof(FloatingPoint)))
     {
         return(this.WriteField(context, (FloatingPoint)field, fieldValue));
     }
     if (type == typeof(CharString) || type.IsSubclassOf(typeof(CharString)))
     {
         return(this.WriteField(context, (CharString)field, fieldIndex, fieldValues, fieldValue));
     }
     if (type == typeof(BitString) || type.IsSubclassOf(typeof(BitString)))
     {
         return(this.WriteField(context, (BitString)field, fieldValue, ref bitOffset));
     }
     if (type == typeof(TypeReference) || type.IsSubclassOf(typeof(TypeReference)))
     {
         return(this.WriteField(context, (TypeReference)field, fieldValue));
     }
     throw new NotImplementedException("Fields of type '" + type.ToString() + "' are not implemented yet.");
 }
Esempio n. 53
0
    static public string ShortName(this System.Type type)
    {
        string[] tempName = type.ToString().Split('.');
        string   result   = tempName[tempName.Length - 1];

        return(result);
    }
Esempio n. 54
0
        private object GetPropertyValue(object inObj, string fieldName)
        {
            System.Type t = inObj.GetType();
            //GameObject hack
            // Due to GameObject.active is obsolete and ativeSelf is read only
            // Use a hack function to override GameObject's active status.
            if (t == typeof(GameObject) && fieldName == "m_IsActive")
            {
                return(((GameObject)inObj).activeSelf);
            }
            object ret = null;

            // Try search Field first than try property
            System.Reflection.FieldInfo fieldInfo = t.GetField(fieldName, bindingFlags);
            if (fieldInfo != null)
            {
                ret = fieldInfo.GetValue(inObj);
                return(ret);
            }
            if (t.ToString().Contains("UnityEngine."))
            {
                fieldName = ViewSystemUtilitys.ParseUnityEngineProperty(fieldName);
            }
            System.Reflection.PropertyInfo info = t.GetProperty(fieldName, bindingFlags);
            if (info != null)
            {
                ret = info.GetValue(inObj);
            }

            //ViewSystemLog.Log($"GetProperty on [{gameObject.name}] Target Object {((UnityEngine.Object)inObj).name} [{t.ToString()}] on [{fieldName}]  Value [{ret}]");
            return(ret);
        }
Esempio n. 55
0
		/// <summary>
		/// Creates a new <see cref="StringEnum"/> instance.
		/// </summary>
		/// <param name="enumType">Enum type.</param>
		public StringEnum(Type enumType)
		{
			if (!enumType.IsEnum)
				throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", enumType.ToString()));

			_enumType = enumType;
		}
Esempio n. 56
0
        public Report GetReport(decimal ID, System.Type ReportType, bool Open)
        {
            Report report = null;

            if (ReportType == typeof(OlapReport))
            {
                report = new OlapReport(ID, this._owner);
            }
            else if (ReportType == typeof(StorecheckReport))
            {
                report = new StorecheckReport(ID, this._owner);
            }
            else if (ReportType == typeof(CustomSqlReport))
            {
                report = new CustomSqlReport(ID, this._owner);
            }
            else if (ReportType == typeof(CustomMdxReport))
            {
                report = new CustomMdxReport(ID, this._owner);
            }
            else
            {
                throw new Exception("ReportType " + ReportType.ToString() + " is not supported");
            }

            if (Open)
            {
                report.Open();
            }

            report.StartExecuteEvent += new EventHandler(report_StartExecuteEvent);
            report.EndExecuteEvent   += new EventHandler(report_EndExecuteEvent);
            return(report);
        }
Esempio n. 57
0
        public object Resolve(Type typeToResolve, Type typeToCreate, string id, NotPresentBehavior notPresent, SearchMode searchMode)
        {
            if (typeToResolve == null)
            {
                throw new ArgumentNullException("typeToResolve");
            }
            if (!Enum.IsDefined(typeof(NotPresentBehavior), notPresent))
            {
                throw new ArgumentException(Resources.InvalidEnumerationValue, "notPresent");
            }
            if (typeToCreate == null)
            {
                typeToCreate = typeToResolve;
            }
            DependencyResolutionLocatorKey key = new DependencyResolutionLocatorKey(typeToResolve, id);
            if (this.context.Locator.Contains(key, searchMode))
            {
                return this.context.Locator.Get(key, searchMode);
            }
            switch (notPresent)
            {
                case NotPresentBehavior.CreateNew:
                    return this.context.HeadOfChain.BuildUp(this.context, typeToCreate, null, key.ID);

                case NotPresentBehavior.ReturnNull:
                    return null;
            }
            throw new DependencyMissingException(string.Format(CultureInfo.CurrentCulture, Resources.DependencyMissing, new object[] { typeToResolve.ToString() }));
        }
Esempio n. 58
0
 public static bool InterfaceFilter(Type typeObj, Object criteriaObj)
 {
     if (typeObj.ToString() == criteriaObj.ToString())
         return true;
     else
         return false;
 }
		private IEnumerable<PluginWrapper> GetModule(string pFileName, Type pTypeInterface)
		{
			var plugins = new List<PluginWrapper>();
			try
			{
				var assembly = Assembly.LoadFrom(pFileName);
				foreach(var type in assembly.GetTypes())
				{
					try
					{
						if(!type.IsPublic || type.IsAbstract)
							continue;
						var typeInterface = type.GetInterface(pTypeInterface.ToString(), true);
						if(typeInterface == null)
							continue;
						var instance = Activator.CreateInstance(type) as IPlugin;
						if(instance != null)
							plugins.Add(new PluginWrapper(pFileName, instance));
					}
					catch(Exception ex)
					{
						Log.Error("Error loading " + pFileName + ":\n" + ex);
					}
				}
			}
			catch(Exception ex)
			{
				Log.Error("Error loading " + pFileName + ":\n" + ex);
			}
			return plugins;
		}
		public static object ParseValue(Type type, string value)
		{
			if(type == typeof(string))
			{
				return value;
			}

			if(type == typeof(bool))
			{
				return bool.Parse(value);
			}
			else if(type.IsEnum)
			{
				return Enum.Parse(type, value);
			}
			else if(type == typeof(float))
			{
				return float.Parse(value);
			}
			else if(type == typeof(Single))
			{
				return Single.Parse(value);
			}
			UnityEngine.Debug.LogError("BDAPersistantSettingsField to parse settings field of type "+type.ToString()+" and value "+value);

			return null;
		}