protected override IEnumerable <EntitySetHandle> OnVisitItems(EvaluationContext evalContext)
        {
            // The relationship (definition) being accessed
            // (don't evaluate in loop for now ... OK while they're just literals)
            IEntity relationship = Right.EvaluateEntity(evalContext);

            IEntity current = Left.EvaluateEntity(evalContext);

            if (current == null)
            {
                yield break;
            }

            // Relationship data
            IEntityRelationshipCollection <IEntity> values = current.GetRelationships(relationship,
                                                                                      Direction);

            foreach (var pair in values)
            {
                var result = new EntitySetHandle
                {
                    Entity     = pair != null ? pair.Entity : null,
                    Expression = this
                };
                yield return(result);
            }
        }
Example #2
0
        public void EnsureTypeHasFields( )
        {
            // Ensure that regex is not applied for empty string, if IsRequired is not set.

            IEntity e = Entity.Get(new EntityRef("test", "employee"));
            IEntityRelationshipCollection <IEntity> coll = e.GetRelationships(EntityType.Fields_Field, Direction.Reverse);

            Assert.IsTrue(coll.Count > 0);
        }
Example #3
0
        /// <summary>
        /// Reads the list of related entity IDs out of an entity for a given relationship type.
        /// </summary>
        private static IEnumerable <IEntity> GetRelationshipList(IEntity entity, IEntity relationshipDefn, Direction direction, string alias)
        {
            IEntityRelationshipCollection <IEntity> oRelated = entity.GetRelationships(relationshipDefn, direction);

            if (oRelated == null)
            {
                return(Enumerable.Empty <IEntity>());
            }

            return(oRelated.Where(ri => ri.Entity != null));
        }
Example #4
0
        /// <summary>
        /// Multi-relationship setter implementation for strong types.
        /// </summary>
        /// <typeparam name="T">Type of entity being pointed to.</typeparam>
        /// <param name="alias">Relationship alias.</param>
        /// <param name="values">New entities to point to, or null.</param>
        /// <param name="direction">Relationship direction.</param>
        protected void SetRelationships <T>(string alias, IEntityCollection <T> values, Direction direction)
            where T : class, IEntity
        {
            IEntityRelationshipCollection <T> converted = null;

            if (values != null)
            {
                converted = new EntityRelationshipCollection <T>(values);
            }

            _entity.SetRelationships(alias, converted, direction);
        }
Example #5
0
        public void GetRelationshipInstancesByRelId( )
        {
            IEntity entity = Entity.GetByName("Test 01").First( );
            long    relId  = Entity.GetId("test", "herbs");

            IEntityRelationshipCollection <IEntity> instances =
                entity.GetRelationships(relId, Direction.Forward);

            foreach (var i in instances)
            {
                IEntity relatedEntity = i.Entity;                 // this is typically what you want
            }
        }
Example #6
0
        /// <summary>
        /// Get the removed entities in a rel collection, ignoring temporary entities
        /// </summary>
        IEnumerable <IEntity> GetRemoved(IEntityRelationshipCollection <IEntity> rels)
        {
            var addedIds   = rels.Tracker.Added.Select(i => i.Key);
            var removedIds = rels.Tracker.Removed.Select(i => i.Key).Except(addedIds).Where(i => !EntityId.IsTemporary(i));

            if (removedIds.Any())
            {
                return(Entity.Get(removedIds));
            }
            else
            {
                return(Enumerable.Empty <IEntity>());
            }
        }
Example #7
0
        /// <summary>
        /// Get the added entities in a rel collection
        /// </summary>
        IEnumerable <IEntity> GetAdded(IEntityRelationshipCollection <IEntity> rels)
        {
            var removedIds = rels.Tracker.Removed.Select(i => i.Key);
            var addedIds   = rels.Tracker.Added.Select(i => i.Key).Except(removedIds);

            if (addedIds.Any())
            {
                return(rels.Where(e => e != null && addedIds.Contains(e.Id)).ToList());
            }
            else
            {
                return(Enumerable.Empty <IEntity>());
            }
        }
Example #8
0
        /// <summary>
        /// Implementation for relationship actions.
        /// </summary>
        /// <param name="entities">Entities to set.</param>
        /// <param name="relId">ID of relationship to update.</param>
        /// <param name="direction">Direction of relationship.</param>
        /// <param name="defaultValue">Proposed default value.</param>
        /// <param name="defaultToCurrentUser">True if the current user should be the default value.</param>
        /// <param name="defaultUseCurrentPerson">True if the account holder of the user should be the default value.</param>
        private void SetDefaultForRelationship(IEnumerable <IEntity> entities, long relId, Direction direction, IEntity defaultValue, bool defaultToCurrentUser, bool defaultUseCurrentPerson)
        {
            if (defaultToCurrentUser || defaultUseCurrentPerson)
            {
                defaultValue = GetCurrentUser(defaultUseCurrentPerson);
            }

            foreach (IEntity entity in entities)
            {
                IEntityRelationshipCollection <IEntity> relValues = entity.GetRelationships(relId, direction);
                if (relValues.Count == 0)
                {
                    relValues.Add(defaultValue);
                }
            }
        }
Example #9
0
        /// <summary>
        /// Multi-flag enum getter implementation for strong types.
        /// </summary>
        /// <typeparam name="TEntity">Entity type for the enum value.</typeparam>
        /// <typeparam name="TEnum">C# enum type</typeparam>
        /// <param name="alias">Alias for the enum relationship.</param>
        /// <param name="direction">Direction of the enum relationship. (Presumably forwards)</param>
        /// <param name="convertAliasToEnum">Callback to convert aliases to enum instance values.</param>
        /// <param name="combineFlags">Callback to 'or' two enum flags together.</param>
        /// <returns>Nullable enum value.</returns>
        protected TEnum?GetMultiEnum <TEntity, TEnum>(string alias, Direction direction, Func <string, TEnum?> convertAliasToEnum, Func <TEnum?, TEnum?, TEnum?> combineFlags)
            where TEntity : class, IEntity
            where TEnum : struct
        {
            // Get related entities
            IEntityRelationshipCollection <TEntity> enumEntities = GetRelationships <TEntity>(alias, direction);

            // Handle null
            if (enumEntities == null)
            {
                return(null);
            }

            TEnum?enumValue = null;

            long aliasFieldId = WellKnownAliases.CurrentTenant.Alias;

            // Convert values to enum and combine
            foreach (TEntity value in enumEntities.Entities)
            {
                // Get alias of enum
                // Note : we would use enumEntity.Alias, except it doesn't return a namespace because it is from IEntityRef.Alias
                string enumAlias = value.GetField <string>(aliasFieldId);

                if (enumValue == null)
                {
                    enumValue = convertAliasToEnum(enumAlias);
                }
                else
                {
                    TEnum?converted = convertAliasToEnum(enumAlias);
                    enumValue = combineFlags(enumValue, converted);
                }
            }

            return(enumValue);
        }
Example #10
0
        public void TestCascadeDeleteWithRelationships2( )
        {
            var f1 = Entity.Create <NavContainer>( );

            f1.Name = "f1";
            f1.Save( );
            var f2 = Entity.Create <NavContainer>( );

            f2.Name = "f2";
            f2.ResourceInFolder.Add(f1);
            var f3 = Entity.Create <NavContainer>( );

            f3.Name = "f3";
            f3.ResourceInFolder.Add(f2);
            f3.ShortcutInFolder.Add(f1);
            f3.Save( );

            long id1 = f1.Id;

            Assert.IsTrue(Entity.Exists(f1), "a f1");
            Assert.IsTrue(Entity.Exists(f2), "a f2");
            Assert.IsTrue(Entity.Exists(f3), "a f3");

            f2.Delete( );

            Assert.AreEqual(0, f3.Shortcuts.Count);

            IEntity e       = Entity.Get(id1);
            var     relDefn = new EntityRef("console", "shortcutInFolder");
            IEntityRelationshipCollection <IEntity> oRelated = e.GetRelationships(relDefn, Direction.Reverse);

            Assert.IsFalse(oRelated.Any(ri => ri.Entity == null));
            Assert.AreEqual(0, oRelated.Count);

            f1.Delete( );
        }
        public void SetChoiceMultiple( )
        {
            var sch = new ScheduleDailyRepeat
            {
                Name = "Test sch" + DateTime.Now
            };


            sch.Save( );

            // _toDelete.Add(sch.Id);


            var setAction = new SetChoiceActivity( );

            setAction.Save( );
            ToDelete.Add(setAction.Id);

            var setChoiceAs = setAction.As <WfActivity>( );

            ActivityImplementationBase nextActivity = setChoiceAs.CreateWindowsActivity( );

            var dayOfWeekRef = ( EntityRef )"core:sdrDayOfWeek";

            var args = new Dictionary <string, object>
            {
                {
                    "Resource to Update", sch
                },
                {
                    "Field to Update", dayOfWeekRef.Entity
                },
                {
                    "New Value", new EntityRef("core:dowSunday").Entity
                },
            };

            RunActivity(nextActivity, args);

            sch = Entity.Get <ScheduleDailyRepeat>(sch.Id);

            IEntityRelationshipCollection <IEntity> dowRefs = sch.GetRelationships(dayOfWeekRef);

            Assert.AreEqual(1, dowRefs.Count( ), "has been set");
            Assert.IsTrue(dowRefs.Any(w => w.Entity.Alias == "dowSunday"));

            args = new Dictionary <string, object>
            {
                {
                    "Resource to Update", sch
                },
                {
                    "Field to Update", dayOfWeekRef.Entity
                },
                {
                    "New Value", new EntityRef("core:dowMonday").Entity
                },
                {
                    "Replace Existing Values", false
                }
            };

            RunActivity(nextActivity, args);

            sch     = Entity.Get <ScheduleDailyRepeat>(sch.Id);
            dowRefs = sch.GetRelationships(dayOfWeekRef);
            Assert.AreEqual(2, dowRefs.Count( ), "has been added");
            Assert.IsTrue(dowRefs.Any(w => w.Entity.Alias == "dowMonday"));

            args = new Dictionary <string, object>
            {
                {
                    "Resource to Update", sch
                },
                {
                    "Field to Update", dayOfWeekRef.Entity
                },
                {
                    "New Value", new EntityRef("core:dowTuesday").Entity
                },
                {
                    "Replace Existing Values", true
                }
            };

            RunActivity(nextActivity, args);

            sch     = Entity.Get <ScheduleDailyRepeat>(sch.Id);
            dowRefs = sch.GetRelationships(dayOfWeekRef);
            Assert.AreEqual(1, dowRefs.Count( ), "has been reset");
            Assert.IsTrue(dowRefs.Any(w => w.Entity.Alias == "dowTuesday"));
        }
Example #12
0
 /// <summary>
 ///     Sets the relationships for the specified relationship definition.
 /// </summary>
 /// <param name="relationshipDefinition">The relationship definition.</param>
 /// <param name="relationships">The relationships.</param>
 /// <param name="direction"></param>
 /// <exception cref="System.NotImplementedException"></exception>
 public void SetRelationships(long relationshipDefinition, IEntityRelationshipCollection relationships, Direction direction)
 {
     throw new NotImplementedException( );
 }
Example #13
0
        /// <summary>
        ///     Locates the invalid permission relationships.
        /// </summary>
        /// <param name="entities">The entities.</param>
        /// <param name="permission">The permission.</param>
        /// <param name="permissionRelationships">The permission relationships.</param>
        /// <param name="direction">The direction.</param>
        /// <param name="invalidPermissions">The invalid permissions.</param>
        private void LocateInvalidPermissionRelationships(IEnumerable <IEntity> entities, Permission permission, IEntityRelationshipCollection <IEntity> permissionRelationships, Direction direction, ISet <long> invalidPermissions)
        {
            if (permissionRelationships != null && permissionRelationships.Count > 0)
            {
                IList <IEntity> enumerable = entities as IList <IEntity> ?? entities.ToList( );

                foreach (var relationship in permissionRelationships.Where(entityRelationship => entityRelationship != null && entityRelationship.Entity != null))
                {
                    LocateInvalidObjects(enumerable, relationship.Entity.Id, direction, invalidObjects =>
                    {
                        /////
                        // If there are any invalid objects, mark the permission as invalid.
                        /////
                        if (invalidObjects != null && invalidObjects.Count > 0)
                        {
                            invalidPermissions.Add(permission.Id);
                        }
                    });
                }
            }
        }
Example #14
0
 /// <summary>
 ///     Sets the relationships for the specified relationship definition.
 /// </summary>
 /// <param name="relationshipDefinition">The relationship definition.</param>
 /// <param name="relationships">The relationships.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 public void SetRelationships(string relationshipDefinition, IEntityRelationshipCollection relationships)
 {
     throw new NotImplementedException( );
 }
        public void Test_RelationshipInstance(string action, string fromPerms, string toPerms, Direction direction, bool saveBothEnds, bool haveFieldChanges, bool expectAllow)
        {
            if (fromPerms == "modify")
            {
                fromPerms = "read,modify";
            }
            if (toPerms == "modify")
            {
                toPerms = "read,modify";
            }

            // Create schema
            EntityType fromType = new EntityType();

            fromType.Inherits.Add(UserResource.UserResource_Type);
            fromType.Name = Guid.NewGuid().ToString();
            fromType.Save();

            EntityType toType = new EntityType();

            toType.Inherits.Add(UserResource.UserResource_Type);
            toType.Name = Guid.NewGuid().ToString();
            toType.Save();

            Relationship rel = new Relationship();

            rel.Name             = Guid.NewGuid().ToString();
            rel.FromType         = fromType;
            rel.ToType           = toType;
            rel.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany;
            rel.Save();

            // Create data
            IEntity toInst = new Entity(toType);

            toInst.Save();
            IEntity fromInst = new Entity(fromType);

            if (action != "Create")
            {
                fromInst.SetRelationships(rel, new EntityRelationshipCollection <IEntity> {
                    toInst
                });
            }
            fromInst.Save();

            // Create test user
            UserAccount userAccount = Entity.Create <UserAccount>();

            userAccount.Name = Guid.NewGuid().ToString();
            userAccount.Save();

            // Grant access
            if (!string.IsNullOrEmpty(fromPerms))
            {
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    fromType.As <SecurableEntity>(),
                    fromPerms.Split(',').Select(pa => new EntityRef(pa)),
                    TestQueries.Entities().ToReport());
            }
            if (!string.IsNullOrEmpty(toPerms))
            {
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    toType.As <SecurableEntity>(),
                    toPerms.Split(',').Select(pa => new EntityRef(pa)),
                    TestQueries.Entities().ToReport());
            }

            // Test

            bool allowed = false;

            try
            {
                using (new SetUser(userAccount))
                {
                    IEntity source = Entity.Get(direction == Direction.Forward ? fromInst.Id : toInst.Id);
                    if (action != "Read")
                    {
                        source = source.AsWritable();
                    }
                    Func <IEntity> target = () => Entity.Get(direction == Direction.Forward ? toInst.Id : fromInst.Id);

                    IEntityRelationshipCollection <IEntity> relCol = null;

                    switch (action)
                    {
                    case "Read":
                        relCol = source.GetRelationships(rel.Id, direction);
                        IEntity entity = relCol.FirstOrDefault();
                        allowed = entity != null;
                        break;

                    case "Create":
                        relCol = new EntityRelationshipCollection <IEntity> {
                            target()
                        };
                        source.SetRelationships(rel, relCol);
                        if (haveFieldChanges)
                        {
                            source.SetField("core:name", Guid.NewGuid().ToString());
                        }
                        if (saveBothEnds)
                        {
                            Entity.Save(new[] { source, target() });
                        }
                        else
                        {
                            source.Save();
                        }
                        allowed = true;
                        break;

                    case "Remove":
                        relCol = source.GetRelationships(rel.Id, direction);
                        relCol.Remove(target());
                        source.SetRelationships(rel, relCol);
                        if (haveFieldChanges)
                        {
                            source.SetField("core:name", Guid.NewGuid().ToString());
                        }
                        if (saveBothEnds)
                        {
                            Entity.Save(new[] { source, target() });
                        }
                        else
                        {
                            source.Save();
                        }
                        allowed = true;
                        break;

                    case "Clear":
                        relCol = source.GetRelationships(rel.Id, direction);
                        relCol.Clear();
                        source.SetRelationships(rel, relCol);
                        if (haveFieldChanges)
                        {
                            source.SetField("core:name", Guid.NewGuid().ToString());
                        }
                        if (saveBothEnds)
                        {
                            Entity.Save(new[] { source, target() });
                        }
                        else
                        {
                            source.Save();
                        }
                        allowed = true;
                        break;

                    default:
                        throw new InvalidOperationException("Unknown " + action);
                    }
                }
                Assert.That(allowed, Is.EqualTo(expectAllow));
            }
            catch (PlatformSecurityException)
            {
                Assert.That(false, Is.EqualTo(expectAllow));
            }
        }
Example #16
0
        public void Test_Relationship(Direction direction, string identityType, int count)
        {
            // Create schema
            EntityType type = Entity.Create <EntityType>( );

            type.Name = "Test Type";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type.Save( );
            Field      stringField = new StringField( ).As <Field>( );
            Field      intField    = new IntField( ).As <Field>( );
            EntityType type2       = Entity.Create <EntityType>( );

            type2.Name = "Test Type2";
            type2.Fields.Add(stringField);
            type2.Fields.Add(intField);
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type2.Save( );
            Relationship relationship = Entity.Create <Relationship>( );

            relationship.Name             = "Rel1";
            relationship.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany;
            relationship.FromType         = direction == Direction.Forward ? type : type2;
            relationship.ToType           = direction == Direction.Forward ? type2 : type;
            relationship.Save( );

            var targets = new List <Resource>( );

            for (int i = 0; i < count; i++)
            {
                string name      = "Target" + Guid.NewGuid( );
                string stringVal = "StringVal" + i;
                int    intVal    = 100 + i;

                Resource target = Entity.Create(type2.Id).AsWritable <Resource>( );
                target.SetField(stringField.Id, stringVal);
                target.SetField(intField.Id, intVal);
                target.Name = name;
                target.Save( );
                targets.Add(target);
            }


            using (new SecurityBypassContext( ))
            {
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( ));
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( ));
            }

            Field lookupField = null;

            if (identityType.Contains("StringField"))
            {
                lookupField = stringField;
            }
            else if (identityType.Contains("IntField"))
            {
                lookupField = intField;
            }

            var identities = new List <string>( );

            for (int i = 0; i < count; i++)
            {
                var    target = targets[i];
                string identity;
                if (identityType.Contains("Null"))
                {
                    continue;
                }
                if (identityType == "Name")
                {
                    identity = "\"" + target.Name + "\"";
                }
                else if (identityType == "Guid")
                {
                    identity = "\"" + target.UpgradeId + "\"";
                }
                else if (identityType == "StringField")
                {
                    identity = "\"StringVal" + i + "\"";
                }
                else if (identityType == "IntField")
                {
                    identity = (100 + i).ToString( );
                }
                else
                {
                    throw new InvalidOperationException( );
                }
                identities.Add(identity);
            }

            // Create JSON
            string jsonMember = "rel1";
            string json       = "{\"" + jsonMember + "\":[" + string.Join(", ", identities) + "]}";

            // Create a mapping
            var mapping    = CreateApiResourceMapping(new EntityRef(type.Id));
            var relMapping = CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, direction == Direction.Reverse);

            relMapping.MappedRelationshipLookupField = lookupField;
            relMapping.Save( );

            // Fill entity
            IEntity entity = RunTest(json, mapping);
            IEntityRelationshipCollection <IEntity> value = entity.GetRelationships(relationship.Id, direction);

            // Assert mapping
            Assert.That(value, Is.Not.Null);
            if (identityType == "Null")
            {
                Assert.That(value, Has.Count.EqualTo(0));
            }
            else
            {
                Assert.That(value, Has.Count.EqualTo(targets.Count));
                var actual   = value.Select(e => e.Id).OrderBy(id => id).ToList( );
                var expected = targets.Select(e => e.Id).OrderBy(id => id).ToList( );

                Assert.That(actual, Is.EquivalentTo(expected));
            }
        }
Example #17
0
 public void SetRelationships(long relationshipDefinition, IEntityRelationshipCollection relationships)
 {
     _entity.SetRelationships(relationshipDefinition, relationships);
 }
Example #18
0
        public void Test_Lookup(Direction direction, string identityType)
        {
            string name = "Target" + Guid.NewGuid();

            // Create schema
            EntityType type = Entity.Create <EntityType>( );

            type.Name = "Test Type";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type.Save( );
            Field      stringField = new StringField( ).As <Field>( );
            Field      intField    = new IntField( ).As <Field>( );
            EntityType type2       = Entity.Create <EntityType>( );

            type2.Fields.Add(stringField);
            type2.Fields.Add(intField);
            type2.Name = "Test Type2";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type2.Save( );
            Relationship relationship = Entity.Create <Relationship>( );

            relationship.Name             = "Rel1";
            relationship.Cardinality_Enum = CardinalityEnum_Enumeration.OneToOne;
            relationship.FromType         = direction == Direction.Forward ? type : type2;
            relationship.ToType           = direction == Direction.Forward ? type2 : type;
            relationship.Save( );
            Resource target = Entity.Create(type2.Id).AsWritable <Resource>();

            target.Name = name;
            target.SetField(stringField.Id, "StringVal");
            target.SetField(intField.Id, 101);
            target.Save( );

            using (new SecurityBypassContext( ))
            {
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( ));
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( ));
            }

            Field lookupField = null;

            string identity;

            if (identityType == "Name")
            {
                identity = "\"" + name + "\"";
            }
            else if (identityType == "Guid")
            {
                identity = "\"" + target.UpgradeId.ToString() + "\"";
            }
            else if (identityType.Contains("Null"))
            {
                identity = "null";
            }
            else if (identityType == "StringField")
            {
                identity = "\"StringVal\"";
            }
            else if (identityType == "IntField")
            {
                identity = "101";
            }
            else
            {
                throw new InvalidOperationException();
            }

            if (identityType.Contains("StringField"))
            {
                lookupField = stringField;
            }
            else if (identityType.Contains("IntField"))
            {
                lookupField = intField;
            }

            // Create JSON
            string jsonMember = "rel1";
            string json       = "{\"" + jsonMember + "\":" + identity + "}";

            // Create a mapping
            var mapping    = CreateApiResourceMapping(new EntityRef(type.Id));
            var relMapping = CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, direction == Direction.Reverse);

            relMapping.MappedRelationshipLookupField = lookupField;
            relMapping.Save( );

            // Fill entity
            IEntity entity = RunTest(json, mapping);
            IEntityRelationshipCollection <IEntity> value = entity.GetRelationships(relationship.Id, direction);

            // Assert mapping
            Assert.That(value, Is.Not.Null);
            if (identityType.Contains("Null"))
            {
                Assert.That(value, Has.Count.EqualTo(0));
            }
            else
            {
                Assert.That(value, Has.Count.EqualTo(1));
                Assert.That(value.First( ).Id, Is.EqualTo(target.Id));
            }
        }
        public void SetRelationship( )
        {
            var employeeType = Entity.Get <EntityType>("test:employee");
            var managerType  = Entity.Get <EntityType>("test:manager");
            var nameField    = Entity.Get <StringField>("core:name");

            IEntity emp = new Entity(employeeType);

            emp.SetField(nameField, "Test Employee");

            IEntity emp2 = new Entity(employeeType);

            emp.SetField(nameField, "Test Employee 2");

            IEntity mgr = (new Entity(employeeType));

            emp.SetField(nameField, "Test Manager");

            mgr.As <Resource>( ).IsOfType.Add(managerType);

            emp.Save( );
            emp2.Save( );
            mgr.Save( );

            ToDelete.Add(emp.Id);
            ToDelete.Add(emp2.Id);
            ToDelete.Add(mgr.Id);


            var setRel = new SetRelationshipActivity( );

            setRel.Save( );
            ToDelete.Add(setRel.Id);

            var setRelAs = setRel.As <WfActivity>( );

            ActivityImplementationBase nextActivity = setRelAs.CreateWindowsActivity( );

            var args = new Dictionary <string, object>
            {
                {
                    "Origin", emp
                },
                {
                    "Relationship", new EntityRef("test:reportsTo").Entity
                },
                {
                    "Destination", mgr
                },
            };

            RunActivity(nextActivity, args);

            emp = Entity.Get(emp.Id);

            IEntityRelationshipCollection <IEntity> rels = emp.GetRelationships("test:reportsTo");

            Assert.AreEqual(1, rels.Count( ), "Ensure the manager has been set");
            Assert.AreEqual(rels.First( ).Entity.Id, mgr.Id, "Ensure the manager has been set to the correct value");


            // clear relationships
            args = new Dictionary <string, object>
            {
                {
                    "Origin", emp
                },
                {
                    "Relationship", new EntityRef("test:reportsTo").Entity
                },
                {
                    "Destination", null
                },
                {
                    "Replace Existing Destination", true
                }
            };

            RunActivity(nextActivity, args);

            emp = Entity.Get(emp.Id);

            rels = emp.GetRelationships("test:reportsTo");

            Assert.AreEqual(0, rels.Count( ), "Ensure the manager has been cleared");

            // set the reverse relationship
            args = new Dictionary <string, object>
            {
                {
                    "Origin", mgr
                },
                {
                    "Relationship", new EntityRef("test:directReports").Entity
                },
                {
                    "Destination", emp
                },
                {
                    "(Internal) Is this a reverse relationship", true
                }
            };

            RunActivity(nextActivity, args);

            mgr = Entity.Get(mgr.Id);

            rels = mgr.GetRelationships("test:directReports");

            Assert.AreEqual(1, rels.Count( ), "Ensure the employee has been set");
            Assert.AreEqual(rels.First( ).Entity.Id, emp.Id, "Ensure the employee has been set to the correct value");

            // add a second relationship, clearing the first
            args = new Dictionary <string, object>
            {
                {
                    "Origin", mgr
                },
                {
                    "Relationship", new EntityRef("test:directReports").Entity
                },
                {
                    "Destination", emp2
                },
                {
                    "(Internal) Is this a reverse relationship", true
                },
                {
                    "Replace Existing Destination", true
                }
            };

            RunActivity(nextActivity, args);

            mgr = Entity.Get(mgr.Id);

            rels = mgr.GetRelationships("test:directReports");

            Assert.AreEqual(1, rels.Count( ), "Ensure the new employee has been set and the old cleared");
            Assert.AreEqual(rels.First( ).Entity.Id, emp2.Id, "Ensure the manager has been set to the correct value");

            // add the first back in
            args = new Dictionary <string, object>
            {
                {
                    "Origin", mgr
                },
                {
                    "Relationship", new EntityRef("test:directReports").Entity
                },
                {
                    "Destination", emp
                },
                {
                    "(Internal) Is this a reverse relationship", true
                },
                {
                    "Replace Existing Destination", false
                }
            };

            RunActivity(nextActivity, args);

            mgr = Entity.Get(mgr.Id);

            rels = mgr.GetRelationships("test:directReports");

            Assert.AreEqual(2, rels.Count( ), "Add a second relationship");
        }
 public void SetRelationships(long relationshipDefinition, IEntityRelationshipCollection relationships)
 {
     throw new NotSupportedException( );
 }
Example #21
0
 void IEntityGeneric <long> .SetRelationships(long relationshipDefinition, IEntityRelationshipCollection relationships)
 {
     throw new NotImplementedException( );
 }
Example #22
0
 public void SetRelationships(string relationshipDefinition, IEntityRelationshipCollection relationships, Direction direction)
 {
     _entity.SetRelationships(relationshipDefinition, relationships, direction);
 }
Example #23
0
 void IEntityGeneric <string> .SetRelationships(string relationshipDefinition, IEntityRelationshipCollection relationships, Direction direction)
 {
     throw new NotImplementedException( );
 }
 public void SetRelationships(string relationshipDefinition, IEntityRelationshipCollection relationships, Direction direction)
 {
     throw new NotSupportedException( );
 }