/// <summary> /// Returns a test instance of one of the provider OM types. /// </summary> /// <param name="type">The type to get instance of.</param> /// <returns>The </returns> public static object GetTestInstance(Type type) { if (type == typeof(ResourceType)) { ResourceProperty p = new ResourceProperty("ID", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, ResourceType.GetPrimitiveResourceType(typeof(int))) { CanReflectOnInstanceTypeProperty = false }; ResourceType resourceType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Foo", "NoBaseType", false); Assert.IsTrue(resourceType.KeyProperties.Count == 0, "It's okay not to have key properties, since we haven't set this type to readonly yet"); resourceType.AddProperty(p); return resourceType; } else if (type == typeof(ResourceProperty)) { return new ResourceProperty("NonKeyProperty", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(int))); } else if (type == typeof(ServiceOperation)) { ServiceOperationParameter parameter = new ServiceOperationParameter("o", ResourceType.GetPrimitiveResourceType(typeof(string))); ServiceOperation operation = new ServiceOperation("Dummy", ServiceOperationResultKind.Void, null, null, "POST", new ServiceOperationParameter[] { parameter }); return operation; } else if (type == typeof(ServiceOperationParameter)) { return new ServiceOperationParameter("o", ResourceType.GetPrimitiveResourceType(typeof(string))); } else if (type == typeof(ResourceSet)) { ResourceProperty p = new ResourceProperty("ID", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, ResourceType.GetPrimitiveResourceType(typeof(int))); ResourceType resourceType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Foo", "NoBaseType", false); resourceType.AddProperty(p); return new ResourceSet("Customers", resourceType); } throw new Exception(String.Format("Unexpected type encountered: '{0}'", type.FullName)); }
public override object GetValue(object value, string property) { APICallLog.Current.Push(); try { // for sub-values of a complex type inside an open property, GetValue will still be used // so we should check before calling GetOpenPropertyValue (which will throw on non-open types) DSP.ResourceType type = QueryProvider.GetResourceType(value); if (type == null || type.IsOpenType) { return(QueryProvider.GetOpenPropertyValue(value, property)); } if (type.ResourceTypeKind != ResourceTypeKind.ComplexType) { throw new DataServiceException(500, "OpenTypeMethods.GetValue used on non-open, non-complex type"); } DSP.ResourceProperty rp = type.Properties.SingleOrDefault(p => p.Name == property); if (rp == null) { throw new DataServiceException(500, "OpenTypeMethods.GetValue used on non-open type with non-existent property"); } return(QueryProvider.GetPropertyValue(value, rp)); } finally { APICallLog.Current.Pop(); } }
public void DataServiceProviderWrapperShouldFailOnMultipleActionsWithSameNameAndBindingType() { var entityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Fake.NS", "Type", false) { CanReflectOnInstanceType = false }; entityType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(int))) {CanReflectOnInstanceTypeProperty = false}); entityType.SetReadOnly(); var resourceSet = new ResourceSet("MyEntitySet", entityType); resourceSet.SetReadOnly(); ResourceType stringType = ResourceType.GetPrimitiveResourceType(typeof(string)); var duplicateAction1 = new ServiceAction("Duplicate", stringType, OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("p1", entityType), new ServiceActionParameter("p2", stringType) }, null); duplicateAction1.SetReadOnly(); var duplicateAction2 = new ServiceAction("Duplicate", ResourceType.GetPrimitiveResourceType(typeof(int)), OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("p1", entityType) }, null); duplicateAction2.SetReadOnly(); var actionProvider = new TestActionProvider { GetServiceActionsCallback = ctx => new[] { duplicateAction1, duplicateAction2 } }; var providerWrapper = CreateProviderWrapper(actionProvider, p => p.AddResourceSet(resourceSet)); Action getVisibleOperations = () => providerWrapper.GetVisibleOperations().ToList(); getVisibleOperations.ShouldThrow<DataServiceException>() .WithMessage(ErrorStrings.DataServiceActionProviderWrapper_DuplicateAction("Duplicate")) .And.StatusCode.Should().Be(500); }
public void AddResourceProperty(string propertyName, string addToResourceType, string resourcePropertyKind, string propertyType, string containerName, bool isClrProperty) { DSP.ResourceProperty newProperty = null; DSP.ResourceType resourceType = GetResourceType(addToResourceType); DSP.ResourceSet assocResourceSet = GetResourceSet(containerName); if (assocResourceSet != null) { DSP.ResourceType assocResourceType = GetResourceType(propertyType); newProperty = new DSP.ResourceProperty( propertyName, ConvertResourcePropertyKind(resourcePropertyKind), assocResourceType); } else { DSP.ResourceType assocResourceType = GetResourceType(propertyType); if (assocResourceType == null) { Type t = Type.GetType(propertyType); assocResourceType = DSP.ResourceType.GetPrimitiveResourceType(t); } newProperty = new DSP.ResourceProperty( propertyName, ConvertResourcePropertyKind(resourcePropertyKind), assocResourceType); } newProperty.CanReflectOnInstanceTypeProperty = isClrProperty; resourceType.AddProperty(newProperty); }
/// <summary>Returns a resource type as specified by the test.</summary> /// <param name="metadata">The DSPMetadata to use.</param> /// <param name="typeSpecification">The type specification. If it's a string, then it means the name of the type to get. If it's a Type it means /// to return a primitive resource type of that type.</param> /// <returns>The ResourceType specified by the test.</returns> public static providers.ResourceType GetResourceTypeFromTestSpecification(this DSPMetadata metadata, object typeSpecification) { if (metadata == null) { return(null); } if (typeSpecification is Type) { return(providers.ResourceType.GetPrimitiveResourceType(typeSpecification as Type)); } else { string typeName = typeSpecification as string; providers.ResourceType type = metadata.GetResourceType(typeName); if (type == null) { metadata.TryResolveResourceType(typeName, out type); } if (type == null) { type = UnitTestsUtil.GetPrimitiveResourceTypes().FirstOrDefault(rt => rt.FullName == typeName); } if (type == null) { type = UnitTestsUtil.GetPrimitiveResourceTypes().FirstOrDefault(rt => rt.Name == typeName); } return(type); } }
/// <summary>Creates new root node for the projection tree.</summary> /// <param name="resourceSetWrapper">The resource set of the root level of the query.</param> /// <param name="orderingInfo">The ordering info for this node. null means no ordering to be applied.</param> /// <param name="filter">The filter for this node. null means no filter to be applied.</param> /// <param name="skipCount">Number of results to skip. null means no results to be skipped.</param> /// <param name="takeCount">Maximum number of results to return. null means return all available results.</param> /// <param name="maxResultsExpected">Maximum number of expected results. Hint that the provider should return /// at least maxResultsExpected + 1 results (if available).</param> /// <param name="expandPaths">The list of expanded paths.</param> /// <param name="baseResourceType">The resource type for all entities in this query.</param> /// <param name="selectExpandClause">The select expand clause for the current node from the URI Parser.</param> internal RootProjectionNode( ResourceSetWrapper resourceSetWrapper, OrderingInfo orderingInfo, Expression filter, int? skipCount, int? takeCount, int? maxResultsExpected, List<ExpandSegmentCollection> expandPaths, ResourceType baseResourceType, SelectExpandClause selectExpandClause) : base( String.Empty, null, null, resourceSetWrapper, orderingInfo, filter, skipCount, takeCount, maxResultsExpected, selectExpandClause) { Debug.Assert(baseResourceType != null, "baseResourceType != null"); this.expandPaths = expandPaths; this.baseResourceType = baseResourceType; }
/// <summary> /// Checks if the given type is assignable to this type. In other words, if this type /// is a subtype of the given type or not. /// </summary> /// <param name="subType">resource type to check.</param> /// <returns>true, if the given type is assignable to this type. Otherwise returns false.</returns> internal static bool IsAssignableFrom(this ResourceType thisType, ResourceType subType) { CollectionResourceType thisCollectionType = thisType as CollectionResourceType; CollectionResourceType subCollectionType = subType as CollectionResourceType; if (thisCollectionType != null && subCollectionType != null) { return thisCollectionType.ItemType.IsAssignableFrom(subCollectionType.ItemType); } EntityCollectionResourceType thisEntityCollectionType = thisType as EntityCollectionResourceType; EntityCollectionResourceType subEntityCollectionType = subType as EntityCollectionResourceType; if (thisEntityCollectionType != null && subEntityCollectionType != null) { return thisEntityCollectionType.ItemType.IsAssignableFrom(subEntityCollectionType.ItemType); } while (subType != null) { if (subType == thisType) { return true; } subType = subType.BaseType; } return false; }
public object ResetResource(object resource) { if (resource is RowEntityType) { RowEntityType entityResource = resource as RowEntityType; DSP.ResourceType type = Types.Where(t => t.Namespace + "." + t.Name == entityResource.TypeName).FirstOrDefault(); foreach (DSP.ResourceProperty property in type.Properties) { if ((property.Kind & DSP.ResourcePropertyKind.Key) == 0 && (property.Kind & DSP.ResourcePropertyKind.ResourceReference) == 0 && (property.Kind & DSP.ResourcePropertyKind.ResourceSetReference) == 0) { entityResource.Properties.Remove(property.Name); } } // reset dynamic properties foreach (string key in entityResource.Properties.Keys.Except(type.Properties.Select(p => p.Name)).ToList()) { //the ToList is so we can modify the collection inside the loop entityResource.Properties.Remove(key); } return(entityResource); } else { return(new RowComplexType(((RowComplexType)resource).TypeName)); } } // ResetResource
} // CurrentDataSource public IEnumerable <KeyValuePair <string, object> > GetOpenPropertyValues(object target) { if (target == null) { throw new DataServiceException(500, "GetOpenPropertyValues called on null target"); } DSP.ResourceType resourceType = null; RowComplexType complexType = target as RowComplexType; if (complexType == null) { throw new DataServiceException(500, "GetOpenPropertyValues: Target is not of type RowComplexType"); } resourceType = this.Types.Where(r => r.FullName == complexType.TypeName).SingleOrDefault(); if (resourceType == null) { throw new DataServiceException(500, "Could not find resource type '" + complexType.TypeName + "'"); } // if its a closed type, this method should not be called if (!resourceType.IsOpenType) { throw new DataServiceException(500, "GetOpenPropertyValues called on non open type '" + resourceType.FullName + "'"); } return(complexType.Properties.Where(pair => !resourceType.Properties.Any(p => p.Name == pair.Key))); } // GetOpenPropertyValues
public OperationSerializerTests() { ResourceType intType = ResourceType.GetPrimitiveResourceType(typeof(int)); var customerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "FQ.NS", "Customer", false); customerType.CanReflectOnInstanceType = false; customerType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, intType) { CanReflectOnInstanceTypeProperty = false }); customerType.SetReadOnly(); var operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType), new ServiceActionParameter("P2", intType) }, null); operation.SetReadOnly(); this.baseTypeOperation = new OperationWrapper(operation); var bestCustomerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, customerType, "FQ.NS", "BestCustomer", false); bestCustomerType.SetReadOnly(); operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", bestCustomerType) }, null); operation.SetReadOnly(); this.derivedTypeOperation = new OperationWrapper(operation); operation = new ServiceAction("Unambiguous", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType) }, null); operation.SetReadOnly(); this.unambiguousOperation = new OperationWrapper(operation); this.entityToSerialize = EntityToSerialize.CreateFromExplicitValues(new object(), bestCustomerType, new TestSerializedEntityKey("http://odata.org/Service.svc/Customers(0)/", bestCustomerType.FullName)); this.testSubject = CreateOperationSerializer(AlwaysAdvertiseActions); }
private static DSPServiceDefinition SetupService() { DSPMetadata metadata = new DSPMetadata("ActionsWithLargePayload", "AstoriaUnitTests.ActionTestsWithLargePayload"); var customer = metadata.AddEntityType("Customer", null, null, false); metadata.AddKeyProperty(customer, "ID", typeof(int)); var customers = metadata.AddResourceSet("Customers", customer); ComplexType = metadata.AddComplexType("AddressComplexType", null, null, false); metadata.AddPrimitiveProperty(ComplexType, "ZipCode", typeof(int)); metadata.AddPrimitiveProperty(ComplexType, "City", typeof(string)); DSPContext context = new DSPContext(); metadata.SetReadOnly(); DSPResource customer1 = new DSPResource(customer); customer1.SetValue("ID", 1); context.GetResourceSetEntities("Customers").Add(customer1); MyDSPActionProvider actionProvider = new MyDSPActionProvider(); SetUpActionWithLargeParameterPayload(actionProvider, metadata, customer); SetUpActionWithLargeCollectionParameterPayload(actionProvider, metadata, customer); SetupLargeNumberOfActions(actionProvider, metadata, customer); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => context, ForceVerboseErrors = true, Writable = true, ActionProvider = actionProvider, }; return service; }
public OperationLinkBuilderTests() { ResourceType intType = ResourceType.GetPrimitiveResourceType(typeof(int)); var customerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "FQ.NS", "Customer", false); customerType.CanReflectOnInstanceType = false; customerType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, intType) { CanReflectOnInstanceTypeProperty = false }); customerType.SetReadOnly(); var operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType), new ServiceActionParameter("P2", intType) }, null); operation.SetReadOnly(); this.operationWithParameters = new OperationWrapper(operation); var typeWithEscapedName = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "FQ NS", "+ /", false); typeWithEscapedName.CanReflectOnInstanceType = false; typeWithEscapedName.AddProperty(new ResourceProperty("Number", ResourcePropertyKind.Primitive, intType) { CanReflectOnInstanceTypeProperty = false }); typeWithEscapedName.SetReadOnly(); operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType), new ServiceActionParameter("P2", typeWithEscapedName) }, null); operation.SetReadOnly(); this.operationWithEscapedParameter = new OperationWrapper(operation); var bestCustomerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, customerType, "FQ.NS", "BestCustomer", false); bestCustomerType.SetReadOnly(); operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType) }, null); operation.SetReadOnly(); this.operationBoundToBaseType = new OperationWrapper(operation); this.entityToSerialize = EntityToSerialize.CreateFromExplicitValues(new object(), bestCustomerType, new TestSerializedEntityKey("http://odata.org/Service.svc/Customers/", bestCustomerType.FullName)); var metadataUri = new Uri("http://odata.org/Service.svc/$metadata"); this.testSubject = new OperationLinkBuilder("MyContainer", metadataUri); }
public void Init() { this.baseType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Fake.NS", "BaseType", false) {CanReflectOnInstanceType = false}; this.baseType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(int))) { CanReflectOnInstanceTypeProperty = false }); this.baseType.SetReadOnly(); this.entityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, this.baseType, "Fake.NS", "Type", false) {CanReflectOnInstanceType = false}; this.entityType.SetReadOnly(); this.derivedType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, this.entityType, "Fake.NS", "DerivedType", false) { CanReflectOnInstanceType = false }; this.derivedType.SetReadOnly(); var resourceSet = new ResourceSet("Set", this.entityType); resourceSet.SetReadOnly(); this.resourceSetWrapper = ResourceSetWrapper.CreateForTests(resourceSet); this.action = new ServiceAction("Fake", ResourceType.GetPrimitiveResourceType(typeof(int)), OperationParameterBindingKind.Sometimes, new[] {new ServiceActionParameter("p1", this.entityType)}, null); this.action.SetReadOnly(); this.actionWrapper = new OperationWrapper(action); this.derivedAction = new ServiceAction("Fake", ResourceType.GetPrimitiveResourceType(typeof(int)), OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("p1", this.derivedType) }, null); this.derivedAction.SetReadOnly(); this.derivedActionWrapper = new OperationWrapper(derivedAction); this.testSubject = new SelectedOperationsCache(); }
public override object TypeIs(object value, DSP.ResourceType type) { // not clear how we can make this tolerant without it blowing up APICallLog.Current.Push(); try { if (value == null) { return(false); } DSP.ResourceType instanceType = QueryProvider.GetResourceType(value); if (instanceType != null) { IDataServiceMetadataProvider metadataProvider = QueryProvider as IDataServiceMetadataProvider; if (metadataProvider != null && metadataProvider.HasDerivedTypes(type)) { if (metadataProvider.GetDerivedTypes(type).Contains(instanceType)) { return(true); } } return(type == instanceType); } return(type.InstanceType.IsAssignableFrom(value.GetType())); } finally { APICallLog.Current.Pop(); } }
private static void SetupTestMetadata(Type entityClrType, Type[] primitiveTypes, out ResourceType entityResourceType, out ProviderMetadataSimulator workspace, out PrimitiveResourceTypeMap primitiveTypeMap) { KeyValuePair<Type, string>[] mappedPrimitiveTypes = BuildTypeMap(primitiveTypes); primitiveTypeMap = new PrimitiveResourceTypeMap(mappedPrimitiveTypes.ToArray()); entityResourceType = new ResourceType(entityClrType, ResourceTypeKind.EntityType, null, entityClrType.Namespace, entityClrType.Name, false); workspace = new ProviderMetadataSimulator(new List<Type>() { entityClrType }); }
/// <summary> /// Initializes a new instance of <see cref="MetadataProviderEdmCollectionType"/>. /// </summary> /// <param name="collectionResourceType">The collection resource type this edm collection type is being created for.</param> /// <param name="elementType">The element type of the collection.</param> public MetadataProviderEdmCollectionType(ResourceType collectionResourceType, IEdmTypeReference elementType) : base(elementType) { Debug.Assert(collectionResourceType != null, "collectionResourceType != null"); Debug.Assert(collectionResourceType is CollectionResourceType || collectionResourceType is EntityCollectionResourceType, "resource type must represent a collection."); this.ResourceType = collectionResourceType; }
/// <summary> /// Initializes a new instance of <see cref="ServiceActionResolverArgs"/>. /// </summary> /// <param name="serviceActionName"> The service action name taken from the URI.</param> /// <param name="bindingType">The binding type based on interpreting the URI preceeding the action, or null if the action is being invoked from the root of the service.</param> public ServiceActionResolverArgs(string serviceActionName, ResourceType bindingType) { WebUtil.CheckStringArgumentNullOrEmpty(serviceActionName, "serviceActionName"); this.ServiceActionName = serviceActionName; // binding type is explicitly allowed to be null. this.BindingType = bindingType; }
/// <summary>Constructor, creates a new resource with preinitialized properties.</summary> /// <param name="resourceType">The type of the resource to create.</param> /// <param name="values">The properties to initialize.</param> public DSPResource(ResourceType resourceType, IEnumerable<KeyValuePair<string, object>> values) : this(resourceType) { foreach (var value in values) { this.properties.Add(value.Key, value.Value); } }
public IEnumerable<ServiceAction> GetServiceActionsByBindingParameterType(DataServiceOperationContext operationContext, ResourceType bindingParameterType) { if (this.GetByBindingTypeCallback != null) { return this.GetByBindingTypeCallback(operationContext, bindingParameterType); } throw new NotImplementedException(); }
/// <summary>Creates a new instance of <see cref="T:Microsoft.OData.Service.Providers.ServiceOperationParameter" />.</summary> /// <param name="name">Name of parameter.</param> /// <param name="parameterType">Data type of parameter.</param> public ServiceOperationParameter(string name, ResourceType parameterType) : base(name, parameterType) { WebUtil.CheckArgumentNull(parameterType, "parameterType"); if (parameterType.ResourceTypeKind != ResourceTypeKind.Primitive) { throw new ArgumentException(Strings.ServiceOperationParameter_TypeNotSupported(name, parameterType.FullName), "parameterType"); } }
private string[] GetKeys(RowEntityType t) { List <string> keys = new List <string>(); string simpleTypeName = t.TypeName.Substring(t.TypeName.LastIndexOf('.') + 1); DSP.ResourceType resourceType = types.Where(rt => rt.Name.Equals(simpleTypeName)).FirstOrDefault(); keys.AddRange(resourceType.KeyProperties.OfType <DSP.ResourceProperty>().Select <DSP.ResourceProperty, string>(rp2 => rp2.Name)); return(keys.ToArray()); }
public void RemoveResourceType(string name) { DSP.ResourceType rt = GetResourceType(name); if (rt != null) { types.Remove(rt); } }
/// <summary> /// Creates a cache-key from the operation name and binding parameter type. /// </summary> /// <param name="operationName">The operation name.</param> /// <param name="bindingType">The binding parameter type.</param> /// <returns>The cache-key.</returns> private static string GetCacheKey(string operationName, ResourceType bindingType) { var cacheKey = operationName; if (bindingType != null) { cacheKey += "_" + bindingType.FullName; } return cacheKey; }
} // HasDerivedTypes public IEnumerable <DSP.ResourceType> GetDerivedTypes(DSP.ResourceType resourceType) { foreach (DSP.ResourceType type in Types) { if (type.BaseType != null && IsDerivedType(resourceType, type)) { yield return(type); } } } // GetDerivedTypes
/// <summary> /// Initializes a new instance of the <see cref="EntityToSerialize"/> class. /// </summary> /// <param name="entity">The entity itself.</param> /// <param name="resourceType">The type of the entity.</param> /// <param name="serializedKey">The serialized entity key for the instance.</param> private EntityToSerialize(object entity, ResourceType resourceType, SerializedEntityKey serializedKey) { Debug.Assert(entity != null, "resource != null"); Debug.Assert(resourceType != null && resourceType.ResourceTypeKind == ResourceTypeKind.EntityType, "resourceType != null && resourceType.ResourceTypeKind == ResourceTypeKind.EntityType"); Debug.Assert(serializedKey != null, "serializedKey != null"); this.entity = entity; this.resourceType = resourceType; this.serializedEntityKey = serializedKey; }
private void SetDerivedReadOnly(DSP.ResourceType resourceType) { foreach (DSP.ResourceType rt in types) { if (rt.BaseType != null && rt.BaseType.Equals(resourceType)) { rt.SetReadOnly(); SetDerivedReadOnly(rt); } } }
/// <summary> /// Initializes a new instance of the LazyResourceType class /// </summary> /// <param name="instanceType">Instance type that will back this metadata type</param> /// <param name="resourceTypeKind">The Type, complex or Resource</param> /// <param name="baseType">BaseType of the ResourceTYpe</param> /// <param name="namespaceName">Namespace of the type</param> /// <param name="name">Name of the type</param> /// <param name="isAbstract">Whether the type is abstract or not</param> public LazyResourceType( Type instanceType, ResourceTypeKind resourceTypeKind, ResourceType baseType, string namespaceName, string name, bool isAbstract) : base(instanceType, resourceTypeKind, baseType, namespaceName, name, isAbstract) { this.LazyProperties = new List<ResourceProperty>(); }
public IEnumerable <ServiceAction> GetServiceActionsByBindingParameterType(DataServiceOperationContext operationContext, ResourceType bindingParameterType) { var collectionType = bindingParameterType as EntityCollectionResourceType; if (collectionType != null && collectionType.ItemType.Name == "EntityTypeWithStringKey") { var serviceAction = new ServiceAction("Action", ResourceType.GetPrimitiveResourceType(typeof(string)), OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("param1", bindingParameterType) }, null); serviceAction.SetReadOnly(); yield return(serviceAction); } }
public EmptyOpenTypesContext() { this.resourceType = new ResourceType(typeof(StubTypeWithId), ResourceTypeKind.EntityType, null, "OpenTypes", "Entity", false); this.resourceType.CanReflectOnInstanceType = true; this.resourceType.IsOpenType = true; var idProperty = new ResourceProperty("Id", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, ResourceType.GetPrimitiveResourceType(typeof(int))); idProperty.CanReflectOnInstanceTypeProperty = true; this.resourceType.AddProperty(idProperty); this.resourceSet = new ResourceSet("Entities", this.resourceType); this.resourceSet.SetReadOnly(); }
public static void VerifyResultsExistForWhere(object service, object context, string defaultSource, params string[] predicates) { IQueryable source = null; IServiceProvider serviceProvider = context as IServiceProvider; if (serviceProvider != null) { Prov.IDataServiceMetadataProvider dataProvider = (Prov.IDataServiceMetadataProvider)serviceProvider.GetService(typeof(Prov.IDataServiceMetadataProvider)); if (dataProvider != null) { Prov.ResourceSet resourceSet; if (dataProvider.TryResolveResourceSet(defaultSource, out resourceSet)) { Prov.IDataServiceQueryProvider queryProvider = (Prov.IDataServiceQueryProvider)serviceProvider.GetService(typeof(Prov.IDataServiceQueryProvider)); source = queryProvider.GetQueryRootForResourceSet(resourceSet); } } } if (source == null) { source = (IQueryable)context.GetType().GetProperty(defaultSource).GetValue(context, null); } TestUtil.RunCombinations(predicates, (predicate) => { IQueryable actualSource = source; string actualPredicate = predicate; int separatorIndex = predicate.IndexOf('|'); string sourceName = defaultSource; if (separatorIndex != -1) { sourceName = predicate.Substring(0, separatorIndex); actualSource = (IQueryable)context.GetType().GetProperty(sourceName).GetValue(context, null); actualPredicate = predicate.Substring(separatorIndex + 1); } Trace.WriteLine("Verifying results exist for predicate [" + actualPredicate + "]"); Prov.ResourceType resourceType = GetResourceTypeForContainer(service, sourceName); object resourceSet = GetResourceSetWrapper(service, sourceName); Assert.IsNotNull(resourceType, "Should be able to find the container and its corresponding type"); IQueryable result = InvokeWhere(service, GetRequestDescription(resourceType, resourceSet, defaultSource), actualSource, actualPredicate); bool found = false; foreach (object o in result) { found = true; break; } Assert.IsTrue(found, "Results not found for predicate [" + actualPredicate + "]"); }); }
/// <summary>Constructor.</summary> /// <param name="itemType">Resource type of a single item in the collection.</param> internal EntityCollectionResourceType(ResourceType itemType) : base(GetInstanceType(itemType), ResourceTypeKind.EntityCollection, string.Empty, GetName(itemType)) { Debug.Assert(itemType != null, "itemType != null"); if (itemType.ResourceTypeKind != ResourceTypeKind.EntityType) { throw new ArgumentException(Strings.ResourceType_CollectionItemCanBeOnlyEntity); } this.itemType = itemType; }
/// <summary> /// Creates a new instance of EndInfo. /// </summary> /// <param name="name">name of the end.</param> /// <param name="resourceType">resource type that the end refers to.</param> /// <param name="resourceProperty">property of the end.</param> /// <param name="multiplicity">Multiplicity of the association.</param> /// <param name="deleteBehavior">Delete behavior.</param> internal ResourceAssociationTypeEnd(string name, ResourceType resourceType, ResourceProperty resourceProperty, string multiplicity, EdmOnDeleteAction deleteBehavior) { Debug.Assert(!String.IsNullOrEmpty(name), "!String.IsNullOrEmpty(name)"); Debug.Assert(resourceType != null, "type != null"); Debug.Assert(multiplicity == XmlConstants.Many || multiplicity == XmlConstants.One || multiplicity == XmlConstants.ZeroOrOne, "Invalid multiplicity value"); Debug.Assert(deleteBehavior == EdmOnDeleteAction.None || deleteBehavior == EdmOnDeleteAction.Cascade, "Invalid deleteBehavior value"); this.name = name; this.resourceType = resourceType; this.resourceProperty = resourceProperty; this.multiplicity = multiplicity; this.deleteAction = deleteBehavior; }
public void VerifyVersionOfEntityWithGeographyPropertyIsV3() { ResourceType rt = new ResourceType(typeof(IDictionary<string, string>), ResourceTypeKind.EntityType, null, "TestNamespace", "TestEntity", false); var keyProperty = new ResourceProperty("ID", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, ResourceType.GetPrimitiveResourceType(typeof(int))) {CanReflectOnInstanceTypeProperty = false }; var geographyProperty = new ResourceProperty("GeographyProperty", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Geography))) { CanReflectOnInstanceTypeProperty = false }; rt.AddProperty(keyProperty); rt.AddProperty(geographyProperty); rt.SetReadOnly(); Assert.AreEqual(v4, rt.MetadataVersion, "MetadataVersion must be 4.0"); Assert.AreEqual(MetadataEdmSchemaVersion.Version4Dot0, rt.SchemaVersion, "Schema version must be 4.0"); }
public void SetContinuationToken(IQueryable query, DSP.ResourceType resourceType, object[] continuationToken) { if (continuationToken == null) { Add("SetContinuationToken", query.GetType().ToString(), resourceType.Namespace + "." + resourceType.Name, "null"); } else { Add("SetContinuationToken", query.GetType().ToString(), resourceType.Namespace + "." + resourceType.Name, string.Join(", ", continuationToken.Select(o => Parent.Serialize(o)).ToArray())); } }
/// <summary> Initializes a new <see cref="T:Microsoft.OData.Service.Providers.OperationParameter" />. </summary> /// <param name="name">Name of parameter.</param> /// <param name="parameterType">resource type of parameter value.</param> protected internal OperationParameter(string name, ResourceType parameterType) { WebUtil.CheckStringArgumentNullOrEmpty(name, "name"); WebUtil.CheckArgumentNull(parameterType, "parameterType"); if (parameterType.ResourceTypeKind == ResourceTypeKind.Primitive && parameterType == ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream))) { throw new ArgumentException(Strings.ServiceOperationParameter_TypeNotSupported(name, parameterType.FullName), "parameterType"); } this.name = name; this.type = parameterType; }
} // GetDerivedTypes private static bool IsDerivedType(DSP.ResourceType baseType, DSP.ResourceType derivedType) { while (derivedType.BaseType != null) { if (derivedType.BaseType == baseType) { return(true); } derivedType = derivedType.BaseType; } return(false); } // IsDerivedType
/// <summary> /// Initializes a new instance of the MetadataProviderEdmEntityType class. /// </summary> /// <param name="namespaceName">Namespace the entity belongs to.</param> /// <param name="resourceType">The resource type this edm type is based on.</param> /// <param name="baseType">The base type of this entity type.</param> /// <param name="isAbstract">Denotes an entity that cannot be instantiated.</param> /// /// <param name="isOpen">Denotes if the type is open.</param> /// <param name="propertyLoadAction">An action that is used to create the properties for this type.</param> internal MetadataProviderEdmComplexType( string namespaceName, ResourceType resourceType, IEdmComplexType baseType, bool isAbstract, bool isOpen, Action<EdmComplexTypeWithDelayLoadedProperties> propertyLoadAction) : base(namespaceName, resourceType.Name, baseType, isAbstract, isOpen, propertyLoadAction) { Debug.Assert(resourceType != null, "resourceType != null"); Debug.Assert(resourceType.ResourceTypeKind == ResourceTypeKind.ComplexType, "Must be a complex type."); this.ResourceType = resourceType; }
private static EntityToSerialize CreateEntityToSerialize(bool shouldIncludeTypeSegment) { ResourceType baseType = new ResourceType(typeof(MyType), ResourceTypeKind.EntityType, null, "TestNamespace", "BaseType", /*isAbstract*/ false); baseType.AddProperty(new ResourceProperty("ID", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, new ResourceType(typeof(int), ResourceTypeKind.Primitive, null, "int"))); baseType.SetReadOnly(); Uri serviceUri = new Uri("http://dummy"); KeySerializer keySerializer = KeySerializer.Create(UrlConvention.CreateWithExplicitValue(false)); Func<ResourceProperty, object> getPropertyValue = p => "fakePropertyValue"; return EntityToSerialize.Create(new MyType { ID = 42 }, baseType, "MySet", shouldIncludeTypeSegment, getPropertyValue, keySerializer, serviceUri); }
} // InvokeServiceOperation #endregion #region IDataServiceMetadataProvider Helper methods internal static bool IsAssignableFrom(DSP.ResourceType baseType, DSP.ResourceType derivedType) { while (derivedType != null) { if (derivedType == baseType) { return(true); } derivedType = derivedType.BaseType; } return(false); }
/// <summary>Creates a new instance of <see cref="T:Microsoft.OData.Service.Providers.ResourceSet" /> class.</summary> /// <param name="name">The name of the set of items as string.</param> /// <param name="elementType">The <see cref="T:Microsoft.OData.Service.Providers.ResourceType" /> of the items in the set.</param> public ResourceSet(string name, ResourceType elementType) { WebUtil.CheckStringArgumentNullOrEmpty(name, "name"); WebUtil.CheckArgumentNull(elementType, "elementType"); if (elementType.ResourceTypeKind != ResourceTypeKind.EntityType) { throw new ArgumentException(Strings.ResourceContainer_ContainerMustBeAssociatedWithEntityType); } this.name = name; this.elementType = elementType; this.queryRootType = typeof(System.Linq.IQueryable<>).MakeGenericType(elementType.InstanceType); }
public override object Convert(object value, DSP.ResourceType type) { if (value == null) { return(null); } if (type.InstanceType.IsAssignableFrom(value.GetType())) { return(value); } throw new InvalidCastException("Instance of '" + value.GetType() + "' cannot be converted to resource type '" + type.FullName + "'"); }
public void AddResourceSet(string name, string typeName) { DSP.ResourceType resourceType = GetResourceType(typeName); if (resourceType != null) { resourceType.SetReadOnly(); SetDerivedReadOnly(resourceType); DSP.ResourceSet newResourceSet = new DSP.ResourceSet(name, resourceType); newResourceSet.SetReadOnly(); addedContainers.Add(newResourceSet); } }
/// <summary> /// For the given association from source to target, perform the appropriate reversed action /// </summary> /// <param name="source">the source of the association to reverse</param> /// <param name="target">the target of the association to reverse</param> /// <param name="forwardPropertyName">the name of the property from source to target</param> /// <param name="remove">whether or not to remove the reversed association</param> private void SetReverseNavigation(RowEntityType source, RowEntityType target, string forwardPropertyName, bool remove) { DSP.ResourceType targetType; DSP.ResourceType sourceType = this.GetResourceType(source); if (target == null) { targetType = sourceType.Properties.Single(p => p.Name == forwardPropertyName).ResourceType; } else { targetType = this.GetResourceType(target); } DSP.ResourceProperty forwardProperty = sourceType.Properties.SingleOrDefault(p => p.Name == forwardPropertyName); if (forwardProperty != null && forwardProperty.CustomState != null) { // because sourceType could match targetType, we need to make sure we filter out the target property DSP.ResourceProperty reverseProperty = targetType.Properties .SingleOrDefault(p => p != forwardProperty && p.CustomState != null && (string)p.CustomState == (string)forwardProperty.CustomState); if (reverseProperty != null) { bool reference = (reverseProperty.Kind & DSP.ResourcePropertyKind.ResourceReference) != 0; if (remove) { if (reference) { this.SetReference_Internal(target, reverseProperty.Name, null, false); } else { this.RemoveReferenceFromCollection_Internal(target, reverseProperty.Name, source, false); } } else { if (reference) { this.SetReference_Internal(target, reverseProperty.Name, source, false); } else { this.AddReferenceToCollection_Internal(target, reverseProperty.Name, source, false); } } } } }
public override object Convert(object value, DSP.ResourceType type) { if (value == null) { return(null); } if (type.InstanceType.IsAssignableFrom(value.GetType())) { return(value); } // not sure how to make this tolerant without it blowing up elsewhere throw new InvalidCastException("Instance of '" + value.GetType() + "' cannot be converted to resource type '" + type.FullName + "'"); }
/// <summary> /// Determines if a ResourceType is derived from or equal to another ResourceType /// </summary> /// <param name="possibleType">Possible parent type of the childType</param> /// <param name="childType">Child Type to compare with</param> /// <returns>true if the possible Type is a Kind of the child type</returns> internal bool IsKindOf(ResourceType possibleType, ResourceType childType) { ResourceType currentType = childType; while (currentType != null) { if (currentType == possibleType) { return true; } currentType = currentType.BaseType; } return false; }
/// <summary>Initializes a new <see cref="T:Microsoft.OData.Service.Providers.ResourceProperty" /> for an open property.</summary> /// <param name="name">Property name for the property as string.</param> /// <param name="kind"> /// <see cref="T:Microsoft.OData.Service.Providers.ResourcePropertyKind" />.</param> /// <param name="propertyResourceType">The <see cref="T:Microsoft.OData.Service.Providers.ResourceType" /> of the resource to which the property refers.</param> public ResourceProperty( string name, ResourcePropertyKind kind, ResourceType propertyResourceType) { WebUtil.CheckStringArgumentNullOrEmpty(name, "name"); WebUtil.CheckArgumentNull(propertyResourceType, "propertyResourceType"); ValidatePropertyParameters(kind, propertyResourceType); this.kind = kind; this.name = name; this.propertyResourceType = propertyResourceType; this.canReflectOnInstanceTypeProperty = kind.HasFlag(ResourcePropertyKind.Stream) ? false : true; }
public bool TryResolveServiceAction(DataServiceOperationContext operationContext, string serviceActionName, out ServiceAction serviceAction) { if (serviceActionName == "Action") { IDataServiceMetadataProvider metadataProvider = (IDataServiceMetadataProvider)operationContext.GetService(typeof(IDataServiceMetadataProvider)); ResourceType resourceType; metadataProvider.TryResolveResourceType(EntityTypeNameWithStringKey, out resourceType); Assert.IsNotNull(resourceType); serviceAction = new ServiceAction("Action", ResourceType.GetPrimitiveResourceType(typeof(string)), OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("param1", ResourceType.GetEntityCollectionResourceType(resourceType)) }, null); serviceAction.SetReadOnly(); return(true); } serviceAction = null; return(false); }
/// <summary> /// Gets the set of operations that should be serialized for a specific instance type based on what was selected in the URI and what is bindable to the given type. /// </summary> /// <param name="instanceTypeBeingSerialized">The instance type being serialized.</param> /// <returns>The selected bindable operations.</returns> internal List<OperationWrapper> GetSelectedOperations(ResourceType instanceTypeBeingSerialized) { Debug.Assert(instanceTypeBeingSerialized != null, "instanceTypeBeingSerialized != null"); List<OperationWrapper> selectedOperationsForPayloadType; if (!this.selectedOperationsByPayloadType.TryGetValue(instanceTypeBeingSerialized, out selectedOperationsForPayloadType)) { // go gather all the selected operations for this type based on what was selected in the URL. selectedOperationsForPayloadType = this.GetSelectedAndBindableOperationsForAssignableTypes(instanceTypeBeingSerialized); // add them to the cache this.selectedOperationsByPayloadType[instanceTypeBeingSerialized] = selectedOperationsForPayloadType; } return selectedOperationsForPayloadType; }
/// <summary>Constructor.</summary> /// <param name="itemType">Resource type of a single item in the collection property.</param> internal CollectionResourceType(ResourceType itemType) : base(GetInstanceType(itemType), ResourceTypeKind.Collection, string.Empty, GetName(itemType)) { Debug.Assert(itemType != null, "itemType != null"); if (itemType.ResourceTypeKind != ResourceTypeKind.Primitive && itemType.ResourceTypeKind != ResourceTypeKind.ComplexType) { throw new ArgumentException(Strings.ResourceType_CollectionItemCanBeOnlyPrimitiveOrComplex); } if (itemType == ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream))) { throw new ArgumentException(Strings.ResourceType_CollectionItemCannotBeStream(itemType.FullName), "itemType"); } this.itemType = itemType; }
/// <summary> /// Adds a set of selected operations from the URL. /// </summary> /// <param name="specificSelectedTypeInUri">The specific type for which the actions are selected. Should be either the base type of the feed or from a type segment.</param> /// <param name="selectedOperations">The selected operations returned by the provider.</param> /// <returns>Whether any operations were selected.</returns> internal bool AddSelectedOperations(ResourceType specificSelectedTypeInUri, IEnumerable<OperationWrapper> selectedOperations) { Debug.Assert(selectedOperations != null, "operations != null"); List<OperationWrapper> operationsAlreadySelected = null; foreach (var selectedOperation in selectedOperations) { if (operationsAlreadySelected == null && !this.selectedOperationsByUriType.TryGetValue(specificSelectedTypeInUri, out operationsAlreadySelected)) { this.selectedOperationsByUriType[specificSelectedTypeInUri] = operationsAlreadySelected = new List<OperationWrapper>(); } operationsAlreadySelected.Add(selectedOperation); } return operationsAlreadySelected != null; }
} // GetQueryRootForResourceSet public DSP.ResourceType GetResourceType(object instance) { if (instance == null) { return(null); } DSP.ResourceType resourceType = null; RowComplexType complexType = instance as RowComplexType; if (complexType != null) { string typeName = complexType.TypeName; resourceType = this.Types.FirstOrDefault(r => r.FullName == typeName); } return(resourceType); } // GetResourceType
[Ignore] // test case issue, request uri and service root in this case is null. public void RequestQueryParserTestFilterTest() { var service = new OpenWebDataService <CustomDataContext>(); service.AttachHost(new TestServiceHost2()); CustomDataContext context = ServiceModelData.InitializeAndGetContext(service); Prov.ResourceType customerType = GetResourceTypeForContainer(service, "Customers"); object customerSet = GetResourceSetWrapper(service, "Customers"); IQueryable result = InvokeWhere(service, GetRequestDescription(customerType, customerSet, "Customers"), context.Customers, "ID eq 5"); XmlDocument document = CreateDocumentFromIQueryable(result); Trace.WriteLine(document.InnerXml); UnitTestsUtil.VerifyXPaths(document, "/Source//*[@NodeType='Lambda']", "/Source//*[@NodeType='Lambda']/Body[@Type='System.Boolean']", "/Source//*[@NodeType='Lambda']/Body[@Type='System.Boolean']/*[@NodeType='Constant' and @Value='5']", "/Source//*[@NodeType='Lambda']/Body[@Type='System.Boolean']/*[@NodeType='MemberAccess' and contains(@Member, 'ID')]"); }
} // GetPropertyValue public object GetOpenPropertyValue(object target, string propertyName) { if (target == null) { throw new DataServiceException(500, "GetOpenPropertyValue called on null target"); } DSP.ResourceType resourceType = null; RowComplexType complexType = target as RowComplexType; if (complexType == null) { throw new DataServiceException(500, "GetOpenPropertyValue: Target is not of type RowComplexType"); } resourceType = this.Types.Where(r => r.FullName == complexType.TypeName).SingleOrDefault(); if (resourceType == null) { throw new DataServiceException(500, "Could not find resource type '" + complexType.TypeName + "'"); } // if its a closed type, this method should not be called if (!resourceType.IsOpenType) { throw new DataServiceException(500, "GetOpenPropertyValue called on non open type '" + resourceType.FullName + "'"); } // if its a declared property, this method should not be called if (resourceType.Properties.Any(p => p.Name == propertyName)) { throw new DataServiceException(500, "GetOpenPropertyValue called for declared property '" + propertyName + "'"); } object value; if (complexType.Properties.TryGetValue(propertyName, out value)) { return(value); } return(null); } // GetOpenPropertyValue
} // TryResolveServiceOperation public bool TryResolveResourceType(string name, out DSP.ResourceType resourceType) { if (types != null) { resourceType = this.Types.Where <DSP.ResourceType>(t => t.FullName == name).FirstOrDefault <DSP.ResourceType>(); if (resourceType == null) { int lastIndexOfPos = name.LastIndexOf("."); if (lastIndexOfPos > -1) { string newTypeName = name.Substring(lastIndexOfPos, name.Length - lastIndexOfPos).Replace(".", ""); resourceType = this.Types.Where <DSP.ResourceType>(t => t.FullName == newTypeName).FirstOrDefault <DSP.ResourceType>(); } } return(resourceType != null); } resourceType = null; return(false); } // TryResolveResourceType
public void ComplexResourceType_Open() { Microsoft.OData.Service.Providers.ResourceType rt = new Microsoft.OData.Service.Providers.ResourceType( typeof(RowComplexType), ResourceTypeKind.ComplexType, null, "AstoriaUnitTests.Stubs", "Address", false); bool errorOccurred = false; try { rt.IsOpenType = true; } catch (InvalidOperationException) { errorOccurred = true; } Assert.IsFalse(errorOccurred); }
public void AddResourceType(string name, string typeName, string resourceTypeKind, bool isOpenType, string baseType, string namespaceName, bool isAbstract) { DSP.ResourceType baseResourceType = null; if (baseType != null) { baseResourceType = GetResourceType(baseType); } Type backingType = Type.GetType("System.Data.Test.Astoria.NonClr." + typeName); DSP.ResourceType newType = new DSP.ResourceType( backingType, ConvertResourceTypeKind(resourceTypeKind), baseResourceType, namespaceName, name, isAbstract); newType.IsOpenType = isOpenType; underConstructionTypes.Add(newType); }
public void RequestQueryParserTestNegativeTests() { // Repro Protocol: filter throws NYI when using null with arithmetic operators var service = new OpenWebDataService <CustomDataContext>(); service.AttachHost(new TestServiceHost2()); CustomDataContext context = ServiceModelData.InitializeAndGetContext(service); string[] predicates = new string[] { "1 eq 1 and not not 2 eq 1 add 1", "1 eq FakePropertyName", "1 eq '1'", "1 add", "'", "?", "1 add 1", "#", "endswith(123, 'abc')", "endswith('abc')", "endswith('abc', 123)", "0xaa eq 0xa", "0xaa eq 0xag", "null add 4 eq 1", "'a' add 'b' eq 'ab'", "endswith(Name add 'b', 'b')", "BestFriend add null", }; // This way of getting the type is less ideal than getting it based on the // container name (see GetResourceTypeForContainer), because it does not work // for custom IDataServiceProvider implementations. In this case there seems to be // no other option. Prov.ResourceType customerType = GetResourceType(service, context.Customers.ElementType.FullName); object customerSet = GetResourceSetWrapper(service, "Customers"); VerifyExceptionForWhere(service, customerSet, customerType, context.Customers, predicates); }
private static DSPServiceDefinition SetupService() { DSPMetadata metadata = new DSPMetadata("ActionsWithLargePayload", "AstoriaUnitTests.ActionTestsWithLargePayload"); var customer = metadata.AddEntityType("Customer", null, null, false); metadata.AddKeyProperty(customer, "ID", typeof(int)); var customers = metadata.AddResourceSet("Customers", customer); ComplexType = metadata.AddComplexType("AddressComplexType", null, null, false); metadata.AddPrimitiveProperty(ComplexType, "ZipCode", typeof(int)); metadata.AddPrimitiveProperty(ComplexType, "City", typeof(string)); DSPContext context = new DSPContext(); metadata.SetReadOnly(); DSPResource customer1 = new DSPResource(customer); customer1.SetValue("ID", 1); context.GetResourceSetEntities("Customers").Add(customer1); MyDSPActionProvider actionProvider = new MyDSPActionProvider(); SetUpActionWithLargeParameterPayload(actionProvider, metadata, customer); SetUpActionWithLargeCollectionParameterPayload(actionProvider, metadata, customer); SetupLargeNumberOfActions(actionProvider, metadata, customer); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => context, ForceVerboseErrors = true, Writable = true, ActionProvider = actionProvider, }; return(service); }
private static object GetRequestDescription(Prov.ResourceType resourceType, object resourceSet, string relativeUri) { // Create the segment info Type segmentInfoType = typeof(Prov.ResourceType).Assembly.GetType("Microsoft.OData.Service.SegmentInfo"); var segmentInfo = Activator.CreateInstance(segmentInfoType, true /*nonPublic*/); segmentInfoType.GetProperty("TargetResourceType", BindingFlags.NonPublic | BindingFlags.Instance).GetSetMethod(true /*nonPublic*/).Invoke(segmentInfo, new object[] { resourceType }); segmentInfoType.GetProperty("TargetResourceSet", BindingFlags.NonPublic | BindingFlags.Instance).GetSetMethod(true /*nonPublic*/).Invoke(segmentInfo, new object[] { resourceSet }); // create segmentInfo array var segmentInfoArray = Array.CreateInstance(segmentInfoType, 1); segmentInfoArray.SetValue(segmentInfo, 0); // Create RequestDescription Type requestDescriptionType = typeof(Prov.ResourceType).Assembly.GetType("Microsoft.OData.Service.RequestDescription"); return(Activator.CreateInstance( requestDescriptionType, BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new object[] { segmentInfoArray, new Uri(new Uri("http://host", UriKind.Absolute), relativeUri) }, System.Globalization.CultureInfo.InvariantCulture)); }
/// <summary>Creates a server resource from the specified client resource</summary> /// <param name="clientResource">The client resource instance.</param> /// <param name="createCollection">Optional func to create a new collection instance on the server. /// The first parameter is the collection resource type, the second is enumeration of server items to be added to the collection.</param> /// <param name="clientInstanceToResourceType">Func to resolve client resource to a server resource type.</param> /// <returns>The server resource instance.</returns> public static DSPResource CreateServerResourceFromClientResource( object clientResource, Func <providers.CollectionResourceType, IEnumerable <object>, object> createCollection, Func <object, providers.ResourceType> clientInstanceToResourceType) { providers.ResourceType resourceType = clientInstanceToResourceType(clientResource); DSPResource resource = new DSPResource(resourceType); IEnumerable <PropertyInfo> properties = clientResource.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var property in properties) { var sameProperties = properties.Where(p => p.Name == property.Name).ToList(); sameProperties.Sort((p1, p2) => p1.DeclaringType.IsAssignableFrom(p2.DeclaringType) ? 1 : -1); if (sameProperties[0] == property) { object value = property.GetValue(clientResource, null); providers.ResourceProperty resourceProperty = resourceType == null ? null : resourceType.Properties.SingleOrDefault(p => p.Name == property.Name); resource.SetRawValue(property.Name, CreateServerValueFromClientValue(value, resourceProperty == null ? null : resourceProperty.ResourceType, createCollection, clientInstanceToResourceType)); } } return(resource); }