Exemplo n.º 1
0
        /// <summary>
        /// Adds the EntitySet information to an action or validates that it has an entitySet Path
        /// </summary>
        /// <param name="model">The model to fix up</param>
        public void Fixup(EntityModelSchema model)
        {
            foreach (Function f in model.Functions.Where(f => f.IsAction() && f.ReturnType != null))
            {
                var serviceOperationAnnotation = f.Annotations.OfType <ServiceOperationAnnotation>().Single();

                // If someone has set the entitySetPath or the entitySet name then we don't need to update anything
                if (serviceOperationAnnotation.EntitySetPath != null || serviceOperationAnnotation.EntitySetName != null)
                {
                    continue;
                }

                EntityDataType entityDataType     = f.ReturnType as EntityDataType;
                var            collectionDataType = f.ReturnType as CollectionDataType;
                if (collectionDataType != null)
                {
                    entityDataType = collectionDataType.ElementDataType as EntityDataType;
                }

                if (entityDataType != null)
                {
                    var possibleMatch = model.EntityContainers.Single().EntitySets.Where(es => entityDataType.Definition.IsKindOf(es.EntityType)).ToList();
                    ExceptionUtilities.Assert(possibleMatch.Count == 1, string.Format(CultureInfo.InvariantCulture, "Cannot resolve function '{0}' to one EntitySet, possible matches were '{1}'", f.Name, string.Join(",", possibleMatch.Select(es => es.Name))));
                    serviceOperationAnnotation.EntitySetName = possibleMatch.Single().Name;
                }
            }
        }
Exemplo n.º 2
0
        IEdmTypeReference IDataTypeVisitor <IEdmTypeReference> .Visit(EntityDataType dataType)
        {
            var entityTypeDefinition = (IEdmEntityType)this.currentEdmModel.FindType(dataType.Definition.FullName);

            return(entityTypeDefinition.ToTypeReference()
                   .Nullable(dataType.IsNullable));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Determines whether an action is bound to an action or not
        /// </summary>
        /// <param name="function">Action to be looked at</param>
        /// <returns>true if its bound to an open type</returns>
        public static bool IsActionBoundOnOpenType(this Function function)
        {
            bool isOpenType = false;

            ExceptionUtilities.Assert(function.IsAction(), "Expected function to be an action");
            var serviceOperationAnnotation = function.Annotations.OfType <ServiceOperationAnnotation>().SingleOrDefault();

            if (serviceOperationAnnotation != null)
            {
                if (serviceOperationAnnotation.BindingKind.IsBound())
                {
                    var            initialBindingDataType = function.Parameters.First().DataType;
                    EntityDataType entityDataType         = initialBindingDataType as EntityDataType;
                    var            collectionDataType     = initialBindingDataType as CollectionDataType;
                    if (collectionDataType != null)
                    {
                        entityDataType = collectionDataType.ElementDataType as EntityDataType;
                    }

                    if (entityDataType != null)
                    {
                        isOpenType = entityDataType.Definition.IsOpen;
                    }
                }
            }

            return(isOpenType);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Determines whether an entity set is expected to be returned from a function call
        /// </summary>
        /// <param name="function">the function being called</param>
        /// <param name="previousEntitySet">the binding entity set</param>
        /// <param name="returningEntitySet">the expected entity set, if appropriate</param>
        /// <returns>whether or not an entity set is expected</returns>
        public static bool TryGetExpectedActionEntitySet(this Function function, EntitySet previousEntitySet, out EntitySet returningEntitySet)
        {
            ExceptionUtilities.CheckArgumentNotNull(function, "function");

            ServiceOperationAnnotation serviceOperationAnnotation = function.Annotations.OfType <ServiceOperationAnnotation>().Single();
            EntityDataType             entityDataType             = function.ReturnType as EntityDataType;
            CollectionDataType         collectionDataType         = function.ReturnType as CollectionDataType;

            if (collectionDataType != null)
            {
                entityDataType = collectionDataType.ElementDataType as EntityDataType;
            }

            if (entityDataType != null)
            {
                if (serviceOperationAnnotation.EntitySetPath == null)
                {
                    returningEntitySet = function.Model.GetDefaultEntityContainer().EntitySets.Single(es => es.EntityType == entityDataType.Definition);
                }
                else
                {
                    string             navigationPropertyName = serviceOperationAnnotation.EntitySetPath.Substring(serviceOperationAnnotation.EntitySetPath.LastIndexOf('/') + 1);
                    NavigationProperty navigationProperty     = previousEntitySet.EntityType.AllNavigationProperties.Single(np => np.Name == navigationPropertyName);
                    var            associationSets            = function.Model.GetDefaultEntityContainer().AssociationSets.Where(a => a.AssociationType == navigationProperty.Association);
                    AssociationSet associationSet             = associationSets.Single(a => a.Ends.Any(e => e.EntitySet == previousEntitySet));
                    returningEntitySet = associationSet.Ends.Single(es => es.EntitySet != previousEntitySet).EntitySet;
                }

                return(true);
            }

            returningEntitySet = null;
            return(false);
        }
Exemplo n.º 5
0
            /// <summary>
            /// Visits the specified entity type.
            /// </summary>
            /// <param name="dataType">Data type.</param>
            /// <returns>the data type with all references resolved</returns>
            public DataType Visit(EntityDataType dataType)
            {
                EntityType resolved = this.parent.ResolveEntityTypeReference(this.model, dataType.Definition);

                return(DataTypes.EntityType
                       .Nullable(dataType.IsNullable)
                       .WithDefinition(resolved));
            }
Exemplo n.º 6
0
        private ICell BuildCell(object value, EntityDataType dataType)
        {
            if (value is DateTimeOffset)
            {
                value = ((DateTimeOffset)value).LocalDateTime;
            }

            if (value is DateTime)
            {
                switch (dataType)
                {
                case EntityDataType.Date:
                    value = ((DateTime)value).ToShortDateString();
                    break;

                case EntityDataType.DateTime:
                case EntityDataType.DateTimeTz:
                    value = ((DateTime)value).ToShortDateString() + " " + ((DateTime)value).ToLongTimeString();
                    break;
                }
            }
            if (value == null)
            {
                return(new Cell
                {
                    View = _defaultView
                });
            }

            if (value is string)
            {
                return(new Cell(value)
                {
                    View = _defaultView
                });
            }
            if (value is decimal)
            {
                return(new Cell(((decimal)value).ToString(CultureInfo.CurrentUICulture))
                {
                    View = _numberView
                });
            }
            if (value is long)
            {
                return(new Cell(((long)value).ToString(CultureInfo.CurrentUICulture))
                {
                    View = _numberView
                });
            }
            if (value is bool)
            {
                return(new SourceGrid.Cells.CheckBox(null, (bool)value));
            }

            throw new InvalidOperationException();
        }
        /// <summary>
        /// Sets the expected base entity type for the top-level entity set.
        /// </summary>
        /// <param name="entitySetInstance">The entity set instance to set the expected set for.</param>
        /// <param name="entitySet">The entity set the entities belong to.</param>
        /// <param name="baseEntityType">The base entity type to set as the expected base entity type.</param>
        /// <returns>The <paramref name="entitySetInstance"/> after its expected type was set.</returns>
        public static EntitySetInstance ExpectedEntityType(this EntitySetInstance entitySetInstance, EntitySet entitySet, EntityDataType baseEntityType)
        {
            ExceptionUtilities.CheckArgumentNotNull(entitySetInstance, "entitySetInstance");
            ExpectedTypeODataPayloadElementAnnotation annotation = AddExpectedTypeAnnotation(entitySetInstance);
            EntityDataType entityType = baseEntityType ?? (entitySet == null ? null : DataTypes.EntityType.WithDefinition(entitySet.EntityType));

            annotation.ExpectedType = entityType;
            annotation.EntitySet    = entitySet;
            return(entitySetInstance);
        }
Exemplo n.º 8
0
        public EntityForeign(string name, string comments, string linkTable, EntityDataType dataType, int?decimals, bool mandatory)
            : base(name, comments, dataType, decimals, mandatory)
        {
            if (linkTable == null)
            {
                throw new ArgumentNullException(nameof(linkTable));
            }

            LinkTable = linkTable;
        }
Exemplo n.º 9
0
            /// <summary>
            /// Visits the specified data type.
            /// </summary>
            /// <param name="dataType">The data type to visit.</param>
            /// <returns>The data types</returns>
            public IEnumerable <DataType> Visit(EntityDataType dataType)
            {
                var properties = dataType.Definition.AllProperties;

                if (dataType.Definition.IsOpen)
                {
                    properties = properties.Where(p => p.IsMetadataDeclaredProperty());
                }

                return(this.VisitProperties(properties).Concat(dataType));
            }
Exemplo n.º 10
0
        private object CoerceType(object value, EntityDataType type)
        {
            if (value == null)
            {
                return(null);
            }

            switch (type)
            {
            case EntityDataType.String:
                if (value is long)
                {
                    value = ((long)value).ToString(CultureInfo.InvariantCulture);
                }
                else if (value is decimal)
                {
                    value = ((decimal)value).ToString(CultureInfo.InvariantCulture);
                }
                break;

            case EntityDataType.Long:
            case EntityDataType.Int:
                if (value is string)
                {
                    value = long.Parse((string)value);
                }
                break;

            case EntityDataType.Bool:
                if (value is string)
                {
                    switch (((string)value).ToLower())
                    {
                    case "true":
                    case "1":
                    case "yes":
                        value = true;
                        break;

                    case "false":
                    case "0":
                    case "no":
                        value = false;
                        break;
                    }
                }
                break;
            }

            return(value);
        }
        /// <summary>
        /// Checks if the expected action descriptor in the case where the entity type is open and the property is open
        /// </summary>
        /// <param name="function">The function to check for name property collision</param>
        /// <param name="bindingEntityDataType">The bindingEntityDataType is the entity to check against</param>
        /// <param name="expectActionDescriptor">current value of the expected behavior</param>
        /// <returns>true is the action descriptor is expected in response payload</returns>
        public bool VerifyIfOpenType(Function function, EntityDataType bindingEntityDataType, bool expectActionDescriptor)
        {
            if ((expectActionDescriptor == false) && bindingEntityDataType.Definition.IsOpen)
            {
                // in open types, an action with a name collision will be returned in metadata
                var possibleNameCollision = bindingEntityDataType.Definition.AllProperties.Where(a => a.Name.Equals(function.Name)).FirstOrDefault();
                if (possibleNameCollision != null)
                {
                    // if property is not declared, then action descriptor will be present
                    expectActionDescriptor = !possibleNameCollision.IsMetadataDeclaredProperty();
                }
            }

            return(expectActionDescriptor);
        }
        /// <summary>
        /// Checks for a name collision between an action's name and a property's name
        /// </summary>
        /// <param name="function">The function to check for name property collision</param>
        /// <param name="bindingEntityDataType">The bindingEntityDataType is the entity to check against</param>
        /// <param name="actualInstanceEntityType">the entity type of the instance of the entity</param>
        /// <returns>a string representing the entity container's name</returns>
        public string BuildExpectedContainerName(Function function, EntityDataType bindingEntityDataType, EntityType actualInstanceEntityType)
        {
            string containerName = string.Empty;

            // check for open entity type on the function definition or on the actual entity itself
            if (bindingEntityDataType.Definition.IsOpen || actualInstanceEntityType.IsOpen)
            {
                containerName = string.Concat(function.Model.GetDefaultEntityContainer().Name, ".");
            }

            var foundNameCollision = bindingEntityDataType.Definition.AllProperties.Where(a => a.Name.Equals(function.Name)).FirstOrDefault();
            if (foundNameCollision != null && !bindingEntityDataType.Definition.IsOpen)
            {
                containerName = string.Concat(function.Model.GetDefaultEntityContainer().Name, ".");
            }

            return containerName;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Converts an entity data type to a entity type.
        /// </summary>
        /// <param name="entity">The entity data type to convert.</param>
        /// <returns>The corresponding entity type.</returns>
        private static IEdmEntityTypeReference GetEntityType(IEdmModel model, EntityDataType entityDataType)
        {
            Debug.Assert(entityDataType != null, "entityDataType != null");

            IEdmSchemaType edmType = model.FindType(entityDataType.Definition.FullName);

            ExceptionUtilities.Assert(
                edmType != null,
                "The expected entity type '{0}' was not found in the entity model for this test.",
                entityDataType.Definition.FullName);

            IEdmEntityType entityType = edmType as IEdmEntityType;

            ExceptionUtilities.Assert(
                entityType != null,
                "The expected entity type '{0}' is not defined as entity type in the test's metadata.",
                entityDataType.Definition.FullName);
            return((IEdmEntityTypeReference)entityType.ToTypeReference(entityDataType.IsNullable));
        }
        /// <summary>
        /// Checks for a name collision between an action's name and a property's name
        /// </summary>
        /// <param name="function">The function to check for name property collision</param>
        /// <param name="bindingEntityDataType">The bindingEntityDataType is the entity to check against</param>
        /// <param name="actualInstanceEntityType">the entity type of the instance of the entity</param>
        /// <returns>a string representing the entity container's name</returns>
        public string BuildExpectedContainerName(Function function, EntityDataType bindingEntityDataType, EntityType actualInstanceEntityType)
        {
            string containerName = string.Empty;

            // check for open entity type on the function definition or on the actual entity itself
            if (bindingEntityDataType.Definition.IsOpen || actualInstanceEntityType.IsOpen)
            {
                containerName = string.Concat(function.Model.GetDefaultEntityContainer().Name, ".");
            }

            var foundNameCollision = bindingEntityDataType.Definition.AllProperties.Where(a => a.Name.Equals(function.Name)).FirstOrDefault();

            if (foundNameCollision != null && !bindingEntityDataType.Definition.IsOpen)
            {
                containerName = string.Concat(function.Model.GetDefaultEntityContainer().Name, ".");
            }

            return(containerName);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Initializes static members of the DataTypes class.
 /// </summary>
 static DataTypes()
 {
     Integer = new IntegerDataType();
     Stream = new StreamDataType();
     String = new StringDataType();
     Boolean = new BooleanDataType();
     FixedPoint = new FixedPointDataType();
     FloatingPoint = new FloatingPointDataType();
     DateTime = new DateTimeDataType();
     Binary = new BinaryDataType();
     Guid = new GuidDataType();
     TimeOfDay = new TimeOfDayDataType();
     ComplexType = new ComplexDataType();
     EntityType = new EntityDataType();
     CollectionType = new CollectionDataType();
     ReferenceType = new ReferenceDataType();
     RowType = new RowDataType();
     EnumType = new EnumDataType();
     Spatial = new SpatialDataType();
 }
        /// <summary>
        /// Find out whether to expect action descriptor given expand and select segments.
        /// </summary>
        /// <param name="selectSegmentList">The select segments</param>
        /// <param name="expandSegmentList">The expand segments</param>
        /// <param name="action">The action</param>
        /// <returns>Whether to expect action descriptor</returns>
        private bool FunctionMatchWithExpandSegmentList(List <ODataUriSegment> selectSegmentList, List <ODataUriSegment> expandSegmentList, Function action)
        {
            // check if $select path and $expand path matchs
            int index = 0;
            NavigationSegment expandNavSegment = null;

            foreach (var expandSegment in expandSegmentList)
            {
                expandNavSegment = expandSegment as NavigationSegment;
                ExceptionUtilities.CheckArgumentNotNull(expandNavSegment, "Unexpected expand segment.");
                NavigationSegment selectNavSegment = selectSegmentList[index] as NavigationSegment;
                if (selectNavSegment == null || !expandNavSegment.NavigationProperty.Equals(selectNavSegment.NavigationProperty))
                {
                    return(false);
                }

                index++;
            }

            // check if the action binding type matches with last segment of $expand path
            EntityDataType bindingEntityDataType = action.Parameters.First().DataType as EntityDataType;

            ExceptionUtilities.CheckArgumentNotNull(bindingEntityDataType, "Unexpected feed-bound action.");
            EntityType bindingEntityType = bindingEntityDataType.Definition;

            if (bindingEntityType != expandNavSegment.NavigationProperty.ToAssociationEnd.EntityType)
            {
                return(false);
            }

            // expect action descriptor (return true) for $expand=Rating if: $select=Rating, $select=Rating/ActionName, $Select=Rating/Container.*
            if (selectSegmentList.Count == expandSegmentList.Count + 1)
            {
                ODataUriSegment lastSelectSegment = selectSegmentList.Last();
                return(this.FuctionMatchWithSelectFunctionSegment(action, lastSelectSegment) || this.IsSelectAllFunctionSegment(lastSelectSegment));
            }

            return(true);
        }
Exemplo n.º 17
0
        private void AppendList(StringBuilder sb, object value, EntityDataType dataType)
        {
            if (value == null)
            {
                return;
            }

            var enumerable = value as IEnumerable;

            if (enumerable == null)
            {
                throw new ApiException("Expected parameter to the IN filter to be a collection");
            }

            bool hadOne = false;

            foreach (object element in enumerable)
            {
                string serialized = ApiUtils.Serialize(element, dataType) ?? "";

                if (serialized.IndexOf('\'') != -1 || serialized.IndexOf(',') != -1)
                {
                    serialized = "'" + serialized.Replace("'", "''") + "'";
                }

                if (hadOne)
                {
                    sb.Append(',');
                }
                else
                {
                    hadOne = true;
                }

                sb.Append(Uri.EscapeDataString(serialized));
            }
        }
        private void VerifyEntityOperations(ODataRequest request, ODataResponse response, List <EntityInstance> entities, bool isTopLevelElement)
        {
            foreach (var entity in entities.Where(et => !et.IsNull))
            {
                var instanceEntityType = this.model.EntityTypes.Single(et => et.FullName == entity.FullTypeName);

                // look at each action/function bound to the same type as entity, ensure it is advertised correctly
                int numberOfDescriptorsVerified = 0;
                var functionsWithBindings       = this.model.Functions.Where(f => f.Annotations.OfType <ServiceOperationAnnotation>().Any(s => s.BindingKind.IsBound())).ToArray();
                foreach (Function function in functionsWithBindings)
                {
                    ServiceOperationAnnotation serviceOperationAnnotation = function.Annotations.OfType <ServiceOperationAnnotation>().SingleOrDefault();
                    if (serviceOperationAnnotation != null)
                    {
                        DataType       bindingParameterDataType = function.Parameters[0].DataType;
                        EntityDataType bindingEntityDataType    = bindingParameterDataType as EntityDataType;
                        if (bindingEntityDataType == null)
                        {
                            ExceptionUtilities.Assert(bindingParameterDataType is CollectionDataType, "Unsupported binding parameter data type.");
                            ExceptionUtilities.Assert(entity.ServiceOperationDescriptors.SingleOrDefault(d => d.Title == function.Name) == null, "Unexpected feed-bound action advertised in entry.");
                            continue;
                        }

                        // Check the base type as well as derived types
                        bool beginServiceOpMatchMatching = bindingEntityDataType.Definition.Model.EntityTypes.Where(t => t.IsKindOf(bindingEntityDataType.Definition)).Where(a => a.FullName.Equals(entity.FullTypeName)).Any();

                        if (beginServiceOpMatchMatching)
                        {
                            // find ServiceOperationDescriptor that matches the function
                            ServiceOperationDescriptor descriptor = entity.ServiceOperationDescriptors.SingleOrDefault(d => ExtractSimpleActionName(d.Title) == function.Name);
                            bool expectActionDescriptor           = true;
                            if (request.Uri.SelectSegments.Count > 0)
                            {
                                expectActionDescriptor = this.ExpectActionWithProjection(request.Uri, function, isTopLevelElement);
                            }

                            if (descriptor == null)
                            {
                                ExceptionUtilities.Assert(!expectActionDescriptor, "Missing service operation descriptor for " + function.Name);
                            }
                            else
                            {
                                expectActionDescriptor = this.VerifyIfOpenType(function, bindingEntityDataType, expectActionDescriptor);

                                ExceptionUtilities.Assert(expectActionDescriptor, "Unexpected service operation descriptor for " + function.Name);

                                // JSONLight will always add the type segment if its a derived type now
                                string derivedTypeFullName = string.Empty;
                                var    acceptHeaderValue   = response.Headers[HttpHeaders.ContentType];
                                if (bindingEntityDataType.Definition.BaseType != null)
                                {
                                    derivedTypeFullName = string.Concat(bindingEntityDataType.Definition.FullName, "/");
                                }

                                if (bindingEntityDataType.Definition.FullName != instanceEntityType.FullName)
                                {
                                    derivedTypeFullName = string.Concat(instanceEntityType.FullName, "/");
                                }

                                // check if there is a possible name collision between a property and an action, if so add the Entity Container name to the expected result
                                string containerName = this.BuildExpectedContainerName(function, bindingEntityDataType, instanceEntityType);
                                string expectedMetadataContainerName = string.Concat(function.Model.GetDefaultEntityContainer().Name, ".");

                                // When running in JSONLight descriptor returns full name, not partial
                                if (IsJsonLightResponse(acceptHeaderValue))
                                {
                                    containerName = string.Concat(function.Model.GetDefaultEntityContainer().Name, ".");

                                    expectedMetadataContainerName = containerName;
                                }

                                string expectedTarget   = string.Concat(entity.Id.TrimEnd('/'), "/", derivedTypeFullName, containerName, function.Name);
                                string expectedMetadata = string.Concat(((ServiceRootSegment)request.Uri.RootSegment).Uri.AbsoluteUri.TrimEnd('/'), "/", Endpoints.Metadata, "#", expectedMetadataContainerName, function.Name);

                                this.Assert(descriptor.Target == expectedTarget, "Expected target " + expectedTarget + " Actual " + descriptor.Target, request, response);
                                this.Assert(descriptor.Metadata == expectedMetadata, "Expected Metadata " + expectedMetadata + " Actual " + descriptor.Metadata, request, response);

                                // verify IsAction flag
                                this.Assert(serviceOperationAnnotation.IsAction == descriptor.IsAction, "Expected action " + serviceOperationAnnotation.IsAction + " Actual " + descriptor.IsAction, request, response);
                                numberOfDescriptorsVerified++;
                            }
                        }
                    }
                }

                this.Assert(numberOfDescriptorsVerified == entity.ServiceOperationDescriptors.Count, "Wrong number of action/function.", request, response);
                this.VerifyExpandedEntityOperations(entity, request, response);
            }
        }
Exemplo n.º 19
0
 private void Append(StringBuilder sb, object value, EntityDataType dataType)
 {
     sb.Append(Uri.EscapeDataString(ApiUtils.Serialize(value, dataType)));
 }
Exemplo n.º 20
0
 /// <summary>
 /// Visits the specified data type.
 /// </summary>
 /// <param name="dataType">The data type.</param>
 /// <returns>Name of the entity type.</returns>
 string IDataTypeVisitor <string> .Visit(EntityDataType dataType)
 {
     return(this.parent.GetFullyQualifiedName(dataType.Definition));
 }
 /// <summary>
 /// Resolves the specified type into its type reference.
 /// </summary>
 /// <param name="dataType">The data type.</param>
 /// <returns>CodeTypeReference that should be used in code to refer to the type.</returns>
 public CodeTypeReference Visit(EntityDataType dataType)
 {
     return(new CodeTypeReference(dataType.Definition.FullName));
 }
Exemplo n.º 22
0
 /// <summary>
 /// Gets the short qualified Edm name
 /// </summary>
 /// <param name="dataType">The data type.</param>
 /// <returns>short qualified Edm name</returns>
 public string Visit(EntityDataType dataType)
 {
     return(dataType.Definition.Name);
 }
Exemplo n.º 23
0
        public static string Serialize(object value, EntityDataType dataType)
        {
            if (value == null)
            {
                return("");
            }
            if (value is string)
            {
                return((string)value);
            }
            if (value is DateTime)
            {
                switch (dataType)
                {
                case EntityDataType.Date:
                    return(PrintDate((DateTime)value));

                case EntityDataType.DateTime:
                    return(PrintDateTime((DateTime)value));

                case EntityDataType.DateTimeTz:
                    return(PrintDateTimeOffset((DateTime)value));

                default:
                    throw new ArgumentOutOfRangeException(nameof(value));
                }
            }
            if (value is DateTimeOffset)
            {
                switch (dataType)
                {
                case EntityDataType.Date:
                    return(PrintDate((DateTimeOffset)value));

                case EntityDataType.DateTime:
                    return(PrintDateTime((DateTimeOffset)value));

                case EntityDataType.DateTimeTz:
                    return(PrintDateTimeOffset((DateTimeOffset)value));

                default:
                    throw new ArgumentOutOfRangeException(nameof(value));
                }
            }
            if (value is int)
            {
                return(((int)value).ToString(CultureInfo.InvariantCulture));
            }
            if (value is long)
            {
                return(((long)value).ToString(CultureInfo.InvariantCulture));
            }
            if (value is float)
            {
                return(((float)value).ToString(CultureInfo.InvariantCulture));
            }
            if (value is double)
            {
                return(((double)value).ToString(CultureInfo.InvariantCulture));
            }
            if (value is decimal)
            {
                return(((decimal)value).ToString(CultureInfo.InvariantCulture));
            }

            throw new ArgumentOutOfRangeException(nameof(value));
        }
Exemplo n.º 24
0
 public EntityCalculatedField(string name, string comments, EntityDataType dataType, int?decimals)
     : base(name, comments, dataType, decimals)
 {
 }
        /// <summary>
        /// Checks if the expected action descriptor in the case where the entity type is open and the property is open
        /// </summary>
        /// <param name="function">The function to check for name property collision</param>
        /// <param name="bindingEntityDataType">The bindingEntityDataType is the entity to check against</param>
        /// <param name="expectActionDescriptor">current value of the expected behavior</param>
        /// <returns>true is the action descriptor is expected in response payload</returns>
        public bool VerifyIfOpenType(Function function, EntityDataType bindingEntityDataType, bool expectActionDescriptor)
        {
            if ((expectActionDescriptor == false) && bindingEntityDataType.Definition.IsOpen)
            {
                // in open types, an action with a name collision will be returned in metadata
                var possibleNameCollision = bindingEntityDataType.Definition.AllProperties.Where(a => a.Name.Equals(function.Name)).FirstOrDefault();
                if (possibleNameCollision != null)
                {
                    // if property is not declared, then action descriptor will be present
                    expectActionDescriptor = !possibleNameCollision.IsMetadataDeclaredProperty();
                }
            }

            return expectActionDescriptor;
        }
Exemplo n.º 26
0
 /// <summary>
 /// Visits the specified entity type.
 /// </summary>
 /// <param name="dataType">Data type.</param>
 /// <returns>the corresponding default query type.</returns>
 public QueryType Visit(EntityDataType dataType)
 {
     return(this.parent.GetDefaultQueryTypeForEntity(dataType));
 }
Exemplo n.º 27
0
        private QueryEntityType GetDefaultQueryTypeForEntity(EntityDataType entityDataType)
        {
            EntityType entityType = entityDataType.Definition;

            return(this.defaultQueryEntityTypes[entityType]);
        }
Exemplo n.º 28
0
 protected EntityTypedField(string name, string comments, EntityDataType dataType, int?decimals)
     : base(name, comments)
 {
     DataType = dataType;
     Decimals = decimals;
 }
Exemplo n.º 29
0
        /// <summary>
        /// Converts an entity data type to a entity type.
        /// </summary>
        /// <param name="entity">The entity data type to convert.</param>
        /// <returns>The corresponding entity type.</returns>
        private static IEdmEntityTypeReference GetEntityType(IEdmModel model, EntityDataType entityDataType)
        {
            Debug.Assert(entityDataType != null, "entityDataType != null");

            IEdmSchemaType edmType = model.FindType(entityDataType.Definition.FullName);
            ExceptionUtilities.Assert(
                edmType != null,
                "The expected entity type '{0}' was not found in the entity model for this test.",
                entityDataType.Definition.FullName);

            IEdmEntityType entityType = edmType as IEdmEntityType;
            ExceptionUtilities.Assert(
                entityType != null,
                "The expected entity type '{0}' is not defined as entity type in the test's metadata.",
                entityDataType.Definition.FullName);
            return (IEdmEntityTypeReference)entityType.ToTypeReference(entityDataType.IsNullable);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Visits the specified entity type.
 /// </summary>
 /// <param name="dataType">Data type.</param>
 /// <returns>A clone of the specified <see cref="DataType"/>.</returns>
 public DataType Visit(EntityDataType dataType)
 {
     return(new EntityDataType().WithDefinition(new EntityTypeReference(dataType.Definition.NamespaceName, dataType.Definition.Name)));
 }
Exemplo n.º 31
0
 /// <summary>
 /// Visits an entity data type
 /// </summary>
 /// <param name="dataType">The data type to visit</param>
 /// <returns>The backing type for the data type</returns>
 public CodeTypeReference Visit(EntityDataType dataType)
 {
     return(this.ResolveClrTypeReference(dataType.Definition));
 }
 /// <summary>
 /// Sets the expected base entity type for the top-level entity set.
 /// </summary>
 /// <param name="entitySetInstance">The entity set instance to set the expected set for.</param>
 /// <param name="baseEntityType">The base entity type to set as the expected base entity type.</param>
 /// <returns>The <paramref name="entitySetInstance"/> after its expected type was set.</returns>
 public static EntitySetInstance ExpectedEntityType(this EntitySetInstance entitySetInstance, EntityDataType baseEntityType)
 {
     ExceptionUtilities.CheckArgumentNotNull(entitySetInstance, "entitySetInstance");
     return(entitySetInstance.ExpectedEntityType(/*entitySet*/ null, baseEntityType));
 }
Exemplo n.º 33
0
        public static IEdmModel BuildTestMetadata(IEntityModelPrimitiveTypeResolver primitiveTypeResolver, IDataServiceProviderFactory provider)
        {
            var schema = new EntityModelSchema()
            {
                new ComplexType("TestNS", "Address")
                {
                    new MemberProperty("City", DataTypes.String.Nullable()),
                    new MemberProperty("Zip", DataTypes.Integer),
                    new ClrTypeAnnotation(typeof(Address))
                },
                new EntityType("TestNS", "Customer")
                {
                    new MemberProperty("ID", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Name", DataTypes.String.Nullable()),
                    new MemberProperty("Emails", DataTypes.CollectionType.WithElementDataType(DataTypes.String.Nullable())),
                    new MemberProperty("Address", DataTypes.ComplexType.WithName("TestNS", "Address")),
                    new ClrTypeAnnotation(typeof(Customer))
                },
                new EntityType("TestNS", "MultiKey")
                {
                    new MemberProperty("KeyB", DataTypes.FloatingPoint)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("KeyA", DataTypes.String.Nullable())
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Keya", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("NonKey", DataTypes.String.Nullable()),
                    new ClrTypeAnnotation(typeof(MultiKey))
                },
                new EntityType("TestNS", "TypeWithPrimitiveProperties")
                {
                    new MemberProperty("ID", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("StringProperty", DataTypes.String.Nullable()),
                    new MemberProperty("BoolProperty", DataTypes.Boolean),
                    new MemberProperty("NullableBoolProperty", DataTypes.Boolean.Nullable()),
                    new MemberProperty("ByteProperty", EdmDataTypes.Byte),
                    new MemberProperty("NullableByteProperty", EdmDataTypes.Byte.Nullable()),
                    new MemberProperty("DateTimeProperty", DataTypes.DateTime.WithTimeZoneOffset(true)),
                    new MemberProperty("NullableDateTimeProperty", DataTypes.DateTime.WithTimeZoneOffset(true).Nullable()),
                    new MemberProperty("DecimalProperty", EdmDataTypes.Decimal()),
                    new MemberProperty("NullableDecimalProperty", EdmDataTypes.Decimal().Nullable()),
                    new MemberProperty("DoubleProperty", EdmDataTypes.Double),
                    new MemberProperty("NullableDoubleProperty", EdmDataTypes.Double.Nullable()),
                    new MemberProperty("GuidProperty", DataTypes.Guid),
                    new MemberProperty("NullableGuidProperty", DataTypes.Guid.Nullable()),
                    new MemberProperty("Int16Property", EdmDataTypes.Int16),
                    new MemberProperty("NullableInt16Property", EdmDataTypes.Int16.Nullable()),
                    new MemberProperty("Int32Property", DataTypes.Integer),
                    new MemberProperty("NullableInt32Property", DataTypes.Integer.Nullable()),
                    new MemberProperty("Int64Property", EdmDataTypes.Int64),
                    new MemberProperty("NullableInt64Property", EdmDataTypes.Int64.Nullable()),
                    new MemberProperty("SByteProperty", EdmDataTypes.SByte),
                    new MemberProperty("NullableSByteProperty", EdmDataTypes.SByte.Nullable()),
                    new MemberProperty("SingleProperty", EdmDataTypes.Single),
                    new MemberProperty("NullableSingleProperty", EdmDataTypes.Single.Nullable()),
                    new MemberProperty("BinaryProperty", DataTypes.Binary.Nullable()),
                    new ClrTypeAnnotation(typeof(TypeWithPrimitiveProperties))
                }
            };

            List <FunctionParameter> defaultParameters = new List <FunctionParameter>()
            {
                new FunctionParameter("soParam", DataTypes.Integer)
            };

            EntitySet       customersSet = new EntitySet("Customers", "Customer");
            EntityContainer container    = new EntityContainer("BinderTestMetadata")
            {
                customersSet,
                new EntitySet("MultiKeys", "MultiKey"),
                new EntitySet("TypesWithPrimitiveProperties", "TypeWithPrimitiveProperties")
            };

            schema.Add(container);

            EntityDataType customerType = DataTypes.EntityType.WithName("TestNS", "Customer");
            EntityDataType multiKeyType = DataTypes.EntityType.WithName("TestNS", "MultiKey");
            EntityDataType entityTypeWithPrimitiveProperties = DataTypes.EntityType.WithName("TestNS", "TypeWithPrimitiveProperties");

            ComplexDataType addressType = DataTypes.ComplexType.WithName("TestNS", "Address");

            addressType.Definition.Add(new ClrTypeAnnotation(typeof(Address)));
            customerType.Definition.Add(new ClrTypeAnnotation(typeof(Customer)));
            multiKeyType.Definition.Add(new ClrTypeAnnotation(typeof(MultiKey)));
            entityTypeWithPrimitiveProperties.Definition.Add(new ClrTypeAnnotation(typeof(TypeWithPrimitiveProperties)));

            //container.Add(CreateServiceOperation("VoidServiceOperation", defaultParameters, null, ODataServiceOperationResultKind.Void));
            //container.Add(CreateServiceOperation("DirectValuePrimitiveServiceOperation", defaultParameters, DataTypes.Integer, ODataServiceOperationResultKind.DirectValue));
            //container.Add(CreateServiceOperation("DirectValueComplexServiceOperation", defaultParameters, addressType, ODataServiceOperationResultKind.DirectValue));
            //container.Add(CreateServiceOperation("DirectValueEntityServiceOperation", defaultParameters, customerType, customersSet, ODataServiceOperationResultKind.DirectValue));

            //container.Add(CreateServiceOperation("EnumerationPrimitiveServiceOperation", defaultParameters, DataTypes.CollectionType.WithElementDataType(DataTypes.Integer), ODataServiceOperationResultKind.Enumeration));
            //container.Add(CreateServiceOperation("EnumerationComplexServiceOperation", defaultParameters, addressType, ODataServiceOperationResultKind.Enumeration));
            //container.Add(CreateServiceOperation("EnumerationEntityServiceOperation", defaultParameters, DataTypes.CollectionOfEntities(customerType.Definition), customersSet, ODataServiceOperationResultKind.Enumeration));

            //container.Add(CreateServiceOperation("QuerySinglePrimitiveServiceOperation", defaultParameters, DataTypes.Integer, ODataServiceOperationResultKind.QueryWithSingleResult));
            //container.Add(CreateServiceOperation("QuerySingleComplexServiceOperation", defaultParameters, addressType, ODataServiceOperationResultKind.QueryWithSingleResult));
            //container.Add(CreateServiceOperation("QuerySingleEntityServiceOperation", defaultParameters, customerType, customersSet, ODataServiceOperationResultKind.QueryWithSingleResult));

            //container.Add(CreateServiceOperation("QueryMultiplePrimitiveServiceOperation", defaultParameters, DataTypes.Integer, ODataServiceOperationResultKind.QueryWithMultipleResults));
            //container.Add(CreateServiceOperation("QueryMultipleComplexServiceOperation", defaultParameters, addressType, ODataServiceOperationResultKind.QueryWithMultipleResults));
            //container.Add(CreateServiceOperation("QueryMultipleEntityServiceOperation", defaultParameters, DataTypes.CollectionOfEntities(customerType.Definition), customersSet, ODataServiceOperationResultKind.QueryWithMultipleResults));

            //container.Add(CreateServiceOperation("ServiceOperationWithNoParameters", new List<FunctionParameter>(), DataTypes.CollectionOfEntities(customerType.Definition), customersSet, ODataServiceOperationResultKind.QueryWithMultipleResults));
            //container.Add(CreateServiceOperation(
            //                        "ServiceOperationWithMultipleParameters",
            //                         new List<FunctionParameter>()
            //                         {
            //                             new FunctionParameter("paramInt", DataTypes.Integer),
            //                             new FunctionParameter("paramString", DataTypes.String.Nullable()),
            //                             new FunctionParameter("paramNullableBool", DataTypes.Boolean.Nullable())
            //                         },
            //                         DataTypes.CollectionOfEntities(customerType.Definition),
            //                         customersSet,
            //                         ODataServiceOperationResultKind.QueryWithMultipleResults));

            new ApplyDefaultNamespaceFixup("TestNS").Fixup(schema);
            new ResolveReferencesFixup().Fixup(schema);
            primitiveTypeResolver.ResolveProviderTypes(schema, new EdmDataTypeResolver());

            return(provider.CreateMetadataProvider(schema));
        }
 public IndexedProperty GetIndexedProperty(string name, EntityDataType entityDataType)
 {
     return new IndexedProperty {PropertyName = name, DataType = entityDataType.ToString()};
 }
Exemplo n.º 35
0
        /// <summary>
        /// Resolves the specified entity model schema type and returns the Edm model type for it.
        /// </summary>
        /// <param name="model">The model to get the type from.</param>
        /// <param name="schemaType">The entity model schema type to resolve.</param>
        /// <returns>The resolved type for the specified <paramref name="schemaType"/>.</returns>
        public static IEdmTypeReference ResolveEntityModelSchemaType(IEdmModel model, DataType schemaType)
        {
            if (schemaType == null)
            {
                return(null);
            }

            PrimitiveDataType primitiveDataType = schemaType as PrimitiveDataType;

            if (primitiveDataType != null)
            {
                return(GetPrimitiveTypeReference(primitiveDataType));
            }

            if (model == null)
            {
                return(null);
            }

            EntityDataType entityDataType = schemaType as EntityDataType;

            if (entityDataType != null)
            {
                IEdmNamedElement edmType = model.FindType(entityDataType.Definition.FullName);
                ExceptionUtilities.Assert(
                    edmType != null,
                    "The expected entity type '{0}' was not found in the entity model for this test.",
                    entityDataType.Definition.FullName);

                IEdmEntityType entityType = edmType as IEdmEntityType;
                ExceptionUtilities.Assert(
                    entityType != null,
                    "The expected entity type '{0}' is not defined as entity type in the test's metadata.",
                    entityDataType.Definition.FullName);
                return(entityType.ToTypeReference());
            }

            ComplexDataType complexDataType = schemaType as ComplexDataType;

            if (complexDataType != null)
            {
                return(GetComplexType(model, complexDataType));
            }

            CollectionDataType collectionDataType = schemaType as CollectionDataType;

            if (collectionDataType != null)
            {
                DataType          collectionElementType = collectionDataType.ElementDataType;
                PrimitiveDataType primitiveElementType  = collectionElementType as PrimitiveDataType;
                if (primitiveElementType != null)
                {
                    IEdmPrimitiveTypeReference primitiveElementTypeReference = GetPrimitiveTypeReference(primitiveElementType);
                    return(primitiveElementTypeReference.ToCollectionTypeReference());
                }

                ComplexDataType complexElementType = collectionElementType as ComplexDataType;
                if (complexElementType != null)
                {
                    IEdmComplexTypeReference complexElementTypeReference = GetComplexType(model, complexElementType);
                    return(complexElementTypeReference.ToCollectionTypeReference());
                }

                EntityDataType entityElementType = collectionElementType as EntityDataType;
                if (entityElementType != null)
                {
                    IEdmEntityTypeReference entityElementTypeReference = GetEntityType(model, entityElementType);
                    return(entityElementTypeReference.ToCollectionTypeReference());
                }

                throw new NotSupportedException("Collection types only support primitive, complex, and entity element types.");
            }

            StreamDataType streamType = schemaType as StreamDataType;

            if (streamType != null)
            {
                Type systemType = streamType.GetFacet <PrimitiveClrTypeFacet>().Value;
                ExceptionUtilities.Assert(systemType == typeof(Stream), "Expected the system type 'System.IO.Stream' for a stream reference property.");
                return(MetadataUtils.GetPrimitiveTypeReference(systemType));
            }

            throw new NotImplementedException("Unrecognized schema type " + schemaType.GetType().Name + ".");
        }