private static void TestAttributeChangeResults(CSEntryChange csentry, AcmaSchemaAttribute testAttribute, AttributeModificationType expectedModificationType, IList <object> expectedValues) { AttributeChange attributeChange = null; if (csentry.AttributeChanges.Contains(testAttribute.Name)) { attributeChange = csentry.AttributeChanges[testAttribute.Name]; } if (attributeChange == null && expectedModificationType == AttributeModificationType.Unconfigured) { return; } else if (attributeChange == null && expectedModificationType != AttributeModificationType.Unconfigured) { Assert.Fail("An AttributeChange was found where none were expected"); } else if (attributeChange == null) { Assert.Fail("An AttributeChange was expected but not found"); } if (attributeChange.ModificationType != expectedModificationType) { Assert.Fail("The AttributeChange was not of the expected type"); } if (expectedModificationType != AttributeModificationType.Delete) { List <AttributeValue> comparerValues1 = attributeChange.ValueChanges.Select(t => new AttributeValue(testAttribute, t.Value)).ToList(); List <AttributeValue> comparerValues2 = expectedValues.Select(t => new AttributeValue(testAttribute, t)).ToList(); CollectionAssert.AreEquivalent(comparerValues1, comparerValues2); } }
void DamageDoneOnHero(BattleHero hero, int damage) { AttackEffect attackEffect = m_AttackEffecPool.GetItem(); attackEffect.transform.position = hero.transform.position; attackEffect.RegulateSize(hero.GetComponent <RectTransform>()); attackEffect.gameObject.SetActive(true); StringBuilder builder = new StringBuilder(AttributeChange.HEALTH_DECREASE_TEXT); builder.Replace("{DECREASE}", damage.ToString()); AttributeChange attributeChange = AttribueChangeEffectPool.GetItem(); attributeChange.PrepareForActivation(hero.transform, false, builder.ToString()); attributeChange.gameObject.SetActive(true); if (!hero.IsEnemy) { CurrentFightSettings.selectedAllyHeroIndex = FindHeroIndex(m_PlayerHeroes, hero); } EventMessenger.NotifyEvent(SaveEvents.SAVE_GAME_STATE); bool isDead = hero.TakeDamage(damage); }
public object GetObjectToSerialize(object obj, Type targetType) { ValueChange valueChange = obj as ValueChange; if (valueChange != null) { return(new ValueChangeSerializable(valueChange)); } AttributeChange attributeChange = obj as AttributeChange; if (attributeChange != null) { return(new AttributeChangeSerializable(attributeChange)); } CSEntryChange csentry = obj as CSEntryChange; if (csentry != null) { return(new CSEntryChangeSerializable(csentry)); } CSEntryChangeResult csentryresult = obj as CSEntryChangeResult; if (csentryresult != null) { return(new CSEntryChangeResultSerializable(csentryresult)); } AnchorAttribute anchor = obj as AnchorAttribute; if (anchor != null) { return(new AnchorAttributeSerializable(anchor)); } SchemaAttribute schemaAttribute = obj as SchemaAttribute; if (schemaAttribute != null) { return(new SchemaAttributeSerializable(schemaAttribute)); } SchemaType schemaType = obj as SchemaType; if (schemaType != null) { return(new SchemaTypeSerializable(schemaType)); } Schema schema = obj as Schema; if (schema != null) { return(new SchemaSerializable(schema)); } return(obj); }
/// <summary> /// Converts an existing AttributeChange to a new AttributeChange of type 'replace' /// </summary> /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param> /// <param name="attribute">The attribute to create the AttributeChange for</param> /// <param name="values">The values to assign</param> /// <param name="existingChange">The existing attribute change that was found on the CSEntryChange</param> private static void ConvertAttributeChangeToReplace(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <object> values, AttributeChange existingChange) { TypeConverter.ThrowOnAnyInvalidDataType(values); attributeChanges.Remove(existingChange); switch (objectModificationType) { case ObjectModificationType.Add: attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, values)); break; case ObjectModificationType.Delete: throw new DeletedObjectModificationException(); case ObjectModificationType.Replace: attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, values)); break; case ObjectModificationType.Update: attributeChanges.Add(AttributeChange.CreateAttributeReplace(attribute.Name, values)); break; case ObjectModificationType.Unconfigured: case ObjectModificationType.None: default: break; } }
private async Task GroupMemberToCSEntryChange(CSEntryChange c, SchemaType schemaType) { if (schemaType.Attributes.Contains("member")) { List <DirectoryObject> members = await GraphHelperGroups.GetGroupMembers(this.client, c.DN, this.token); List <object> memberIds = members.Where(u => !this.userFilter.ShouldExclude(u.Id, this.token)).Select(t => t.Id).ToList <object>(); if (memberIds.Count > 0) { c.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("member", memberIds)); } } if (schemaType.Attributes.Contains("owner")) { List <DirectoryObject> owners = await GraphHelperGroups.GetGroupOwners(this.client, c.DN, this.token); List <object> ownerIds = owners.Where(u => !this.userFilter.ShouldExclude(u.Id, this.token)).Select(t => t.Id).ToList <object>(); if (ownerIds.Count > 0) { c.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("owner", ownerIds)); } } }
private void AddAttributeChanges <T>(ref CSEntryChange csEntryChange, T item) { if (csEntryChange == null) { throw new ArgumentNullException(nameof(csEntryChange)); } if (item == null) { throw new ArgumentNullException(nameof(item)); } IEnumerable <PropertyInfo> properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(x => x.CanRead && x.CanWrite) .Where(x => x.PropertyType == typeof(string)) .Where(x => x.GetGetMethod(true).IsPublic); string name, value; foreach (PropertyInfo info in properties) { value = info.GetValue(item, null) as string; if (string.IsNullOrEmpty(value) || info.Name.Equals("Id", StringComparison.CurrentCultureIgnoreCase)) { continue; } name = $"{char.ToLower(info.Name[0])}{info.Name.Substring(1)}"; csEntryChange.AttributeChanges.Add( AttributeChange.CreateAttributeAdd(name, info.GetValue(item, null))); } }
/// <summary> /// Converts an AttributeChange of type 'delete' to a new AttributeChange of type 'update' /// </summary> /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param> /// <param name="attribute">The attribute to create the AttributeChange for</param> /// <param name="valueChanges">The value changes to apply</param> /// <param name="existingChange">The existing attribute change that was found on the CSEntryChange</param> private static void ConvertAttributeChangeUpdateFromDelete(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <ValueChange> valueChanges, AttributeChange existingChange) { attributeChanges.Remove(existingChange); IList <object> valueAdds = valueChanges.Where(t => t.ModificationType == ValueModificationType.Add).Select(t => t.Value).ToList(); switch (objectModificationType) { case ObjectModificationType.Add: throw new InvalidOperationException("The attribute change type is not valid for the object modification type"); case ObjectModificationType.Delete: throw new DeletedObjectModificationException(); case ObjectModificationType.Replace: throw new InvalidOperationException("The attribute change type is not valid for the object modification type"); case ObjectModificationType.Update: attributeChanges.Add(AttributeChange.CreateAttributeReplace(attribute.Name, valueAdds)); break; case ObjectModificationType.None: case ObjectModificationType.Unconfigured: default: throw new UnknownOrUnsupportedModificationTypeException(objectModificationType); } }
private static CSEntryChangeResult PutCSEntryChangeAdd(CSEntryChange csentry, CSEntryChange deltaCSEntry, MASchemaType maType, SchemaType type, IManagementAgentParameters config) { deltaCSEntry.ObjectModificationType = csentry.ObjectModificationType; IApiInterfaceObject primaryInterface = maType.ApiInterface; object instance = primaryInterface.CreateInstance(csentry); foreach (AttributeChange change in primaryInterface.ApplyChanges(csentry, type, ref instance)) { deltaCSEntry.AttributeChanges.Add(change); } deltaCSEntry.DN = primaryInterface.GetDNValue(instance); List <AttributeChange> anchorChanges = new List <AttributeChange>(); foreach (string anchorAttributeName in maType.AnchorAttributeNames) { object value = primaryInterface.GetAnchorValue(anchorAttributeName, instance); deltaCSEntry.AnchorAttributes.Add(AnchorAttribute.Create(anchorAttributeName, value)); anchorChanges.Add(AttributeChange.CreateAttributeAdd(anchorAttributeName, value)); } return(CSEntryChangeResult.Create(csentry.Identifier, anchorChanges, MAExportError.Success)); }
// for single value public void AddCSEntryAttribute(AttributeType _attributeType, CSEntryChange _csentry, string _attributeName, object _attributeValue) { try { switch (_attributeType) { case AttributeType.String: _csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(_attributeName, _attributeValue.ToString())); break; case AttributeType.Boolean: _csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(_attributeName, System.Convert.ToBoolean(_attributeValue.ToString()))); break; case AttributeType.Integer: _csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(_attributeName, System.Convert.ToInt64(_attributeValue.ToString()))); break; default: throw new ExtensionException("Unsupported attribute type : " + _attributeType.GetTypeCode().ToString()); } } catch (Exception ex) { throw new ExtensibleExtensionException("Exception in AddCSEntryAttribute", ex); } }
/// <summary> /// Determines if the specified single-valued attribute change matches this object filter /// </summary> /// <param name="attributeChange">The attribute change object</param> /// <returns>A value indicating whether the specified object should be filtered from the result set</returns> private bool IsFilteredSingleValue(AttributeChange attributeChange) { ValueChange valueChange = attributeChange.ValueChanges.FirstOrDefault(t => t.ModificationType == ValueModificationType.Add); if (valueChange == null) { return(false); } switch (this.Attribute.Type) { case AttributeType.Binary: return(ComparisonEngine.CompareBinary((byte[])valueChange.Value, this.Value, this.Operator)); case AttributeType.Boolean: return(ComparisonEngine.CompareBoolean(valueChange.Value as string, this.Value, this.Operator)); case AttributeType.Integer: return(ComparisonEngine.CompareLong(valueChange.Value as string, this.Value, this.Operator)); case AttributeType.String: return(ComparisonEngine.CompareString((string)valueChange.Value, this.Value, this.Operator)); case AttributeType.Reference: default: throw new NotSupportedException(); } }
private CSEntryChangeResult PutCSEntryChangeAdd(CSEntryChange csentry, ExportContext context) { CreateGroupOptions options = new CreateGroupOptions(); IList <string> members = new List <string>(); foreach (AttributeChange change in csentry.AttributeChanges) { if (change.Name == "name") { options.Name = change.GetValueAdd <string>(); } else if (change.Name == "description") { options.Description = change.GetValueAdd <string>(); } else if (change.Name == "member") { members = change.GetValueAdds <string>(); } } IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client; IGroup result = AsyncHelper.RunSync(client.Groups.CreateGroupAsync(options, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token); foreach (string member in members) { AsyncHelper.RunSync(client.Groups.AddUserToGroupAsync(result.Id, member, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token); } List <AttributeChange> anchorChanges = new List <AttributeChange>(); anchorChanges.Add(AttributeChange.CreateAttributeAdd("id", result.Id)); return(CSEntryChangeResult.Create(csentry.Identifier, anchorChanges, MAExportError.Success)); }
/// <summary> /// Evaluates the rule against the specified attribute attributeChange /// </summary> /// <param name="attributeChange">The attribute attributeChange to evaluate</param> /// <returns>A value indicating whether the conditions of the rule were met</returns> private bool EvaluateRuleOnAttributeChange(AttributeChange attributeChange) { if (this.Attribute.Name != attributeChange.Name) { throw new InvalidOperationException("The attribute change did not match the expected attribute in the rule"); } if (attributeChange.ModificationType == AttributeModificationType.Add && this.TriggerEvents.HasFlag(TriggerEvents.Add)) { return(true); } else if (attributeChange.ModificationType == AttributeModificationType.Update && this.TriggerEvents.HasFlag(TriggerEvents.Update)) { return(true); } else if (attributeChange.ModificationType == AttributeModificationType.Replace && this.TriggerEvents.HasFlag(TriggerEvents.Update)) { return(true); } else if (attributeChange.ModificationType == AttributeModificationType.Delete && this.TriggerEvents.HasFlag(TriggerEvents.Delete)) { return(true); } return(false); }
public void SilentlyRemoveNonExistentAlias() { string id = null; string dn = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}"; User e = new User { PrimaryEmail = dn, Password = Guid.NewGuid().ToString(), Name = new UserName { GivenName = "gn", FamilyName = "sn" } }; e = UnitTestControl.TestParameters.UsersService.Add(e); id = e.Id; string alias1 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}"; string alias2 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}"; UnitTestControl.TestParameters.UsersService.AddAlias(id, alias1); UnitTestControl.TestParameters.UsersService.AddAlias(id, alias2); CSEntryChange cs = CSEntryChange.Create(); cs.ObjectModificationType = ObjectModificationType.Update; cs.DN = dn; cs.ObjectType = SchemaConstants.User; cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id)); cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("aliases", new List <ValueChange> { new ValueChange($"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}", ValueModificationType.Delete) })); try { CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.User], UnitTestControl.TestParameters); if (result.ErrorCode != MAExportError.Success) { Assert.Fail(result.ErrorName); } System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval); e = UnitTestControl.TestParameters.UsersService.Get(id); CollectionAssert.AreEquivalent(new string[] { alias1, alias2 }, e.Aliases); } finally { if (id != null) { UnitTestControl.TestParameters.UsersService.Delete(id); } } }
public void ExpandSimpleAttributeSVBinary() { AcmaSchemaAttribute attribute = ActiveConfig.DB.GetAttribute("objectSid"); AcmaSchemaObjectClass schemaObject = ActiveConfig.DB.GetObjectClass("person"); string declarationString = "{objectSid}"; AttributeDeclarationParser p = new AttributeDeclarationParser(declarationString); AttributeDeclaration target = p.GetAttributeDeclaration(); CSEntryChange sourceObject = CSEntryChange.Create(); sourceObject.ObjectModificationType = ObjectModificationType.Add; sourceObject.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, new byte[] { 0, 1, 2, 3, 4 })); object value = target.Expand(sourceObject).First(); if (value == null) { Assert.Fail("The declaration string did not return a value"); } else if (!(value is byte[])) { Assert.Fail("The declaration string returned the wrong data type"); } else if (!((byte[])value).SequenceEqual(new byte[] { 0, 1, 2, 3, 4 })) { Assert.Fail("The declaration string did not return the expected value"); } }
public void ExpandSimpleAttributeSVBoolean() { AcmaSchemaAttribute attribute = ActiveConfig.DB.GetAttribute("connectedToCallista"); AcmaSchemaObjectClass schemaObject = ActiveConfig.DB.GetObjectClass("person"); string declarationString = "{connectedToCallista}"; AttributeDeclarationParser p = new AttributeDeclarationParser(declarationString); AttributeDeclaration target = p.GetAttributeDeclaration(); CSEntryChange sourceObject = CSEntryChange.Create(); sourceObject.ObjectModificationType = ObjectModificationType.Add; sourceObject.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, true)); object value = target.Expand(sourceObject).First(); if (value == null) { Assert.Fail("The declaration string did not return a value"); } else if (!(value is bool)) { Assert.Fail("The declaration string returned the wrong data type"); } else if ((bool)value != true) { Assert.Fail("The declaration string did not return the expected value"); } }
public void UpdateDescription() { Group e = null; try { e = UnitTestControl.CreateGroup(); CSEntryChange cs = CSEntryChange.Create(); cs.ObjectModificationType = ObjectModificationType.Update; cs.DN = e.Email; cs.ObjectType = SchemaConstants.Group; cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id)); cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("description")); CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters); if (result.ErrorCode != MAExportError.Success) { Assert.Fail($"{result.ErrorName}\n{result.ErrorDetail}"); } e = UnitTestControl.TestParameters.GroupsService.Get(e.Id); Assert.AreEqual(cs.DN, e.Email); Assert.AreEqual(true, e.AdminCreated); Assert.AreEqual(string.Empty, e.Description); } finally { UnitTestControl.Cleanup(e); } }
private CSEntryChange GetCsEntryChange <T, V>(T item1, V item2, string dn, string objectType) { if (item1 == null) { throw new ArgumentNullException(nameof(item1)); } if (item2 == null) { throw new ArgumentNullException(nameof(item2)); } if (string.IsNullOrEmpty(dn)) { throw new ArgumentNullException(nameof(dn)); } if (string.IsNullOrEmpty(objectType)) { throw new ArgumentNullException(nameof(objectType)); } CSEntryChange csEntryChange = CSEntryChange.Create(); csEntryChange.DN = dn; csEntryChange.ObjectModificationType = ObjectModificationType.Add; csEntryChange.ObjectType = objectType; csEntryChange.AttributeChanges.Add( AttributeChange.CreateAttributeAdd("objectID", dn)); AddAttributeChanges(ref csEntryChange, item1); AddAttributeChanges(ref csEntryChange, item2); return(csEntryChange); }
/// <summary> /// Contributes to a CSEntryChange for the specified MA_Delta_Object by populating newly added object and its attributes /// </summary> /// <param name="maObject">The MAObject to construct the CSEntry for</param> /// <param name="csentry">The CSEntryChange object to contribute to</param> private static void GetObject(MAObjectHologram maObject, CSEntryChange csentry, IEnumerable <AcmaSchemaAttribute> requiredAttributes) { try { foreach (AcmaSchemaAttribute maAttribute in requiredAttributes) { List <object> values = new List <object>(); AttributeValues dbvalues = maObject.GetAttributeValues(maAttribute); values.AddRange(dbvalues.Where(t => !t.IsNull).Select(t => t.Value)); if (values.Count > 0) { if (maAttribute.Type == ExtendedAttributeType.Reference) { csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(maAttribute.Name, values.Select(t => t.ToString()).ToList <object>())); } else if (maAttribute.Type == ExtendedAttributeType.DateTime) { csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(maAttribute.Name, values.Select(t => ((DateTime)t).ToResourceManagementServiceDateFormat()).ToList <object>())); } else { csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(maAttribute.Name, values)); } } } } catch (SafetyRuleViolationException ex) { csentry.ErrorCodeImport = MAImportError.ImportErrorCustomContinueRun; csentry.ErrorName = ex.Message; csentry.ErrorDetail = ex.Message + "\n" + ex.StackTrace; } }
/// <summary> /// Creates a new AttributeChange of type 'update' /// </summary> /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param> /// <param name="attribute">The attribute to create the AttributeChange for</param> /// <param name="valueChanges">The value changes to apply</param> private static void CreateAttributeChangeUpdate(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <ValueChange> valueChanges) { switch (objectModificationType) { case ObjectModificationType.Add: attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, valueChanges.Where(t => t.ModificationType == ValueModificationType.Add).Select(t => t.Value).ToList <object>())); break; case ObjectModificationType.Delete: throw new DeletedObjectModificationException(); case ObjectModificationType.Replace: attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, valueChanges.Where(t => t.ModificationType == ValueModificationType.Add).Select(t => t.Value).ToList <object>())); break; case ObjectModificationType.Update: attributeChanges.Add(AttributeChange.CreateAttributeUpdate(attribute.Name, valueChanges)); break; case ObjectModificationType.Unconfigured: case ObjectModificationType.None: default: throw new UnknownOrUnsupportedModificationTypeException(objectModificationType); } }
/// <summary> /// Converts a CSEntryChange from an 'replace' modification type to 'update', converting the contained AttributeChanges from 'add' to 'replace', and adding in the appropriate 'delete' AttributeChanges /// </summary> /// <param name="csentry">The CSEntryChange to modify</param> /// <returns>A copy of the original CSEntryChange with the modification type set to 'update'</returns> public static CSEntryChange ConvertCSEntryChangeReplaceToUpdate(this CSEntryChange csentry, MAObjectHologram maObject) { CSEntryChange newcsentry = CSEntryChange.Create(); newcsentry.ObjectModificationType = ObjectModificationType.Update; newcsentry.ObjectType = csentry.ObjectType; newcsentry.DN = csentry.DN; AcmaSchemaObjectClass objectClass = ActiveConfig.DB.GetObjectClass(csentry.ObjectType); foreach (AttributeChange attributeChange in csentry.AttributeChanges) { AttributeChange newAttributeChange = AttributeChange.CreateAttributeReplace(attributeChange.Name, attributeChange.ValueChanges.Select(t => t.Value).ToList <object>()); newcsentry.AttributeChanges.Add(newAttributeChange); } foreach (AcmaSchemaAttribute attribute in objectClass.Attributes.Where(t => !t.IsBuiltIn && !t.IsInheritedInClass(objectClass.Name))) { if (!csentry.AttributeChanges.Any(t => t.Name == attribute.Name)) { if (maObject.HasAttribute(attribute)) { newcsentry.AttributeChanges.Add(AttributeChange.CreateAttributeDelete(attribute.Name)); } } } Logger.WriteLine("Converted CSEntryChangeReplace to CSEntryChangeUpdate", LogLevel.Debug); return(newcsentry); }
/// <summary> /// Converts an AttributeChange of type 'update' to a new AttributeChange of type 'update' /// </summary> /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param> /// <param name="attribute">The attribute to create the AttributeChange for</param> /// <param name="valueChanges">The value changes to apply</param> /// <param name="existingChange">The existing attribute change that was found on the CSEntryChange</param> private static void ConvertAttributeChangeUpdateFromUpdate(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <ValueChange> valueChanges, AttributeChange existingChange) { IList <ValueChange> mergedList = MergeValueChangeLists(attribute, existingChange.ValueChanges, valueChanges); attributeChanges.Remove(existingChange); switch (objectModificationType) { case ObjectModificationType.Add: throw new InvalidOperationException("The attribute change type is not valid for the object modification type"); case ObjectModificationType.Delete: throw new DeletedObjectModificationException(); case ObjectModificationType.Replace: throw new InvalidOperationException("The attribute change type is not valid for the object modification type"); case ObjectModificationType.Update: attributeChanges.Add(AttributeChange.CreateAttributeUpdate(attribute.Name, mergedList)); break; case ObjectModificationType.None: case ObjectModificationType.Unconfigured: default: throw new UnknownOrUnsupportedModificationTypeException(objectModificationType); } }
public void TestToCSEntryChangeUpdate() { IAttributeAdapter schemaItem = UnitTestControl.Schema["user"].AttributeAdapters.First(t => t.FieldName == "orgUnitPath"); User u = new User { OrgUnitPath = "/Test" }; CSEntryChange x = CSEntryChange.Create(); x.ObjectModificationType = ObjectModificationType.Update; IList <AttributeChange> result = schemaItem.CreateAttributeChanges(x.DN, x.ObjectModificationType, u).ToList(); AttributeChange change = result.FirstOrDefault(t => t.Name == "orgUnitPath"); Assert.IsNotNull(change); Assert.AreEqual("/Test", change.GetValueAdd <string>()); Assert.AreEqual(AttributeModificationType.Replace, change.ModificationType); x.AttributeChanges.Add(change); User ux = new User(); schemaItem.UpdateField(x, ux); Assert.AreEqual("/Test", ux.OrgUnitPath); }
/// <summary> /// Creates a new AttributeChange of type 'delete' /// </summary> /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param> /// <param name="attribute">The attribute to create the AttributeChange for</param> private static void CreateAttributeChangeDelete(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute) { switch (objectModificationType) { case ObjectModificationType.Add: // This is a new object, so there is nothing to delete break; case ObjectModificationType.Delete: throw new DeletedObjectModificationException(); case ObjectModificationType.Replace: // This object is being replaced, so the absence of an attribute add implies that any existing attribute values shall be deleted break; case ObjectModificationType.Update: attributeChanges.Add(AttributeChange.CreateAttributeDelete(attribute.Name)); break; case ObjectModificationType.None: case ObjectModificationType.Unconfigured: default: throw new UnknownOrUnsupportedModificationTypeException(objectModificationType); } }
/// <summary> /// Evaluates the rule against the specified attribute change /// </summary> /// <param name="attributeChange">The attribute change to evaluate</param> /// <returns>A value indicating whether the conditions of the rule were met</returns> private bool EvaluateRuleOnAttributeChange(AttributeChange attributeChange) { bool result = false; if (attributeChange.ModificationType == AttributeModificationType.Add && this.TriggerEvents.HasFlag(TriggerEvents.Add)) { result = true; } else if (attributeChange.ModificationType == AttributeModificationType.Update && this.TriggerEvents.HasFlag(TriggerEvents.Update)) { result = true; } else if (attributeChange.ModificationType == AttributeModificationType.Replace && this.TriggerEvents.HasFlag(TriggerEvents.Update)) { result = true; } else if (attributeChange.ModificationType == AttributeModificationType.Delete && this.TriggerEvents.HasFlag(TriggerEvents.Delete)) { result = true; } if (result) { Logger.WriteLine("Attribute change rule '{0}' passed due to attribute modification type '{1}' on '{2}'", LogLevel.Debug, this.AttributeName, attributeChange.ModificationType.ToString(), attributeChange.Name); } return(result); }
private async Task CreateChannelCSEntryChanges(string groupid, SchemaType schemaType) { if (!this.context.Types.Types.Contains("channel")) { return; } var channels = await GraphHelperTeams.GetChannels(this.betaClient, groupid, this.token); foreach (var channel in channels) { var members = await GraphHelperTeams.GetChannelMembers(this.betaClient, groupid, channel.Id, this.token); CSEntryChange c = CSEntryChange.Create(); c.ObjectType = "channel"; c.ObjectModificationType = ObjectModificationType.Add; c.AnchorAttributes.Add(AnchorAttribute.Create("id", channel.Id)); c.DN = channel.Id; c.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("displayName", channel.DisplayName)); if (!string.IsNullOrWhiteSpace(channel.Description)) { c.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("description", channel.Description)); } if (members.Count > 0) { c.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("member", members.Select(t => t.Id).ToList <object>())); } this.context.ImportItems.Add(c, this.token); } }
public void TestManagerIsMember() { Group e = null; User user = null; try { e = UnitTestControl.CreateGroup(); Thread.Sleep(1000); user = UserTests.CreateUser(); UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, new Member() { Email = user.PrimaryEmail, Role = "MANAGER" }); Thread.Sleep(5000); GroupMembership members = UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(e.Email); ApiInterfaceGroupMembership i = new ApiInterfaceGroupMembership(UnitTestControl.TestParameters); IList <AttributeChange> changes = i.GetChanges(e.Email, ObjectModificationType.Add, UnitTestControl.MmsSchema.Types["group"], members); AttributeChange manager = changes.First(t => t.Name == "manager"); AttributeChange member = changes.First(t => t.Name == "member"); Assert.AreEqual(manager.ValueChanges.First().Value, user.PrimaryEmail); Assert.AreEqual(member.ValueChanges.First().Value, user.PrimaryEmail); } finally { UnitTestControl.Cleanup(e, user); } }
/// <summary> /// Creates an AttributeChange of the specified type /// </summary> /// <param name="csentry">The CSEntryChange to add the AttributeChange to</param> /// <param name="attributeName">The name of the attribute</param> /// <param name="modificationType">The type of modification to apply to the attribute</param> /// <param name="value">The value to apply to the modification operation</param> public static void CreateAttributeChange(this CSEntryChange csentry, string attributeName, AttributeModificationType modificationType, object value) { switch (modificationType) { case AttributeModificationType.Add: csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(attributeName, value)); break; case AttributeModificationType.Delete: csentry.AttributeChanges.Add(AttributeChange.CreateAttributeDelete(attributeName)); break; case AttributeModificationType.Replace: if (value == null) { csentry.AttributeChanges.Add(AttributeChange.CreateAttributeReplace(attributeName, value)); } else { csentry.AttributeChanges.Add(AttributeChange.CreateAttributeDelete(attributeName)); } break; case AttributeModificationType.Update: csentry.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate(attributeName, value)); break; case AttributeModificationType.Unconfigured: default: throw new InvalidOperationException("Unknown modification type"); } }
public void TestExternalManagerIsExternalMember() { Group e = null; try { e = UnitTestControl.CreateGroup(); Thread.Sleep(1000); string member2 = "*****@*****.**"; UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, new Member() { Email = member2, Role = "MANAGER" }); Thread.Sleep(5000); GroupMembership members = UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(e.Email); ApiInterfaceGroupMembership i = new ApiInterfaceGroupMembership(UnitTestControl.TestParameters); IList <AttributeChange> changes = i.GetChanges(e.Email, ObjectModificationType.Add, UnitTestControl.MmsSchema.Types["group"], members); AttributeChange manager = changes.First(t => t.Name == "externalManager"); AttributeChange member = changes.First(t => t.Name == "externalMember"); Assert.AreEqual(manager.ValueChanges.First().Value, member2); Assert.AreEqual(member.ValueChanges.First().Value, member2); } finally { UnitTestControl.Cleanup(e); } }
public void TestCSEntryChangeSplitCSEntries() { List <CSEntryChange> incomingchanges = new List <CSEntryChange>(); ObjectModificationType objectModificationType = ObjectModificationType.Add; AcmaSchemaAttribute testAttribute1 = ActiveConfig.DB.GetAttribute("supervisor"); AcmaSchemaAttribute testAttribute2 = ActiveConfig.DB.GetAttribute("accountName"); CSEntryChange csentry; Guid reference = Guid.NewGuid(); csentry = CreateNewCSEntry(objectModificationType); csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(testAttribute1.Name, reference)); csentry.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(testAttribute2.Name, "testuser")); incomingchanges.Add(csentry); CSEntryChange csentry2; csentry2 = CreateNewCSEntry(objectModificationType); csentry2.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(testAttribute2.Name, "testuser")); incomingchanges.Add(csentry2); List <CSEntryChange> changes = CSEntryChangeExtensions.SplitReferenceUpdatesFromCSEntryChanges(incomingchanges).ToList(); if (changes.Count != 3) { Assert.Fail("The operation returned the incorrect number of changes"); } }
public void TestFromCSEntryChangeAdd() { IAttributeAdapter schemaItem = UnitTestControl.Schema["contact"].GetAdapterForMmsAttribute("organizations"); ContactEntry e = new ContactEntry(); CSEntryChange x = CSEntryChange.Create(); x.ObjectModificationType = ObjectModificationType.Add; x.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("organizations_work_name", "myorg")); x.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("organizations_work_department", "department")); x.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("organizations_work_jobDescription", "jobdescription")); x.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("organizations_work_location", "location")); x.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("organizations_work_symbol", "symbol")); x.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("organizations_work_title", "title")); schemaItem.UpdateField(x, e); Organization o = e.Organizations.First(t => t.Rel == "http://schemas.google.com/g/2005#work"); Assert.AreEqual("myorg", o.Name); Assert.AreEqual("department", o.Department); Assert.AreEqual("jobdescription", o.JobDescription); Assert.AreEqual("location", o.Location); Assert.AreEqual("symbol", o.Symbol); Assert.AreEqual("title", o.Title); Assert.AreEqual(true, o.Primary); }
public AttributeChange Compare(string name, object valueBefore, object valueAfter) { AttributeChange attributeChange = null; if ((valueBefore == null && valueAfter != null) || (valueBefore != null && !valueBefore.Equals(valueAfter))) { attributeChange = new AttributeChange(name, valueBefore, valueAfter); } return attributeChange; }
public static HtmlDocumentFacade ProcessStyleDirectives(this HtmlDocumentFacade doc) { int docOrder = 0; var directives = new List<StyleDirective>(); var attributeLinkStyles = doc.querySelectorAll("style[" + AttributeLinkAttribute + "]"); attributeLinkStyles.ForEach(attribeLinkStyleNode => { #region process all attribute style nodes string attributeLink = Fun.Val(() => { string overrideAttributeLink = attribeLinkStyleNode.getAttribute(AttributeLinkAttribute); if (string.IsNullOrEmpty(overrideAttributeLink)) return "Attributes"; return overrideAttributeLink; }); var attributeClasses = new List<StyleDirective>(); string content = attribeLinkStyleNode.innerHTML.Trim(); var styleSheet = HtmlDocumentFacade.processCssContent(content); var rules = styleSheet.rules.ToList(); rules.ForEach(rule => { var styleDirective = new StyleDirective { Rule = rule, DocOrder = docOrder++, Node = attribeLinkStyleNode, }; if (rule.selectorText.Contains(attributeLink)) { attributeClasses.Add(styleDirective); } else { directives.Add(styleDirective); if (attributeClasses.Count > 0) { styleDirective.AttributeDirectives = attributeClasses; attributeClasses = new List<StyleDirective>(); } } }); #endregion }); directives.Sort(); Action<AttributeChanges, HtmlNodeFacade, string> saveOld = (attributeChanges, targetElement, attribName) => { if (attributeChanges != null && !attributeChanges.ContainsKey(attribName)) { string oldValue = targetElement.getAttribute(attribName); attributeChanges[attribName] = new AttributeChange { OriginalValue = string.IsNullOrEmpty(oldValue) ? null : oldValue, }; } }; Action<AttributeChanges, HtmlNodeFacade, string> saveOldClass = (attributeChanges, targetElement, className) => { if (!targetElement.hasClass(className)) { if (!attributeChanges.ClassesToRemoveNN.Contains(className)) { attributeChanges.ClassesToRemove.Add(className); } } }; //var clientSideChanges = new Dictionary<string, Dictionary<string, string>>(); //id => attribute name => value //Action<HtmlNodeFacade, string, string> setClientSideAttribValue = (el, attribName, newValue) => //{ // if (!clientSideChanges.ContainsKey(el.id)) clientSideChanges[el.id] = new Dictionary<string, string>(); // var attribChanges = clientSideChanges[el.id]; // attribChanges[attribName] = newValue; //}; foreach (var cssRule in directives) { if(cssRule.AttributeDirectives == null) continue; cssRule.AttributeDirectives.Sort(); var targetElements = doc.querySelectorAll(cssRule.Rule.selectorText); var pc = doc.ProcessContext; foreach (var attributeDir in cssRule.AttributeDirectives) { var srcElements = doc.querySelectorAll(attributeDir.Rule.selectorText); foreach (var srcElement in srcElements) { bool serversideOnly = (_TestForServerSideOnly(srcElement)); bool clientsideOnly = (_TestForClientSideOnly(srcElement)); if (clientsideOnly) continue; string scriptToExecute = null; if (srcElement.tagName == "SCRIPT") { string innerHTML = srcElement.innerHTML.Trim(); if (innerHTML.Contains("function ")) { var scriptTag = HtmlDocumentFacade.processJSTag(innerHTML); var fns = scriptTag.Functions .Where(fn => fn.Params.Length == 1) .Select(fn => fn.Name) ; scriptToExecute = string.Join(";", fns.ToArray()); } else { scriptToExecute = innerHTML.RemoveWhitespace().Trim(';'); } } var attribs = srcElement.attributes; foreach (var targetElement in targetElements) { if(scriptToExecute!=null ) targetElement.setAttribute("data-dbs-onload", scriptToExecute); AttributeChanges attributeChanges = null; string elId = pc.GetOrCreateID(targetElement); //need elements to have id for client side linkage among other things if (serversideOnly) { if (!pc.AttributeChangesNN.ContainsKey(elId)) { attributeChanges = new AttributeChanges(); pc.AttributeChanges[elId] = attributeChanges; } else { attributeChanges = pc.AttributeChanges[elId]; } } foreach (var attrib in attribs) { var nm = attrib.name; switch (nm) { case "class": case "hidden": case "data-mode": continue; case "data-class": saveOldClass(attributeChanges, targetElement, attrib.value); targetElement.addClass(attrib.value); break; case "data-hidden": saveOld(attributeChanges, targetElement, "hidden"); targetElement.setAttribute("hidden", attrib.value); break; case "data-data-mode": saveOld(attributeChanges, targetElement, "data-mode"); targetElement.setAttribute("data-mode", attrib.value); break; default: saveOld(attributeChanges, targetElement, nm); targetElement.setAttribute(nm, attrib.value); break; } } } } } } return doc; //styleDirectiveRules.Sort(); //var styleDirectiveContext = new StyleDirectiveContext(); //foreach (var directive in styleDirectiveRules) //{ // #region Process Directives // string serversideMethodString = directive.Compiler; // if (serversideMethodString == DBS_Attr) // { // //ProcessDBSAttr(directive, styleDirectiveContext); // } // else // { // } // #endregion //} //foreach (var actionKVP in styleDirectiveContext.ElementActions) //{ // actionKVP.Value(actionKVP.Key); //} //return doc; }