private LitTable BuildTable(Type type)
 {
     LitTable table = null;
     if (!type.IsDefined(typeof(TableAttribute), false))
     {
         if (!type.IsDefined(typeof(SPResultAttribute), false))
             throw new LightException("no TableAttribute or SPResultAttribute found on " + type.FullName);
         else
             table = new LitTable(type, null, null);
     }
     else
     {
         TableAttribute tableAttr = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), false)[0];
         string name = tableAttr.Name;
         string schema = tableAttr.Schema;
         if (name == null || name.Length == 0)
             name = type.Name;
         table = new LitTable(type, name, schema);
     }
     FindInherited(type, table);
     ProcessFields(type, table);
     ProcessProperties(type, table);
     ProcessMethods(type, table);
     return table;
 }
        /// <inheritdoc />
        public ConversionCost GetConversionCost(Type sourceType, Type targetType, IConverter elementConverter)
        {
            if (typeof(XPathNavigator).IsAssignableFrom(sourceType)
                && targetType.IsDefined(typeof(XmlTypeAttribute), true)
                && targetType.IsDefined(typeof(XmlRootAttribute), true))
                return ConversionCost.Typical;

            return ConversionCost.Invalid;
        }
 private void FindInherited(Type type, LitTable table)
 {
     if (type.IsDefined(typeof(MapAttribute), false))
     {
         object[] attrs = type.GetCustomAttributes(typeof(MapAttribute), false);
         foreach (MapAttribute attr in attrs)
         {
             IDataBridge data = null;
             BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
             MemberInfo member = type.GetProperty(attr.Field, flags);
             if (member != null)
             {
                 data = new PropertyBridge((PropertyInfo)member);
             }
             else
             {
                 member = type.GetField(attr.Field, flags);
                 if (member != null)
                     data = new FieldBridge((FieldInfo)member);
                 else
                     throw new LightException("member " + attr.Field + " not found in class " + type.Name);
             }
             if (attr.Name == null || attr.Name.Length == 0)
                 attr.Name = member.Name;
             SqlColumn column = new SqlColumn(table, attr.Name, data);
             if (attr.Alias == null || attr.Alias.Length == 0)
                 column.Alias = attr.Field;
             else
                 column.Alias = attr.Alias;
             column.IsID = attr.ID;
             column.IsPK = attr.PK;
             table.Add(column);
         }
     }
 }
 protected void ProcessType(Type type)
 {
     if (type.IsDefined(typeof(MapClassAttribute), false))
     {
         m_classDescriptors.Add(CreateMapping(type));
     }
 }
Example #5
0
 public object DrawAndGetNewValue(Type memberType, string memberName, object value, Entity entity, int index, IComponent component)
 {
     if(memberType.IsDefined(typeof(FlagsAttribute), false)) {
         return EditorGUILayout.EnumMaskField(memberName, (Enum)value);
     }
     return EditorGUILayout.EnumPopup(memberName, (Enum)value);
 }
        /// <summary>
        /// 获取生命周期
        /// </summary>
        public static Lifecycle GetLifecycle(Type type)
        {
            if (!type.IsDefined(typeof(LifeCycleAttribute), false))
                return Lifecycle.Singleton;

            return type.GetCustomAttribute<LifeCycleAttribute>(false).Lifetime;
        }
        private bool IsCompilerGenerated(Type t)
        {
            if (t == null)
                return false;

            return t.IsDefined(typeof(CompilerGeneratedAttribute), false) || IsCompilerGenerated(t.DeclaringType);
        }
Example #8
0
        private static void getGroups(string fieldName, Type type, object original, object translation,
            NumberSystem originalNumSys, NumberSystem translationNumSys, Dictionary<object, TranslationGroup> dic,
            ref TranslationGroup ungrouped, IEnumerable<object> classGroups, string path)
        {
            if (!type.IsDefined<LingoStringClassAttribute>(true))
            {
                if (fieldName == null)
                    throw new ArgumentException(@"Type ""{0}"" must be marked with the [LingoStringClass] attribute.".Fmt(type.FullName), "type");
                else
                    throw new ArgumentException(@"Field ""{0}.{1}"" must either be marked with the [LingoIgnore] attribute, or be of type TrString, TrStringNumbers, or a type with the [LingoStringClass] attribute.".Fmt(type.FullName, fieldName), "type");
            }

            var thisClassGroups = type.GetCustomAttributes(true).OfType<LingoInGroupAttribute>().Select(attr => attr.Group);
            if (classGroups != null)
                thisClassGroups = thisClassGroups.Concat(classGroups);

            foreach (var f in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                if (f.FieldType == typeof(TrString) || f.FieldType == typeof(TrStringNum))
                {
                    string notes = f.GetCustomAttributes<LingoNotesAttribute>().Select(lna => lna.Notes).FirstOrDefault();
                    var trInfo = f.FieldType == typeof(TrString)
                        ? (TranslationInfo) new TrStringInfo
                        {
                            Label = path + f.Name,
                            Notes = notes,
                            NewOriginal = ((TrString) f.GetValue(original)).Translation,
                            TranslationTr = (TrString) f.GetValue(translation)
                        }
                        : (TranslationInfo) new TrStringNumInfo((TrStringNum) f.GetValue(original), (TrStringNum) f.GetValue(translation), originalNumSys, translationNumSys)
                        {
                            Label = path + f.Name,
                            Notes = notes
                        };

                    var groups = f.GetCustomAttributes<LingoInGroupAttribute>().Select(attr => attr.Group).Concat(thisClassGroups);
                    if (!groups.Any())
                    {
                        if (ungrouped == null)
                            ungrouped = new TranslationGroup { Label = "Ungrouped strings", Notes = "This group contains strings not found in any other group." };
                        ungrouped.Infos.Add(trInfo);
                    }
                    else
                    {
                        foreach (var group in groups)
                        {
                            TranslationGroup grp;
                            if (!dic.TryGetValue(group, out grp))
                            {
                                grp = createGroup(group);
                                dic[group] = grp;
                            }
                            grp.Infos.Add(trInfo);
                        }
                    }
                }
                else if (!f.IsDefined<LingoIgnoreAttribute>(true))
                    getGroups(f.Name, f.FieldType, f.GetValue(original), f.GetValue(translation), originalNumSys, translationNumSys, dic, ref ungrouped, thisClassGroups, path + f.Name + " / ");
            }
        }
        private void AddTypeToLookupTables(Type type)
        {
            if (type == null)
            {
                return;
            }

            // we've seen it already
            if (_typeByName.ContainsKey(type.Name))
            {
                return;
            }

            // look this Type up by name
            _typeByName[type.Name] = type;

            if (!type.IsDefined(typeof(JsonApiResourceTypeAttribute), true))
            {
                return;
            }

            var attribute =
                type.GetCustomAttributes(typeof(JsonApiResourceTypeAttribute), true).FirstOrDefault() as JsonApiResourceTypeAttribute;

            if (attribute != null)
            {
                _typeByJsonApiResourceTypeName[attribute.JsonApiResourceTypeName] = type;
            }
        }
Example #10
0
        /// <summary>
        /// Constructor from an enumerated type
        /// </summary>
        /// <param name="enumType">A type representing an existing enumeration</param>
        /// <exception cref="System.ArgumentException">Throw if the type if not an enumerated type</exception>
        public PortableEnum(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("Parameter is not an enumerated type");
            }

            _entries = new Dictionary<string, long>();
            string[] names = Enum.GetNames(enumType);
            Array values = Enum.GetValues(enumType);

            for (int i = 0; i < names.Length; ++i)
            {
                long v = (long)Convert.ChangeType(values.GetValue(i), typeof(long));

                _entries.Add(names[i], v);
            }

            if (enumType.IsDefined(typeof(FlagsAttribute), false))
            {
                _isFlags = true;
            }
            else
            {
                _isFlags = false;
            }

            _value = 0;
            _name = enumType.Name;
        }
 /// <summary>
 /// Handles the specified Type depending on the scanning strategy
 /// of the <see cref="TypeConfiguration"/>.
 /// </summary>
 /// <param name="type">Type to handle.</param>
 internal void Handle( Type type )
 {
     switch ( ScanningStrategy )
     {
         case ScanFor.TypesThatAreDecoratedWithThisAttribute:
             if ( type.IsDefined( Type, true ) )
             {
                 Action( type );
             }
             break;
         case ScanFor.TypesThatImplementThisInterface:
             if ( Type.IsAssignableFrom( type ) && type.IsInterface == false )
             {
                 Action( type );
             }
             break;
         case ScanFor.TypesThatInheritFromThisAbstractClass:
             if ( Type.IsAssignableFrom( type ) && type.IsAbstract == false )
             {
                 Action( type );
             }
             break;
         case ScanFor.TypesThatInheritFromThisClass:
             if ( Type.IsAssignableFrom( type ) && type != Type )
             {
                 Action( type );
             }
             break;
         default:
             Action( type );
             break;
     }
 }
 private MemberSetter[] CreateMemberSetters(Type type)
 {
     var selfMembers = type
         .GetProperties(bindingFlags)
         .Where(m => m.CanWrite)
         .Union(type.GetFields(bindingFlags).Cast<MemberInfo>())
         .Where(m => m.IsDefined(typeof (InjectAttribute), true))
         .ToArray();
     MemberSetter[] baseSetters = null;
     if (!type.IsDefined<FrameworkBoundaryAttribute>(false))
     {
         var baseType = type.BaseType;
         if (baseType != typeof (object))
             baseSetters = GetMembers(baseType);
     }
     if (selfMembers.Length == 0 && baseSetters != null)
         return baseSetters;
     var baseMembersCount = baseSetters == null ? 0 : baseSetters.Length;
     var result = new MemberSetter[selfMembers.Length + baseMembersCount];
     if (baseMembersCount > 0)
         Array.Copy(baseSetters, 0, result, 0, baseMembersCount);
     for (var i = 0; i < selfMembers.Length; i++)
     {
         var member = selfMembers[i];
         var resultIndex = i + baseMembersCount;
         result[resultIndex].member = member;
         result[resultIndex].setter = MemberAccessorsFactory.GetSetter(member);
     }
     return result;
 }
Example #13
0
        private static void ProcessInitializeOnLoadAttributes()
        {
            m_TotalNumRuntimeInitializeMethods = 0;
            m_RuntimeInitializeClassInfoList   = new List <RuntimeInitializeClassInfo>();
            IEnumerator <System.Type> enumerator = loadedTypes.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    System.Type current = enumerator.Current;
                    if (current.IsDefined(typeof(InitializeOnLoadAttribute), false))
                    {
                        ProcessEditorInitializeOnLoad(current);
                    }
                    ProcessStaticMethodAttributes(current);
                }
            }
            finally
            {
                if (enumerator == null)
                {
                }
                enumerator.Dispose();
            }
        }
        /// <inheritdoc/>
        public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            if (HandleNullableTypes(ref objectType) && reader.TokenType == JsonToken.Null)
                return null;

            if (reader.TokenType == JsonToken.String || !objectType.IsDefined(typeof(FlagsAttribute), false))
            {
                return Enum.Parse(objectType, serializer.Deserialize<String>(reader));
            }
            else
            {
                var enumNames = (String[])serializer.Deserialize(reader, typeof(String[]));
                if (enumNames == null)
                    throw new JsonReaderException(NucleusStrings.JsonValueCannotBeNull);

                var enumValue = 0ul;

                for (int i = 0; i < enumNames.Length; i++)
                {
                    enumValue |= Convert.ToUInt64(Enum.Parse(objectType, enumNames[i]));
                }

                return Enum.ToObject(objectType, enumValue);
            }
        }
        public ViewModelConfig CreateViewModelConfig(Type type)
        {
            if (!type.IsBaseObject() && !type.IsDefined(typeof(ComplexTypeAttribute))) return null;

            string serviceName = "";

            if (type.IsBaseObject())
            {
                if (type.IsAssignableFrom(typeof(HCategory)))
                    serviceName = typeof(IBaseCategoryService<>).GetTypeName();
                else if (type.IsAssignableFrom(typeof(ICategorizedItem)))
                    serviceName = typeof(IBaseCategorizedItemService<>).GetTypeName();
                else
                    serviceName = typeof(IBaseObjectService<>).GetTypeName();
            }

            return new ViewModelConfig(
                mnemonic: type.GetTypeName(),
                entity: type.GetTypeName(),
                listView: new ListView(),
                detailView: new DetailView(),
                lookupProperty:
                    type.IsBaseObject()
                        ? (type.GetProperty("Title") ?? type.GetProperty("Name") ?? type.GetProperty("ID")).Name
                        : "",
                service: serviceName);
        }
        private Boolean AllowsUnauthorized(Type authorizedControllerType, MethodInfo method)
        {
            if (method.IsDefined(typeof(AuthorizeAttribute), false)) return false;
            if (method.IsDefined(typeof(AllowAnonymousAttribute), false)) return true;
            if (method.IsDefined(typeof(AllowUnauthorizedAttribute), false)) return true;

            while (authorizedControllerType != typeof(Controller))
            {
                if (authorizedControllerType.IsDefined(typeof(AuthorizeAttribute), false)) return false;
                if (authorizedControllerType.IsDefined(typeof(AllowAnonymousAttribute), false)) return true;
                if (authorizedControllerType.IsDefined(typeof(AllowUnauthorizedAttribute), false)) return true;

                authorizedControllerType = authorizedControllerType.BaseType;
            }

            return true;
        }
 private static Type GetModelBinder(Type modelType)
 {
     if (modelType.IsDefined(typeof(ViewModelAttribute), false))
     {
         return typeof(ModelModelBinder);
     }
     return null;
 }
 public virtual bool ShouldMap(Type type)
 {
     return !type.ClosesInterface(typeof(IAutoMappingOverride<>)) &&
         !type.HasInterface(typeof(IMappingProvider)) &&
         !type.IsNestedPrivate && 
     	!type.IsDefined(typeof(CompilerGeneratedAttribute), false)
         && type.IsClass;
 }
 public void Process(Type type, Registry registry)
 {
     if (type.IsDefined(typeof (ServiceContractAttribute), false))
     {
         var closedGenericMethod = _method.MakeGenericMethod(type);
         var module = new WcfModule();
         registry.For(type).Use(x => closedGenericMethod.Invoke(module, new object[0]));
     }
 }
Example #20
0
        public EnumImporter(Type type)
            : base(type)
        {
            if (!type.IsEnum)
                throw new ArgumentException(string.Format("{0} does not inherit from System.Enum.", type), "type");

            if (type.IsDefined(typeof(FlagsAttribute), true))
                throw new ArgumentException(string.Format("{0} is a bit field, which are not currently supported.", type), "type");
        }
		public IPersistenceConversationalInfo GetInfo(Type type)
		{
			if (!type.IsDefined(typeof (PersistenceConversationalAttribute), true))
			{
				return null;
			}
			object[] atts = type.GetCustomAttributes(typeof (PersistenceConversationalAttribute), true);
			return atts[0] as PersistenceConversationalAttribute;
		}
Example #22
0
        /// <summary>
        /// Determines whether a particular type is compiler-generated.
        /// <para>Courtesy of Cameron MacFarland at http://stackoverflow.com/a/11839713/3191599</para>
        /// </summary>
        /// <param name="t">The type.</param>
        /// <returns><see langword="true"/> if this type is generated by the compiler; <see langword="false"/> otherwise.</returns>
        public static bool IsCompilerGenerated(Type t)
        {
            if (t == null)
            {
                return false;
            }

            return t.IsDefined(typeof(CompilerGeneratedAttribute), false)
                || IsCompilerGenerated(t.DeclaringType);
        }
 public Resolution Check(Type type)
 {
     if (type.IsSubclassOf(typeof(System.Enum)) && type.IsDefined(typeof(System.FlagsAttribute), true)) {
         if (!type.Name.EndsWith("s") && !type.Name.EndsWith("ae") && !type.Name.EndsWith("i")) {
             // FIXME: I18N
      					return new Resolution (this, String.Format ("Change the type name of the enumeration <code>{0}</code> to plural.", type.FullName), type.FullName);
         }
     }
     return null;
 }
        private static object DeserializeStruct(XmlDictionaryReader reader, Type targetType)
        {
            if (targetType.IsDefined(typeof(DataContractAttribute), false))
            {
                Dictionary<string, MemberInfo> dataMembers = GetDataMembers(targetType);
                object targetObject = Activator.CreateInstance(targetType);

                reader.ReadStartElement(XmlRpcProtocol.Struct);
                
                while( reader.NodeType != XmlNodeType.EndElement )
                {
                    string memberName;

                    reader.ReadStartElement(XmlRpcProtocol.Member);
                    reader.ReadStartElement(XmlRpcProtocol.Name);
                    memberName = reader.ReadContentAsString();
                    reader.ReadEndElement();
                    
                    reader.ReadStartElement(XmlRpcProtocol.Value);
                    reader.MoveToContent();
                    if (dataMembers.ContainsKey(memberName))
                    {
                        MemberInfo member = dataMembers[memberName];
                        if (member is PropertyInfo)
                        {
                            ((PropertyInfo)member).SetValue(
                                targetObject, 
                                Deserialize(reader, ((PropertyInfo)member).PropertyType), 
                                BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.NonPublic, 
                                null, null,
                                CultureInfo.CurrentCulture);
                        }
                        else if (member is FieldInfo)
                        {
                            ((FieldInfo)member).SetValue(
                                targetObject,
                                Deserialize(reader, ((FieldInfo)member).FieldType),
                                BindingFlags.Instance|BindingFlags.SetField|BindingFlags.Public|BindingFlags.NonPublic,
                                null,
                                CultureInfo.CurrentCulture);
                        }
                    }
                    reader.ReadEndElement(); // value
                    reader.ReadEndElement(); // member
                }
                reader.ReadEndElement(); // struct
                reader.MoveToContent();
                return targetObject;                
            }
            else
            {
                throw new InvalidOperationException();
            }
            
        }
        /// <summary>
        /// Determines if the specified type is an anonymous type.
        /// </summary>
        /// <param name="type">The type to check.</param>
        /// <returns>True if the type is an anonymous type, otherwise false.</returns>
        public static bool IsAnonymousType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            return (type.IsClass
                    && type.IsSealed
                    && type.BaseType == typeof(object)
                    && type.Name.StartsWith("<>", StringComparison.Ordinal)
                    && type.IsDefined(typeof(CompilerGeneratedAttribute), true));
        }
        private static bool IsAnonymousType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            return (type.IsClass
                    && type.IsSealed
                    && type.BaseType == typeof(object)
                    && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$Anonymous"))
                    && type.IsDefined(typeof(CompilerGeneratedAttribute), true));
        }
        public ITypeImporter Bind(ImportContext context, Type type)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (type == null)
                throw new ArgumentNullException("type");

            return type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true) ? 
                   new EnumImporter(type) : null;
        }
 /// <summary>
 /// Checks if the given type has a component attribute
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static bool IsComponent(Type type)
 {
     foreach (var attribute in ComponentAttributes)
     {
         if (type.IsDefined(attribute, false))
         {
             return true;
         }
     }
     return false;
 }
Example #29
0
            // Serialized properties should use name from SwaggerPropertyAttribute if it exists.
            internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
            {
                if (!type.IsDefined<SwaggerDataAttribute>())
                {
                    return base.GetterValueFactory(type);
                }

                return ReflectionUtils.GetProperties(type)
                    .Where(x => x.CanRead)
                    .Where(x => !ReflectionUtils.GetGetterMethodInfo(x).IsStatic)
                    .ToDictionary(GetMemberName, ReflectionUtils.GetGetMethod);
            }
        public static TypedMessageConverter Create(Type messageContract, String action, String defaultNamespace, DataContractFormatAttribute formatterAttribute)
        {
            if (messageContract == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageContract"));

            if (!messageContract.IsDefined(typeof(MessageContractAttribute), false))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SFxMessageContractAttributeRequired, messageContract), "messageContract"));

            if (defaultNamespace == null)
                defaultNamespace = NamingHelper.DefaultNamespace;

            return new XmlMessageConverter(GetOperationFormatter(messageContract, formatterAttribute, defaultNamespace, action));
        }
        private static bool ShouldIntercept(Type type)
        {
            if (type.IsDefined(typeof(RequiresFeatureAttribute), true))
            {
                return true;
            }

            if (type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(m => m.IsDefined(typeof(RequiresFeatureAttribute), true)))
            {
                return true;
            }

            return false;
        }
 private void ValidateContractType(System.Type implementedContract, ReflectedAndBehaviorContractCollection reflectedAndBehaviorContracts)
 {
     if (!implementedContract.IsDefined(typeof(ServiceContractAttribute), false))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SfxServiceContractAttributeNotFound", new object[] { implementedContract.FullName })));
     }
     if (!reflectedAndBehaviorContracts.Contains(implementedContract))
     {
         if (implementedContract == typeof(IMetadataExchange))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SfxReflectedContractKeyNotFoundIMetadataExchange", new object[] { this.serviceType.FullName })));
         }
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SfxReflectedContractKeyNotFound2", new object[] { implementedContract.FullName, this.serviceType.FullName })));
     }
 }
        //Next method is taken there
        //http://www.codeproject.com/Tips/194804/See-if-a-Flags-enum-is-valid
        private static bool IsFlagsValid(System.Type enumType, long value)
        {
            if (enumType.IsEnum && enumType.IsDefined(typeof(FlagsAttribute), false))
            {
                long compositeValues = Enum.GetValues(enumType)
                                       .Cast <object>()
                                       .Aggregate <object, long>(0, (current, flag) => current | Convert.ToInt64(flag));

                return((~compositeValues & value) == 0);
            }
            else
            {
                return(false);
            }
        }
Example #34
0
 public static TypedMessageConverter Create(System.Type messageContract, string action, string defaultNamespace, DataContractFormatAttribute formatterAttribute)
 {
     if (messageContract == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageContract"));
     }
     if (!messageContract.IsDefined(typeof(MessageContractAttribute), false))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.ServiceModel.SR.GetString("SFxMessageContractAttributeRequired", new object[] { messageContract }), "messageContract"));
     }
     if (defaultNamespace == null)
     {
         defaultNamespace = "http://tempuri.org/";
     }
     return(new XmlMessageConverter(GetOperationFormatter(messageContract, formatterAttribute, defaultNamespace, action)));
 }
Example #35
0
        public SessionMetaInfo(System.Type type)
        {
            Type           = type;
            IsAbstractBase = type.IsGenericTypeDefinition ||
                             type.IsDefined(SessionProxyGeneratorBase.AbstractBaseSessionAttribute, false);

            IsBaseMostSession = type.BaseType == SessionProxyGeneratorBase.SessionBaseType;

            Operations = GetOperationMethodInfos(type).ToList();
            //Operations = (from method in type.GetMethods(
            //              BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
            //              where method.IsDefined(SessionProxyGeneratorBase.OperationAttributeType)
            //              select method).AsEnumerable();

            if (!Operations.All(item => item.IsVirtual))
            {
                throw new InvalidOperationException("Non-virtual operation found.");
            }

            DataProperties = GetProperties(type, false);
            //AllDataProperties = GetProperties(type, true);
        }
Example #36
0
        bool InnerMapCtor(Type actualType, Type expectedType, bool singletonMode
                          , ConstructorInfo ctor, ParameterInfo[] ps
                          , out InstanceBox typeInstance
                          , out Exception exception)
        {
            bool hasExpectedType = expectedType != null;

            if (!singletonMode &&
                (actualType.IsDefined(SingletonMappingAttribute.Type, true) || (hasExpectedType && expectedType.IsDefined(SingletonMappingAttribute.Type, true))))
            {
                singletonMode = true;
            }

            InstanceCreatorCallback callback = null;

            if (ps.Length == 0)
            {
                callback = lastMappingValues => this.WrappingObject(Activator.CreateInstance(actualType, true));
            }
            else
            {
                var psValues = new InstanceBox[ps.Length];
                for (int i = 0; i < ps.Length; i++)
                {
                    var         p          = ps[i];
                    var         pType      = p.ParameterType;
                    var         pName      = p.Name;
                    InstanceBox p_instance = null;
                    if (p.IsDefined(LastMappingAttribute.Type, true) ||
                        (pType.IsDefined(LastMappingAttribute.Type, true) && !p.IsDefined(IgnoreAttribute.Type, true)))
                    {
                        p_instance = new InstanceBox(pName, null, pType);
                    }

                    #region 从当前容器获取

                    else if (this.MapContains(actualType, pName))
                    {
                        p_instance = this.FindInstanceBox(actualType, pName);
                    }
                    else if (hasExpectedType && this.MapContains(expectedType, pName))
                    {
                        p_instance = this.FindInstanceBox(expectedType, pName);
                    }

                    else if (this.MapContains(pName))
                    {
                        p_instance = this.FindInstanceBox(pName);
                    }

                    else if (this.MapContains(actualType))
                    {
                        p_instance = this.FindInstanceBox(actualType);
                    }
                    else if (hasExpectedType && this.MapContains(expectedType))
                    {
                        p_instance = this.FindInstanceBox(expectedType);
                    }

                    #endregion

                    #region 从父级容器获取

                    else if (this._hasParent && this._parentLocator.ContainsValue(actualType, pName, true))
                    {
                        p_instance = new InstanceBox(pName, lmp => this._parentLocator.GetValue(actualType, pName));
                    }
                    else if (this._hasParent && hasExpectedType && this._parentLocator.ContainsValue(expectedType, pName, true))
                    {
                        p_instance = new InstanceBox(pName, lmp => this._parentLocator.GetValue(expectedType, pName));
                    }

                    else if (this._hasParent && this._parentLocator.ContainsValue(pName, true))
                    {
                        p_instance = new InstanceBox(pName, lmp => this._parentLocator.GetValue(pName));
                    }
                    else if (this._hasParent && this._parentLocator.ContainsService(actualType, true))
                    {
                        p_instance = new InstanceBox(pName, lmp => this._parentLocator.GetService(actualType));
                    }
                    else if (this._hasParent && hasExpectedType && this._parentLocator.ContainsService(expectedType, true))
                    {
                        p_instance = new InstanceBox(pName, lmp => this._parentLocator.GetService(expectedType));
                    }

                    #endregion

                    else if (!pType.IsSimpleType())
                    {
                        //- 从映射事件获取 -or- 尝试智能解析
                        p_instance = this.OnMapResolve(pType) ?? this.AutoResolveExpectType(pType);
                    }

                    if (p_instance == null)
                    {
                        exception    = new ArgumentException(actualType.FullName + ":构造函数的参数“" + pName + "”尚未配置映射!", pName);
                        typeInstance = null;
                        return(false);
                    }
                    psValues[i] = p_instance;
                }

                var cotrHandler = Aoite.Reflection.ConstructorInfoExtensions.DelegateForCreateInstance(ctor);
                callback = lastMappingValues =>
                {
                    System.Collections.IEnumerator cpe = null;
                    Func <bool> moveNextLastMap        = () =>
                    {
                        if (cpe == null)
                        {
                            if (lastMappingValues == null)
                            {
                                return(false);
                            }
                            cpe = lastMappingValues.GetEnumerator();
                        }
                        return(cpe.MoveNext());
                    };

                    object[] values = new object[psValues.Length];
                    for (int i = 0; i < psValues.Length; i++)
                    {
                        var instanceBox = psValues[i];
                        if (instanceBox.LastMappingType != null)
                        {
                            if (moveNextLastMap())
                            {
                                values[i] = cpe.Current;
                                continue;
                            }
                            var lastMappingBox = OnLastMappingResolve(instanceBox.LastMappingType);
                            if (lastMappingBox == null)
                            {
                                throw new ArgumentException(actualType.FullName + ":构造函数的参数“" + instanceBox.Name + "”指定了后期映射关系,但调用方却没有传递映射值!", instanceBox.Name);
                            }
                            instanceBox = lastMappingBox;
                        }

                        values[i] = instanceBox.GetInstance();
                    }
                    return(WrappingObject(cotrHandler(values)));
                };
            }
            typeInstance = singletonMode ? new SingletonInstanceBox(actualType.FullName, callback) : new InstanceBox(actualType.FullName, callback);
            this.Map(expectedType ?? actualType, typeInstance);
            exception = null;
            return(true);
        }
Example #37
0
        public static string Format(Type enumType, object value, string format)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }

            if (!enumType.IsEnum)
            {
                throw new ArgumentException("enumType is not an Enum type.", "enumType");
            }

            Type vType          = value.GetType();
            Type underlyingType = Enum.GetUnderlyingType(enumType);

            if (vType.IsEnum)
            {
                if (vType != enumType)
                {
                    throw new ArgumentException(string.Format(
                                                    "Object must be the same type as the enum. The type" +
                                                    " passed in was {0}; the enum type was {1}.",
                                                    vType.FullName, enumType.FullName));
                }
            }
            else if (vType != underlyingType)
            {
                throw new ArgumentException(string.Format(
                                                "Enum underlying type and the object must be the same type" +
                                                " or object. Type passed in was {0}; the enum underlying" +
                                                " type was {1}.", vType.FullName, underlyingType.FullName));
            }

            if (format.Length == 1)
            {
                switch (format [0])
                {
                case 'f':
                case 'F':
                    return(FormatFlags(enumType, value));

                case 'g':
                case 'G':
                    if (!enumType.IsDefined(typeof(FlagsAttribute), false))
                    {
                        return(GetName(enumType, value) ?? value.ToString());
                    }

                    goto case 'f';

                case 'X':
                    return(FormatSpecifier_X(enumType, value, true));

                case 'x':
                    return(FormatSpecifier_X(enumType, value, false));

                case 'D':
                case 'd':
                    if (vType.IsEnum)
                    {
                        value = ((Enum)value).Value;
                    }

                    return(value.ToString());
                }
            }

            throw new FormatException("Format String can be only \"G\",\"g\",\"X\"," +
                                      "\"x\",\"F\",\"f\",\"D\" or \"d\".");
        }
Example #38
0
        public static string Format(Type enumType, object value, string format)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }

            if (!enumType.IsEnum)
            {
                throw new ArgumentException("enumType is not an Enum type.", "enumType");
            }

            Type vType          = value.GetType();
            Type underlyingType = Enum.GetUnderlyingType(enumType);

            if (vType.IsEnum)
            {
                if (vType != enumType)
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                              "Object must be the same type as the enum. The type" +
                                                              " passed in was {0}; the enum type was {1}.",
                                                              vType.FullName, enumType.FullName));
                }
            }
            else if (vType != underlyingType)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          "Enum underlying type and the object must be the same type" +
                                                          " or object. Type passed in was {0}; the enum underlying" +
                                                          " type was {1}.", vType.FullName, underlyingType.FullName));
            }

            if (format.Length != 1)
            {
                throw new FormatException("Format String can be only \"G\",\"g\",\"X\"," +
                                          "\"x\",\"F\",\"f\",\"D\" or \"d\".");
            }

            char   formatChar = format [0];
            string retVal;

            if ((formatChar == 'G' || formatChar == 'g'))
            {
                if (!enumType.IsDefined(typeof(FlagsAttribute), false))
                {
                    retVal = GetName(enumType, value);
                    if (retVal == null)
                    {
                        retVal = value.ToString();
                    }

                    return(retVal);
                }

                formatChar = 'f';
            }

            if ((formatChar == 'f' || formatChar == 'F'))
            {
                return(FormatFlags(enumType, value));
            }

            retVal = String.Empty;
            switch (formatChar)
            {
            case 'X':
                retVal = FormatSpecifier_X(enumType, value, true);
                break;

            case 'x':
                retVal = FormatSpecifier_X(enumType, value, false);
                break;

            case 'D':
            case 'd':
                if (underlyingType == typeof(ulong))
                {
                    ulong ulongValue = Convert.ToUInt64(value);
                    retVal = ulongValue.ToString();
                }
                else
                {
                    long longValue = Convert.ToInt64(value);
                    retVal = longValue.ToString();
                }
                break;

            default:
                throw new FormatException("Format String can be only \"G\",\"g\",\"X\"," +
                                          "\"x\",\"F\",\"f\",\"D\" or \"d\".");
            }
            return(retVal);
        }