Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataQueryOptions"/> class based on the incoming request and some metadata information from
        /// the <see cref="ODataQueryContext"/>.
        /// </summary>
        /// <param name="context">The <see cref="ODataQueryContext"/> which contains the <see cref="IEdmModel"/> and some type information.</param>
        /// <param name="request">The incoming request message.</param>
        /// <param name="assembliesResolver"></param>
        public ODataQueryOptions(ODataQueryContext context, HttpRequest request, AssembliesResolver assembliesResolver)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            _assembliesResolver = assembliesResolver;

            Context   = context;
            Request   = request;
            RawValues = new ODataRawQueryOptions();

            var queryOptionDict = request.Query.ToDictionary(p => p.Key, p => p.Value.FirstOrDefault());

            _queryOptionParser = new ODataQueryOptionParser(
                context.Model,
                context.ElementType,
                context.NavigationSource,
                queryOptionDict);

            BuildQueryOptions(queryOptionDict);
        }
Ejemplo n.º 2
0
        ///// <summary>
        ///// Applies the $select and $expand query options to the given entity using the given <see cref="ODataQuerySettings"/>.
        ///// </summary>
        ///// <param name="entity">The original entity.</param>
        ///// <param name="settings">The <see cref="ODataQuerySettings"/> that contains all the query application related settings.</param>
        ///// <returns>The new entity after the $select and $expand query has been applied to.</returns>
        //public object ApplyTo(object entity, ODataQuerySettings settings, string AssembliesResolver)
        //{
        //    return ApplyTo(entity, settings, AssembliesResolver);
        //}

        /// <summary>
        /// Applies the $select and $expand query options to the given entity using the given <see cref="ODataQuerySettings"/>.
        /// </summary>
        /// <param name="entity">The original entity.</param>
        /// <param name="settings">The <see cref="ODataQuerySettings"/> that contains all the query application related settings.</param>
        /// <param name="assembliesResolver">The name of the assembly to use.</param>
        /// <returns>The new entity after the $select and $expand query has been applied to.</returns>
        public object ApplyTo(object entity, ODataQuerySettings settings, AssembliesResolver assembliesResolver)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }
            if (settings == null)
            {
                throw Error.ArgumentNull("settings");
            }
            if (Context.ElementClrType == null)
            {
                throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo");
            }

            // Ensure we have decided how to handle null propagation
            ODataQuerySettings updatedSettings = settings;

            if (settings.HandleNullPropagation == HandleNullPropagationOption.Default)
            {
                updatedSettings = new ODataQuerySettings(updatedSettings);
                updatedSettings.HandleNullPropagation = HandleNullPropagationOption.True;
            }

            return(SelectExpandBinder.Bind(entity, updatedSettings, assembliesResolver, this));
        }
Ejemplo n.º 3
0
        //public static Type GetClrType(IEdmTypeReference edmTypeReference, IEdmModel edmModel, string assembliesResolver)
        //{
        //    return GetClrType(edmTypeReference, edmModel, assembliesResolver);
        //}

        public static Type GetClrType(IEdmTypeReference edmTypeReference, IEdmModel edmModel,
                                      AssembliesResolver assembliesResolver)
        {
            if (edmTypeReference == null)
            {
                throw Error.ArgumentNull("edmTypeReference");
            }

            Type primitiveClrType = _builtInTypesMapping
                                    .Where(
                kvp =>
                edmTypeReference.Definition.IsEquivalentTo(kvp.Value) &&
                (!edmTypeReference.IsNullable || IsNullable(kvp.Key)))
                                    .Select(kvp => kvp.Key)
                                    .FirstOrDefault();

            if (primitiveClrType != null)
            {
                return(primitiveClrType);
            }
            else
            {
                return(GetClrType(edmTypeReference.Definition, edmModel, assembliesResolver));
            }
        }
Ejemplo n.º 4
0
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource,
            ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext, AssembliesResolver assembliesResolver)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            bool isDynamicProperty = false;
            string propertyName = property.Name;
            if (edmProperty != null)
            {
                propertyName = EdmLibHelpers.GetClrPropertyName(edmProperty, readContext.Model);
            }
            else
            {
                IEdmStructuredType structuredType = resourceType.StructuredDefinition();
                isDynamicProperty = structuredType != null && structuredType.IsOpen;
            }

            // dynamic properties have null values
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null;

            EdmTypeKind propertyKind;
            object value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext,
                out propertyKind);

            if (isDynamicProperty)
            {
                SetDynamicProperty(resource, resourceType, propertyKind, propertyName, value, propertyType,
                    readContext, assembliesResolver);
            }
            else
            {
                SetDeclaredProperty(resource, propertyKind, propertyName, value, edmProperty, readContext, assembliesResolver);
            }
        }
        public static void AddToCollection(this IEnumerable items, IEnumerable collection, Type elementType,
            Type resourceType, string propertyName, Type propertyType, AssembliesResolver assembliesResolver)
        {
            Contract.Assert(items != null);
            Contract.Assert(collection != null);
            Contract.Assert(elementType != null);
            Contract.Assert(resourceType != null);
            Contract.Assert(propertyName != null);
            Contract.Assert(propertyType != null);

            MethodInfo addMethod = null;
            IList list = collection as IList;

            if (list == null)
            {
                addMethod = collection.GetType().GetMethod("Add", new Type[] { elementType });
                if (addMethod == null)
                {
                    string message = Error.Format(SRResources.CollectionShouldHaveAddMethod, propertyType.FullName, propertyName, resourceType.FullName);
                    throw new SerializationException(message);
                }
            }
            else if (list.GetType().IsArray)
            {
                string message = Error.Format(SRResources.GetOnlyCollectionCannotBeArray, propertyName, resourceType.FullName);
                throw new SerializationException(message);
            }

            items.AddToCollectionCore(collection, elementType, list, addMethod, assembliesResolver);
        }
        /// <summary>
        /// Registers the Web API <see cref="IHttpController"/> types that available for the application. This
        /// method uses the configured <see cref="IHttpControllerTypeResolver"/> to determine which controller
        /// types to register.
        /// </summary>
        /// <param name="container">The container the controllers should be registered in.</param>
        /// <param name="configuration">The <see cref="HttpConfiguration"/> to use to get the Controller
        /// types to register.</param>
        /// <param name="assemblies">The assemblies to search.</param>
        /// <exception cref="ArgumentNullException">Thrown when one of the arguments is a null
        /// reference (Nothing in VB).</exception>
        public static void RegisterWebApiControllers(this Container container, HttpConfiguration configuration,
                                                     IEnumerable <Assembly> assemblies)
        {
            Requires.IsNotNull(container, nameof(container));
            Requires.IsNotNull(configuration, nameof(configuration));
            Requires.IsNotNull(assemblies, nameof(assemblies));

            IAssembliesResolver assembliesResolver = new AssembliesResolver(assemblies);

            var controllerTypes = GetControllerTypesFromConfiguration(configuration, assembliesResolver);

            foreach (Type controllerType in controllerTypes)
            {
                Registration registration = Lifestyle.Transient.CreateRegistration(controllerType, container);

                if (typeof(ApiController).IsAssignableFrom(controllerType))
                {
                    // Suppress the Disposable Transient Component warning, because Web API's controller factory
                    // ensures correct disposal of controllers.
                    registration.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent,
                                                           justification:
                                                           "Web API registers controllers for disposal when the request ends during the " +
                                                           "call to ApiController.ExecuteAsync.");
                }

                container.AddRegistration(controllerType, registration);
            }
        }
        private static void AddToCollectionCore(this IEnumerable items, IEnumerable collection, Type elementType, IList list, MethodInfo addMethod, AssembliesResolver assembliesResolver)
        {
            bool isNonstandardEdmPrimitiveCollection;
            EdmLibHelpers.IsNonstandardEdmPrimitive(elementType, assembliesResolver, out isNonstandardEdmPrimitiveCollection);

            foreach (object item in items)
            {
                object element = item;

                if (isNonstandardEdmPrimitiveCollection && element != null)
                {
                    // convert non-standard edm primitives if required.
                    element = EdmPrimitiveHelpers.ConvertPrimitiveValue(element, elementType);
                }

                if (list != null)
                {
                    list.Add(element);
                }
                else
                {
                    Contract.Assert(addMethod != null);
                    addMethod.Invoke(collection, new object[] { element });
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataConventionModelBuilder"/> class.
        /// </summary>
        /// <param name="assembliesResolver">The assemblies resolve to use for type resolution</param>
        /// <param name="isQueryCompositionMode">If the model is being built for only querying.</param>
        /// <remarks>The model built if <paramref name="isQueryCompositionMode"/> is <c>true</c> has more relaxed
        /// inference rules and also treats all types as entity types. This constructor is intended for use by unit testing only.</remarks>
        public ODataConventionModelBuilder(AssembliesResolver assembliesResolver, bool isQueryCompositionMode)
        {
            if (assembliesResolver == null)
            {
                throw Error.ArgumentNull("AssembliesResolver");
            }

            Initialize(assembliesResolver, isQueryCompositionMode);
        }
Ejemplo n.º 9
0
        private Assembly[] GetAssemblies()
        {
            OnConfigureAssemblyResolution();
            var rootPath           = PlatformProvider.Current.GetAbsolutePath(ModulesPath);
            var assembliesResolver = new AssembliesResolver(
                new ServerAssemblySourceProvider(rootPath));

            return(((IAssembliesReadOnlyResolver)assembliesResolver).GetAssemblies().ToArray());
        }
Ejemplo n.º 10
0
        public static object Bind(object entity, ODataQuerySettings settings, AssembliesResolver assembliesResolver,
                                  SelectExpandQueryOption selectExpandQuery)
        {
            Contract.Assert(entity != null);

            SelectExpandBinder binder = new SelectExpandBinder(settings, assembliesResolver, selectExpandQuery);

            return(binder.Bind(entity));
        }
Ejemplo n.º 11
0
        public static IQueryable Bind(IQueryable queryable, ODataQuerySettings settings,
                                      AssembliesResolver assembliesResolver, SelectExpandQueryOption selectExpandQuery)
        {
            Contract.Assert(queryable != null);

            SelectExpandBinder binder = new SelectExpandBinder(settings, assembliesResolver, selectExpandQuery);
            var bound = binder.Bind(queryable);

            return(bound);
        }
Ejemplo n.º 12
0
 internal void Initialize(AssembliesResolver assembliesResolver, bool isQueryCompositionMode)
 {
     _isQueryCompositionMode      = isQueryCompositionMode;
     _configuredNavigationSources = new HashSet <INavigationSourceConfiguration>();
     _mappedTypes                    = new HashSet <StructuralTypeConfiguration>();
     _ignoredTypes                   = new HashSet <Type>();
     ModelAliasingEnabled            = true;
     _allTypesWithDerivedTypeMapping = new Lazy <IDictionary <Type, List <Type> > >(
         () => BuildDerivedTypesMapping(assembliesResolver),
         isThreadSafe: false);
 }
Ejemplo n.º 13
0
        public static Type GetClrType(IEdmType edmType, IEdmModel edmModel, AssembliesResolver assembliesResolver)
        {
            IEdmSchemaType edmSchemaType = edmType as IEdmSchemaType;

            Contract.Assert(edmSchemaType != null);

            string             typeName      = edmSchemaType.FullName();
            IEnumerable <Type> matchingTypes = GetMatchingTypes(typeName, assembliesResolver);

            return(matchingTypes.FirstOrDefault());
        }
        public static void AddAssembly(this HttpConfiguration httpConfiguration, Assembly assembly)
        {
            Dispatcher.IAssembliesResolver existingAssembliesResolver = GetAssembliesResolver(httpConfiguration);
            ICollection <Assembly>         existingAssemblies         = existingAssembliesResolver.GetAssemblies();

            if (!existingAssemblies.Contains(assembly))
            {
                AssembliesResolver assembliesResolver = new AssembliesResolver(existingAssemblies);
                assembliesResolver.Add(assembly);
                httpConfiguration.Services.Replace(typeof(Dispatcher.IAssembliesResolver), assembliesResolver);
            }
        }
Ejemplo n.º 15
0
        internal void TryAppendAssembly(byte[] rawAssembly)
        {
            Assembly asm;

            try
            {
                asm = Assembly.Load(rawAssembly);
                AssembliesResolver.Register(asm);
                _assemblies.Add(asm);
            }
            catch { }
        }
        /// <summary>
        /// Registers the Web API <see cref="IHttpController"/> types that available for the application. This
        /// method uses the configured <see cref="IHttpControllerTypeResolver"/> to determine which controller
        /// types to register.
        /// </summary>
        /// <param name="container">The container the controllers should be registered in.</param>
        /// <param name="configuration">The <see cref="HttpConfiguration"/> to use to get the Controller
        /// types to register.</param>
        /// <param name="assemblies">The assemblies to search.</param>
        /// <exception cref="ArgumentNullException">Thrown when one of the arguments is a null
        /// reference (Nothing in VB).</exception>
        public static void RegisterWebApiControllers(this Container container, HttpConfiguration configuration,
                                                     IEnumerable <Assembly> assemblies)
        {
            Requires.IsNotNull(container, "container");
            Requires.IsNotNull(configuration, "configuration");
            Requires.IsNotNull(assemblies, "assemblies");

            IAssembliesResolver assembliesResolver = new AssembliesResolver(assemblies);

            var controllerTypes = GetControllerTypesFromConfiguration(configuration, assembliesResolver);

            controllerTypes.ForEach(type => container.Register(type, type));
        }
Ejemplo n.º 17
0
        //public static IRouteBuilder MapODataRoute<T>(this IRouteBuilder builder, string prefix) where T : class
        //{
        //    builder.Routes.Add(new ODataRoute(prefix, DefaultODataModelProvider.BuildEdmModel(typeof(T))));
        //    return builder;
        //}

        public static IServiceCollection AddOData <T>([NotNull] this IServiceCollection services,
                                                      Action <ODataConventionModelBuilder> after = null)
            where T : class
        {
            services.AddOData();
            var type          = typeof(T);
            var assemblyNames = new AssembliesResolver(type.GetTypeInfo().Assembly);
            var model         = DefaultODataModelProvider.BuildEdmModel(type, assemblyNames, after);

            services.AddSingleton(model);
            services.AddSingleton(assemblyNames);
            return(services);
        }
Ejemplo n.º 18
0
 internal static void SetDynamicProperty(object resource, IEdmStructuredTypeReference resourceType,
     EdmTypeKind propertyKind, string propertyName, object propertyValue, IEdmTypeReference propertyType,
     ODataDeserializerContext readContext, AssembliesResolver assembliesResolver)
 {  
     if (propertyKind == EdmTypeKind.Collection && propertyValue.GetType() != typeof(EdmComplexObjectCollection)
         && propertyValue.GetType() != typeof(EdmEnumObjectCollection))
     {
         SetDynamicCollectionProperty(resource, propertyName, propertyValue, propertyType.AsCollection(),
             resourceType.StructuredDefinition(), readContext, assembliesResolver);
     }
     else
     {
         SetDynamicProperty(resource, propertyName, propertyValue, resourceType.StructuredDefinition(),
             readContext);
     }
 }
Ejemplo n.º 19
0
        // figures out if the given clr type is nonstandard edm primitive like uint, ushort, char[] etc.
        // and returns the corresponding clr type to which we map like uint => long.
        public static Type IsNonstandardEdmPrimitive(Type type, out bool isNonstandardEdmPrimitive,
                                                     AssembliesResolver assembliesResolver)
        {
            IEdmPrimitiveTypeReference edmType = GetEdmPrimitiveTypeReferenceOrNull(type);

            if (edmType == null)
            {
                isNonstandardEdmPrimitive = false;
                return(type);
            }

            Type reverseLookupClrType = GetClrType(edmType, EdmCoreModel.Instance, assembliesResolver);

            isNonstandardEdmPrimitive = (type != reverseLookupClrType);

            return(reverseLookupClrType);
        }
Ejemplo n.º 20
0
        public SelectExpandBinder(ODataQuerySettings settings, AssembliesResolver assembliesResolver,
                                  SelectExpandQueryOption selectExpandQuery)
        {
            Contract.Assert(settings != null);
            Contract.Assert(assembliesResolver != null);
            Contract.Assert(selectExpandQuery != null);
            Contract.Assert(selectExpandQuery.Context != null);
            Contract.Assert(selectExpandQuery.Context.Model != null);
            Contract.Assert(settings.HandleNullPropagation != HandleNullPropagationOption.Default);

            _selectExpandQuery  = selectExpandQuery;
            _context            = selectExpandQuery.Context;
            _model              = _context.Model;
            _modelID            = ModelContainer.GetModelID(_model);
            _settings           = settings;
            _assembliesResolver = assembliesResolver;
        }
Ejemplo n.º 21
0
        private static Dictionary <Type, List <Type> > BuildDerivedTypesMapping(AssembliesResolver assembliesResolver)
        {
            IEnumerable <Type> allTypes =
                //DefaultAssemblyPartDiscoveryProvider.
                TypeHelper.GetLoadedTypes(assembliesResolver).Where(t => t.GetTypeInfo().IsVisible&& t.GetTypeInfo().IsClass&& t != typeof(object));
            Dictionary <Type, List <Type> > allTypeMapping = allTypes.ToDictionary(k => k, k => new List <Type>());

            foreach (Type type in allTypes)
            {
                List <Type> derivedTypes;
                if (type.GetTypeInfo().BaseType != null && allTypeMapping.TryGetValue(type.GetTypeInfo().BaseType, out derivedTypes))
                {
                    derivedTypes.Add(type);
                }
            }

            return(allTypeMapping);
        }
Ejemplo n.º 22
0
        internal static void SetDeclaredProperty(object resource, EdmTypeKind propertyKind, string propertyName,
            object propertyValue, IEdmProperty edmProperty, ODataDeserializerContext readContext, AssembliesResolver assembliesResolver)
        {
            if (propertyKind == EdmTypeKind.Collection)
            {
                SetCollectionProperty(resource, edmProperty, propertyValue, propertyName, assembliesResolver);
            }
            else
            {
                if (!readContext.IsUntyped)
                {
                    if (propertyKind == EdmTypeKind.Primitive)
                    {
                        propertyValue = EdmPrimitiveHelpers.ConvertPrimitiveValue(propertyValue,
                            GetPropertyType(resource, propertyName));
                    }
                }

                SetProperty(resource, propertyName, propertyValue);
            }
        }
Ejemplo n.º 23
0
		// TODO: Move this into AssembliesResolver and cache results
		internal static IEnumerable<Type> GetLoadedTypes(AssembliesResolver assembliesResolver)
		{
			var result = new List<Type>();
			foreach (var assembly in assembliesResolver.Assemblies)
			{
				// Go through all assemblies referenced by the application and search for types matching a predicate
				var assemblyParts =
					DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(assembly.FullName)
						.Select(s => (s as AssemblyPart).Assembly);
				foreach (var assemblyPart in assemblyParts)
				{
					Type[] exportedTypes = null;
					if (assemblyPart == null || assemblyPart.IsDynamic)
					{
						// can't call GetTypes on a null (or dynamic?) assembly
						continue;
					}

					try
					{
						exportedTypes = assemblyPart.GetTypes();
					}
					catch (ReflectionTypeLoadException ex)
					{
						exportedTypes = ex.Types;
					}
					catch
					{
						continue;
					}

					if (exportedTypes != null)
					{
						result.AddRange(exportedTypes.Where(t => t != null && t.GetTypeInfo().IsVisible));
					}
				}

			}
			return result;
		}
Ejemplo n.º 24
0
        // TODO: Move this into AssembliesResolver and cache results
        internal static IEnumerable <Type> GetLoadedTypes(AssembliesResolver assembliesResolver)
        {
            var result = new List <Type>();

            foreach (var assembly in assembliesResolver.Assemblies)
            {
                // Go through all assemblies referenced by the application and search for types matching a predicate
                var assemblyParts =
                    DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(assembly.FullName)
                    .Select(s => (s as AssemblyPart).Assembly);
                foreach (var assemblyPart in assemblyParts)
                {
                    Type[] exportedTypes = null;
                    if (assemblyPart == null || assemblyPart.IsDynamic)
                    {
                        // can't call GetTypes on a null (or dynamic?) assembly
                        continue;
                    }

                    try
                    {
                        exportedTypes = assemblyPart.GetTypes();
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        exportedTypes = ex.Types;
                    }
                    catch
                    {
                        continue;
                    }

                    if (exportedTypes != null)
                    {
                        result.AddRange(exportedTypes.Where(t => t != null && t.GetTypeInfo().IsVisible));
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// Registers the Web API <see cref="IHttpController"/> types that available for the application. This
        /// method uses the configured <see cref="IHttpControllerTypeResolver"/> to determine which controller
        /// types to register.
        /// </summary>
        /// <param name="container">The container the controllers should be registered in.</param>
        /// <param name="configuration">The <see cref="HttpConfiguration"/> to use to get the Controller
        /// types to register.</param>
        /// <param name="assemblies">The assemblies to search.</param>
        /// <exception cref="ArgumentNullException">Thrown when one of the arguments is a null
        /// reference (Nothing in VB).</exception>
        public static void RegisterWebApiControllers(this Container container, HttpConfiguration configuration,
                                                     IEnumerable <Assembly> assemblies)
        {
            Requires.IsNotNull(container, "container");
            Requires.IsNotNull(configuration, "configuration");
            Requires.IsNotNull(assemblies, "assemblies");

            IAssembliesResolver assembliesResolver = new AssembliesResolver(assemblies);

            var controllerTypes = GetControllerTypesFromConfiguration(configuration, assembliesResolver);

            foreach (Type controllerType in controllerTypes)
            {
                Registration registration = Lifestyle.Transient.CreateRegistration(controllerType, container);

                // Suppress the Disposable Transient Component warning, because MVC's controller factory
                // ensures correct disposal of controllers.
                registration.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent);

                container.AddRegistration(controllerType, registration);
            }
        }
        public static void AddToCollection(this IEnumerable items, IEnumerable collection, Type elementType, string paramName, Type paramType, AssembliesResolver assembliesResolver)
        {
            Contract.Assert(items != null);
            Contract.Assert(collection != null);
            Contract.Assert(elementType != null);
            Contract.Assert(paramType != null);

            MethodInfo addMethod = null;
            IList list = collection as IList;

            if (list == null)
            {
                addMethod = collection.GetType().GetMethod("Add", new Type[] { elementType });
                if (addMethod == null)
                {
                    string message = Error.Format(SRResources.CollectionParameterShouldHaveAddMethod, paramType, paramName);
                    throw new SerializationException(message);
                }
            }

            items.AddToCollectionCore(collection, elementType, list, addMethod, assembliesResolver);
        }
Ejemplo n.º 27
0
        public static void RegisterWebApiControllers(this IContainer container, HttpConfiguration configuration)
        {
            var assembliesResolver = configuration.Services.GetAssembliesResolver();

            if (assembliesResolver == null)
            {
                throw new InvalidOperationException("Could not find AssembliesResolver");
            }

            var typeResolver = configuration.Services.GetHttpControllerTypeResolver();

            var apiControllerType = typeof(ApiController);

            var assemblies = assembliesResolver.GetAssemblies();
            var cachedAssembliesResolver = new AssembliesResolver(assemblies.ToList());

            var apiControllerTypes = typeResolver.GetControllerTypes(cachedAssembliesResolver).Select(t => t);

            foreach (var type in apiControllerTypes)
            {
                container.Register(type, type);
            }
        }
Ejemplo n.º 28
0
        ///// <summary>
        ///// Applies the $select and $expand query options to the given entity using the given <see cref="ODataQuerySettings"/>.
        ///// </summary>
        ///// <param name="entity">The original entity.</param>
        ///// <param name="settings">The <see cref="ODataQuerySettings"/> that contains all the query application related settings.</param>
        ///// <returns>The new entity after the $select and $expand query has been applied to.</returns>
        //public object ApplyTo(object entity, ODataQuerySettings settings, string AssembliesResolver)
        //{
        //    return ApplyTo(entity, settings, AssembliesResolver);
        //}
        /// <summary>
        /// Applies the $select and $expand query options to the given entity using the given <see cref="ODataQuerySettings"/>.
        /// </summary>
        /// <param name="entity">The original entity.</param>
        /// <param name="settings">The <see cref="ODataQuerySettings"/> that contains all the query application related settings.</param>
        /// <param name="assembliesResolver">The name of the assembly to use.</param>
        /// <returns>The new entity after the $select and $expand query has been applied to.</returns>
        public object ApplyTo(object entity, ODataQuerySettings settings, AssembliesResolver assembliesResolver)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }
            if (settings == null)
            {
                throw Error.ArgumentNull("settings");
            }
            if (Context.ElementClrType == null)
            {
                throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo");
            }

            // Ensure we have decided how to handle null propagation
            ODataQuerySettings updatedSettings = settings;
            if (settings.HandleNullPropagation == HandleNullPropagationOption.Default)
            {
                updatedSettings = new ODataQuerySettings(updatedSettings);
                updatedSettings.HandleNullPropagation = HandleNullPropagationOption.True;
            }

            return SelectExpandBinder.Bind(entity, updatedSettings, assembliesResolver, this);
        }
Ejemplo n.º 29
0
        internal static void SetDynamicCollectionProperty(object resource, string propertyName, object value,
            IEdmCollectionTypeReference edmPropertyType, IEdmStructuredType structuredType,
            ODataDeserializerContext readContext, AssembliesResolver assembliesResolver)
        {
            Contract.Assert(value != null);
            Contract.Assert(readContext != null);
            Contract.Assert(readContext.Model != null);

            IEnumerable collection = value as IEnumerable;
            Contract.Assert(collection != null);

            Type resourceType = resource.GetType();
            Type elementType = EdmLibHelpers.GetClrType(edmPropertyType.ElementType(), readContext.Model, assembliesResolver);
            Type propertyType = typeof(ICollection<>).MakeGenericType(elementType);
            IEnumerable newCollection;
            if (CollectionDeserializationHelpers.TryCreateInstance(propertyType, edmPropertyType, elementType,
                out newCollection))
            {
                collection.AddToCollection(newCollection, elementType, resourceType, propertyName, propertyType, assembliesResolver);
                SetDynamicProperty(resource, propertyName, newCollection, structuredType, readContext);
            }
        }
Ejemplo n.º 30
0
        internal static void SetCollectionProperty(object resource, string propertyName,
            IEdmCollectionTypeReference edmPropertyType, object value, bool clearCollection, AssembliesResolver assembliesResolver)
        {
            if (value != null)
            {
                IEnumerable collection = value as IEnumerable;
                Contract.Assert(collection != null,
                    "SetCollectionProperty is always passed the result of ODataFeedDeserializer or ODataCollectionDeserializer");

                Type resourceType = resource.GetType();
                Type propertyType = GetPropertyType(resource, propertyName);

                Type elementType;
                if (!propertyType.IsCollection(out elementType))
                {
                    string message = Error.Format(SRResources.PropertyIsNotCollection, propertyType.FullName, propertyName, resourceType.FullName);
                    throw new SerializationException(message);
                }

                IEnumerable newCollection;
                if (CanSetProperty(resource, propertyName) &&
                    CollectionDeserializationHelpers.TryCreateInstance(propertyType, edmPropertyType, elementType, out newCollection))
                {
                    // settable collections
                    collection.AddToCollection(newCollection, elementType, resourceType, propertyName, propertyType, assembliesResolver);
                    if (propertyType.IsArray)
                    {
                        newCollection = CollectionDeserializationHelpers.ToArray(newCollection, elementType);
                    }

                    SetProperty(resource, propertyName, newCollection);
                }
                else
                {
                    // get-only collections.
                    newCollection = GetProperty(resource, propertyName) as IEnumerable;
                    if (newCollection == null)
                    {
                        string message = Error.Format(SRResources.CannotAddToNullCollection, propertyName, resourceType.FullName);
                        throw new SerializationException(message);
                    }

                    if (clearCollection)
                    {
                        newCollection.Clear(propertyName, resourceType);
                    }

                    collection.AddToCollection(newCollection, elementType, resourceType, propertyName, propertyType, assembliesResolver);
                }
            }
        }
        private static void AddToCollectionCore(this IEnumerable items, IEnumerable collection, Type elementType, IList list, MethodInfo addMethod, AssembliesResolver assembliesResolver)
        {
            bool isNonstandardEdmPrimitiveCollection;

            EdmLibHelpers.IsNonstandardEdmPrimitive(elementType, assembliesResolver, out isNonstandardEdmPrimitiveCollection);

            foreach (object item in items)
            {
                object element = item;

                if (isNonstandardEdmPrimitiveCollection && element != null)
                {
                    // convert non-standard edm primitives if required.
                    element = EdmPrimitiveHelpers.ConvertPrimitiveValue(element, elementType);
                }

                if (list != null)
                {
                    list.Add(element);
                }
                else
                {
                    Contract.Assert(addMethod != null);
                    addMethod.Invoke(collection, new object[] { element });
                }
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Apply the filter query to the given IQueryable.
        /// </summary>
        /// <remarks>
        /// The <see cref="ODataQuerySettings.HandleNullPropagation"/> property specifies
        /// how this method should handle null propagation.
        /// </remarks>
        /// <param name="query">The original <see cref="IQueryable"/>.</param>
        /// <param name="querySettings">The <see cref="ODataQuerySettings"/> that contains all the query application related settings.</param>
        /// <param name="assembliesResolver">The assembly to use.</param>
        /// <returns>The new <see cref="IQueryable"/> after the filter query has been applied to.</returns>
        public IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings, AssembliesResolver assembliesResolver)
        {
            if (query == null)
            {
                throw Error.ArgumentNull("query");
            }

            if (assembliesResolver == null)
            {
                throw Error.ArgumentNull("AssembliesResolver");
            }

            if (Context.ElementClrType == null)
            {
                throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo");
            }

            var filter = FilterBinder.Bind(FilterClause, Context.ElementClrType, Context.Model, assembliesResolver, querySettings);

            return(ExpressionHelpers.Where(query, filter, Context.ElementClrType));
        }
Ejemplo n.º 33
0
        internal static void SetCollectionProperty(object resource, IEdmProperty edmProperty, object value, string propertyName, AssembliesResolver assembliesResolver)
        {
            Contract.Assert(edmProperty != null);

            SetCollectionProperty(resource, propertyName, edmProperty.Type.AsCollection(), value, false, assembliesResolver);
        }
Ejemplo n.º 34
0
        internal static void SetCollectionProperty(object resource, IEdmProperty edmProperty, object value, string propertyName, AssembliesResolver assembliesResolver)
        {
            Contract.Assert(edmProperty != null);

            SetCollectionProperty(resource, propertyName, edmProperty.Type.AsCollection(), value, false, assembliesResolver);
        }
Ejemplo n.º 35
0
        //    /// <summary>
        //    /// Initializes a new instance of the <see cref="ODataConventionModelBuilder"/> class.
        //    /// </summary>
        //    public ODataConventionModelBuilder(string assembliesResolver)
        //    {
        //        Initialize(
        //assembliesResolver,
        //isQueryCompositionMode: false
        //);
        //    }

        /// <summary>
        /// Initializes a new <see cref="ODataConventionModelBuilder"/>.
        /// </summary>
        public ODataConventionModelBuilder(AssembliesResolver assembliesResolver)
            : this(assembliesResolver, isQueryCompositionMode : false)
        {
        }
Ejemplo n.º 36
0
 public static Type IsNonstandardEdmPrimitive(Type type, AssembliesResolver assembliesResolver, out bool isNonstandardEdmPrimitive)
 {
     return(IsNonstandardEdmPrimitive(type, out isNonstandardEdmPrimitive, assembliesResolver));
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Apply the filter query to the given IQueryable.
        /// </summary>
        /// <remarks>
        /// The <see cref="ODataQuerySettings.HandleNullPropagation"/> property specifies
        /// how this method should handle null propagation.
        /// </remarks>
        /// <param name="query">The original <see cref="IQueryable"/>.</param>
        /// <param name="querySettings">The <see cref="ODataQuerySettings"/> that contains all the query application related settings.</param>
        /// <param name="assembliesResolver">The assembly to use.</param>
        /// <returns>The new <see cref="IQueryable"/> after the filter query has been applied to.</returns>
        public IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings, AssembliesResolver assembliesResolver)
        {
            if (query == null)
            {
                throw Error.ArgumentNull("query");
            }

            if (assembliesResolver == null)
            {
                throw Error.ArgumentNull("AssembliesResolver");
            }

            if (Context.ElementClrType == null)
            {
                throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo");
            }

            var filter = FilterBinder.Bind(FilterClause, Context.ElementClrType, Context.Model, assembliesResolver, querySettings);
            return ExpressionHelpers.Where(query, filter, Context.ElementClrType);
        }
Ejemplo n.º 38
0
        static void Main(string[] args)
        {
            Karyon.EurekaIntegration.ApplicationLifecycleController netflixoss = null;
            HttpSelfHostServer server = null;
            bool registered           = false;

            System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener(true));

            try
            {
                //register application at Eureka service.
                netflixoss = Karyon.EurekaIntegration.ApplicationLifecycleController.CreateInstance();
                registered = netflixoss.RegisterApplicationInstance();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.ToString());
            }

            if (!registered)
            {
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
                if (netflixoss != null)
                {
                    netflixoss.Dispose();
                }
                return;
            }

            try
            {
                Console.WriteLine("Configuring instance services...");
                string listenToPath = string.Format("http://{0}:{1}",
                                                    (netflixoss.AppConfig.ListenToPublic ? netflixoss.DataCenterMetadata.PublicIPv4 : netflixoss.DataCenterMetadata.LocalIPv4),
                                                    netflixoss.AppConfig.ApplicationPort.ToString());
                HttpSelfHostConfiguration config           = new HttpSelfHostConfiguration(listenToPath);
                AssembliesResolver        assemblyResolver = new AssembliesResolver();
                config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);
                config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
                config.Routes.MapHttpRoute("API Default", "api/{controller}");
                //add Karyon.NET healthcheck API endpoint as "<root>/healthcheck"
                config.Routes.MapHttpRoute("Healthcheck", "healthcheck", defaults: new { controller = "Healthcheck" });

                server = new HttpSelfHostServer(config);
                server.OpenAsync().Wait();
                Console.WriteLine("");
                Console.WriteLine("Listening to " + config.BaseAddress.ToString() + "; Press Enter to quit.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.ToString());
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    server.CloseAsync();
                }
                try
                {
                    if (netflixoss != null)
                    {
                        netflixoss.UnregisterApplicationInstance();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: " + ex.Message);
                }
                finally
                {
                    if (netflixoss != null)
                    {
                        netflixoss.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 39
0
        // OData formatter requires the type name of the entity that is being written if the type has derived types.
        // Expression
        //      source is GrandChild ? "GrandChild" : ( source is Child ? "Child" : "Root" )
        // Notice that the order is important here. The most derived type must be the first to check.
        // If entity framework had a way to figure out the type name without selecting the whole object, we don't have to do this magic.
        internal static Expression CreateTypeNameExpression(Expression source, IEdmEntityType elementType, IEdmModel model, AssembliesResolver assembliesResolver)
        {
            IReadOnlyList <IEdmEntityType> derivedTypes = GetAllDerivedTypes(elementType, model);

            if (derivedTypes.Count == 0)
            {
                // no inheritance.
                return(null);
            }
            else
            {
                Expression expression = Expression.Constant(elementType.FullName());
                for (int i = 0; i < derivedTypes.Count; i++)
                {
                    Type clrType = EdmLibHelpers.GetClrType(derivedTypes[i], model, assembliesResolver);
                    if (clrType == null)
                    {
                        throw new ODataException(Error.Format(SRResources.MappingDoesNotContainEntityType, derivedTypes[0].FullName()));
                    }

                    expression = Expression.Condition(
                        test: Expression.TypeIs(source, clrType),
                        ifTrue: Expression.Constant(derivedTypes[i].FullName()),
                        ifFalse: expression);
                }

                return(expression);
            }
        }
Ejemplo n.º 40
0
 private static IEnumerable<Type> GetMatchingTypes(string edmFullName, AssembliesResolver assembliesResolver)
 {
     return
         TypeHelper.GetLoadedTypes(assembliesResolver)
             .Where(t => t.GetTypeInfo().IsPublic && t.EdmFullName() == edmFullName);
 }
Ejemplo n.º 41
0
 private static IEnumerable <Type> GetMatchingTypes(string edmFullName, AssembliesResolver assembliesResolver)
 {
     return
         (TypeHelper.GetLoadedTypes(assembliesResolver)
          .Where(t => t.GetTypeInfo().IsPublic&& t.EdmFullName() == edmFullName));
 }
Ejemplo n.º 42
0
        // figures out if the given clr type is nonstandard edm primitive like uint, ushort, char[] etc.
        // and returns the corresponding clr type to which we map like uint => long.
        public static Type IsNonstandardEdmPrimitive(Type type, out bool isNonstandardEdmPrimitive,
			AssembliesResolver assembliesResolver)
        {
            IEdmPrimitiveTypeReference edmType = GetEdmPrimitiveTypeReferenceOrNull(type);
            if (edmType == null)
            {
                isNonstandardEdmPrimitive = false;
                return type;
            }

            Type reverseLookupClrType = GetClrType(edmType, EdmCoreModel.Instance, assembliesResolver);
            isNonstandardEdmPrimitive = (type != reverseLookupClrType);

            return reverseLookupClrType;
        }
        public static void AddToCollection(this IEnumerable items, IEnumerable collection, Type elementType,
                                           Type resourceType, string propertyName, Type propertyType, AssembliesResolver assembliesResolver)
        {
            Contract.Assert(items != null);
            Contract.Assert(collection != null);
            Contract.Assert(elementType != null);
            Contract.Assert(resourceType != null);
            Contract.Assert(propertyName != null);
            Contract.Assert(propertyType != null);

            MethodInfo addMethod = null;
            IList      list      = collection as IList;

            if (list == null)
            {
                addMethod = collection.GetType().GetMethod("Add", new Type[] { elementType });
                if (addMethod == null)
                {
                    string message = Error.Format(SRResources.CollectionShouldHaveAddMethod, propertyType.FullName, propertyName, resourceType.FullName);
                    throw new SerializationException(message);
                }
            }
            else if (list.GetType().IsArray)
            {
                string message = Error.Format(SRResources.GetOnlyCollectionCannotBeArray, propertyName, resourceType.FullName);
                throw new SerializationException(message);
            }

            items.AddToCollectionCore(collection, elementType, list, addMethod, assembliesResolver);
        }
Ejemplo n.º 44
0
 public static Type IsNonstandardEdmPrimitive(Type type, AssembliesResolver assembliesResolver, out bool isNonstandardEdmPrimitive)
 {
     return IsNonstandardEdmPrimitive(type, out isNonstandardEdmPrimitive, assembliesResolver);
 }
        public static void AddToCollection(this IEnumerable items, IEnumerable collection, Type elementType, string paramName, Type paramType, AssembliesResolver assembliesResolver)
        {
            Contract.Assert(items != null);
            Contract.Assert(collection != null);
            Contract.Assert(elementType != null);
            Contract.Assert(paramType != null);

            MethodInfo addMethod = null;
            IList      list      = collection as IList;

            if (list == null)
            {
                addMethod = collection.GetType().GetMethod("Add", new Type[] { elementType });
                if (addMethod == null)
                {
                    string message = Error.Format(SRResources.CollectionParameterShouldHaveAddMethod, paramType, paramName);
                    throw new SerializationException(message);
                }
            }

            items.AddToCollectionCore(collection, elementType, list, addMethod, assembliesResolver);
        }
Ejemplo n.º 46
0
		public static Type GetClrType(IEdmType edmType, IEdmModel edmModel, AssembliesResolver assembliesResolver)
        {
            IEdmSchemaType edmSchemaType = edmType as IEdmSchemaType;

            Contract.Assert(edmSchemaType != null);

            string typeName = edmSchemaType.FullName();
            IEnumerable<Type> matchingTypes = GetMatchingTypes(typeName, assembliesResolver);

			return matchingTypes.FirstOrDefault();
        }
Ejemplo n.º 47
0
        //public static Type GetClrType(IEdmTypeReference edmTypeReference, IEdmModel edmModel, string assembliesResolver)
        //{
        //    return GetClrType(edmTypeReference, edmModel, assembliesResolver);
        //}

        public static Type GetClrType(IEdmTypeReference edmTypeReference, IEdmModel edmModel,
            AssembliesResolver assembliesResolver)
        {
            if (edmTypeReference == null)
            {
                throw Error.ArgumentNull("edmTypeReference");
            }

            Type primitiveClrType = _builtInTypesMapping
                .Where(
                    kvp =>
                        edmTypeReference.Definition.IsEquivalentTo(kvp.Value) &&
                        (!edmTypeReference.IsNullable || IsNullable(kvp.Key)))
                .Select(kvp => kvp.Key)
                .FirstOrDefault();

            if (primitiveClrType != null)
            {
                return primitiveClrType;
            }
            else
            {
                return GetClrType(edmTypeReference.Definition, edmModel, assembliesResolver);
            }
        }