/// <summary>
        /// Gets the property info for the resource property declared on this type.
        /// </summary>
        /// <param name="resourceType">The resource type to get the property on.</param>
        /// <param name="resourceProperty">Resource property instance to get the property info for.</param>
        /// <returns>Returns the PropertyInfo object for the specified resource property.</returns>
        internal PropertyInfo GetPropertyInfo(ResourceType resourceType, ResourceProperty resourceProperty)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(resourceType != null, "resourceType != null");
            Debug.Assert(resourceProperty != null, "resourceProperty != null");
            Debug.Assert(resourceProperty.CanReflectOnInstanceTypeProperty, "resourceProperty.CanReflectOnInstanceTypeProperty");
            Debug.Assert(resourceType.Properties.Contains(resourceProperty), "The resourceType does not define the specified resourceProperty.");

            if (this.propertyInfosDeclaredOnThisType == null)
            {
                this.propertyInfosDeclaredOnThisType = new Dictionary<ResourceProperty, PropertyInfo>(ReferenceEqualityComparer<ResourceProperty>.Instance);
            }

            PropertyInfo propertyInfo;
            if (!this.propertyInfosDeclaredOnThisType.TryGetValue(resourceProperty, out propertyInfo))
            {
                BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
                propertyInfo = resourceType.InstanceType.GetProperty(resourceProperty.Name, bindingFlags);
                if (propertyInfo == null)
                {
                    throw new ODataException(Strings.PropertyInfoResourceTypeAnnotation_CannotFindProperty(resourceType.FullName, resourceType.InstanceType, resourceProperty.Name));
                }

                this.propertyInfosDeclaredOnThisType.Add(resourceProperty, propertyInfo);
            }

            Debug.Assert(propertyInfo != null, "propertyInfo != null");
            return propertyInfo;
        }
Example #2
0
        /// <summary>
        /// Compute the result type of a binary operator based on the type of its operands and the operator kind.
        /// </summary>
        /// <param name="type">The type of the operators.</param>
        /// <param name="operatorKind">The kind of operator.</param>
        /// <returns>The result type of the binary operator.</returns>
        internal static ResourceType GetBinaryOperatorResultType(ResourceType type, BinaryOperatorKind operatorKind)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(type != null, "type != null");

            switch (operatorKind)
            {
                case BinaryOperatorKind.Or:                 // fall through
                case BinaryOperatorKind.And:                // fall through
                case BinaryOperatorKind.Equal:              // fall through
                case BinaryOperatorKind.NotEqual:           // fall through
                case BinaryOperatorKind.GreaterThan:        // fall through
                case BinaryOperatorKind.GreaterThanOrEqual: // fall through
                case BinaryOperatorKind.LessThan:           // fall through
                case BinaryOperatorKind.LessThanOrEqual:
                    Type resultType = Nullable.GetUnderlyingType(type.InstanceType) == null
                        ? typeof(bool)
                        : typeof(bool?);
                    return ResourceType.GetPrimitiveResourceType(resultType);

                case BinaryOperatorKind.Add:        // fall through
                case BinaryOperatorKind.Subtract:   // fall through
                case BinaryOperatorKind.Multiply:   // fall through
                case BinaryOperatorKind.Divide:     // fall through
                case BinaryOperatorKind.Modulo:
                    return type;

                default:
                    throw new ODataException(Strings.General_InternalError(InternalErrorCodes.QueryNodeUtils_BinaryOperatorResultType_UnreachableCodepath));
            }
        }
        /// <summary>
        /// Writes the custom mapped EPM properties to an XML writer which is expected to be positioned such to write
        /// a child element of the entry element.
        /// </summary>
        /// <param name="writer">The XmlWriter to write to.</param>
        /// <param name="epmTargetTree">The EPM target tree to use.</param>
        /// <param name="epmValueCache">The entry properties value cache to use to access the properties.</param>
        /// <param name="resourceType">The resource type of the entry.</param>
        /// <param name="metadata">The metadata provider to use.</param>
        internal static void WriteEntryEpm(
            XmlWriter writer,
            EpmTargetTree epmTargetTree,
            EntryPropertiesValueCache epmValueCache,
            ResourceType resourceType,
            DataServiceMetadataProviderWrapper metadata)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(epmTargetTree != null, "epmTargetTree != null");
            Debug.Assert(epmValueCache != null, "epmValueCache != null");
            Debug.Assert(resourceType != null, "For any EPM to exist the metadata must be available.");

            // If there are no custom mappings, just return null.
            EpmTargetPathSegment customRootSegment = epmTargetTree.NonSyndicationRoot;
            Debug.Assert(customRootSegment != null, "EPM Target tree must always have non-syndication root.");
            if (customRootSegment.SubSegments.Count == 0)
            {
                return;
            }

            foreach (EpmTargetPathSegment targetSegment in customRootSegment.SubSegments)
            {
                Debug.Assert(!targetSegment.IsAttribute, "Target segments under the custom root must be for elements only.");

                string alreadyDeclaredPrefix = null;
                WriteElementEpm(writer, targetSegment, epmValueCache, resourceType, metadata, ref alreadyDeclaredPrefix);
            }
        }
		public bool Extract(Expression tree, IQueryable<DSResource> resourceRoot, ResourceType resourceType, EntityMetadata entityMetadata)
		{
			this.resourceRoot = resourceRoot;
			this.entityMetadata = entityMetadata;
			this.navigationProperty = null;
			this.referredEntityKeys = new Dictionary<string, object>();
			this.referringEntityKeys = new Dictionary<string, object>();
			this.currentState = ReferredResourceExtractor.ExtractionState.ExtractingReferredEntityInfo;
			this.Visit(tree);
			if (this.currentState == ReferredResourceExtractor.ExtractionState.ExtractingReferringEntityInfo)
			{
				DSResource dSResource = ResourceTypeExtensions.CreateKeyOnlyResource(resourceType, this.referringEntityKeys);
				if (dSResource != null)
				{
					this.ReferredResource = ResourceTypeExtensions.CreateKeyOnlyResource(this.navigationProperty.ResourceType, this.referredEntityKeys);
					if (this.ReferredResource != null)
					{
						this.currentState = ReferredResourceExtractor.ExtractionState.ExtractionDone;
					}
				}
			}
			if (this.currentState != ReferredResourceExtractor.ExtractionState.ExtractionDone)
			{
				this.currentState = ReferredResourceExtractor.ExtractionState.ExtractionFailed;
			}
			return this.currentState == ReferredResourceExtractor.ExtractionState.ExtractionDone;
		}
		public CollectionResourceTypeSerializer(ResourceType resourceType) : base(resourceType)
		{
			object[] resourceTypeKind = new object[2];
			resourceTypeKind[0] = resourceType.ResourceTypeKind;
			resourceTypeKind[1] = ResourceTypeKind.Collection;
			ExceptionHelpers.ThrowArgumentExceptionIf("resourceType", resourceType.ResourceTypeKind != ResourceTypeKind.Collection, new ExceptionHelpers.MessageLoader(SerializerBase.GetInvalidArgMessage), resourceTypeKind);
		}
Example #6
0
        public static TableResourceContainer GetUtilityRowResourceContainer(string accountName, string tableName)
        {
            System.Data.Services.Providers.ResourceType resourceType = new System.Data.Services.Providers.ResourceType(typeof(UtilityRow), ResourceTypeKind.EntityType, null, accountName, tableName, false)
            {
                CanReflectOnInstanceType = false,
                IsOpenType = true
            };
            ResourceProperty utilityRowResourceProperty = new UtilityRowResourceProperty("PartitionKey", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, System.Data.Services.Providers.ResourceType.GetPrimitiveResourceType(typeof(string)))
            {
                CanReflectOnInstanceTypeProperty = false
            };

            resourceType.AddProperty(utilityRowResourceProperty);
            ResourceProperty resourceProperty = new UtilityRowResourceProperty("RowKey", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, System.Data.Services.Providers.ResourceType.GetPrimitiveResourceType(typeof(string)))
            {
                CanReflectOnInstanceTypeProperty = false
            };

            resourceType.AddProperty(resourceProperty);
            ResourceProperty utilityRowResourceProperty1 = new UtilityRowResourceProperty("Timestamp", ResourcePropertyKind.Primitive | ResourcePropertyKind.ETag, System.Data.Services.Providers.ResourceType.GetPrimitiveResourceType(typeof(DateTime)))
            {
                CanReflectOnInstanceTypeProperty = false
            };

            resourceType.AddProperty(utilityRowResourceProperty1);
            TableResourceContainer tableResourceContainer = new TableResourceContainer(tableName, resourceType);

            tableResourceContainer.SetReadOnly();
            return(tableResourceContainer);
        }
Example #7
0
		public static DSResource CreateResourceWithKeyAndReferenceSetCmdlets(ResourceType resourceType, Dictionary<string, object> keyProperties, EntityMetadata entityMetadata)
		{
			DSResource dSResource = ResourceTypeExtensions.CreateKeyOnlyResource(resourceType, keyProperties);
			if (dSResource != null)
			{
				PSEntityMetadata pSEntityMetadatum = entityMetadata as PSEntityMetadata;
				ReadOnlyCollection<ResourceProperty> properties = resourceType.Properties;
				foreach (ResourceProperty resourceProperty in properties.Where<ResourceProperty>((ResourceProperty it) => (it.Kind & ResourcePropertyKind.ResourceSetReference) == ResourcePropertyKind.ResourceSetReference))
				{
					PSEntityMetadata.ReferenceSetCmdlets referenceSetCmdlet = null;
					if (!pSEntityMetadatum.CmdletsForReferenceSets.TryGetValue(resourceProperty.Name, out referenceSetCmdlet) || !referenceSetCmdlet.Cmdlets.ContainsKey(CommandType.GetReference))
					{
						continue;
					}
					if (referenceSetCmdlet.GetRefHidden)
					{
						dSResource.SetValue(resourceProperty.Name, null);
					}
					else
					{
						PSReferencedResourceSet pSReferencedResourceSet = new PSReferencedResourceSet(resourceProperty, resourceType);
						dSResource.SetValue(resourceProperty.Name, pSReferencedResourceSet);
					}
				}
				return dSResource;
			}
			else
			{
				return null;
			}
		}
 protected void ApplyProperty(ODataProperty property, ResourceType resourceType, object resource)
 {
     ResourceType type;
     string name = property.Name;
     ResourceProperty resourceProperty = resourceType.TryResolvePropertyName(name);
     if (resourceProperty == null)
     {
         type = null;
     }
     else
     {
         if (resourceProperty.Kind == ResourcePropertyKind.Stream)
         {
             return;
         }
         if (base.Update && resourceProperty.IsOfKind(ResourcePropertyKind.Key))
         {
             return;
         }
         type = resourceProperty.ResourceType;
     }
     object propertyValue = this.ConvertValue(property.Value, ref type);
     if (resourceProperty == null)
     {
         Deserializer.SetOpenPropertyValue(resource, name, propertyValue, base.Service);
     }
     else
     {
         Deserializer.SetPropertyValue(resourceProperty, resource, propertyValue, base.Service);
     }
 }
Example #9
0
 /// <summary>
 /// Constructor creates contained serializers
 /// </summary>
 /// <param name="resourceType">Resource type being serialized</param>
 /// <param name="element">Instance of <paramref name="resourceType"/></param>
 internal EpmContentDeSerializer(ResourceType resourceType, object element)
 {
     Debug.Assert(resourceType.HasEntityPropertyMappings == true, "Must have entity property mappings to instantiate EpmContentDeSerializer");
     this.resourceType = resourceType;
     this.element = element;
     this.resourceType.EnsureEpmInfoAvailability();
 }
Example #10
0
 private static ResourceType GetReturnTypeFromResultType(ResourceType resultType, ServiceOperationResultKind resultKind)
 {
     if (((resultKind == ServiceOperationResultKind.Void) && (resultType != null)) || ((resultKind != ServiceOperationResultKind.Void) && (resultType == null)))
     {
         throw new ArgumentException(System.Data.Services.Strings.ServiceOperation_ResultTypeAndKindMustMatch("resultKind", "resultType", ServiceOperationResultKind.Void));
     }
     if ((resultType != null) && (resultType.ResourceTypeKind == ResourceTypeKind.Collection))
     {
         throw new ArgumentException(System.Data.Services.Strings.ServiceOperation_InvalidResultType(resultType.FullName));
     }
     if ((resultType != null) && (resultType.ResourceTypeKind == ResourceTypeKind.EntityCollection))
     {
         throw new ArgumentException(System.Data.Services.Strings.ServiceOperation_InvalidResultType(resultType.FullName));
     }
     if (resultType == null)
     {
         return null;
     }
     if (((resultType.ResourceTypeKind == ResourceTypeKind.Primitive) || (resultType.ResourceTypeKind == ResourceTypeKind.ComplexType)) && ((resultKind == ServiceOperationResultKind.Enumeration) || (resultKind == ServiceOperationResultKind.QueryWithMultipleResults)))
     {
         return ResourceType.GetCollectionResourceType(resultType);
     }
     if ((resultType.ResourceTypeKind == ResourceTypeKind.EntityType) && ((resultKind == ServiceOperationResultKind.Enumeration) || (resultKind == ServiceOperationResultKind.QueryWithMultipleResults)))
     {
         return ResourceType.GetEntityCollectionResourceType(resultType);
     }
     return resultType;
 }
Example #11
0
 internal string GetActionTitleSegmentByResourceType(ResourceType resourceType, string containerName)
 {
     string str;
     if (!this.actionTitleSegmentByResourceType.TryGetValue(resourceType, out str))
     {
         bool flag = false;
         if (resourceType.IsOpenType)
         {
             flag = true;
         }
         else
         {
             foreach (ResourceProperty property in resourceType.Properties)
             {
                 if (property.Name.Equals(this.Name, StringComparison.Ordinal))
                 {
                     flag = true;
                     break;
                 }
             }
         }
         str = flag ? (containerName + "." + this.Name) : this.Name;
         this.actionTitleSegmentByResourceType[resourceType] = str;
     }
     return str;
 }
Example #12
0
		public PrimitiveTypeSerializer(ResourceType resourceType, ResourceProperty resourceProperty) : base(resourceType)
		{
			object defaultValue;
			object[] resourceTypeKind = new object[2];
			resourceTypeKind[0] = resourceType.ResourceTypeKind;
			resourceTypeKind[1] = ResourceTypeKind.Primitive;
			ExceptionHelpers.ThrowArgumentExceptionIf("resourceType", resourceType.ResourceTypeKind != ResourceTypeKind.Primitive, new ExceptionHelpers.MessageLoader(SerializerBase.GetInvalidArgMessage), resourceTypeKind);
			this.defaultValue = null;
			if (resourceProperty != null)
			{
				if ((resourceProperty.Kind & ResourcePropertyKind.Primitive) != ResourcePropertyKind.Primitive || resourceProperty.ResourceType.InstanceType != resourceType.InstanceType)
				{
					throw new ArgumentException("resourceProperty");
				}
				else
				{
					PropertyCustomState customState = resourceProperty.GetCustomState();
					PrimitiveTypeSerializer primitiveTypeSerializer = this;
					if (customState != null)
					{
						defaultValue = customState.DefaultValue;
					}
					else
					{
						defaultValue = null;
					}
					primitiveTypeSerializer.defaultValue = defaultValue;
					this.name = resourceProperty.Name;
				}
			}
		}
Example #13
0
 private IEnumerable<ODataAssociationLink> GetEntityAssociationLinks(ResourceType currentResourceType, Uri relativeUri, IEnumerable<ProjectionNode> projectionNodesForCurrentResourceType)
 {
     if (!base.Service.Configuration.DataServiceBehavior.ShouldIncludeAssociationLinksInResponse)
     {
         return null;
     }
     List<ODataAssociationLink> list = new List<ODataAssociationLink>(currentResourceType.Properties.Count);
     if (projectionNodesForCurrentResourceType == null)
     {
         foreach (ResourceProperty property in base.Provider.GetResourceSerializableProperties(base.CurrentContainer, currentResourceType))
         {
             if (property.TypeKind == ResourceTypeKind.EntityType)
             {
                 list.Add(GetAssociationLink(relativeUri, property));
             }
         }
         return list;
     }
     foreach (ProjectionNode node in projectionNodesForCurrentResourceType)
     {
         string propertyName = node.PropertyName;
         ResourceProperty navigationProperty = node.TargetResourceType.TryResolvePropertyName(propertyName);
         if (((navigationProperty != null) && (navigationProperty.TypeKind == ResourceTypeKind.EntityType)) && (list != null))
         {
             list.Add(GetAssociationLink(relativeUri, navigationProperty));
         }
     }
     return list;
 }
Example #14
0
		public ICommand GetCommand(CommandType commandType, UserContext userContext, ResourceType entityType, EntityMetadata entityMetadata, string membershipId)
		{
			if (entityType.Name == "CommandInvocation")
			{
				CommandType commandType1 = commandType;
				switch (commandType1)
				{
					case CommandType.Create:
					case CommandType.Read:
					case CommandType.Delete:
					{
						return new GICommand(commandType, this.runspaceStore, entityType, userContext, membershipId);
					}
					case CommandType.Update:
					{
						throw new NotImplementedException();
					}
					default:
					{
						throw new NotImplementedException();
					}
				}
			}
			else
			{
				throw new NotImplementedException();
			}
		}
Example #15
0
		public MovableWhereFinder(Expression tree, IQueryable<DSResource> resourceRoot, ResourceType baseResourceType)
		{
			this.resourceRoot = resourceRoot;
			this.baseResourceType = baseResourceType;
			this.MovableWhereExpression = null;
			this.Visit(tree);
		}
Example #16
0
 private IEdmEntityType AddEntityType(ResourceType resourceType, string resourceTypeNamespace)
 {
     Action<MetadataProviderEdmEntityType> propertyLoadAction = delegate (MetadataProviderEdmEntityType type) {
         IEnumerable<ResourceProperty> allVisiblePropertiesDeclaredInThisType = this.GetAllVisiblePropertiesDeclaredInThisType(resourceType);
         if (allVisiblePropertiesDeclaredInThisType != null)
         {
             foreach (ResourceProperty property in allVisiblePropertiesDeclaredInThisType)
             {
                 IEdmProperty property2 = this.CreateProperty(type, property);
                 if (property.IsOfKind(ResourcePropertyKind.Key))
                 {
                     type.AddKeys(new IEdmStructuralProperty[] { (IEdmStructuralProperty) property2 });
                 }
             }
         }
     };
     MetadataProviderEdmEntityType schemaType = new MetadataProviderEdmEntityType(resourceTypeNamespace, resourceType.Name, (resourceType.BaseType != null) ? ((IEdmEntityType) this.EnsureSchemaType(resourceType.BaseType)) : null, resourceType.IsAbstract, resourceType.IsOpenType, propertyLoadAction);
     this.CacheSchemaType(schemaType);
     if (resourceType.IsMediaLinkEntry && ((resourceType.BaseType == null) || !resourceType.BaseType.IsMediaLinkEntry))
     {
         this.SetHasDefaultStream(schemaType, true);
     }
     if (resourceType.HasEntityPropertyMappings)
     {
         MetadataProviderUtils.ConvertEntityPropertyMappings(this, resourceType, schemaType);
     }
     MetadataProviderUtils.ConvertCustomAnnotations(this, resourceType.CustomAnnotations, schemaType);
     return schemaType;
 }
Example #17
0
 private ResourceType(Type type, ResourceType baseType, string namespaceName, string name, bool isAbstract)
 {
     this.lockPropertiesLoad = new object();
     this.propertyInfosDeclaredOnThisType = new Dictionary<ResourceProperty, ResourcePropertyInfo>(ReferenceEqualityComparer<ResourceProperty>.Instance);
     this.schemaVersion = ~MetadataEdmSchemaVersion.Version1Dot0;
     WebUtil.CheckArgumentNull<Type>(type, "type");
     WebUtil.CheckArgumentNull<string>(name, "name");
     this.name = name;
     this.namespaceName = namespaceName ?? string.Empty;
     if ((name == "String") && object.ReferenceEquals(namespaceName, "Edm"))
     {
         this.fullName = "Edm.String";
     }
     else
     {
         this.fullName = string.IsNullOrEmpty(namespaceName) ? name : (namespaceName + "." + name);
     }
     this.type = type;
     this.abstractType = isAbstract;
     this.canReflectOnInstanceType = true;
     if (baseType != null)
     {
         this.baseType = baseType;
     }
 }
Example #18
0
 private IEnumerable<ODataProperty> GetAllEntityProperties(object customObject, ResourceType currentResourceType, Uri relativeUri)
 {
     List<ODataProperty> list = new List<ODataProperty>(currentResourceType.Properties.Count);
     foreach (ResourceProperty property in base.Provider.GetResourceSerializableProperties(base.CurrentContainer, currentResourceType))
     {
         if (property.TypeKind != ResourceTypeKind.EntityType)
         {
             list.Add(this.GetODataPropertyForEntityProperty(customObject, currentResourceType, relativeUri, property));
         }
     }
     if (currentResourceType.IsOpenType)
     {
         foreach (KeyValuePair<string, object> pair in base.Provider.GetOpenPropertyValues(customObject))
         {
             string key = pair.Key;
             if (string.IsNullOrEmpty(key))
             {
                 throw new DataServiceException(500, System.Data.Services.Strings.Syndication_InvalidOpenPropertyName(currentResourceType.FullName));
             }
             list.Add(this.GetODataPropertyForOpenProperty(key, pair.Value));
         }
         if (!currentResourceType.HasEntityPropertyMappings || (this.contentFormat == ODataFormat.VerboseJson))
         {
             return list;
         }
         HashSet<string> propertiesLookup = new HashSet<string>(from p in list select p.Name);
         foreach (EpmSourcePathSegment segment in from p in currentResourceType.EpmSourceTree.Root.SubProperties
             where !propertiesLookup.Contains(p.PropertyName)
             select p)
         {
             list.Add(this.GetODataPropertyForOpenProperty(segment.PropertyName, base.Provider.GetOpenPropertyValue(customObject, segment.PropertyName)));
         }
     }
     return list;
 }
 public IEnumerable<ResourceType> GetDerivedTypes(
     ResourceType resourceType
 )
 {
     // We don't support type inheritance yet
     yield break;
 } 
Example #20
0
        /// <summary>
        /// Converts the given value to the ATOM string representation
        /// and uses the writer to write it.
        /// </summary>
        /// <param name="writer">The writer to write the stringified value.</param>
        /// <param name="value">The value to be written.</param>
        /// <param name="expectedType">The expected resource type of the value or null if no metadata is available.</param>
        internal static void WritePrimitiveValue(XmlWriter writer, object value, ResourceType expectedType)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(value != null, "value != null");
            
            string result;
            bool preserveWhitespace;
            if (!TryConvertPrimitiveToString(value, out result, out preserveWhitespace))
            {
                throw new ODataException(Strings.AtomValueUtils_CannotConvertValueToAtomPrimitive(value.GetType().FullName));
            }

            if (expectedType != null)
            {
                ValidationUtils.ValidateIsExpectedPrimitiveType(value, expectedType);
            }

            if (preserveWhitespace)
            {
                writer.WriteAttributeString(
                    AtomConstants.XmlNamespacePrefix,
                    AtomConstants.XmlSpaceAttributeName,
                    AtomConstants.XmlNamespace,
                    AtomConstants.XmlPreserveSpaceAttributeValue);
            }

            writer.WriteString(result);
        }
Example #21
0
		public ReferenceTypeSerializer(ResourceType referringResourceType, ResourceProperty resourceProperty) : base(resourceProperty.ResourceType)
		{
			if (resourceProperty.ResourceType.ResourceTypeKind == ResourceTypeKind.EntityType)
			{
				object[] name = new object[1];
				name[0] = resourceProperty.Name;
				referringResourceType.ThrowIfNull("referringResourceType", new ParameterExtensions.MessageLoader(SerializerBase.GetReferringResourceTypeCannotNullMessage), name);
				DataContext currentContext = DataServiceController.Current.GetCurrentContext();
				if (currentContext != null)
				{
					PSEntityMetadata entityMetadata = currentContext.UserSchema.GetEntityMetadata(referringResourceType) as PSEntityMetadata;
					PSEntityMetadata.ReferenceSetCmdlets referenceSetCmdlet = null;
					if (!entityMetadata.CmdletsForReferenceSets.TryGetValue(resourceProperty.Name, out referenceSetCmdlet))
					{
						this.referencePropertyType = PSEntityMetadata.ReferenceSetCmdlets.ReferencePropertyType.Instance;
					}
					else
					{
						this.referencePropertyType = referenceSetCmdlet.PropertyType;
						return;
					}
				}
				return;
			}
			else
			{
				throw new ArgumentException("resourceType");
			}
		}
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="returnType">The return type of the function.</param>
        /// <param name="argumentTypes">The argument types for this function signature.</param>
        private BuiltInFunctionSignature(ResourceType returnType, params ResourceType[] argumentTypes)
            : base(argumentTypes)
        {
            Debug.Assert(returnType != null, "returnType != null");
            Debug.Assert(returnType.ResourceTypeKind == ResourceTypeKind.Primitive, "Only primitive values are supported as built-in function return types.");

            this.returnType = returnType;
        }
Example #23
0
		public ReferredEntityInstance(DSResource resource, UserContext userContext, ResourceType type, EntityMetadata metadata, string membershipId)
		{
			this.userContext = userContext;
			this.resourceType = type;
			this.metadata = metadata;
			this.membershipId = membershipId;
			this.resource = resource;
		}
 public ResourceAssociationSet GetResourceAssociationSet(
     ResourceSet resourceSet,
     ResourceType resourceType,
     ResourceProperty resourceProperty)
 {
     // resourceProperty.GetAnnotation().ResourceAssociationSet;
     return resourceProperty.CustomState as ResourceAssociationSet;
 } 
 internal EntityCollectionResourceType(ResourceType itemType) : base(GetInstanceType(itemType), ResourceTypeKind.EntityCollection, string.Empty, GetName(itemType))
 {
     if (itemType.ResourceTypeKind != ResourceTypeKind.EntityType)
     {
         throw new ArgumentException(Strings.ResourceType_CollectionItemCanBeOnlyEntity);
     }
     this.itemType = itemType;
 }
 public ServiceOperationParameter(string name, ResourceType parameterType) : base(name, parameterType)
 {
     WebUtil.CheckArgumentNull<ResourceType>(parameterType, "parameterType");
     if (parameterType.ResourceTypeKind != ResourceTypeKind.Primitive)
     {
         throw new ArgumentException(Strings.ServiceOperationParameter_TypeNotSupported(name, parameterType.FullName), "parameterType");
     }
 }
 public EntityPropertyMappingInfo(EntityPropertyMappingAttribute attribute, ResourceType definingType, ResourceType actualPropertyType, bool isEFProvider)
 {
     this.isEFProvider = isEFProvider;
     this.attribute = attribute;
     this.definingType = definingType;
     this.actualPropertyType = actualPropertyType;
     this.propertyValuePath = attribute.SourcePath.Split(new char[] { '/' });
     this.isSyndicationMapping = this.attribute.TargetSyndicationItem != SyndicationItemProperty.CustomProperty;
 }
Example #28
0
		internal void AddComplexCollectionProperty(ResourceType resourceType, string name, ResourceType complexType)
		{
			CollectionResourceType collectionResourceType = ResourceType.GetCollectionResourceType(complexType);
			ResourceProperty resourcePropertyWithDescription = new ResourcePropertyWithDescription(name, ResourcePropertyKind.Collection, collectionResourceType);
			resourcePropertyWithDescription.CanReflectOnInstanceTypeProperty = false;
			PropertyCustomState propertyCustomState = new PropertyCustomState();
			resourcePropertyWithDescription.CustomState = propertyCustomState;
			resourceType.AddProperty(resourcePropertyWithDescription);
		}
Example #29
0
		public GICommand(CommandType commandType, ExclusiveItemStore<PSRunspace, UserContext> runspaceStore, ResourceType entityType, UserContext userContext, string membershipId)
		{
			this.commandType = commandType;
			this.runspaceStore = runspaceStore;
			this.entityType = entityType;
			this.userContext = userContext;
			this.membershipId = membershipId;
			this.parameters = new Dictionary<string, object>();
		}
Example #30
0
		public EntityTypeSerializer(ResourceType resourceType, bool serializeKeyOnly = false) : base(resourceType)
		{
			object[] resourceTypeKind = new object[2];
			resourceTypeKind[0] = resourceType.ResourceTypeKind;
			resourceTypeKind[1] = ResourceTypeKind.EntityType;
			ExceptionHelpers.ThrowArgumentExceptionIf("resourceType", resourceType.ResourceTypeKind != ResourceTypeKind.EntityType, new ExceptionHelpers.MessageLoader(SerializerBase.GetInvalidArgMessage), resourceTypeKind);
			this.serializeKeyOnly = serializeKeyOnly;
			this.TestHookEntityMetadata = null;
		}
Example #31
0
        /// <summary>
        /// Writes an EPM element target.
        /// </summary>
        /// <param name="writer">The writer to write to.</param>
        /// <param name="targetSegment">The target segment describing the element to write.</param>
        /// <param name="epmValueCache">The entry properties value cache to use to access the properties.</param>
        /// <param name="resourceType">The resource type of the entry.</param>
        /// <param name="metadata">The metadata provider to use.</param>
        /// <param name="alreadyDeclaredPrefix">The name of the prefix if it was already declared.</param>
        private static void WriteElementEpm(
            XmlWriter writer, 
            EpmTargetPathSegment targetSegment, 
            EntryPropertiesValueCache epmValueCache, 
            ResourceType resourceType, 
            DataServiceMetadataProviderWrapper metadata,
            ref string alreadyDeclaredPrefix)
        {
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(targetSegment != null && !targetSegment.IsAttribute, "Only element target segments are supported by this method.");

            // If the prefix is null, the WCF DS will still write it as the default namespace, so we need it to be an empty string.
            string elementPrefix = targetSegment.SegmentNamespacePrefix ?? string.Empty;
            writer.WriteStartElement(elementPrefix, targetSegment.SegmentName, targetSegment.SegmentNamespaceUri);

            // Write out the declaration explicitly only if the prefix is not empty (just like the WCF DS does)
            if (elementPrefix.Length > 0)
            {
                WriteNamespaceDeclaration(writer, targetSegment, ref alreadyDeclaredPrefix);
            }

            // Serialize the sub segment attributes first
            foreach (EpmTargetPathSegment subSegment in targetSegment.SubSegments)
            {
                if (subSegment.IsAttribute)
                {
                    WriteAttributeEpm(writer, subSegment, epmValueCache, resourceType, metadata, ref alreadyDeclaredPrefix);
                }
            }

            if (targetSegment.HasContent)
            {
                Debug.Assert(!targetSegment.SubSegments.Any(subSegment => !subSegment.IsAttribute), "If the segment has a content, it must not have any element children.");

                string textPropertyValue = GetEntryPropertyValueAsText(targetSegment, epmValueCache, resourceType, metadata);

                // TODO: In V3 we should check for textPropertyValue == null and write out the m:null in that case.
                Debug.Assert(textPropertyValue != null, "Null property value should not get here, the GetEntryPropertyValueAsText should take care of that for now.");

                writer.WriteString(textPropertyValue);
            }
            else
            {
                // Serialize the sub segment elements now
                foreach (EpmTargetPathSegment subSegment in targetSegment.SubSegments)
                {
                    if (!subSegment.IsAttribute)
                    {
                        WriteElementEpm(writer, subSegment, epmValueCache, resourceType, metadata, ref alreadyDeclaredPrefix);
                    }
                }
            }

            // Close the element
            writer.WriteEndElement();
        }
Example #32
0
        public static TableResourceContainer GetUtilityTableResourceContainer(string accountName, bool PremiumTableAccountRequest)
        {
            System.Data.Services.Providers.ResourceType resourceType = new System.Data.Services.Providers.ResourceType(typeof(UtilityTable), ResourceTypeKind.EntityType, null, accountName, "Tables", false)
            {
                CanReflectOnInstanceType = false,
                IsOpenType = true
            };
            if (PremiumTableAccountRequest)
            {
                resourceType.AddProperty(TableResourceContainer.ProvisionedIOPSProperty);
                resourceType.AddProperty(TableResourceContainer.TableStatusProperty);
                resourceType.AddProperty(TableResourceContainer.RequestedIOPSProperty);
            }
            ResourceProperty utilityTableResourceProperty = new UtilityTableResourceProperty("TableName", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, System.Data.Services.Providers.ResourceType.GetPrimitiveResourceType(typeof(string)))
            {
                CanReflectOnInstanceTypeProperty = false
            };

            resourceType.AddProperty(utilityTableResourceProperty);
            TableResourceContainer tableResourceContainer = new TableResourceContainer("Tables", resourceType);

            tableResourceContainer.SetReadOnly();
            return(tableResourceContainer);
        }
Example #33
0
 public UtilityRowResourceProperty(string name, ResourcePropertyKind kind, System.Data.Services.Providers.ResourceType propertyResourceType, ResourceSet targetContainer) : base(name, kind, propertyResourceType)
 {
 }
Example #34
0
 /// <summary>
 /// Gets the ResourceAssociationSet instance when given the source association end.
 /// </summary>
 /// <param name="resourceSet">Resource set of the source association end.</param>
 /// <param name="resourceType">Resource type of the source association end.</param>
 /// <param name="resourceProperty">Resource property of the source association end.</param>
 /// <returns>ResourceAssociationSet instance.</returns>
 public abstract ResourceAssociationSet GetResourceAssociationSet(ResourceSet resourceSet, ResourceType resourceType, ResourceProperty resourceProperty);
Example #35
0
        /// <summary>
        /// Find the corresponding ResourceType for a given Type, primitive or not
        /// </summary>
        /// <param name="knownTypes">Non-primitive types to search</param>
        /// <param name="type">Type to look for</param>
        /// <param name="resourceType">Corresponding ResourceType, if found</param>
        /// <returns>True if type found, false otherwise</returns>
        protected static bool TryGetType(IDictionary <Type, ResourceType> knownTypes, Type type, out ResourceType resourceType)
        {
            Debug.Assert(knownTypes != null, "knownTypes != null");
            Debug.Assert(type != null, "type != null");

            resourceType = ResourceType.GetPrimitiveResourceType(type);

            if (resourceType == null)
            {
                knownTypes.TryGetValue(type, out resourceType);
            }

            return(resourceType != null);
        }
Example #36
0
        /// <summary>
        /// Returns the resource type of the given instance and validates that the instance returns a single resource.
        /// </summary>
        /// <param name="resource">clr instance of a resource.</param>
        /// <returns>resource type of the given instance.</returns>
        protected ResourceType GetSingleResource(object resource)
        {
            ResourceType resourceType = this.ProviderWrapper.GetResourceType(resource);

            return(resourceType);
        }
 public ServiceOperationParameter(string name, ResourceType parameterType)
 {
     Contract.Requires(!string.IsNullOrEmpty(name));
     Contract.Requires(parameterType.ResourceTypeKind == ((System.Data.Services.Providers.ResourceTypeKind)(2)));
 }
Example #38
0
 public TableResourceContainer(string name, System.Data.Services.Providers.ResourceType elementType) : base(name, elementType)
 {
 }
Example #39
0
 public UtilityRowResourceProperty(string name, ResourcePropertyKind kind, System.Data.Services.Providers.ResourceType propertyResourceType) : this(name, kind, propertyResourceType, null)
 {
 }
 public ResourceProperty(string name, ResourcePropertyKind kind, ResourceType propertyResourceType)
 {
     Contract.Requires(!string.IsNullOrEmpty(name));
     Contract.Requires(propertyResourceType != null);
 }
Example #41
0
        /// <summary>
        /// Adds a new <see cref="ServiceOperation"/> based on the specified <paramref name="method"/>
        /// instance.
        /// </summary>
        /// <param name="method">Method to expose as a service operation.</param>
        /// <param name="protocolMethod">Protocol (for example HTTP) method the service operation responds to.</param>
        private void AddServiceOperation(MethodInfo method, string protocolMethod)
        {
            Debug.Assert(method != null, "method != null");
            Debug.Assert(!method.IsAbstract, "!method.IsAbstract - if method is abstract, the type is abstract - already checked");

            // This method is only called for V1 providers, since in case of custom providers,
            // they are suppose to load the metadata themselves.
            if (this.metadata.ServiceOperations.ContainsKey(method.Name))
            {
                throw new InvalidOperationException(Strings.BaseServiceProvider_OverloadingNotSupported(this.Type, method));
            }

            bool hasSingleResult = SingleResultAttribute.MethodHasSingleResult(method);
            ServiceOperationResultKind resultKind;
            ResourceType resourceType = null;

            if (method.ReturnType == typeof(void))
            {
                resultKind = ServiceOperationResultKind.Void;
                this.UpdateEdmSchemaVersion(MetadataEdmSchemaVersion.Version1Dot1);
            }
            else
            {
                // Load the metadata of the resource type on the fly.
                // For Edm provider, it might not mean anything, but for reflection service provider, we need to
                // load the metadata of the type if its used only in service operation case
                Type resultType = null;
                if (WebUtil.IsPrimitiveType(method.ReturnType))
                {
                    resultKind   = ServiceOperationResultKind.DirectValue;
                    resultType   = method.ReturnType;
                    resourceType = ResourceType.GetPrimitiveResourceType(resultType);
                }
                else
                {
                    Type queryableElement = GetGenericInterfaceElementType(method.ReturnType, IQueryableTypeFilter);
                    if (queryableElement != null)
                    {
                        resultKind = hasSingleResult ?
                                     ServiceOperationResultKind.QueryWithSingleResult :
                                     ServiceOperationResultKind.QueryWithMultipleResults;
                        resultType = queryableElement;
                    }
                    else
                    {
                        Type enumerableElement = GetIEnumerableElement(method.ReturnType);
                        if (enumerableElement != null)
                        {
                            resultKind = ServiceOperationResultKind.Enumeration;
                            resultType = enumerableElement;
                        }
                        else
                        {
                            resultType = method.ReturnType;
                            resultKind = ServiceOperationResultKind.DirectValue;
                            this.UpdateEdmSchemaVersion(MetadataEdmSchemaVersion.Version1Dot1);
                        }
                    }

                    Debug.Assert(resultType != null, "resultType != null");
                    resourceType = ResourceType.GetPrimitiveResourceType(resultType);
                    if (resourceType == null)
                    {
                        resourceType = this.PopulateMetadataForType(resultType, this.TypeCache, this.ChildTypesCache, this.EntitySets.Values);
                    }
                }

                if (resourceType == null)
                {
                    throw new InvalidOperationException(Strings.BaseServiceProvider_UnsupportedReturnType(method, method.ReturnType));
                }

                if (resultKind == ServiceOperationResultKind.Enumeration && hasSingleResult)
                {
                    throw new InvalidOperationException(Strings.BaseServiceProvider_IEnumerableAlwaysMultiple(this.Type, method));
                }

                if (hasSingleResult ||
                    (!hasSingleResult &&
                     (resourceType.ResourceTypeKind == ResourceTypeKind.ComplexType ||
                      resourceType.ResourceTypeKind == ResourceTypeKind.Primitive)))
                {
                    this.UpdateEdmSchemaVersion(MetadataEdmSchemaVersion.Version1Dot1);
                }
            }

            ParameterInfo[]             parametersInfo = method.GetParameters();
            ServiceOperationParameter[] parameters     = new ServiceOperationParameter[parametersInfo.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                ParameterInfo parameterInfo = parametersInfo[i];
                if (parameterInfo.IsOut || parameterInfo.IsRetval)
                {
                    throw new InvalidOperationException(Strings.BaseServiceProvider_ParameterNotIn(method, parameterInfo));
                }

                ResourceType parameterType = ResourceType.GetPrimitiveResourceType(parameterInfo.ParameterType);
                if (parameterType == null)
                {
                    throw new InvalidOperationException(
                              Strings.BaseServiceProvider_ParameterTypeNotSupported(method, parameterInfo, parameterInfo.ParameterType));
                }

                string parameterName = parameterInfo.Name ?? "p" + i.ToString(CultureInfo.InvariantCulture);
                parameters[i] = new ServiceOperationParameter(parameterName, parameterType);
            }

            ResourceSet container = null;

            if (resourceType != null && resourceType.ResourceTypeKind == ResourceTypeKind.EntityType)
            {
                if (!this.TryFindAnyContainerForType(resourceType, out container))
                {
                    throw new InvalidOperationException(
                              Strings.BaseServiceProvider_ServiceOperationMissingSingleEntitySet(method, resourceType.FullName));
                }
            }

            ServiceOperation operation = new ServiceOperation(method.Name, resultKind, resourceType, container, protocolMethod, parameters);

            operation.CustomState = method;
            MimeTypeAttribute attribute = MimeTypeAttribute.GetMimeTypeAttribute(method);

            if (attribute != null)
            {
                operation.MimeType = attribute.MimeType;
            }

            this.metadata.ServiceOperations.Add(method.Name, operation);
        }