Ejemplo n.º 1
0
        /// <summary>
        /// Adds stream properties to structural value.
        /// </summary>
        /// <param name="entity">The target structural value.</param>
        /// <param name="payload">The payload with the entity values.</param>
        /// <param name="xmlBaseAnnotations">The xml base annotations ancestors and local element</param>
        private void AddStreamProperties(QueryStructuralValue entity, EntityInstance payload, IEnumerable <XmlBaseAnnotation> xmlBaseAnnotations)
        {
            ExceptionUtilities.CheckArgumentNotNull(entity, "entity");
            ExceptionUtilities.CheckArgumentNotNull(payload, "payload");

            var xmlBaseAnnotationsList = xmlBaseAnnotations.ToList();

            if (payload.IsMediaLinkEntry())
            {
                string editLink = this.NormalizeLinkFromPayload(payload.StreamEditLink, xmlBaseAnnotationsList);
                string selfLink = this.NormalizeLinkFromPayload(payload.StreamSourceLink, xmlBaseAnnotationsList);

                entity.SetStreamValue(null, payload.StreamContentType, payload.StreamETag, editLink, selfLink, new byte[0]);
            }

            foreach (var stream in payload.Properties.OfType <NamedStreamInstance>())
            {
                string contentType = stream.SourceLinkContentType;
                if (contentType == null)
                {
                    contentType = stream.EditLinkContentType;
                }

                string editLink = this.NormalizeLinkFromPayload(stream.EditLink, xmlBaseAnnotationsList);
                string selfLink = this.NormalizeLinkFromPayload(stream.SourceLink, xmlBaseAnnotationsList);

                entity.SetStreamValue(stream.Name, contentType, stream.ETag, editLink, selfLink, new byte[0]);
            }
        }
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            var epmTrees = payloadElement.Annotations.OfType<XmlTreeAnnotation>().ToList();

            if (epmTrees.Count > 0)
            {
                var entityType = payloadElement.Annotations
                    .OfType<DataTypeAnnotation>()
                    .Select(d => d.DataType)
                    .OfType<EntityDataType>()
                    .Select(d => d.Definition)
                    .SingleOrDefault();
                ExceptionUtilities.CheckObjectNotNull(entityType, "Could not get entity type from payload annotations");
            }

            // do EPM first so that in-content values win
            base.Visit(payloadElement);

            if (epmTrees.Count > 0)
            {
                // When deep EPM is involved, we can generate named values for mapped properties of a complex
                // property that has null value. So, trim any child paths of null values.
                var nullValueList = this.valuesByName.Where(v => v.Value.Value == null).ToList();
                foreach (var nullValue in nullValueList)
                {
                    var nullChildPaths = this.orderedNames.Where(n => n.StartsWith(nullValue.Key + ".", StringComparison.OrdinalIgnoreCase)).ToList();
                    foreach (var nullChildPath in nullChildPaths)
                    {
                        this.RemoveValue(nullChildPath);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public override Object Evaluate(EntityInstance entityInstance, object[] objects)
        {
            string        text   = (string)objects[0];
            StringBuilder result = new StringBuilder();

            bool capitalizeNext = true;

            for (int i = 0; i < text.Length; i++)
            {
                char c = text[i];
                if (char.IsLetter(c) && capitalizeNext)
                {
                    result.Append(char.ToUpper(c));
                    capitalizeNext = false;
                }
                else
                {
                    result.Append(c);
                    if (char.IsWhiteSpace(c))
                    {
                        capitalizeNext = true;
                    }
                }
            }

            return(result.ToString());
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Matches an actual entity instance of a person against.
 /// </summary>
 /// <param name="actualEntityInstance">The actual entity instance to verify.</param>
 /// <param name="expectedId">The expected id of the Person.</param>
 /// <param name="expectedName">The expected name of the Person.</param>
 /// <param name="expectedDateOfBirth">The expected date of birth of the person.</param>
 /// <param name="expectedETag">The expected ETag of the entity instance.</param>
 internal static void MatchEntityInstanceOfPerson(EntityInstance <Person> actualEntityInstance, string expectedId, string expectedName, string expectedDateOfBirth, string expectedETag)
 {
     Assert.AreEqual(expectedId, actualEntityInstance.Entity.Id);
     Assert.AreEqual(ValueUtilities.GetNullableString(expectedName), actualEntityInstance.Entity.Name);
     Assert.AreEqual(ValueUtilities.GetNullableDateTimeOffset(expectedDateOfBirth), actualEntityInstance.Entity.DateOfBirth);
     Assert.AreEqual(ValueUtilities.GetNullableString(expectedETag), actualEntityInstance.ETag);
 }
Ejemplo n.º 5
0
        public override Object Evaluate(EntityInstance entityInstance, object[] objects)
        {
            string propertyList = ((string)objects[0]).Trim();
            string keyName      = ((string)objects[1]).Trim();;
            string delimiter    = (string)objects[2];

            string[] propertyArray;
            string   keyFound;

            if (delimiter.Length == 0)
            {
                delimiter = ":";
            }

            propertyArray = propertyList.Split(delimiter.ToCharArray());

            foreach (string e in propertyArray)
            {
                keyFound = e.Split('=')[0].Trim();
                if (keyFound.Equals(keyName, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(e.Split('=')[1].Trim());
                }
            }

            return(null);
        }
Ejemplo n.º 6
0
        public override void Visit(EntityInstance payloadElement)
        {
            base.Visit(payloadElement);

            // Remove the actions and functions
            payloadElement.ServiceOperationDescriptors.Clear();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Entries might come with MLE annotation but might not satisfy all the conditions for MLEs.
        /// This method removes the MLE annotation if it is not an MLE or adds it if absent
        /// </summary>
        /// <param name="payloadElement">payloadElement to fix MLE annotation for</param>
        private void FixMleAnnotation(EntityInstance payloadElement)
        {
            // validate that if IsMediaLinkEntry returns true then indeed it is a valid MLE
            if (payloadElement.IsMediaLinkEntry())
            {
                var isMLEann = payloadElement.Annotations.OfType <IsMediaLinkEntryAnnotation>().Single();

                // MLE should have both of these, if not make it not an MLE
                if (payloadElement.StreamSourceLink == null || payloadElement.StreamContentType == null)
                {
                    if (isMLEann != null)
                    {
                        payloadElement.Annotations.Remove(isMLEann);
                    }

                    payloadElement.StreamSourceLink = null;
                    ExceptionUtilities.Assert(!payloadElement.IsMediaLinkEntry(), "should not be a media link entry");
                }
                else
                {
                    payloadElement.StreamSourceLink = FixUris(payloadElement.StreamSourceLink);
                    payloadElement.StreamEditLink   = FixUris(payloadElement.StreamEditLink);

                    if (isMLEann == null)
                    {
                        payloadElement = payloadElement.AsMediaLinkEntry();
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            var properties = new List<PropertyInstance>();
            var navprops = new List<PropertyInstance>();
            foreach (var propertyInstance in payloadElement.Properties)
            {
                this.Recurse(propertyInstance);
                var isnavprop = propertyInstance as NavigationPropertyInstance;
                if (isnavprop != null)
                {
                    navprops.Add(propertyInstance);
                }
                else
                {
                    properties.Add(propertyInstance);
                }
            }
            payloadElement.Properties = navprops.Concat(properties);

            foreach (var serviceOperationDescriptor in payloadElement.ServiceOperationDescriptors)
            {
                this.Recurse(serviceOperationDescriptor);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public virtual void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            this.VisitEnumerable(payloadElement.Properties);
            this.VisitEnumerable(payloadElement.ServiceOperationDescriptors);
        }
        /// <summary>
        /// Normalizes navigation property.
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            base.Visit(payloadElement);

            // Inject an empty $select projection for top-level entries (if no projection exists)
            this.InjectEmptyContextUriProjection(payloadElement);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            payloadElement.WithContentType("application/xml");
            base.Visit(payloadElement);
        }
Ejemplo n.º 12
0
        public static bool IsDerivedOf(ComputationContext ctx, FunctionParameter derivedParam,
                                       FunctionParameter baseParam, EntityInstance baseTemplate)
        {
            // unlike the result type, for parameters we check strict matching, this is because
            // we could have overloaded function in base type, and then figuring out
            // which function in derived type inherits from which base function would take longer
            // when we allowed more relaxed matching (i.e. allowing to have supertypes as arguments when deriving)

            // note we use names comparison because we need to check for Self
            if (!baseParam.TypeName.IsExactlySame(derivedParam.TypeName, baseTemplate, jokerMatchesAll: true))
            {
                return(false);
            }

            if (baseParam.IsVariadic != derivedParam.IsVariadic)
            {
                return(false);
            }

            if (baseParam.IsVariadic)
            {
                if (!baseParam.Variadic.IsWithinLimits(derivedParam.Variadic.MinLimit) ||
                    !baseParam.Variadic.IsWithinLimits(derivedParam.Variadic.Max1Limit))
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            var epmTrees = payloadElement.Annotations.OfType <XmlTreeAnnotation>().ToList();

            if (epmTrees.Count > 0)
            {
                var entityType = payloadElement.Annotations
                                 .OfType <DataTypeAnnotation>()
                                 .Select(d => d.DataType)
                                 .OfType <EntityDataType>()
                                 .Select(d => d.Definition)
                                 .SingleOrDefault();
                ExceptionUtilities.CheckObjectNotNull(entityType, "Could not get entity type from payload annotations");
            }

            // do EPM first so that in-content values win
            base.Visit(payloadElement);

            if (epmTrees.Count > 0)
            {
                // When deep EPM is involved, we can generate named values for mapped properties of a complex
                // property that has null value. So, trim any child paths of null values.
                var nullValueList = this.valuesByName.Where(v => v.Value.Value == null).ToList();
                foreach (var nullValue in nullValueList)
                {
                    var nullChildPaths = this.orderedNames.Where(n => n.StartsWith(nullValue.Key + ".", StringComparison.OrdinalIgnoreCase)).ToList();
                    foreach (var nullChildPath in nullChildPaths)
                    {
                        this.RemoveValue(nullChildPath);
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public static bool IsSame(ComputationContext ctx, FunctionParameter derivedParam,
                                  FunctionParameter baseParam, EntityInstance baseTemplate)
        {
            // unlike the result type, for parameters we check strict matching, this is because
            // we could have overloaded function in base type, and then figuring out
            // which function in derived type inherits from which base function would take longer
            // when we allowed more relaxed matching (i.e. allowing to have supertypes as arguments when deriving)
            IEntityInstance base_param_type = baseParam.Evaluation.Components.TranslateThrough(baseTemplate);

            if (!base_param_type.IsExactlySame(derivedParam.Evaluation.Components, jokerMatchesAll: true))
            {
                return(false);
            }

            if (baseParam.IsVariadic != derivedParam.IsVariadic)
            {
                return(false);
            }

            if (baseParam.IsVariadic)
            {
                if (baseParam.Variadic.MinLimit != derivedParam.Variadic.MinLimit ||
                    baseParam.Variadic.Max1Limit != derivedParam.Variadic.Max1Limit)
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Annotates the entry with app:edited values.
        /// </summary>
        /// <param name="entry">The entry to annotate.</param>
        /// <param name="editedDate">The value of the app:edited element.</param>
        /// <returns>The entry with the annotation applied.</returns>
        public static EntityInstance AppEdited(this EntityInstance entry, string editedDate)
        {
            ExceptionUtilities.CheckArgumentNotNull(entry, "entry");

            entry.AddAnnotation(CreateAppElement(TestAtomConstants.AtomPublishingEditedElementName, editedDate));
            return(entry);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Annotates the entry with atom:published values.
        /// </summary>
        /// <param name="entry">The entry to annotate.</param>
        /// <param name="publishedDate">The value of the atom:published element.</param>
        /// <returns>The feed with the annotation applied.</returns>
        public static EntityInstance AtomPublished(this EntityInstance entry, string publishedDate)
        {
            ExceptionUtilities.CheckArgumentNotNull(entry, "entry");

            entry.AddAnnotation(XmlTreeAnnotation.Atom(TestAtomConstants.AtomPublishedElementName, publishedDate));
            return(entry);
        }
        /// <summary>
        /// Builds an instance of QueryStructureValue from an entity instance.
        /// </summary>
        /// <param name="instance">The entity instance</param>
        /// <param name="type">The QueryEntityType of the entity</param>
        /// <param name="xmlBaseAnnotations">The xml base annotations from parent elements, if any</param>
        /// <returns>The converted structural value of entity instance.</returns>
        private QueryStructuralValue BuildFromEntityInstance(EntityInstance instance, QueryEntityType type, IEnumerable<XmlBaseAnnotation> xmlBaseAnnotations)
        {
            QueryStructuralValue entity;
            
            // Helpful for debugging purposes to understand when things fail, on which entity they fail on
            this.Logger.WriteLine(LogLevel.Trace, "Build From Entity Instance with Id: {0}", instance.Id);

            // handle MEST.
            var queryEntityType = type;
            if (type.EntityType.FullName != instance.FullTypeName)
            {
                queryEntityType = type.DerivedTypes.Cast<QueryEntityType>().SingleOrDefault(t => t.EntityType.FullName == instance.FullTypeName);
                ExceptionUtilities.CheckObjectNotNull(queryEntityType, "Cannot find query entity type for entity type {0}.", instance.FullTypeName);
            }

            if (!instance.Annotations.OfType<DataTypeAnnotation>().Any())
            {
                instance.Annotations.Add(new DataTypeAnnotation() { DataType = DataTypes.EntityType.WithDefinition(queryEntityType.EntityType) });
            }

            // remove navigation properties so that they can be added after
            var navigationProperties = instance.Properties.OfType<NavigationPropertyInstance>().ToList();
            navigationProperties.ForEach(n => instance.Remove(n));

            // convert to query value
            entity = (QueryStructuralValue)this.PayloadElementToQueryValueConverter.Convert(instance, queryEntityType);
            
            // add expanded navigation properties.
            this.AddNavigationProperties(entity, navigationProperties.Where(p => p.IsExpanded), xmlBaseAnnotations);

            // add stream properties
            this.AddStreamProperties(entity, instance, xmlBaseAnnotations);
            
            return entity;
        }
 public HarvestInteraction(EntityInstance target, EntityData targetData, Func <bool> onHarvest, IInventory inventory, ushort harvestTickTime) : base(target, true)
 {
     _targetData         = targetData;
     _onHarvest          = onHarvest;
     _initiatorInventory = inventory;
     _ticksPerHarvest    = _ticksUntilNextHarvest = harvestTickTime;
 }
Ejemplo n.º 19
0
        public static Texture2D GetEntityImageAndRect(EntityInstance entityData, string assetPath, out Rect rect)
        {
            rect = Rect.zero;

            EntityInstanceTile tile = entityData.Tile;

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

            LDtkRelativeGetterTilesetTexture textureGetter = new LDtkRelativeGetterTilesetTexture();
            Texture2D tex = textureGetter.GetRelativeAsset(tile.TilesetDefinition, assetPath);

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

            Rect src = tile.UnitySourceRect;

            Vector2Int pos        = new Vector2Int((int)src.position.x, (int)src.position.y);
            Vector2Int correctPos = LDtkCoordConverter.ImageSliceCoord(pos, tex.height, (int)src.height);

            Rect actualRect = new Rect(src)
            {
                position = correctPos,
            };

            rect = actualRect;
            return(tex);
        }
            public PayloadReaderTestDescriptor ToTestDescriptor(PayloadReaderTestDescriptor.Settings settings, IEdmModel model, bool throwOnUndeclaredPropertyForNonOpenType)
            {
                var cityType = model.FindDeclaredType("TestModel.CityType").ToTypeReference();
                var cities = model.EntityContainer.FindEntitySet("Cities");
                EntityInstance entity = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1)
                    .ExpectedEntityType(cityType, cities)
                    .JsonRepresentation(
                        "{" +
                            "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.DefaultContainer.Cities()/$entity\"," +
                            "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.CityType\"," +
                            "\"Id\":1," +
                            this.Json +
                        "}");
                foreach (PropertyInstance property in this.ExpectedEntity.Properties)
                {
                    entity.Add(property.DeepCopy());
                }

                ExpectedException expectedException = this.ExpectedException;
                if (throwOnUndeclaredPropertyForNonOpenType)
                {
                    expectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "UndeclaredProperty", "TestModel.CityType");
                }

                return new PayloadReaderTestDescriptor(settings)
                {
                    DebugDescription = this.DebugDescription,
                    PayloadElement = entity,
                    PayloadEdmModel = model,
                    ExpectedException = expectedException
                };
            }
        private IDataEntity SetupMapToOpDataEntity()
        {
            var            mapToDataEntity = new OPADataEntityBuilder(new DateTime(2017, 8, 1));
            EntityInstance entityInstance  = TestEntityInstance();

            return(mapToDataEntity.MapOpaToEntity(entityInstance, null));
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Removes the MLE annotation from an EntityInstance
 /// <param name="payloadElement">The entity instance to be modified</param>
 /// </summary>
 public override void Visit(EntityInstance payloadElement)
 {
     ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
     var annotation = payloadElement.Annotations.Where(a => a is IsMediaLinkEntryAnnotation).SingleOrDefault();
     payloadElement.Annotations.Remove(annotation);
     base.Visit(payloadElement);
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            var properties = new List <PropertyInstance>();
            var navprops   = new List <PropertyInstance>();

            foreach (var propertyInstance in payloadElement.Properties)
            {
                this.Recurse(propertyInstance);
                var isnavprop = propertyInstance as NavigationPropertyInstance;
                if (isnavprop != null)
                {
                    navprops.Add(propertyInstance);
                }
                else
                {
                    properties.Add(propertyInstance);
                }
            }
            payloadElement.Properties = navprops.Concat(properties);

            foreach (var serviceOperationDescriptor in payloadElement.ServiceOperationDescriptors)
            {
                this.Recurse(serviceOperationDescriptor);
            }
        }
        private IDataEntity GetOutputEntity()
        {
            IOPADataEntityBuilder createDataEntity = new OPADataEntityBuilder(new DateTime(2017, 8, 1));
            EntityInstance        entityInstance   = TestEntityInstance();

            return(createDataEntity.CreateOPADataEntity(entityInstance, null));
        }
        public override void Visit(EntityInstance payloadElement)
        {
            base.Visit(payloadElement);

            // Remove the actions and functions
            payloadElement.ServiceOperationDescriptors.Clear();
        }
 /// <summary>
 /// Pretty prints for an EntityInstance
 /// </summary>
 /// <param name="payloadElement">Entity Instance to print</param>
 public override void Visit(EntityInstance payloadElement)
 {
     var indentString = this.GenerateIndent();
     string id = payloadElement.Id.Replace(this.AstoriaServiceDescriptor.ServiceUri.AbsoluteUri, string.Empty);
     this.builder.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0}Id:{1}", indentString, id));
     base.Visit(payloadElement);
 }
Ejemplo n.º 27
0
            public PayloadReaderTestDescriptor ToTestDescriptor(PayloadReaderTestDescriptor.Settings settings, IEdmModel model, bool withMetadataAnnotation = false)
            {
                IEdmEntityContainer container       = model.FindEntityContainer("DefaultContainer");
                IEdmEntitySet       citiesEntitySet = container.FindEntitySet("Cities");
                IEdmType            cityType        = model.FindType("TestModel.CityType");

                EntityInstance entity = PayloadBuilder.Entity("TestModel.CityType")
                                        .ExpectedEntityType(cityType, citiesEntitySet)
                                        .JsonRepresentation(
                    "{" +
                    (withMetadataAnnotation ? ("\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://http://odata.org/test/$metadata#DefaultContainer.Cities/$entity\",") : string.Empty) +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.CityType\"," +
                    this.Json +
                    ",\"Id\":1" +
                    "}");

                foreach (PropertyInstance property in this.ExpectedEntity.Properties)
                {
                    entity.Add(property.DeepCopy());
                }

                entity.Add(PayloadBuilder.PrimitiveProperty("Id", 1));

                return(new NavigationLinkTestCaseDescriptor(settings)
                {
                    DebugDescription = this.DebugDescription,
                    PayloadElement = entity,
                    PayloadEdmModel = model,
                    ExpectedException = this.ExpectedException,
                    ExpectedIsCollectionValues = this.ExpectedIsCollectionValues,
                });
            }
Ejemplo n.º 28
0
    /// <summary>
    /// Create an entity without any given data
    /// </summary>
    /// <param name="entitySO">The entity base SO</param>
    /// <returns></returns>
    public EntityEntry CreateEmptyEntity(EntityTypeSO entitySO)
    {
        int id = EntityIDCounter;

        EntityData data = new EntityData()
        {
            EntityName     = entitySO.EntityDefaultName,
            EntitySO       = entitySO,
            BehaviourDatas = new List <BehaviourData>()
        };

        // Create new entity instance
        EntityInstance newInstance = Instantiate(data.EntitySO.EntityPrefab, EntityRoot);

        newInstance.gameObject.name = data.EntityName;

        // Register entry to the list
        EntityEntry entry = new EntityEntry()
        {
            Data = data, Instance = newInstance
        };

        m_EntityEntries.Add(entry);
        m_EntityEntryLookUpTable.Add(id, entry);
        newInstance.OnInstantiate(id);

        EntityIDCounter++;

        return(entry);
    }
Ejemplo n.º 29
0
    public override void Fire(InstantWeapon weapon, EquippedItem item, EntityInstance source, EntityInstance target)
    {
        var p      = ProjectilePrototype.Instantiate <Projectile>();
        var hp     = source.Entity.Hardpoints[item.Position.x, item.Position.y];
        var barrel = source.GetBarrel(hp);
        var angle  = weapon.Spread / 2;

        p.SourceEntity = source.Entity;
        p.Velocity     = Quaternion.Euler(
            Random.Range(-angle, angle),
            Random.Range(-angle, angle),
            Random.Range(-angle, angle)) *
                         barrel.forward *
                         weapon.Velocity;
        p.StartPosition = p.transform.position = barrel.position + p.Velocity * (Random.value * Time.deltaTime);
        if (InheritVelocity)
        {
            p.Velocity += new Vector3(source.Entity.Velocity.x, 0, source.Entity.Velocity.y);
        }
        p.Damage           = weapon.Damage;
        p.Range            = weapon.Range;
        p.Penetration      = weapon.Penetration;
        p.Spread           = weapon.DamageSpread;
        p.DamageType       = weapon.WeaponData.DamageType;
        p.Zone             = source.Entity.Zone;
        p.AirburstDistance = target != null?length(source.Entity.Position - target.Entity.Position) : (weapon.Range * .75f);

        p.Trail.Clear();
    }
Ejemplo n.º 30
0
        public async Task AddEntityAsync(EntityInstance entity)
        {
            string cmdString = "INSERT INTO [EntityInstances] ([ModifiedByUserId], [Name], [Normal], [Position], [UpdatedTimestamp], [Uv])\r\nVALUES (@p0, @p1, @p2, @p3, @p4, @p5);";
            //string connString = "Data Source=vnpmosa65\\aie;Initial Catalog=WebPlantRVM;Integrated Security=True;";
            string connString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Web3D;Integrated Security=True;";

            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand comm = new SqlCommand())
                {
                    comm.Connection  = conn;
                    comm.CommandText = cmdString;
                    comm.Parameters.AddWithValue("@p0", entity.ModifiedByUserId);
                    comm.Parameters.AddWithValue("@p1", entity.Name);
                    comm.Parameters.AddWithValue("@p2", (entity.Normal != null) ? entity.Normal : "");
                    comm.Parameters.AddWithValue("@p3", (entity.Position != null) ? entity.Position : "");
                    comm.Parameters.AddWithValue("@p4", DateTime.Now);
                    comm.Parameters.AddWithValue("@p5", (entity.Uv != null) ? entity.Uv : "");
                    try
                    {
                        conn.Open();
                        comm.ExecuteNonQuery();
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine(e.ToString());
                        // do something with the exception
                        // don't hide it
                    }
                }
            }
            //await _context.EntityInstances.AddAsync(entity);
            //         await _context.SaveChangesAsync();
        }
            /// <summary>
            /// Visits an entity instance and fixes its annotations, type name, and property ordering/typing
            /// </summary>
            /// <param name="payloadElement">The entity instance</param>
            public override void Visit(EntityInstance payloadElement)
            {
                base.Visit(payloadElement);

                if (payloadElement.FullTypeName == null && this.contextData.ResolveName != null)
                {
                    payloadElement.FullTypeName = this.contextData.ResolveName(this.typeStack.Peek());
                }

                this.SortAndNormalizeProperties(payloadElement);

                payloadElement.WithContentType(MimeTypes.ApplicationXml);

                if (payloadElement.IsMediaLinkEntry())
                {
                    payloadElement.Annotations.RemoveAll(a => a is ContentTypeAnnotation);
                }

                // need to fix-up any places we've mapped an empty string to an element, as these are indistinguishable from null
                var epmQueue = new Queue <XmlTreeAnnotation>(payloadElement.Annotations.OfType <XmlTreeAnnotation>());

                while (epmQueue.Count > 0)
                {
                    var tree = epmQueue.Dequeue();
                    if (!tree.IsAttribute && string.IsNullOrEmpty(tree.PropertyValue))
                    {
                        tree.PropertyValue = null;
                    }

                    tree.Children.ForEach(c => epmQueue.Enqueue(c));
                }
            }
Ejemplo n.º 32
0
    /// <summary>
    /// Create a new entity from the given entity data
    /// </summary>
    /// <param name="data">The data used to create an entity</param>
    /// <returns></returns>
    public EntityEntry CreateEntity(EntityData fromData)
    {
        int id = EntityIDCounter;

        EntityData data = fromData.Clone();

        // Create new entity instance
        EntityInstance newInstance = Instantiate(data.EntitySO.EntityPrefab, EntityRoot);

        // Attach behaviours and setup parameters
        for (int i = 0; i < data.BehaviourDatas.Count; i++)
        {
            var behaviourData     = data.BehaviourDatas[i];
            var behaviourInstance = behaviourData.BehaviourSO.AddBehaviourToEntity(newInstance);
            behaviourInstance.UpdateAllParameters(behaviourData.ParamDatas);
        }

        // Register entry to the list
        EntityEntry entry = new EntityEntry()
        {
            Data = data, Instance = newInstance
        };

        m_EntityEntries.Add(entry);
        m_EntityEntryLookUpTable.Add(id, entry);
        newInstance.OnInstantiate(id);

        EntityIDCounter++;

        return(entry);
    }
Ejemplo n.º 33
0
        public void JsonDeserializeEntityInstance()
        {
            TextAsset jsonProject = TestJsonLoader.LoadJson(TestJsonLoader.MOCK_ENTITY_INSTANCE);

            //try deserializing entity
            EntityInstance entity = JsonConvert.DeserializeObject <EntityInstance>(jsonProject.text);
        }
        /// <summary>
        /// Normalizes navigation property.
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            base.Visit(payloadElement);

            // Inject an empty $select projection for top-level entries (if no projection exists)
            this.InjectEmptyContextUriProjection(payloadElement);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Generates the next link for an expanded feed.
        /// </summary>
        /// <param name="containingEntity">The containing entity.</param>
        /// <param name="navigation">The expanded navigation property.</param>
        /// <param name="lastEntityValue">The last entity value.</param>
        /// <returns>
        /// The expected next link
        /// </returns>
        public string GenerateExpandedNextLink(EntityInstance containingEntity, NavigationPropertyInstance navigation, QueryStructuralValue lastEntityValue)
        {
            ExceptionUtilities.CheckArgumentNotNull(containingEntity, "containingEntity");
            ExceptionUtilities.CheckArgumentNotNull(navigation, "navigation");
            ExceptionUtilities.CheckArgumentNotNull(lastEntityValue, "lastEntityValue");

            var navigationUriString = ((ExpandedLink)navigation.Value).UriString;

            if (string.IsNullOrEmpty(navigationUriString))
            {
                navigationUriString = UriHelpers.ConcatenateUriSegments(containingEntity.EditLink, navigation.Name);
            }

            var skipTokenValues = new List <object>();

            foreach (var keyProperty in lastEntityValue.Type.Properties.Where(p => p.IsPrimaryKey))
            {
                skipTokenValues.Add(lastEntityValue.GetScalarValue(keyProperty.Name).Value);
            }

            var skiptoken = this.BuildSkipTokenFromValues(skipTokenValues);

            var nextLinkUri = new ODataUri(new UnrecognizedSegment(navigationUriString));

            nextLinkUri.SkipToken = skiptoken;

            return(this.UriToStringConverter.ConvertToString(nextLinkUri));
        }
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            payloadElement.WithContentType("application/xml");
            base.Visit(payloadElement);
        }
Ejemplo n.º 37
0
            private void WriteMetadataProperty(EntityInstance payloadElement)
            {
                if (payloadElement.ETag == null && payloadElement.FullTypeName == null && payloadElement.Id == null)
                {
                    return;
                }

                this.writer.WriteName("__metadata");
                this.writer.StartObjectScope();

                if (payloadElement.Id != null)
                {
                    this.writer.WriteName("uri");
                    this.writer.WriteString(payloadElement.Id);
                }

                if (payloadElement.FullTypeName != null)
                {
                    this.writer.WriteName("type");
                    this.writer.WriteString(payloadElement.FullTypeName);
                }

                if (payloadElement.ETag != null)
                {
                    this.writer.WriteName("etag");
                    this.writer.WriteString(payloadElement.ETag);
                }

                this.WriteServiceOperationDescriptorAnnotations("actions", payloadElement.ServiceOperationDescriptors.Where(s => s.IsAction));

                this.WriteServiceOperationDescriptorAnnotations("functions", payloadElement.ServiceOperationDescriptors.Where(s => s.IsFunction));

                this.writer.EndScope();
            }
        /// <summary>
        /// Visits the entity instance.
        /// </summary>
        /// <param name="payloadElement">The payload element being visited.</param>
        public override void Visit(EntityInstance payloadElement)
        {
            base.Visit(payloadElement);

            foreach (var namedStreamProperty in payloadElement.Properties.OfType<NamedStreamInstance>().ToArray())
            {
                payloadElement.Remove(namedStreamProperty);
            }
        }
        /// <summary>
        /// Normalizes entity.
        /// </summary>
        /// <param name="payloadElement">The payload element to normalize.</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            // First recurse to children so that we get those normalized and then normalize the parent entity.
            base.Visit(payloadElement);

            this.DeduplicateProperties(payloadElement);
        }
        /// <summary>
        /// Converts the ATOM metadata annotation of stream properties and assocation links
        /// into XmlTree annotations and removes the stream properties/association links from the payload.
        /// </summary>
        /// <param name="payloadElement">The entity instance to visit.</param>
        public override void Visit(EntityInstance payloadElement)
        {
            IEnumerable<PropertyInstance> properties = payloadElement.Properties;
            if (properties != null)
            {
                // First remove all the stream properties in request payloads
                if (this.readerTestConfiguration.IsRequest)
                {
                    List<NamedStreamInstance> streamProperties = properties.OfType<NamedStreamInstance>().ToList();
                    foreach (var streamProperty in streamProperties)
                    {
                        // Edit link
                        string editRelationValue = TestAtomConstants.ODataStreamPropertyEditMediaRelatedLinkRelationPrefix + streamProperty.Name;
                        XmlTreeAnnotation annotation = GetStreamPropertyLinkXmlTreeAnnotation(streamProperty, editRelationValue);
                        if (annotation != null)
                        {
                            payloadElement.AddAnnotation(annotation);
                        }

                        // Self link
                        string sourceRelationValue = TestAtomConstants.ODataStreamPropertyMediaResourceRelatedLinkRelationPrefix + streamProperty.Name;
                        annotation = GetStreamPropertyLinkXmlTreeAnnotation(streamProperty, sourceRelationValue);
                        if (annotation != null)
                        {
                            payloadElement.AddAnnotation(annotation);
                        }

                        payloadElement.Remove(streamProperty);
                    }
                }

                // Then also convert the association links of navigation properties and 
                // remove all navigation properties that do not have a URI - for request
                if (this.readerTestConfiguration.IsRequest)
                {
                    List<NavigationPropertyInstance> navigationProperties = properties.OfType<NavigationPropertyInstance>().ToList();
                    foreach (var navProperty in navigationProperties)
                    {
                        XmlTreeAnnotation annotation = GetAssociationLinkXmlTreeAnnotation(navProperty.AssociationLink);
                        navProperty.AssociationLink = null;

                        if (navProperty.Value == null)
                        {
                            payloadElement.Remove(navProperty);
                        }

                        if (annotation != null)
                        {
                            payloadElement.AddAnnotation(annotation);
                        }
                    }
                }
            }

            base.Visit(payloadElement);
        }
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            if (payloadElement.Id == null)
            {
                payloadElement.Id = String.Empty;
            }
            base.Visit(payloadElement);
        }       
        /// <summary>
        /// Converts the complex instance into an entity instance based on the metadata
        /// </summary>
        /// <param name="payloadElement">The payload element to potentially replace</param>
        /// <returns>The original element or a copy to replace it with</returns>
        public override ODataPayloadElement Visit(ComplexInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
            if (payloadElement.Annotations.OfType<EntitySetAnnotation>().Any())
            {
                var entityInstance = new EntityInstance(payloadElement.FullTypeName, payloadElement.IsNull);
                entityInstance.Properties = this.VisitCollection(payloadElement.Properties);
                return payloadElement.ReplaceWith(entityInstance);
            }

            return base.Visit(payloadElement);
        }
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
            var selflink = payloadElement.Annotations.OfType<SelfLinkAnnotation>().SingleOrDefault();
            if (selflink != null)
            {
                if (payloadElement.EditLink == null)
                {
                    payloadElement.EditLink = selflink.Value;
                }
                payloadElement.Annotations.Remove(selflink);
            }

            base.Visit(payloadElement);
        }
        /// <summary>
        /// Visits the entity instance and removes any complex with no properties as this will not be written.
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            foreach (var property in payloadElement.Properties.ToList())
            {
                ComplexProperty complex = property as ComplexProperty;
                if (complex != null && complex.Value.Properties.Count() == 0)
                {
                    payloadElement.Remove(complex);
                }
            }

            base.Visit(payloadElement);
        }
        /// <summary>
        /// Normalizes property order on an entry.
        /// </summary>
        /// <param name="payloadElement">The payload element to normalize.</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            // First recurse to children so that we get those normalized and then normalize the parent entity.
            base.Visit(payloadElement);

            // When we write properties into JSON we write them all in the original order except for association links.
            // Since association links are matched against nav. properties, most of the time that is not visible
            // but if there's an association link without its nav. link portion that one will be reported last.
            payloadElement.Properties =
                payloadElement.Properties.Where(p => !p.IsAssociationLinkOnly())
                .Concat(payloadElement.Properties.Where(p => p.IsAssociationLinkOnly()))
                .ToList();
        }
        /// <summary>
        /// Visits the entity instance.
        /// </summary>
        /// <param name="payloadElement">The payload element being visited.</param>
        public override void Visit(EntityInstance payloadElement)
        {
            base.Visit(payloadElement);

            foreach (var navPropWithAssociationLink in payloadElement.Properties.OfType<NavigationPropertyInstance>().Where(p => p.AssociationLink != null).ToArray())
            {
                if (navPropWithAssociationLink.Value == null)
                {
                    payloadElement.Remove(navPropWithAssociationLink);
                }
                else
                {
                    navPropWithAssociationLink.AssociationLink = null;
                }
            }
        }
 /// <summary>
 /// Tracks a pending update to the given descriptor based on values read from a response payload
 /// </summary>
 /// <param name="data">The descriptor data to update</param>
 /// <param name="payload">The payload that was read</param>
 /// <param name="baseUri">The base uri of the context</param>
 public void TrackUpdateFromPayload(EntityDescriptorData data, EntityInstance payload, Uri baseUri)
 {
     ExceptionUtilities.CheckArgumentNotNull(data, "data");
     var update = new PayloadUpdate() { Descriptor = data, Payload = payload, BaseUri = baseUri };
     if (!this.IgnoreAllUpdates)
     {
         if (this.ApplyUpdatesImmediately)
         {
             Apply(update);
         }
         else
         {
             this.payloadUpdates.Add(update);
         }
     }
 }
        /// <summary>
        /// Visits the entity instance.
        /// </summary>
        /// <param name="payloadElement">The payload element being visited.</param>
        public override void Visit(EntityInstance payloadElement)
        {
            base.Visit(payloadElement);

            if (format == ODataFormat.Atom)
            {
                if (!IsMLE(payloadElement))
                {
                    payloadElement.RemoveAnnotations(typeof(IsMediaLinkEntryAnnotation));
                }

                payloadElement.RemoveAnnotations(typeof(SelfLinkAnnotation));
                payloadElement.EditLink = null;
                payloadElement.StreamEditLink = null;
                payloadElement.StreamSourceLink = null;
                payloadElement.StreamETag = null;
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Builds an entity instance of the given type out of the given anonymous object
        /// </summary>
        /// <param name="entityType">The metadata type information for the entity</param>
        /// <param name="anonymous">The data as an anonymous type</param>
        /// <returns>An entity instance with the given values</returns>
        public EntityInstance EntityInstance(EntityType entityType, object anonymous)
        {
            ExceptionUtilities.CheckArgumentNotNull(entityType, "entityType");

            EntityInstance instance = new EntityInstance(entityType.FullName, anonymous == null);

            if (entityType.GetBaseTypesAndSelf().Any(t => t.HasStream()))
            {
                instance.AsMediaLinkEntry();
            }

            // TODO: id?
            if (anonymous != null)
            {
                this.PopulatePropertiesFromObject(instance, entityType.AllProperties, anonymous);

                // TODO: populate navigation properties
            }

            return instance;
        }
        /// <summary>
        /// Normalizes property order on an entry.
        /// </summary>
        /// <param name="payloadElement">The payload element to normalize.</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            // First recurse to children so that we get those normalized and then normalize the parent entity.
            base.Visit(payloadElement);

            // When we write properties into ATOM we write them in this order:
            // - Navigation properties
            // - Named stream properties
            // - All other properties (simple properties)
            // Inside each group the original order is maintained.
            // Also note that the association link order is lost due to the way we report it through the API, so put those after all the properties
            //   (only pure association links, otherwise we match them against the nav. links)
            payloadElement.Properties =
                payloadElement.Properties.Where(p => p.ElementType == ODataPayloadElementType.NavigationPropertyInstance && !p.IsAssociationLinkOnly())
                .Concat(payloadElement.Properties.Where(p => p.ElementType == ODataPayloadElementType.NamedStreamInstance))
                .Concat(payloadElement.Properties.Where(p =>
                    p.ElementType != ODataPayloadElementType.NavigationPropertyInstance &&
                    p.ElementType != ODataPayloadElementType.NamedStreamInstance))
                .Concat(payloadElement.Properties.Where(p => p.IsAssociationLinkOnly()))
                .ToList();
        }
            /// <summary>
            /// Normalizes the given entity payload element
            /// </summary>
            /// <param name="entityPayload">The entity payload element</param>
            /// <param name="entityDescriptorData">The descriptor data for the entity</param>
            public void Normalize(EntityInstance entityPayload, EntityDescriptorData entityDescriptorData)
            {
                ExceptionUtilities.CheckArgumentNotNull(entityPayload, "entityPayload");
                ExceptionUtilities.CheckArgumentNotNull(entityDescriptorData, "entityDescriptorData");
                this.typeStack.Push(entityDescriptorData.EntityClrType);

                // do this before recursing because it could be over-written by the visit method
                entityPayload.FullTypeName = entityDescriptorData.ServerTypeName;
                
                entityPayload.Id = string.Empty;
                if (entityDescriptorData.Identity != null)
                {
                    entityPayload.Id = entityDescriptorData.Identity.OriginalString;
                }

                entityPayload.Accept(this);
            }
 private bool IsMLE(EntityInstance entity)
 {
     return entity.StreamSourceLink != null ||
         HasDefaultStream(entity) ||
         HasPropertiesOnEntryChildLevel(entity);
 }
        private bool HasDefaultStream(EntityInstance entity)
        {
            if (entity.FullTypeName == null)
            {
                return false;
            }

            if (payloadEdmModel != null)
            {
                var edmEntityType = payloadEdmModel.GetEntityType(entity.FullTypeName);
                return edmEntityType != null && edmEntityType.HasStream;
            }

            return false;
        }
        private bool HasPropertiesOnEntryChildLevel(EntityInstance entity)
        {
            var xmlPayloadAnnotation = entity.Annotations.OfType<XmlPayloadElementRepresentationAnnotation>().SingleOrDefault();

            return xmlPayloadAnnotation != null &&
                xmlPayloadAnnotation
                .XmlNodes
                .OfType<XElement>()
                .Single(e => e.Name == TestAtomConstants.AtomXNamespace + "entry")
                .Elements(TestAtomConstants.ODataMetadataXNamespace + "properties")
                .Any();
        }
            /// <summary>
            /// Visits a payload element whose root is a EntityInstance.
            /// </summary>
            /// <param name="payloadElement">The root node of payload element being visited.</param>
            public void Visit(EntityInstance payloadElement)
            {
                ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
                this.isRootElement = false;

                if (payloadElement.IsNull)
                {
                    this.writer.WriteNull();
                }
                else
                {
                    this.writer.StartObjectScope();

                    this.WriteMetadataProperty(payloadElement);

                    foreach (var property in payloadElement.Properties)
                    {
                        this.Recurse(property);
                    }

                    this.writer.EndScope();
                }
            }
            private void WriteMetadataProperty(EntityInstance payloadElement)
            {
                if (payloadElement.ETag == null && payloadElement.FullTypeName == null && payloadElement.Id == null)
                {
                    return;
                }

                this.writer.WriteName("__metadata");
                this.writer.StartObjectScope();

                if (payloadElement.Id != null)
                {
                    this.writer.WriteName("uri");
                    this.writer.WriteString(payloadElement.Id);
                }

                if (payloadElement.FullTypeName != null)
                {
                    this.writer.WriteName("type");
                    this.writer.WriteString(payloadElement.FullTypeName);
                }

                if (payloadElement.ETag != null)
                {
                    this.writer.WriteName("etag");
                    this.writer.WriteString(payloadElement.ETag);
                }

                this.WriteServiceOperationDescriptorAnnotations("actions", payloadElement.ServiceOperationDescriptors.Where(s => s.IsAction));

                this.WriteServiceOperationDescriptorAnnotations("functions", payloadElement.ServiceOperationDescriptors.Where(s => s.IsFunction));

                this.writer.EndScope();
            }
 /// <summary>
 /// Removes ATOM metadata annotations from an <see cref="EntityInstance"/>.
 /// </summary>
 /// <param name="payloadElement">The entity instance to visit.</param>
 public override void Visit(EntityInstance payloadElement)
 {
     payloadElement.RemoveAnnotations(typeof(NamedStreamAtomLinkMetadataAnnotation));
     base.Visit(payloadElement);
 }
        private void AddFoldedLinksToEntityInsertPayload(DataServiceContextData contextData, EntityDescriptorData entityDescriptorData, EntityInstance payload)
        {
            var entityType = this.ModelSchema.EntityTypes.Single(t => t.FullName == entityDescriptorData.EntityClrType.FullName);

            foreach (var linkDescriptor in contextData.LinkDescriptorsData.Where(l => l.SourceDescriptor == entityDescriptorData))
            {
                if (linkDescriptor.TargetDescriptor.State == EntityStates.Added)
                {
                    continue;
                }

                var navigationProperty = entityType.AllNavigationProperties.Single(n => n.Name == linkDescriptor.SourcePropertyName);

                string contentType = MimeTypes.ApplicationAtomXml + ";type=";
                if (navigationProperty.ToAssociationEnd.Multiplicity == EndMultiplicity.Many)
                {
                    contentType += "feed";
                }
                else
                {
                    contentType += "entry";
                }

                // note: the edit-link is used rather than identity because the server needs to be able to query for the target entity
                // and the identity may not be an actual uri
                var link = new DeferredLink() { UriString = linkDescriptor.TargetDescriptor.EditLink.OriginalString }
                    .WithContentType(contentType).WithTitleAttribute(linkDescriptor.SourcePropertyName);

                payload.Add(new NavigationPropertyInstance(linkDescriptor.SourcePropertyName, link));
            }
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Construct expected relationship link value.
 /// </summary>
 /// <param name="entity">entity that the link belongs to</param>
 /// <param name="navigation">navigation property instance for the relationship link</param>
 /// <returns>expected relationship link value</returns>
 private string BuildExpectedAssociationUri(EntityInstance entity, NavigationPropertyInstance navigation)
 {
     return UriHelpers.ConcatenateUriSegments(entity.GetEditLink(), Endpoints.Ref, Uri.EscapeDataString(navigation.Name));
 }
            /// <summary>
            /// Visits an entity instance and fixes its annotations, type name, and property ordering/typing
            /// </summary>
            /// <param name="payloadElement">The entity instance</param>
            public override void Visit(EntityInstance payloadElement)
            {
                base.Visit(payloadElement);

                if (payloadElement.FullTypeName == null && this.contextData.ResolveName != null)
                {
                    payloadElement.FullTypeName = this.contextData.ResolveName(this.typeStack.Peek());
                }

                this.SortAndNormalizeProperties(payloadElement);

                payloadElement.WithContentType(MimeTypes.ApplicationXml);

                if (payloadElement.IsMediaLinkEntry())
                {
                    payloadElement.Annotations.RemoveAll(a => a is ContentTypeAnnotation);
                }

                // need to fix-up any places we've mapped an empty string to an element, as these are indistinguishable from null
                var epmQueue = new Queue<XmlTreeAnnotation>(payloadElement.Annotations.OfType<XmlTreeAnnotation>());
                while (epmQueue.Count > 0)
                {
                    var tree = epmQueue.Dequeue();
                    if (!tree.IsAttribute && string.IsNullOrEmpty(tree.PropertyValue))
                    {
                        tree.PropertyValue = null;
                    }

                    tree.Children.ForEach(c => epmQueue.Enqueue(c));
                }
            }