Пример #1
0
 //#if NET35
 // TODO: Consider adding functionality to TypeExtensions to avoid this difference.
 private static Dictionary <object, string> GetNameMapping(System.Type enumType)
 {
     return(enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
            .Where(f =>
     {
         OriginalNameAttribute a = f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
                                   .FirstOrDefault() as OriginalNameAttribute;
         if (a != null)
         {
             return a.PreferredAlias;
         }
         return true;
     })
            .ToDictionary(f => f.GetValue(null),
                          f =>
     {
         OriginalNameAttribute a = f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
                                   .FirstOrDefault() as OriginalNameAttribute;
         if (a != null)
         {
             return a.Name;
         }
         return f.Name;
     }));
 }
Пример #2
0
        /// <summary>
        /// Gets the clr name according to server defined name in the specified <paramref name="t"/>.
        /// </summary>
        /// <param name="t">Member to get clr name for.</param>
        /// <param name="serverDefinedName">name from server.</param>
        /// <param name="ignoreMissingProperties">flag to ignore missing properties.</param>
        /// <returns>Client clr name.</returns>
        internal static string GetClientPropertyName(Type t, string serverDefinedName, bool ignoreMissingProperties)
        {
            PropertyInfo propertyInfo = t.GetProperty(serverDefinedName);

            if (propertyInfo != null)
            {
                return(serverDefinedName);
            }

            propertyInfo = t.GetProperties().ToList().Where(
                m =>
            {
                OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)m.GetCustomAttributes(typeof(OriginalNameAttribute), true).SingleOrDefault();
                return(originalNameAttribute != null && originalNameAttribute.OriginalName == serverDefinedName);
            }).SingleOrDefault();
            if (propertyInfo == null && !ignoreMissingProperties)
            {
                throw c.Error.InvalidOperation(c.Strings.ClientType_MissingProperty(t.ToString(), serverDefinedName));
            }
            else if (propertyInfo == null)
            {
                return(null);
            }

            return(propertyInfo.Name);
        }
Пример #3
0
        public ODataRepository(C context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            PropertyInfo dataServiceQueryProperty =
                typeof(C).GetProperties().FirstOrDefault(p => p.PropertyType == typeof(DataServiceQuery <T>));
            DataServiceQuery <T> dataServiceQuery = dataServiceQueryProperty?.GetValue(context) as DataServiceQuery <T>;

            if (dataServiceQuery == null)
            {
                throw new NotSupportedException(
                          string.Format("DataServiceContext type {0} does not support queries for entity type {1}",
                                        typeof(C).FullName, typeof(T).FullName));
            }
            this._dataServiceQuery = dataServiceQuery;
            this._context          = context;
            OriginalNameAttribute originalNameAttribute =
                (OriginalNameAttribute)
                dataServiceQueryProperty.GetCustomAttributes(typeof(OriginalNameAttribute), true).SingleOrDefault();

            this._entitySetName = originalNameAttribute?.OriginalName;
        }
Пример #4
0
            private static Dictionary <object, string> GetNameMapping(System.Type enumType)
            {
                FieldInfo[] fields = enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                Dictionary <object, string> innerdic = new Dictionary <object, string>();

                for (int i = 0; i < fields.Length; i++)
                {
                    FieldInfo             f    = fields[i];
                    object[]              objs = f.GetCustomAttributes(typeof(OriginalNameAttribute), false);
                    OriginalNameAttribute obj  = null;
                    if (objs != null && objs.Length > 0)
                    {
                        obj = objs[0] as OriginalNameAttribute;
                    }
                    if (obj != null)
                    {
                        if (!string.IsNullOrEmpty(obj.Name))
                        {
                            innerdic.Add(f.GetValue(null), obj.Name);
                        }
                        else
                        {
                            innerdic.Add(f.GetValue(null), f.Name);
                        }
                    }
                }
                return(innerdic);
            }
Пример #5
0
        /// <summary>Gets the server defined name in <see cref="OriginalNameAttribute"/> of the specified <paramref name="propertyInfo"/>.</summary>
        /// <param name="propertyInfo">Member to get server defined name of.</param>
        /// <returns>Server defined name.</returns>
        internal static string GetServerDefinedName(PropertyInfo propertyInfo)
        {
            OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)propertyInfo.GetCustomAttributes(typeof(OriginalNameAttribute), true).SingleOrDefault();

            if (originalNameAttribute != null)
            {
                return(originalNameAttribute.OriginalName);
            }

            return(propertyInfo.Name);
        }
Пример #6
0
        /// <summary>Gets the server defined name in <see cref="OriginalNameAttribute"/> of the specified <paramref name="memberInfo"/>.</summary>
        /// <param name="memberInfo">Member to get server defined name of.</param>
        /// <returns>The server defined name.</returns>
        internal static string GetServerDefinedName(MemberInfo memberInfo)
        {
            OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)memberInfo.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();

            if (originalNameAttribute != null)
            {
                return(originalNameAttribute.OriginalName);
            }

            return(memberInfo.Name);
        }
Пример #7
0
        /// <summary>Gets the full server defined type name in <see cref="OriginalNameAttribute"/> of the specified <paramref name="type"/>.</summary>
        /// <param name="type">Member to get server defined name of.</param>
        /// <returns>The server defined type full name.</returns>
        internal static string GetServerDefinedTypeFullName(Type type)
        {
            OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)type.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();

            if (originalNameAttribute != null)
            {
                return(type.Namespace + "." + originalNameAttribute.OriginalName);
            }

            return(type.FullName);
        }
Пример #8
0
        /// <summary>
        /// Gets the original name of an enum field in case it was renamed for
        /// name style conventions.
        /// </summary>
        /// <returns>The original name, or an empty string if the name cannot be retrieved.</returns>
        public static string GetOriginalEnumFieldName(object obj)
        {
            FieldInfo fi = obj.GetType().GetField(obj.ToString());

            if (fi != null)
            {
                OriginalNameAttribute originalName = (OriginalNameAttribute)
                                                     fi.GetCustomAttributes(typeof(OriginalNameAttribute),
                                                                            false).FirstOrDefault();
                if (originalName != null)
                {
                    return(originalName.Name);
                }
            }
            return("");
        }
Пример #9
0
        /// <summary>
        /// Tries to resolve a type with specified name from the loaded assemblies.
        /// </summary>
        /// <param name="typeName">Name of the type to resolve.</param>
        /// <param name="fullNamespace">Namespace of the type.</param>
        /// <param name="languageDependentNamespace">Namespace that the resolved type is expected to be.
        /// Usually same as <paramref name="fullNamespace"/> but can be different
        /// where namespace for client types does not match namespace in service types.</param>
        /// <param name="matchedType">The resolved type.</param>
        /// <returns>true if type was successfully resolved; otherwise false.</returns>
        internal static bool TryResolveType(string typeName, string fullNamespace, string languageDependentNamespace, out Type matchedType)
        {
            Debug.Assert(typeName != null, "typeName != null");

            matchedType = null;
            int    namespaceLength   = fullNamespace?.Length ?? 0;
            string serverDefinedName = typeName.Substring(namespaceLength + 1);

            // Searching only loaded assemblies, not referenced assemblies
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                matchedType = assembly.GetType(string.Concat(languageDependentNamespace, typeName.Substring(namespaceLength)), false);
                if (matchedType != null)
                {
                    return(true);
                }

                IEnumerable <Type> types = null;

                try
                {
                    types = assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException)
                {
                    // Ignore
                }

                if (types != null)
                {
                    foreach (Type type in types)
                    {
                        OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)type.GetCustomAttributes(typeof(OriginalNameAttribute), true).SingleOrDefault();
                        if (string.Equals(originalNameAttribute?.OriginalName, serverDefinedName, StringComparison.Ordinal) &&
                            type.Namespace.Equals(languageDependentNamespace, StringComparison.Ordinal))
                        {
                            matchedType = type;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Пример #10
0
        /// <summary>
        /// Gets the clr name according to server defined name in the specified <paramref name="t"/>.
        /// </summary>
        /// <param name="t">The type used to get the client PropertyInfo.</param>
        /// <param name="serverDefinedName">Name from server.</param>
        /// <param name="undeclaredPropertyBehavior">Flag to support untyped properties.</param>
        /// <returns>Client PropertyInfo, or null if the method is not found.</returns>
        internal static PropertyInfo GetClientPropertyInfo(Type t, string serverDefinedName, UndeclaredPropertyBehavior undeclaredPropertyBehavior)
        {
            PropertyInfo propertyInfo = t.GetProperty(serverDefinedName);

            if (propertyInfo == null)
            {
                propertyInfo = t.GetProperties().Where(
                    m =>
                {
                    OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)m.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();
                    return(originalNameAttribute != null && originalNameAttribute.OriginalName == serverDefinedName);
                }).SingleOrDefault();
            }

            if (propertyInfo == null && (undeclaredPropertyBehavior == UndeclaredPropertyBehavior.ThrowException))
            {
                throw c.Error.InvalidOperation(c.Strings.ClientType_MissingProperty(t.ToString(), serverDefinedName));
            }

            return(propertyInfo);
        }
Пример #11
0
        /// <summary>
        /// Get a client method with the specified server side name.
        /// </summary>
        /// <param name="t">Client type used to search method.</param>
        /// <param name="serverDefinedName">Method name on server side.</param>
        /// <param name="parameters">An array of System.Type objects of the parameters for the method to get</param>
        /// <returns>Client MethodInfo, or null if the method is not found.</returns>
        internal static MethodInfo GetClientMethod(Type t, string serverDefinedName, Type[] parameters)
        {
            MethodInfo methodInfo = t.GetMethod(serverDefinedName, parameters);

            if (methodInfo == null)
            {
                var clientNamedMethodInfo = t.GetMethods().Where(
                    m =>
                {
                    OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)m.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();
                    return(originalNameAttribute != null && originalNameAttribute.OriginalName == serverDefinedName);
                }).FirstOrDefault();

                if (clientNamedMethodInfo != null)
                {
                    methodInfo = t.GetMethod(clientNamedMethodInfo.Name, parameters);
                }
            }

            return(methodInfo);
        }
Пример #12
0
        protected string ResolveNameFromType(Type clientType)
        {
            OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)clientType.GetCustomAttributes(typeof(OriginalNameAttribute), true).SingleOrDefault();

            if (clientType.Namespace.Equals("AstoriaUnitTests.TDD.Tests.Client", StringComparison.Ordinal))
            {
                if (originalNameAttribute != null)
                {
                    return(string.Concat("namespace.test.", originalNameAttribute.OriginalName));
                }

                return(string.Concat("namespace.test.", clientType.Name));
            }

            if (originalNameAttribute != null)
            {
                return(clientType.Namespace + "." + originalNameAttribute.OriginalName);
            }

            return(clientType.FullName);
        }
Пример #13
0
        /// <summary>
        /// Gets the clr name according to server defined name in the specified <paramref name="t"/>.
        /// </summary>
        /// <param name="t">Member to get clr name for.</param>
        /// <param name="serverDefinedName">name from server.</param>
        /// <returns>Client clr name.</returns>
        internal static string GetClientMemberName(Type t, string serverDefinedName)
        {
            MemberInfo memberInfo = t.GetMember(serverDefinedName).SingleOrDefault();

            if (memberInfo != null)
            {
                return(serverDefinedName);
            }

            memberInfo = t.GetMembers().ToList().Where(
                m =>
            {
                OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)m.GetCustomAttributes(typeof(OriginalNameAttribute), true).SingleOrDefault();
                return(originalNameAttribute != null && originalNameAttribute.OriginalName == serverDefinedName);
            }).SingleOrDefault();
            if (memberInfo == null)
            {
                throw c.Error.InvalidOperation(c.Strings.ClientType_MissingProperty(t.ToString(), serverDefinedName));
            }

            return(memberInfo.Name);
        }
Пример #14
0
        /// <summary>
        /// Gets the clr name according to server defined name in the specified <paramref name="t"/>.
        /// </summary>
        /// <param name="t">Member to get clr name for.</param>
        /// <param name="serverDefinedName">name from server.</param>
        /// <returns>Client clr name.</returns>
        internal static string GetClientFieldName(Type t, string serverDefinedName)
        {
            List <string> serverDefinedNames = serverDefinedName.Split(',').Select(name => name.Trim()).ToList();
            List <string> clientMemberNames  = new List <string>();

            foreach (var serverSideName in serverDefinedNames)
            {
                FieldInfo memberInfo = t.GetField(serverSideName) ?? t.GetFields().ToList().Where(m =>
                {
                    OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)m.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();
                    return(originalNameAttribute != null && originalNameAttribute.OriginalName == serverSideName);
                }).SingleOrDefault();

                if (memberInfo == null)
                {
                    throw c.Error.InvalidOperation(c.Strings.ClientType_MissingProperty(t.ToString(), serverSideName));
                }

                clientMemberNames.Add(memberInfo.Name);
            }

            return(string.Join(",", clientMemberNames));
        }
Пример #15
0
        /// <summary>
        /// Get ClientField name for a serverside name
        /// </summary>
        /// <param name="serverSideName">server side name from the list of serverdefined name</param>
        /// <returns>Client field name for the serverside name</returns>
        public string GetClientFieldName(string serverSideName)
        {
            string memberInfoName;

            if (!ServerSideNameDict.TryGetValue(serverSideName, out memberInfoName))
            {
                FieldInfo memberInfo = type.GetField(serverSideName) ?? type.GetFields().ToList().Where(m =>
                {
                    OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)m.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();
                    return(originalNameAttribute != null && originalNameAttribute.OriginalName == serverSideName);
                }).SingleOrDefault();

                if (memberInfo == null)
                {
                    throw c.Error.InvalidOperation(c.Strings.ClientType_MissingProperty(type.ToString(), serverSideName));
                }

                memberInfoName = memberInfo.Name;
                ServerSideNameDict[serverSideName] = memberInfoName;
            }

            return(memberInfoName);
        }
Пример #16
0
        private IEnumerable <PropertyInfo> GetAllProperties()
        {
            List <PropertyInfo> properties = new List <PropertyInfo>();

            _hasProperties = false;
            Dictionary <string, PropertyInfo> propertyInfoDict = new Dictionary <string, PropertyInfo>();

            foreach (PropertyInfo propertyInfo in type.GetPublicProperties(true /*instanceOnly*/, false))
            {
                //// examples where class<PropertyType>

                //// the normal examples
                //// PropertyType Property { get; set }
                //// Nullable<PropertyType> Property { get; set; }

                //// if 'Property: struct' then we would be unable set the property during construction (and have them stick)
                //// but when its a class, we can navigate if non-null and set the nested properties
                //// PropertyType Property { get; } where PropertyType: class

                //// we do support adding elements to collections
                //// ICollection<PropertyType> { get; /*ignored set;*/ }

                //// indexed properties are not supporter because
                //// we don't have anything to use as the index
                //// PropertyType Property[object x] { /*ignored get;*/ /*ignored set;*/ }

                //// also ignored
                //// if PropertyType.IsPointer (like byte*)
                //// if PropertyType.IsArray except for byte[] and char[]
                //// if PropertyType == IntPtr or UIntPtr

                //// Properties overriding abstract or virtual properties on a base type
                //// are also ignored (because they are part of the base type declaration
                //// and not of the derived type).

                OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)propertyInfo.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();
                string serverDefinedName = originalNameAttribute != null ? originalNameAttribute.OriginalName : propertyInfo.Name;

                propertyInfoDict[serverDefinedName] = propertyInfo;

                Type propertyType = propertyInfo.PropertyType; // class / interface / value
                propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType;

                if (propertyType.IsPointer ||
                    (propertyType.IsArray && (typeof(byte[]) != propertyType) && typeof(char[]) != propertyType) ||
                    (typeof(IntPtr) == propertyType) ||
                    (typeof(UIntPtr) == propertyType))
                {
                    continue;
                }

                Debug.Assert(!propertyType.ContainsGenericParameters(), "remove when test case is found that encounters this");

                if (propertyInfo.CanRead &&
                    (!propertyType.IsValueType() || propertyInfo.CanWrite) &&
                    !propertyType.ContainsGenericParameters() &&
                    propertyInfo.GetIndexParameters().Length == 0)
                {
                    properties.Add(propertyInfo);
                    _hasProperties = true;
                }
            }

            _propertyInfoDict = propertyInfoDict;

            return(properties);
        }
Пример #17
0
        /// <summary>
        /// Gets the type name (without namespace) of the specified <paramref name="type"/>,
        /// appropriate as an externally-visible type name.
        /// </summary>
        /// <param name="type">Type to get name for.</param>
        /// <returns>The type name for <paramref name="type"/>.</returns>
        internal static string GetModelTypeName(Type type)
        {
            Debug.Assert(type != null, "type != null");

            string typeName;
            OriginalNameAttribute originalNameAttribute = (OriginalNameAttribute)type.GetCustomAttributes(typeof(OriginalNameAttribute), false).SingleOrDefault();

            if (originalNameAttribute != null)
            {
                typeName = originalNameAttribute.OriginalName;
            }
            else
            {
                typeName = type.Name;
            }

#if ODATA_CLIENT
            if (type.IsGenericType())
#else
            if (type.IsGenericType)
#endif
            {
                Type[]        genericArguments = type.GetGenericArguments();
                StringBuilder builder          = new StringBuilder(typeName.Length * 2 * (1 + genericArguments.Length));
                if (type.IsNested)
                {
                    Debug.Assert(type.DeclaringType != null, "type.DeclaringType != null");
                    builder.Append(GetModelTypeName(type.DeclaringType));
                    builder.Append('_');
                }

                builder.Append(typeName);
                builder.Append('[');
                for (int i = 0; i < genericArguments.Length; i++)
                {
                    if (i > 0)
                    {
                        builder.Append(' ');
                    }

                    if (genericArguments[i].IsGenericParameter)
                    {
                        builder.Append(genericArguments[i].Name);
                    }
                    else
                    {
                        string genericNamespace = GetModelTypeNamespace(genericArguments[i]);
                        if (!String.IsNullOrEmpty(genericNamespace))
                        {
                            builder.Append(genericNamespace);
                            builder.Append('.');
                        }

                        builder.Append(GetModelTypeName(genericArguments[i]));
                    }
                }

                builder.Append(']');
                return(builder.ToString());
            }
            else if (type.IsNested)
            {
                Debug.Assert(type.DeclaringType != null, "type.DeclaringType != null");
                return(GetModelTypeName(type.DeclaringType) + "_" + typeName);
            }
            else
            {
                return(typeName);
            }
        }