private void AssignAdminRole(IOrganizationService service, Guid id) { string adminRoleName = "System Administrator"; try { QueryExpression query = new QueryExpression { EntityName = "role", ColumnSet = new ColumnSet("name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = {adminRoleName} } } } }; EntityCollection roles = service.RetrieveMultiple(query); EntityReferenceCollection entityRefCln = new EntityReferenceCollection(); foreach (Entity entity in roles.Entities) { entityRefCln.Add(entity.ToEntityReference()); } service.Associate("team", id, new Relationship("teamroles_association"), entityRefCln); } catch (Exception ex) { } }
public void TestAssocDissocN1() { using (var context = new Xrm(orgAdminUIService)) { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(Contact.EntityLogicalName, contact1.Id)); Relationship relationship = new Relationship("account_primary_contact"); orgAdminUIService.Associate(Account.EntityLogicalName, account1.Id, relationship, relatedEntities); var retrieved = orgAdminUIService.Retrieve(Account.EntityLogicalName, account1.Id, new ColumnSet(true)) as Account; Assert.AreEqual(contact1.Id, retrieved.PrimaryContactId.Id); orgAdminUIService.Disassociate(Account.EntityLogicalName, account1.Id, relationship, relatedEntities); retrieved = orgAdminUIService.Retrieve(Account.EntityLogicalName, account1.Id, new ColumnSet(true)) as Account; Assert.IsNull(retrieved.PrimaryContactId); relatedEntities.Add(new EntityReference(Contact.EntityLogicalName, contact2.Id)); try { orgAdminUIService.Associate(Account.EntityLogicalName, account1.Id, relationship, relatedEntities); Assert.Fail(); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(FaultException)); } } }
public void TestAssocDissoc1N() { using (var context = new Xrm(orgAdminUIService)) { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, account1.Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, account2.Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, account3.Id)); Relationship relationship = new Relationship("account_primary_contact"); orgAdminUIService.Associate(Contact.EntityLogicalName, contact1.Id, relationship, relatedEntities); foreach (var acc in context.AccountSet.Where(x => x.Name.StartsWith("Account"))) { Assert.AreEqual(contact1.Id, acc.PrimaryContactId.Id); Assert.AreEqual(Contact.EntityLogicalName, acc.PrimaryContactId.LogicalName); } context.ClearChanges(); orgAdminUIService.Disassociate(Contact.EntityLogicalName, contact1.Id, relationship, relatedEntities); foreach (var acc in context.AccountSet.Where(x => x.Name.StartsWith("Account"))) { Assert.IsNull(acc.PrimaryContactId); } } }
public void TestNestedJoinsLinkedSelectOnId() { using (var context = new Xrm(orgAdminUIService)) { var res = contact1.Id; EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, account1.Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, account2.Id)); orgAdminUIService.Associate( Contact.EntityLogicalName, contact1.Id, new Relationship("account_primary_contact"), relatedEntities); var query = from con in context.ContactSet join acc in context.AccountSet on con.ContactId equals acc.PrimaryContactId.Id join lead in context.LeadSet on acc.AccountId equals lead.ParentAccountId.Id where con.Id == res select new { con.Id, con.LastName, acc.Name, lead.Subject }; var result = query.AsEnumerable().Where(x => x.Subject.StartsWith("Some")); Assert.AreEqual(4, result.Count()); foreach (var r in result) { Assert.AreEqual(contact1.LastName, r.LastName); Assert.IsTrue(account1.Name == r.Name || account2.Name == r.Name); Assert.IsTrue(r.Subject.StartsWith("Some")); } } }
public void TestAssocNNTwoWay() { using (var context = new Xrm(orgAdminUIService)) { var relatedAccounts = new EntityReferenceCollection(); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, account1.Id)); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, account2.Id)); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, account3.Id)); var relatedContacts = new EntityReferenceCollection(); relatedContacts.Add(new EntityReference(Contact.EntityLogicalName, contact1.Id)); relatedContacts.Add(new EntityReference(Contact.EntityLogicalName, contact2.Id)); Relationship relationship = new Relationship(dg_account_contact.EntityLogicalName); orgAdminUIService.Associate(Account.EntityLogicalName, account1.Id, relationship, relatedContacts); var relationQuery = new RelationshipQueryCollection(); var query = new QueryExpression(Contact.EntityLogicalName); query.ColumnSet = new ColumnSet("firstname"); relationQuery.Add(relationship, query); var req = new RetrieveRequest(); req.ColumnSet = new ColumnSet("name"); req.RelatedEntitiesQuery = relationQuery; req.Target = new EntityReference(Account.EntityLogicalName, account1.Id); var retrievedAccount = (orgAdminUIService.Execute(req) as RetrieveResponse).Entity as Account; var related = retrievedAccount.RelatedEntities[relationship].Entities; Assert.AreEqual(2, related.Count()); Assert.AreEqual(contact1.Id, related.FirstOrDefault(e => (e as Contact).FirstName == contact1.FirstName).Id); Assert.AreEqual(contact2.Id, related.FirstOrDefault(e => (e as Contact).FirstName == contact2.FirstName).Id); } }
private EntityReferenceCollection GetRecipient(CodeActivityContext executionContext) { TraceService.Trace("Getting Recipient"); EntityReferenceCollection toRecipient = new EntityReferenceCollection(); if (this.WorkflowContext.InputParameters.Contains("ToRecipient")) { EntityCollection toRecipientEntityCollection = this.WorkflowContext.InputParameters["ToRecipient"] as EntityCollection; foreach (Entity toRecipientEntity in toRecipientEntityCollection.Entities) { toRecipient.Add(toRecipientEntity.ToEntityReference()); } return(toRecipient); } else { string toRecipientRecordURL = this.ToRecipientRecordURL.Get <String>(executionContext); if (string.IsNullOrEmpty(toRecipientRecordURL)) { return(null); } else { toRecipient.Add(ConvertURLtoEntityReference(toRecipientRecordURL)); return(toRecipient); } } }
/// <summary> /// Create and configure the organization service proxy. /// Create a team, a queue and a role. /// Add read queue privileges to the role. /// Assign the role to the team so that they can read the queue. /// Assign the queue to the team. /// Optionally delete any entity records that were created for this sample. // </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetAssociateDisassociate1> // Associate the accounts to the contact record. // Create a collection of the entities that will be // associated to the contact. EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account1Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account2Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account3Id)); // Create an object that defines the relationship between the contact and account. Relationship relationship = new Relationship("account_primary_contact"); //Associate the contact with the 3 accounts. _service.Associate(Contact.EntityLogicalName, _contactId, relationship, relatedEntities); Console.WriteLine("The entities have been associated."); //Disassociate the records. _service.Disassociate(Contact.EntityLogicalName, _contactId, relationship, relatedEntities); //</snippetAssociateDisassociate1> Console.WriteLine("The entities have been disassociated."); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Create a team, a queue and a role. /// Add read queue privileges to the role. /// Assign the role to the team so that they can read the queue. /// Assign the queue to the team. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _service = (IOrganizationService)_serviceProxy; // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetAssociateDisassociateDE1> // The account ID would typically be passed in as an argument or determined by a query. // The contact ID would typically be passed in as an argument or determined by a query. // Associate the accounts to the contact record. //Create a collection of the entity ids that will be associated to the contact. EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference("account", _account1Id)); relatedEntities.Add(new EntityReference("account", _account2Id)); relatedEntities.Add(new EntityReference("account", _account3Id)); // Create an object that defines the relationship between the contact and account. Relationship relationship = new Relationship("account_primary_contact"); //Associate the contact with the 3 accounts. _service.Associate("contact", _contactId, relationship, relatedEntities); Console.WriteLine("The entities have been associated."); //Disassociate the records. _service.Disassociate("contact", _contactId, relationship, relatedEntities); //</snippetAssociateDisassociateDE1> Console.WriteLine("The entities have been disassociated."); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
internal void Associate_Disassociate() { //建立等等要關聯用的客戶資料 var account1 = new Account() { Name = "TestAccount" }; var acc1Id = _orgService.Create(account1); var account2 = new Account() { Name = "TestAccount2" }; var acc2Id = _orgService.Create(account2); //建立等等要關聯用的聯絡人資料 var contact1 = new Contact() { FirstName = "Lin", LastName = "Jeremy" }; var contact1Id = _orgService.Create(contact1); //建立客戶主要聯絡人的實體關聯物件 Relationship rel = new Relationship("account_primary_contact"); //把要被設定主要聯絡人的客戶加入到集合中 var accounts = new EntityReferenceCollection(); accounts.Add(new EntityReference(Account.EntityLogicalName, acc1Id)); accounts.Add(new EntityReference(Account.EntityLogicalName, acc2Id)); //從連絡人執行關聯到客戶 _orgService.Associate(Contact.EntityLogicalName, contact1Id, rel, accounts); onLog(string.Format("Associate Product Success")); //從聯絡人解除跟客戶的關聯 _orgService.Disassociate(Contact.EntityLogicalName, contact1Id, rel, accounts); onLog(string.Format("Disassociate Product Success")); //把要設定主要聯絡人的聯絡人加入到集合中 var contacts = new EntityReferenceCollection(); contacts.Add(new EntityReference(Contact.EntityLogicalName, contact1Id)); //從客戶執行關聯到聯絡人 _orgService.Associate(Account.EntityLogicalName, acc1Id, rel, contacts); _orgService.Associate(Account.EntityLogicalName, acc2Id, rel, contacts); onLog(string.Format("Other Way Associate Product Success")); }
/// <summary> /// Create and configure the organization service proxy. /// Create a team, a queue and a role. /// Add read queue privileges to the role. /// Assign the role to the team so that they can read the queue. /// Assign the queue to the team. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { _service = (IOrganizationService)_serviceProxy; // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetAssociateDisassociateDE1> // The account ID would typically be passed in as an argument or determined by a query. // The contact ID would typically be passed in as an argument or determined by a query. // Associate the accounts to the contact record. //Create a collection of the entity ids that will be associated to the contact. EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference("account", _account1Id)); relatedEntities.Add(new EntityReference("account", _account2Id)); relatedEntities.Add(new EntityReference("account", _account3Id)); // Create an object that defines the relationship between the contact and account. Relationship relationship = new Relationship("account_primary_contact"); //Associate the contact with the 3 accounts. _service.Associate("contact", _contactId, relationship, relatedEntities); Console.WriteLine("The entities have been associated."); //Disassociate the records. _service.Disassociate("contact", _contactId, relationship, relatedEntities); //</snippetAssociateDisassociateDE1> Console.WriteLine("The entities have been disassociated."); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Maintains the references of the provided entity by deleting the obsolete references (those in the data store but no longer active on one of the properties) /// and persisting the new references into the data store. /// </summary> /// <param name="entity">The entity to maintain the references for.</param> public virtual void MaintainReferences(IEntity entity) { using (LogGroup logGroup = LogGroup.Start("Maintaining the references for the provided entity.", LogLevel.Debug)) { EntityReferenceCollection updateList = new EntityReferenceCollection(); EntityReferenceCollection deleteList = new EntityReferenceCollection(); // Get the current/actives references foreach (EntityReference reference in GetActiveReferences(entity)) { updateList.Add(reference); } // Get the obsolete references foreach (EntityReference reference in GetObsoleteReferences(entity, updateList.GetEntityIDs(entity.ID))) { deleteList.Add(reference); } // Delete the obsolete references LogWriter.Debug("References to delete: " + deleteList.Count); DeleteObsoleteReferences(deleteList); // Update/save the current references LogWriter.Debug("References to update: " + updateList.Count); PersistReferences(updateList); Provider.Referencer.SetCountProperties(entity, false); } }
private static void SaveN2NToServerSingle(Entity[] entities, string connectionstring) { var service = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionstring); var req = new RetrieveRelationshipRequest { Name = entities[0].LogicalName }; var metadata = (RetrieveRelationshipResponse)service.Execute(req); var relationship = (ManyToManyRelationshipMetadata)metadata.RelationshipMetadata; foreach (var e in entities) { var exists = false; try { var existingEntity = service.Retrieve(e.LogicalName, e.Id, new ColumnSet()); if (existingEntity != null) { exists = true; } } catch { } if (!exists) { var rc = new EntityReferenceCollection(); rc.Add(new EntityReference(relationship.Entity2LogicalName, e.GetAttributeValue <Guid>(relationship.Entity2IntersectAttribute))); service.Associate(relationship.Entity1LogicalName , e.GetAttributeValue <Guid>(relationship.Entity1IntersectAttribute) , new Relationship(relationship.SchemaName) , rc); } } }
public void AssociateEntity(string PrimaryEntityName, Guid PrimaryEntityId, string _relationshipName, string _relationshipEntityName, string entityName, string ParentId) { try { EntityCollection relations = getAssociations(PrimaryEntityName, PrimaryEntityId, _relationshipName, _relationshipEntityName, entityName, ParentId); if (relations.Entities.Count == 0) { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(entityName, new Guid(ParentId))); Relationship relationship = new Relationship(_relationshipName); if (PrimaryEntityName == entityName) { relationship.PrimaryEntityRole = EntityRole.Referencing; } service.Associate(PrimaryEntityName, PrimaryEntityId, relationship, relatedEntities); } } catch (Exception ex) { Console.WriteLine("Error : {0} - {1}", ex.Message, ex.StackTrace); // objCommon.tracingService.Trace("Error : {0} - {1}", ex.Message, ex.StackTrace);// //throw ex; // if (ex.Detail.ErrorCode != 2147220937)//ignore if the error is a duplicate insert //{ // throw ex; //} } }
public override void Execute() { var record = _crmContext.RecordCache.Get(_alias); var md = GlobalTestingContext.Metadata.GetEntityMetadata(record.LogicalName, EntityFilters.Relationships); var relationship = md.ManyToManyRelationships.FirstOrDefault(r => (r.Entity1LogicalName == record.LogicalName && r.Entity2LogicalName == _relatedEntityName) || (r.Entity1LogicalName == _relatedEntityName && r.Entity2LogicalName == record.LogicalName)); if (relationship == null) { throw new TestExecutionException(Constants.ErrorCodes.N_N_RELATIONSHIP_NOT_FOUND, record.LogicalName, _relatedEntityName); } Logger.WriteLine($"Using relationship {relationship.SchemaName}"); EntityReferenceCollection toAssociate = new EntityReferenceCollection(); foreach (var row in _recordsToConnect.Rows) { var lookupValue = ObjectConverter.GetLookupValue(_crmContext, row[Constants.SpecFlow.TABLE_VALUE], _relatedEntityName); if (lookupValue == null) { throw new TestExecutionException(Constants.ErrorCodes.RECORD_NOT_FOUND, row[Constants.SpecFlow.TABLE_VALUE], _relatedEntityName); } toAssociate.Add(lookupValue); } Logger.WriteLine($"Associating {toAssociate.Count} records"); GlobalTestingContext.ConnectionManager.CurrentConnection.Associate(record.LogicalName, record.Id, new Relationship(relationship.SchemaName), toAssociate); }
public void createNewFieldLevelSecurityProfile() { IOrganizationService service = CRMHelper.ConnectToMSCRM(); //Create Security Profile Entity profile = new Entity("fieldsecurityprofile"); profile["name"] = "Profile Created From Code"; profile["description"] = "Profile Created from Code and just to use for test purpose"; Guid profileId = service.Create(profile); // Create Field Permission Entity permission = new Entity("fieldpermission"); permission["fieldsecurityprofileid"] = new EntityReference(profile.LogicalName, profileId); permission["entityname"] = "opportunity"; permission["attributelogicalname"] = "estimatedvalue"; permission["canread"] = new OptionSetValue(FieldPermissionType.NotAllowed); permission["cancreate"] = new OptionSetValue(FieldPermissionType.NotAllowed); permission["canupdate"] = new OptionSetValue(FieldPermissionType.NotAllowed); Guid permissionId = service.Create(permission); // Associate Field Security Profile with Users Guid userId = new Guid("0CEAF899-6D01-4577-80DF-0EDEBCE57570"); Relationship relationShip = new Relationship("systemuserprofiles_association"); EntityReferenceCollection collection = new EntityReferenceCollection(); collection.Add(new EntityReference(profile.LogicalName, profileId)); service.Associate("systemuser", userId, relationShip, collection); }
public void TestCreateCustomEmail() { Entity contact = CreateContact(); Entity payment = CreatePayment(contact); EntityReference paymentReference = payment.ToEntityReference(); WhoAmIResponse whoAmI = this.CrmOrganisationService.Execute(new WhoAmIRequest()) as WhoAmIResponse; Entity whoAmIUser = new Entity("systemuser"); whoAmIUser.Id = whoAmI.UserId; EntityReferenceCollection to = new EntityReferenceCollection(); to.Add(contact.ToEntityReference()); ITextProcessor crmTextProcessor = new TextProcessor(this.CrmOrganisationService); CreateCustomEmail createCustomEmail = new CreateCustomEmail(this.CrmOrganisationService, crmTextProcessor); createCustomEmail.CreateEmail( "DXTools Payment Notification Template" , whoAmI.UserId , paymentReference , paymentReference , new EntityReference("systemuser", whoAmI.UserId) , to , new string[] { "DXTools Payment Attachment Sample.docx", "DXTools Sample T&C.pdf" } , false , false); }
private void UpdateProcedureTOWOrkorder(IOrganizationService service, Guid id, EntityReference procedure) { EntityReferenceCollection entityReferenceCollection = new EntityReferenceCollection(); entityReferenceCollection.Add(procedure); service.Associate("msdyn_workorder", id, new Relationship("smp_smp_procedure_msdyn_workorder"), entityReferenceCollection); }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" Common objCommon = new Common(executionContext); objCommon.tracingService.Trace("Load CRM Service from context --- OK"); #endregion #region "Read Parameters" String _relationshipName = this.RelationshipName.Get(executionContext); String _recordURL = this.RecordURL.Get(executionContext); if (_recordURL == null || _recordURL == "") { return; } string[] urlParts = _recordURL.Split("?".ToArray()); string[] urlParams = urlParts[1].Split("&".ToCharArray()); string ParentObjectTypeCode = urlParams[0].Replace("etc=", ""); string entityName = objCommon.sGetEntityNameFromCode(ParentObjectTypeCode, objCommon.service); string ParentId = urlParams[1].Replace("id=", ""); objCommon.tracingService.Trace("ParentObjectTypeCode=" + ParentObjectTypeCode + "--ParentId=" + ParentId); #endregion #region "Disassociate Execution" EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(entityName, new Guid(ParentId))); Relationship relationship = new Relationship(_relationshipName); objCommon.service.Disassociate(objCommon.context.PrimaryEntityName, objCommon.context.PrimaryEntityId, relationship, relatedEntities); #endregion }
public void TestDisassociateWOPrimaryNamePlugin() { using (var context = new Xrm(orgAdminUIService)) { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); dg_bus bus = new dg_bus { dg_Ticketprice = 1 }; bus.Id = orgAdminService.Create(bus); dg_child child = new dg_child { dg_name = "Margrethe", dg_parentBusId = bus.ToEntityReference() }; child.Id = orgAdminService.Create(child); relatedEntities.Add(new EntityReference(dg_child.EntityLogicalName, child.Id)); Relationship relationship = new Relationship("dg_bus_parental"); orgAdminUIService.Disassociate(dg_bus.EntityLogicalName, bus.Id, relationship, relatedEntities); var retrievedBus = dg_bus.Retrieve(orgAdminService, bus.Id, x => x.dg_Ticketprice); Assert.AreEqual(26, retrievedBus.dg_Ticketprice); } }
public void AssociateRecords(EntityReference TargetRecord, EntityReference RelatedRecord, Relationship Relationship) { EntityReferenceCollection relatedRecords = new EntityReferenceCollection(); relatedRecords.Add(RelatedRecord); this.AssociateRecords(TargetRecord, relatedRecords, Relationship); }
private void ApplyTemplateToUsers(List <Guid> rulesIds, string question, RuleManager rm, BackgroundWorker worker) { worker.ReportProgress(0, "Waiting for input..."); if ( MessageBox.Show(this, question, "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { var usDialog = new UserSelectionDialog(service); if (usDialog.ShowDialog() == DialogResult.OK) { foreach (var user in usDialog.SelectedUsers) { worker.ReportProgress(0, string.Format("Applying rule(s) to user(s) '{0}'", user.GetAttributeValue <string>("fullname"))); var erc = new EntityReferenceCollection(); foreach (var ruleId in rulesIds) { erc.Add(new EntityReference("savedquery", ruleId)); } rm.ApplyRulesToUser(erc, user.Id); } } } }
//<snippetCRUDOperations1> /// <summary> /// This method performs entity create, retrieve, and update operations. /// The delete operation is handled in the DeleteRequiredrecords() method. /// </summary> /// <param name="serviceProxy">An established connection to the Organization web service.</param> /// <param name="records">A collection of entity records created by this sample.</param> public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records) { // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio // and avoids spelling errors in attribute names when using the Entity property bag. serviceProxy.EnableProxyTypes(); // Here we will use the interface instead of the proxy object. IOrganizationService service = (IOrganizationService)serviceProxy; // Display information about the logged on user. Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId; SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid, new ColumnSet(new string[] {"firstname", "lastname"})); Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName); // Retrieve the version of Microsoft Dynamics CRM. RetrieveVersionRequest versionRequest = new RetrieveVersionRequest(); RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)service.Execute(versionRequest); Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version); //<snippetCRUDOperations2> // Instantiate an account object. Note the use of the option set enumerations defined // in OptionSets.cs. Account account = new Account { Name = "Fourth Coffee" }; account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer); account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor); // Create an account record named Fourth Coffee. // Save the record reference so we can delete it during cleanup later. Guid accountId = service.Create(account); //</snippetCRUDOperations2> records.Add(new EntityReference(Account.EntityLogicalName, accountId)); Console.Write("{0} {1} created, ", account.LogicalName, account.Name); // Retrieve the account containing several of its attributes. This results in // better performance compared to retrieving all attributes. ColumnSet cols = new ColumnSet( new String[] { "name", "address1_postalcode", "lastusedincampaign" }); Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols); Console.Write("retrieved, "); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // There is no address 2 postal code needed. retrievedAccount.Address2_PostalCode = null; // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a Boolean value. retrievedAccount.CreditOnHold = false; // Update the account record. service.Update(retrievedAccount); Console.WriteLine("and updated."); }
/// <summary> /// Creates a link between a context and target record /// </summary> /// <param name="contextEntity">Entity object representing the representing the record that we wish to relate</param> /// <param name="relationship">Relationship object representing the relationship between the context and target entity</param> /// <param name="targetEntity">EntityReference object representing the record that we wish to relate to</param> /// <param name="service">IOrganizationService object that lets us manipulate CDS metadata</param> public static void Associate(Entity contextEntity, Relationship relationship, EntityReference targetEntity, IOrganizationService service) { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(targetEntity); service.Associate(contextEntity.LogicalName, contextEntity.Id, relationship, relatedEntities); }
private void RemoveImplicitAntigens(IOrganizationService organisationService, ProxyClasses.Rarity_SourceAssociation raritySourceAssoc) { Guid sourceId = raritySourceAssoc.Rarity.Id; Guid rarityAssocId = raritySourceAssoc.Id; var antigenAssocsToBeDisassociated = new EntityReferenceCollection(); //...get all the antigen assocaitions implied by this rarity var matchingRarityIntersectRecords = GetAllSourceIntersectRecordsForRarity(organisationService, rarityAssocId); //For each antigen assoc implied by this rarity assoc foreach (nhs_AnitenSrcAssoc_nhs_RaritySrcAssoc rarityIntersectRecord in matchingRarityIntersectRecords) { var antigenAssocId = rarityIntersectRecord.Nhs_antigensourceassociationid; //Get the antigen association as an entity reference var antigenAssocEntityRef = new EntityReference( Antigen_SourceAssociation.LogicalName, (Guid)antigenAssocId); var matchingAntigenIntersectRecords = GetAllSourceIntersectRecordsForAntigen(organisationService, antigenAssocId); // Add the intersect entity to the list of relationships to be deleted antigenAssocsToBeDisassociated.Add(antigenAssocEntityRef); //Test whether this antigen association is implied by other rarities //i.e. work out if any other rarities imply this same antigen source association var isAntigenImpliedByOtherRarities = (from antigenIntersectRecord in matchingAntigenIntersectRecords where antigenIntersectRecord.Nhs_antigensourceassociationid == rarityIntersectRecord.Nhs_antigensourceassociationid && //its for the same antigen assoc antigenIntersectRecord.Nhs_AnitenSrcAssoc_nhs_RaritySrcAssocId != rarityIntersectRecord.Nhs_AnitenSrcAssoc_nhs_RaritySrcAssocId //but a implied by a different rarity select antigenIntersectRecord).Count() > 0; // check if the antigen source association is explicit var isExplicit = (bool)rarityIntersectRecord.GetAttributeValue <AliasedValue>("antigenSourceAssoc.nhs_isexplicit").Value; //If there are no other rarities implying this antigen assoc // and the antigen association is also not explicit. if (!isAntigenImpliedByOtherRarities && !isExplicit) { //Deactivate the antigen source association Helper.SetState( organisationService, antigenAssocEntityRef, new OptionSetValue((int)ProxyClasses.Antigen_SourceAssociation.eStatus.Inactive), new OptionSetValue((int)ProxyClasses.Antigen_SourceAssociation.eStatusReason.Inactive_Inactive)); } } if (antigenAssocsToBeDisassociated.Count() > 0) { //...we need to unlink this any deactivated rarity assocations from their respective antigen associations organisationService.Disassociate( ProxyClasses.Rarity_SourceAssociation.LogicalName, raritySourceAssoc.Id, new Relationship("nhs_AntigenSrcAssoc_nhs_RaritySrcAssoc"), antigenAssocsToBeDisassociated); } }
public static void Associate(this DataAccessContext pluginContext, string relationshipName, EntityReference entity1, EntityReference entity2) { var relationship = new Relationship(relationshipName); var relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(entity2); pluginContext.OrganizationService.Associate(entity1.LogicalName, entity1.Id, relationship, relatedEntities); }
public void When_execute_is_called_with_a_non_existing_reference_exception_is_thrown() { using (var context = new Xrm(orgAdminUIService)) { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, account1.Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, Guid.NewGuid())); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, account3.Id)); Relationship relationship = new Relationship("account_primary_contact"); try { orgAdminUIService.Associate(Contact.EntityLogicalName, contact1.Id, relationship, relatedEntities); Assert.Fail(); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(FaultException)); } } }
public static EntityReferenceCollection ToEntityReferenceCollection(this IList <Entity> entities) { var entityRefCol = new EntityReferenceCollection(); foreach (var entity in entities) { entityRefCol.Add(entity.ToEntityReference()); } return(entityRefCol); }
private EntityReferenceCollection GetEntityReferenceCollection(IEnumerable <Guid> ids) { var collection = new EntityReferenceCollection(); foreach (var id in ids) { collection.Add(new EntityReference("account", id)); } return(collection); }
public static EntityReferenceCollection CreateEntityReferenceCollection(List <Guid> guidList, string logicalName) { var entityRefCollection = new EntityReferenceCollection(); foreach (Guid guid in guidList) { entityRefCollection.Add(new EntityReference(logicalName, guid)); } return(entityRefCollection); }
private EntityReferenceCollection CreateReferenceCollection(string relationshipName, string entityName, List <Guid> idsToCollect) { EntityReferenceCollection entityReferenceCollection = new EntityReferenceCollection(); foreach (Guid id in idsToCollect) { EntityReference entityReference = new EntityReference(entityName, id); entityReferenceCollection.Add(entityReference); } return(entityReferenceCollection); }
public void CreatePriceLisItem(Entity entity, Entity productEntity) { _tracingService.Trace("Started CreatePriceLisItem Method.."); var uomName = entity.Contains("gsc_unit") ? entity.GetAttributeValue <String>("gsc_unit") : null; var uomId = Guid.Empty; _tracingService.Trace("UOm Name=" + uomName.ToString()); EntityCollection uomCollection = CommonHandler.RetrieveRecordsByOneValue("uom", "name", uomName, _organizationService, null, OrderType.Ascending, new[] { "name" }); if (uomCollection != null && uomCollection.Entities.Count > 0) { _tracingService.Trace("Unit Retrieved.."); uomId = uomCollection.Entities[0].Id; } _tracingService.Trace("Entity Price List Item.."); Entity priceListItem = new Entity("productpricelevel"); priceListItem["pricelevelid"] = entity.GetAttributeValue <EntityReference>("gsc_pricelistid") != null ? entity.GetAttributeValue <EntityReference>("gsc_pricelistid") : null; priceListItem["productid"] = new EntityReference("product", productEntity.Id); priceListItem["uomid"] = new EntityReference("uom", uomId); priceListItem["amount"] = entity.Contains("gsc_amount") ? entity.GetAttributeValue <Money>("gsc_amount") : new Money(0); priceListItem["transactioncurrencyid"] = entity.GetAttributeValue <EntityReference>("transactioncurrencyid") != null ? entity.GetAttributeValue <EntityReference>("transactioncurrencyid") : null; _tracingService.Trace("Product " + productEntity.Id.ToString()); Guid priceListItemId = _organizationService.Create(priceListItem); _tracingService.Trace("Price List Created.." + priceListItemId.ToString()); //Collection of entities to be associated to Price List Item EntityReferenceCollection priceListItemCollection = new EntityReferenceCollection(); priceListItemCollection.Add(new EntityReference("productpricelevel", priceListItemId)); //Associate Extended Price List Item with Price List Item _organizationService.Associate("gsc_cmn_extendedpricelistitem", entity.Id, new Relationship("gsc_gsc_cmn_extendedpricelistitem_productpric"), priceListItemCollection); _tracingService.Trace("Price List Associated.."); _tracingService.Trace("Ended CreatePriceLisItem Method.."); }
public void TestContextIntersectEntity() { using (var context = new Xrm(orgAdminUIService)) { var acc1 = orgAdminUIService.Create(new Account()); var acc2 = orgAdminUIService.Create(new Account()); var acc3 = orgAdminUIService.Create(new Account()); var con = orgAdminUIService.Create(new Contact()); var relatedAccounts = new EntityReferenceCollection(); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, acc1)); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, acc2)); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, acc3)); Relationship relationship = new Relationship(dg_account_contact.EntityLogicalName); orgAdminUIService.Associate(Contact.EntityLogicalName, con, relationship, relatedAccounts); Assert.AreEqual(3, context.dg_account_contactSet.Where(x => x.contactid == con).ToList().Count()); } }
//<snippetCRUDOperations1> /// <summary> /// This method performs entity create, retrieve, and update operations. /// The delete operation is handled in the DeleteRequiredrecords() method. /// </summary> /// <param name="serviceProxy">An established connection to the Organization web service.</param> /// <param name="records">A collection of entity records created by this sample.</param> public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records) { // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio // and avoids spelling errors in attribute names when using the Entity property bag. serviceProxy.EnableProxyTypes(); // Here we will use the interface instead of the proxy object. IOrganizationService service = (IOrganizationService)serviceProxy; // Display information about the logged on user. Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId; SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid, new ColumnSet(new string[] { "firstname", "lastname" })); Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName); // Retrieve the version of Microsoft Dynamics CRM. RetrieveVersionRequest versionRequest = new RetrieveVersionRequest(); RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)service.Execute(versionRequest); Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version); //<snippetCRUDOperations2> // Instantiate an account object. Note the use of the option set enumerations defined // in OptionSets.cs. Account account = new Account { Name = "Fourth Coffee" }; account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer); account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor); // Create an account record named Fourth Coffee. // Save the record reference so we can delete it during cleanup later. Guid accountId = service.Create(account); //</snippetCRUDOperations2> var eref = new EntityReference(Account.EntityLogicalName, accountId); eref.Name = account.Name; records.Add(eref); Console.Write("{0} {1} created, ", account.LogicalName, account.Name); // Retrieve the account containing several of its attributes. This results in // better performance compared to retrieving all attributes. ColumnSet cols = new ColumnSet( new String[] { "name", "address1_postalcode", "lastusedincampaign" }); Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols); Console.Write("retrieved, "); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // There is no address 2 postal code needed. retrievedAccount.Address2_PostalCode = null; // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a Boolean value. retrievedAccount.CreditOnHold = false; // Update the account record. service.Update(retrievedAccount); Console.WriteLine("and updated."); }
/// <summary> /// Imports the specified profile. /// </summary> /// <param name="profile">The profile.</param> /// <param name="transportReportFileName">Name of the transport report file.</param> private void Import(NtoNAssociationsTransportProfile profile, string transportReportFileName) { int totalTreatedRecords = 0; int totalImportFailures = 0; int totalImportSuccess = 0; int ReconnectionRetryCount = 5; try { NtoNTransportReport report = new NtoNTransportReport(transportReportFileName); //Get Transport Report if (File.Exists(transportReportFileName)) { report = ReadTransportReport(transportReportFileName); } MSCRMConnection connection = profile.getTargetConneciton(); ; _serviceProxy = cm.connect(connection); IOrganizationService service = (IOrganizationService)_serviceProxy; LogManager.WriteLog("Start importing data in " + connection.ConnectionName); //Mesure import time DateTime importStartDT = DateTime.Now; //es = ReadEnvStructure(profile.SourceConnectionName); foreach (SelectedNtoNRelationship ee in profile.SelectedNtoNRelationships) { //Check if there are any records to import if (ee.ExportedRecords == 0) { continue; } //Mesure import time DateTime entityImportStartDT = DateTime.Now; string entityFolderPath = Folder + "\\" + profile.ProfileName + "\\Data\\" + ee.RelationshipSchemaName; string[] filePaths = Directory.GetFiles(entityFolderPath, "*.xml"); LogManager.WriteLog("Importing " + ee.RelationshipSchemaName + " records."); int treatedRecordsForEntity = 0; int importedRecordsForEntity = 0; int importFailuresForEntity = 0; foreach (string filePath in filePaths) { List<Type> knownTypes = new List<Type>(); knownTypes.Add(typeof(Entity)); XmlDictionaryReaderQuotas XRQ = new XmlDictionaryReaderQuotas(); XRQ.MaxStringContentLength = int.MaxValue; using(FileStream fs = new FileStream(filePath, FileMode.Open)) using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, XRQ)) { DataContractSerializer ser = new DataContractSerializer(typeof(EntityCollection), knownTypes); EntityCollection fromDisk = (EntityCollection)ser.ReadObject(reader, true); foreach (Entity en in fromDisk.Entities) { EntityReference relatedEntity1 = new EntityReference(); EntityReference relatedEntity2 = new EntityReference(); try { Guid relatedEntity1Id = getRelatedEntityGuid(en[ee.Entity1IntersectAttribute]); Guid relatedEntity2Id = getRelatedEntityGuid(en[ee.Entity2IntersectAttribute]); relatedEntity1 = new EntityReference { LogicalName = ee.Entity1LogicalName, Id = relatedEntity1Id }; relatedEntity2 = new EntityReference { LogicalName = ee.Entity2LogicalName, Id = relatedEntity2Id }; if (!AlreadyAssociated(_serviceProxy, ee, relatedEntity1Id, relatedEntity2Id)) { if (ee.IntersectEntityName == "listmember") { Guid entity_id = Guid.Empty; Guid list_id = Guid.Empty; if (ee.Entity1LogicalName == "list") { entity_id = relatedEntity2Id; list_id = relatedEntity1Id; } else { entity_id = relatedEntity1Id; list_id = relatedEntity2Id; } AddMemberListRequest request = new AddMemberListRequest(); request.EntityId = entity_id; request.ListId = list_id; AddMemberListResponse response = (AddMemberListResponse)service.Execute(request); } else if (ee.IntersectEntityName == "campaignitem") { Guid entity_id = Guid.Empty; Guid list_id = Guid.Empty; string EntityName = ""; if (ee.Entity1LogicalName == "campaign") { entity_id = relatedEntity2Id; list_id = relatedEntity1Id; EntityName = (string)en["entitytype"]; relatedEntity2.LogicalName = EntityName; } else { entity_id = relatedEntity1Id; list_id = relatedEntity2Id; EntityName = (string)en["entitytype"]; relatedEntity1.LogicalName = EntityName; } AddItemCampaignRequest req = new AddItemCampaignRequest(); req.CampaignId = relatedEntity1Id; req.EntityName = EntityName; req.EntityId = entity_id; AddItemCampaignResponse resp = (AddItemCampaignResponse)service.Execute(req); } else if (ee.IntersectEntityName == "campaignactivityitem") { Guid entity_id = Guid.Empty; Guid list_id = Guid.Empty; string EntityName = ""; if (ee.Entity1LogicalName == "campaignactivity") { entity_id = relatedEntity2Id; list_id = relatedEntity1Id; EntityName = (string)en["itemobjecttypecode"]; relatedEntity2.LogicalName = EntityName; } else { entity_id = relatedEntity1Id; list_id = relatedEntity2Id; EntityName = (string)en["itemobjecttypecode"]; relatedEntity1.LogicalName = EntityName; } AddItemCampaignActivityRequest req = new AddItemCampaignActivityRequest(); req.CampaignActivityId = relatedEntity1Id; req.EntityName = EntityName; req.ItemId = entity_id; AddItemCampaignActivityResponse resp = (AddItemCampaignActivityResponse)service.Execute(req); } else { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(relatedEntity2); Relationship relationship = new Relationship(ee.RelationshipSchemaName); relationship.PrimaryEntityRole = EntityRole.Referencing; service.Associate(relatedEntity1.LogicalName, relatedEntity1.Id, relationship, relatedEntities); } } importedRecordsForEntity++; totalImportSuccess++; } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { totalImportFailures++; importFailuresForEntity++; NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure { CreatedOn = DateTime.Now.ToString(), NtoNRelationshipName = ee.RelationshipSchemaName, Reason = ex.Detail.Message, UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(), UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString() }; report.TotalImportFailures += 1; //Insert the Failure line in the Failures Report WriteNewImportFailureLine(failure, importFailuresReportFileName); } catch (Exception ex) { //Check if the authentification session is expired if (ex.InnerException != null && ex.InnerException.Message.StartsWith("ID3242")) { LogManager.WriteLog("Error:The CRM authentication session expired. Reconnection attempt n° " + ReconnectionRetryCount); ReconnectionRetryCount--; //On 5 failed reconnections exit if (ReconnectionRetryCount == 0) throw; _serviceProxy = cm.connect(connection); service = (IOrganizationService)_serviceProxy; LogManager.WriteLog("Error:The CRM authentication session expired."); totalImportFailures++; importFailuresForEntity++; NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure { CreatedOn = DateTime.Now.ToString(), NtoNRelationshipName = ee.RelationshipSchemaName, Reason = ex.InnerException.Message, UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(), UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString() }; report.TotalImportFailures += 1; //Insert the Failure line in the Failures Report WriteNewImportFailureLine(failure, importFailuresReportFileName); } else { throw; } } totalTreatedRecords++; treatedRecordsForEntity++; updateTransportReport(report, ee, importedRecordsForEntity, importFailuresForEntity, entityImportStartDT); } } } LogManager.WriteLog("Treated " + treatedRecordsForEntity + " " + ee.RelationshipSchemaName + " records with " + importedRecordsForEntity + " successfully imported records and " + importFailuresForEntity + " failures."); } TimeSpan importTimeSpan = DateTime.Now - importStartDT; LogManager.WriteLog("Import finished for " + connection.ConnectionName + ". Treated " + totalTreatedRecords + " records in " + importTimeSpan.ToString().Substring(0, 10) + ". Successfuly imported " + totalImportSuccess + " records and " + totalImportFailures + " failures."); WriteTransportReport(report, transportReportFileName); } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText); } catch (Exception ex) { if (ex.InnerException != null) LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message); else { LogManager.WriteLog("Error:" + ex.Message); } } }
/// <summary> /// Prepares the provided entity for deletion by removing dependent referenced, etc. /// </summary> /// <param name="entity">The entity to prepare for deletion.</param> public override void PreDelete(IEntity entity) { using (LogGroup logGroup = LogGroup.Start("Preparing to delete the provided entity.", NLog.LogLevel.Debug)) { if (entity == null) throw new ArgumentNullException("entity"); Db4oDataStore store = (Db4oDataStore)GetDataStore(entity); //if (entity.ID == Guid.Empty) // throw new ArgumentException("entity.ID must be set."); EntityReferenceCollection toDelete = new EntityReferenceCollection(); if (entity != null && entity.ID != Guid.Empty) { //Provider.Activator.Activate(entity); EntityReferenceCollection latestReferences = Provider.Referencer.GetReferences(entity); // Delete all references foreach (PropertyInfo property in entity.GetType().GetProperties()) { bool isReference = EntitiesUtilities.IsReference(entity.GetType(), property.Name, property.PropertyType); if (isReference) { using (LogGroup logGroup2 = LogGroup.StartDebug("Checking reference property '" + property.Name + "' for obsolete references.")) { Type referenceType = EntitiesUtilities.GetReferenceType(entity, property.Name); // If the reference type is not null then continue if (referenceType != null) { EntityReferenceCollection references = DataAccess.Data.Referencer.GetReferences(entity.GetType(), entity.ID, property.Name, referenceType, false); if (references.Count > 0) { LogWriter.Debug("Found references: " + references.Count.ToString()); foreach (EntityReference reference in references) { LogWriter.Debug("Found reference between '" + reference.Type1Name + "' and '" + reference.Type2Name + "'."); toDelete.Add(reference); } } else LogWriter.Debug("No references found associated with this property."); } // Otherwise skip it because the reference property hasn't been set } } } } LogWriter.Debug("References to delete: " + toDelete.Count); //entitiesToUpdate = toUpdate.ToArray(); Provider.Referencer.DeleteObsoleteReferences(toDelete); } }
/// <summary> /// Retrieves the active references from the provided entity. This only includes those references currently active and not those in the data store. /// </summary> /// <param name="entity">The entity containing that the references are assigned to.</param> /// <param name="autoBind">A value indicating whether to bind the reference objects to the data store ready for updating.</param> /// <returns>A collection of the active entity references.</returns> public virtual EntityReferenceCollection GetActiveReferences(IEntity entity, bool autoBind) { if (entity == null) throw new ArgumentNullException("entity"); EntityReferenceCollection collection = new EntityReferenceCollection(entity); // Loop through all the properties on the entity class foreach (PropertyInfo property in entity.GetType().GetProperties()) { if (EntitiesUtilities.IsReference(entity.GetType(), property.Name, property.PropertyType)) { LogWriter.Debug("Property is a reference: " + property.Name); foreach (EntityReference reference in GetActiveReferences(entity, property.Name, property.PropertyType, autoBind)) { LogWriter.Debug("Found reference."); collection.Add(reference); } } } // TODO: Check if references actually need to be switched (below). In theory they shouldn't and the switch will incur a very // minor performance hit (likely negligable) // Ensure that all references have the correct perspective //for (int i = 0; i < collection.Count; i++) //{ // if (collection[i].SourceEntity == null || collection[i].ReferenceEntity == null) // Provider.Activator.ActivateReference(collection[i]); // collection[i] = collection[i].SwitchFor(entity); //} return collection; }
/// <summary> /// Retrieves the active references from the provided property. This only includes those references currently active and not those in the data store. /// </summary> /// <param name="entity">The entity containing the property that the references are assigned to.</param> /// <param name="propertyName">The name of the property that the references are assigned to.</param> /// <param name="returnType">The type of the property that the references are assigned to.</param> /// /// <param name="autoBind">A value indicating whether to bind the reference objects to the data store ready for updating.</param> /// <returns>A collection of the entity references.</returns> public virtual EntityReferenceCollection GetActiveReferences(IEntity entity, string propertyName, Type returnType, bool autoBind) { EntityReferenceCollection collection = new EntityReferenceCollection(entity); using (LogGroup logGroup = LogGroup.Start("Retrieving the reference entities from the specified property on the provided entity.", LogLevel.Debug)) { Type entityType = entity.GetType(); PropertyInfo property = EntitiesUtilities.GetProperty(entityType, propertyName, returnType); if (property == null) LogWriter.Debug("Property: [null]"); else LogWriter.Debug("Property name: " + property.Name); if (property != null) { if (EntitiesUtilities.IsReference(entityType, propertyName, returnType)) { Type referencedEntityType = EntitiesUtilities.GetReferenceType(entity, propertyName, returnType); string mirrorPropertyName = EntitiesUtilities.GetMirrorPropertyName(entity, property); if (EntitiesUtilities.IsMultipleReference(entity.GetType(), property)) { foreach (EntityReference r in GetActiveReferencesFromMultipleReferenceProperty(entity, property, mirrorPropertyName)) { if (r != null) collection.Add(r); } } else if (EntitiesUtilities.IsSingleReference(entityType, property)) { EntityReference r = GetActiveReferenceFromSingleReferenceProperty(entity, property, mirrorPropertyName); if (r != null) collection.Add(r); } else throw new NotSupportedException("The property type '" + property.PropertyType.ToString() + "' is not supported."); } else throw new ArgumentException("The specified property is not a reference."); LogWriter.Debug("References found: " + collection.Count.ToString()); } else { throw new Exception("Cannot find property '" + propertyName + "' on type '" + entity.GetType().ToString() + "'."); } // Assign the provided entity to each reference so it doesn't need to be loaded again foreach (EntityReference reference in collection) { if (reference.Entity1ID == entity.ID) reference.SourceEntity = entity; else if (reference.Entity2ID == entity.ID) reference.ReferenceEntity = entity; } if (autoBind) BindReferences(collection); } return collection; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { Contact contact1 = new Contact { FirstName = "Colin", LastName = "Wilcox", Address1_City = "Redmond", Address1_StateOrProvince = "WA", Address1_PostalCode = "98052", Anniversary = new DateTime(2010, 3, 5), CreditLimit = new Money(300), Description = "Alpine Ski House", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(1), NumberOfChildren = 1, Address1_Latitude = 47.6741667, Address1_Longitude = -122.1202778, CreditOnHold = false }; _contactId1 = _serviceProxy.Create(contact1); Console.Write("Created a sample contact 1: {0}, ", contact1.FirstName + " " + contact1.LastName); Contact contact2 = new Contact { FirstName = "Brian", LastName = "Smith", Address1_City = "Bellevue", FamilyStatusCode = new OptionSetValue(3), Address1_StateOrProvince = "WA", Address1_PostalCode = "98008", Anniversary = new DateTime(2010, 4, 5), CreditLimit = new Money(30000), Description = "Coho Winery", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(2), NumberOfChildren = 2, Address1_Latitude = 47.6105556, Address1_Longitude = -122.1994444, CreditOnHold = false }; _contactId2 = _serviceProxy.Create(contact2); Console.Write("Created a sample contact 2: {0}, ", contact2.FirstName + " " + contact2.LastName); Contact contact3 = new Contact { FirstName = "Darren", LastName = "Parker", Address1_City = "Kirkland", FamilyStatusCode = new OptionSetValue(3), Address1_StateOrProvince = "WA", Address1_PostalCode = "98033", Anniversary = new DateTime(2010, 10, 5), CreditLimit = new Money(10000), Description = "Coho Winery", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(2), NumberOfChildren = 2, Address1_Latitude = 47.6105556, Address1_Longitude = -122.1994444, CreditOnHold = false }; _contactId3 = _serviceProxy.Create(contact3); Console.Write("Created a sample contact 3: {0}, ", contact3.FirstName + " " + contact3.LastName); Contact contact4 = new Contact { FirstName = "Ben", LastName = "Smith", Address1_City = "Kirkland", FamilyStatusCode = new OptionSetValue(3), Address1_StateOrProvince = "WA", Address1_PostalCode = "98033", Anniversary = new DateTime(2010, 7, 5), CreditLimit = new Money(12000), Description = "Coho Winery", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(2), NumberOfChildren = 2, Address1_Latitude = 47.6105556, Address1_Longitude = -122.1994444, CreditOnHold = true }; _contactId4 = _serviceProxy.Create(contact4); Console.Write("Created a sample contact 4: {0}, ", contact4.FirstName + " " + contact4.LastName); Incident incident1 = new Incident { Title = "Test Case 1", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem Description = "Description for Test Case 1.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId2) }; _incidentId1 = _serviceProxy.Create(incident1); Console.Write("Created a sample incident 1: {0}, ", incident1.Title); Relationship relationship1 = new Relationship("incident_customer_contacts"); EntityReferenceCollection relatedEntities1 = new EntityReferenceCollection(); relatedEntities1.Add(new EntityReference(Contact.EntityLogicalName, _contactId1)); _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId1, relationship1, relatedEntities1); Console.Write("Added relationship between incident 1 and contact 1, "); Account account1 = new Account { Name = "Coho Winery", Address1_Name = "Coho Vineyard & Winery", Address1_City = "Redmond" }; _accountId1 = _serviceProxy.Create(account1); Console.Write("Created a sample account 1: {0}, ", account1.Name); Incident incident2 = new Incident { Title = "Test Case 2", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem Description = "Description for Sample Case 2.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId1) }; _incidentId2 = _serviceProxy.Create(incident2); Console.Write("Created a sample incident 2: {0}, ", incident2.Title); Relationship relationship2 = new Relationship("incident_customer_accounts"); EntityReferenceCollection relatedEntities2 = new EntityReferenceCollection(); relatedEntities2.Add(new EntityReference(Account.EntityLogicalName, _accountId1)); _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId2, relationship2, relatedEntities2); Console.Write("Added relationship between incident 2 and account 1, "); Lead lead = new Lead() { FirstName = "Diogo", LastName = "Andrade" }; _leadId = _serviceProxy.Create(lead); Console.Write("Created a sample Lead: {0} ", lead.FirstName + " " + lead.LastName); Account account2 = new Account { Name = "Contoso Ltd", ParentAccountId = new EntityReference(Account.EntityLogicalName, _accountId1), Address1_Name = "Contoso Pharmaceuticals", Address1_City = "Redmond", OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadId) }; _accountId2 = _serviceProxy.Create(account2); Console.Write("Created a sample account 2: {0}, ", account2.Name); Relationship relationship3 = new Relationship("account_primary_contact"); EntityReferenceCollection relatedEntities3 = new EntityReferenceCollection(); relatedEntities3.Add(new EntityReference(Account.EntityLogicalName, _accountId2)); _serviceProxy.Associate(Contact.EntityLogicalName, _contactId2, relationship3, relatedEntities3); Console.WriteLine("Added relationship between account 2 and contact 2."); }
/// <summary> /// Retrieves the references that are no longer active on the provided entity and haven't yet been removed from the data store. /// </summary> /// <param name="entity">The entity containing the active references to compare with.</param> /// <param name="propertyName">The name of the property that the references correspond with.</param> /// <param name="referenceType">The type of the referenced entity.</param> /// <param name="idsOfEntitiesToKeep">An array of IDs of the entities that are still active and are not obsolete.</param> /// <returns>A collection of the obsolete references that correspond with the provided entity.</returns> public virtual EntityReferenceCollection GetObsoleteReferences(IEntity entity, string propertyName, Type referenceType, Guid[] idsOfEntitiesToKeep) { EntityReferenceCollection collection = new EntityReferenceCollection(entity); using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the obsolete references for the '" + propertyName + "' property.")) { foreach (EntityReference r in GetReferences(entity.GetType(), entity.ID, propertyName, referenceType, false)) { EntityReference reference = (EntityReference)r; // If the ID is NOT found in the idsOfEntitiesToKeep array then it should be added to the list. // The list is references intended for deletion if (Array.IndexOf(idsOfEntitiesToKeep, reference.Entity1ID) == -1 && Array.IndexOf(idsOfEntitiesToKeep, reference.Entity2ID) == -1) { LogWriter.Debug("Neither entity was found in the list to keep. Adding to list to delete."); collection.Add(reference); } } } return collection; }
/// <summary> /// This method first connects to the Outlook service. Afterwards, /// client information is retrieved and the client state is changed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetRetrieveDataFilters1> // Create and Retrieve Offline Filter // In your Outlook client, this will appear in the System Filters tab // under File | CRM | Synchronize | Outlook Filters. Console.Write("Creating offline filter"); String contactName = String.Format("offlineFilteredContact {0}", DateTime.Now.ToLongTimeString()); String fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"contact\"><attribute name=\"contactid\" /><filter type=\"and\">" + "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"description\" operator=\"eq\" value=\"{0}\" />" + "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", contactName); SavedQuery filter = new SavedQuery(); filter.FetchXml = fetchXml; filter.IsQuickFindQuery = false; filter.QueryType = SavedQueryQueryType.OfflineFilters; filter.ReturnedTypeCode = Contact.EntityLogicalName; filter.Name = "ReadOnlyFilter_" + contactName; filter.Description = "Sample offline filter for Contact entity"; _offlineFilter = _serviceProxy.Create(filter); Console.WriteLine(" and retrieving offline filter"); SavedQuery result = (SavedQuery)_serviceProxy.Retrieve( SavedQuery.EntityLogicalName, _offlineFilter, new ColumnSet("name", "description")); Console.WriteLine("Name: {0}", result.Name); Console.WriteLine("Description: {0}", result.Description); Console.WriteLine(); // Create and Retrieve Offline Template // In your Outlook client, this will appear in the User Filters tab // under File | CRM | Synchronize | Outlook Filters. Console.Write("Creating offline template"); String accountName = String.Format("offlineFilteredAccount {0}", DateTime.Now.ToLongTimeString()); fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"account\"><attribute name=\"accountid\" /><filter type=\"and\">" + "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"name\" operator=\"eq\" value=\"{0}\" />" + "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", accountName); SavedQuery template = new SavedQuery(); template.FetchXml = fetchXml; template.IsQuickFindQuery = false; template.QueryType = SavedQueryQueryType.OfflineTemplate; template.ReturnedTypeCode = Account.EntityLogicalName; template.Name = "ReadOnlyFilter_" + accountName; template.Description = "Sample offline template for Account entity"; _offlineTemplate = _serviceProxy.Create(template); Console.WriteLine(" and retrieving offline template"); result = (SavedQuery)_serviceProxy.Retrieve( SavedQuery.EntityLogicalName, _offlineTemplate, new ColumnSet("name", "description")); Console.WriteLine("Name: {0}", result.Name); Console.WriteLine("Description: {0}", result.Description); Console.WriteLine(); //</snippetRetrieveDataFilters1> //<snippetRetrieveDataFilters2> // Call InstantiateFiltersRequest Console.WriteLine("Retrieving user's ID and creating the template collection"); WhoAmIRequest whoAmI = new WhoAmIRequest(); Guid id = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId; EntityReferenceCollection templates = new EntityReferenceCollection(); templates.Add(new EntityReference( SavedQuery.EntityLogicalName, _offlineTemplate)); Console.WriteLine("Activating the selected offline templates for this user"); InstantiateFiltersRequest request = new InstantiateFiltersRequest { UserId = id, TemplateCollection = templates }; InstantiateFiltersResponse response = (InstantiateFiltersResponse)_serviceProxy.Execute(request); Console.WriteLine(); //</snippetRetrieveDataFilters2> //<snippetRetrieveDataFilters3> // Call ResetUserFiltersRequest Console.WriteLine("Resetting the user's offline templates to the defaults"); ResetUserFiltersRequest resetRequest = new ResetUserFiltersRequest { QueryType = SavedQueryQueryType.OfflineFilters }; ResetUserFiltersResponse resetResponse = (ResetUserFiltersResponse)_serviceProxy.Execute(resetRequest); Console.WriteLine(); //</snippetRetrieveDataFilters3> DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public void Test_GetReference_Sync_Exclude() { using (LogGroup logGroup = LogGroup.Start("Testing the GetReference function with a synchronous reference to ensure it retrieves the correct reference.", NLog.LogLevel.Debug)) { TestUtilities.CreateDummyReferences(100); TestUser user = new TestUser(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestUser user2 = new TestUser(); user2.ID = Guid.NewGuid(); user2.FirstName = "Test"; user2.LastName = "User 2"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); role.Name = "Test Role"; TestRole role2 = new TestRole(); role2.ID = Guid.NewGuid(); role2.Name = "Test Role 2"; user.Roles = new TestRole[] {role}; user2.Roles = new TestRole[] { role2 }; //role2.Users = new TestUser[] {user, user2}; LogWriter.Debug("User 1 ID: " + user.ID.ToString()); LogWriter.Debug("User 2 ID: " + user2.ID.ToString()); LogWriter.Debug("Role 1 ID: " + role.ID.ToString()); LogWriter.Debug("Role 2 ID: " + role2.ID.ToString()); EntityReferenceCollection userReferences = DataAccess.Data.Referencer.GetActiveReferences(user); EntityReferenceCollection user2References = DataAccess.Data.Referencer.GetActiveReferences(user2); Assert.AreEqual(1, userReferences.Count, "userReferences.Length is incorrect"); Assert.AreEqual(1, user2References.Count, "user2References.Length is incorrect"); EntityReference originalReference1 = userReferences[0]; EntityReference originalReference2 = user2References[0]; LogWriter.Debug("Original reference - Entity 1 ID: " + originalReference1.Entity1ID.ToString()); LogWriter.Debug("Original reference - Entity 2 ID: " + originalReference1.Entity2ID.ToString()); LogWriter.Debug("Original reference - Property 1 name: " + originalReference1.Property1Name); LogWriter.Debug("Original reference - Property 2 name: " + originalReference1.Property2Name); LogWriter.Debug("Original reference - Type 1 name: " + originalReference1.Type1Name); LogWriter.Debug("Original reference - Type 2 name: " + originalReference1.Type2Name); DataAccess.Data.Saver.Save(role2); DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); DataAccess.Data.Saver.Save(user2); string referenceStoreName = DataUtilities.GetDataStoreName("TestUser", "TestRole"); EntityReferenceCollection referenceEntities = DataAccess.Data.Referencer.GetReferences(user.GetType().Name, role.GetType().Name); Assert.AreEqual(2, referenceEntities.Count, "Incorrect number of references found in the store after saving entities."); // Switch the references around if necessary if (referenceEntities[0].Entity1ID == originalReference2.Entity1ID) { EntityReference r1 = referenceEntities[1]; EntityReference r2 = referenceEntities[0]; referenceEntities = new EntityReferenceCollection(); referenceEntities.Add(r1); referenceEntities.Add(r2); } bool firstReferenceMatches = (((referenceEntities[0].Includes(originalReference1.Entity1ID, originalReference1.Property1Name) && referenceEntities[0].Includes(originalReference1.Entity2ID, originalReference1.Property2Name)) || ((referenceEntities[0].Includes(originalReference2.Entity1ID, originalReference2.Property1Name) && referenceEntities[0].Includes(originalReference2.Entity2ID, originalReference2.Property2Name))))); bool secondReferenceMatches = (((referenceEntities[1].Includes(originalReference1.Entity1ID, originalReference1.Property1Name) && referenceEntities[1].Includes(originalReference1.Entity2ID, originalReference1.Property2Name)) || ((referenceEntities[1].Includes(originalReference2.Entity1ID, originalReference2.Property1Name) && referenceEntities[1].Includes(originalReference2.Entity2ID, originalReference2.Property2Name))))); Assert.IsTrue(firstReferenceMatches, "First reference doesn't match original references."); Assert.IsTrue(secondReferenceMatches, "Second reference doesn't match original references."); EntityReference reference = DataAccess.Data.Referencer.GetReference(user.GetType(), user.ID, "Roles", role.GetType(), role2.ID, "Users", false); Assert.IsNull(reference, "The return value should be null."); } }
/// <summary> /// Retrieves the active references from the provided entity property. This only includes those references currently active and not those in the data store. /// </summary> /// <param name="entity">The entity containing the property that the references are assigned to.</param> /// <param name="property">The property that the references are assigned to.</param> /// <param name="mirrorPropertyName">The name of the mirror property.</param> /// <returns>An array of the entity references.</returns> protected virtual EntityReference[] GetActiveReferencesFromMultipleReferenceProperty(IEntity entity, PropertyInfo property, string mirrorPropertyName) { EntityReferenceCollection collection = new EntityReferenceCollection(entity); using (LogGroup logGroup = LogGroup.Start("Retrieving the references from a multiple reference property.", LogLevel.Debug)) { LogWriter.Debug("Multiple reference property."); object propertyValue = property.GetValue(entity, null); LogWriter.Debug("Property value: " + (propertyValue == null ? "[null]" : propertyValue.ToString())); Collection<IEntity> referencedEntities = new Collection<IEntity>(); referencedEntities.AddRange(EntitiesUtilities.GetReferencedEntities(entity, property)); LogWriter.Debug("# of referenced entities found: " + referencedEntities.Count); EntityReferenceCollection references = new EntityReferenceCollection(entity, property.Name, referencedEntities.ToArray(), mirrorPropertyName); LogWriter.Debug("Reference objects created."); foreach (EntityReference reference in references) { LogWriter.Debug("Adding reference with ID: " + reference.ID.ToString()); LogWriter.Debug("Source entity ID: " + reference.Entity1ID.ToString()); LogWriter.Debug("Referenced entity ID: " + reference.Entity2ID.ToString()); LogWriter.Debug("Source entity name: " + reference.Type1Name); LogWriter.Debug("Referenced entity name: " + reference.Type2Name); LogWriter.Debug("Source property name: " + reference.Property1Name); LogWriter.Debug("Mirror property name: " + reference.Property2Name); collection.Add((EntityReference)reference); } } return collection.ToArray(); }
/// <summary> /// Maintains the references of the provided entity by deleting the obsolete references (those in the data store but no longer active on one of the properties) /// and persisting the new references into the data store. /// </summary> /// <param name="entity">The entity to maintain the references for.</param> public virtual void MaintainReferences(IEntity entity) { using (LogGroup logGroup = LogGroup.Start("Maintaining the references for the provided entity.", LogLevel.Debug)) { EntityReferenceCollection updateList = new EntityReferenceCollection(); EntityReferenceCollection deleteList = new EntityReferenceCollection(); // Get the current/actives references foreach (EntityReference reference in GetActiveReferences(entity)) { updateList.Add(reference); } // Get the obsolete references foreach (EntityReference reference in GetObsoleteReferences(entity, updateList.GetEntityIDs(entity.ID))) { deleteList.Add(reference); } // Delete the obsolete references LogWriter.Debug("References to delete: " + deleteList.Count); DeleteObsoleteReferences(deleteList); // Update/save the current references LogWriter.Debug("References to update: " + updateList.Count); PersistReferences(updateList); Provider.Referencer.SetCountProperties(entity, false); } }
/// <summary> /// !! Doesn;t work same entity type!! /// </summary> public void Disassociate(string relationshipName, string keyAttributeFrom, Guid entityFrom, string keyAttributeTo, IEnumerable<Guid> relatedEntities) { var metadata = GetRelationshipMetadata(relationshipName); var isReferencing = metadata.Entity1IntersectAttribute == keyAttributeFrom; var relatedType = isReferencing ? metadata.Entity2LogicalName : metadata.Entity1LogicalName; var targetType = isReferencing ? metadata.Entity1LogicalName : metadata.Entity2LogicalName; var relationship = new Relationship(relationshipName) { PrimaryEntityRole = isReferencing ? EntityRole.Referencing : EntityRole.Referenced }; var entityReferenceCollection = new EntityReferenceCollection(); foreach (var id in relatedEntities) entityReferenceCollection.Add(CreateLookup(relatedType, id)); Disassociate(targetType, entityFrom, relationship, entityReferenceCollection); }
/// <summary> /// Retrieves all the references to the specified entity. The specified entity can be either the source or reference entity as references work both ways. /// </summary> /// <param name="entityType">The type of the entity to retrieve the corresponding references for.</param> /// <param name="entityID">The ID of the entity to retrieve the corresponding references for.</param> /// <param name="referenceType">The type of entity at the other side of the reference to the one specified.</param> /// <param name="activateAll">A value indicating whether to activate the references by loading the corresponding entities and setting them to the SourceEntity and ReferenceEntity properties.</param> /// <returns>A collection of references that match the provided parameters.</returns> public override EntityReferenceCollection GetReferences(Type entityType, Guid entityID, Type referenceType, bool activateAll) { EntityReferenceCollection collection = new EntityReferenceCollection(); using (LogGroup logGroup = LogGroup.StartDebug("Retrieving references.")) { if (entityType == null) throw new ArgumentNullException("entityType"); if (referenceType == null) throw new ArgumentNullException("referenceType"); LogWriter.Debug("Entity type: " + entityType.ToString()); LogWriter.Debug("Reference type: " + referenceType.ToString()); Db4oDataStore dataStore = (Db4oDataStore)GetDataStore(entityType.Name, referenceType.Name); if(dataStore.DoesExist) { EntityReferenceCollection list = new EntityReferenceCollection(); IQuery query1 = dataStore.ObjectContainer.Query(); query1.Constrain(typeof(EntityReference)); IConstraint constraint1 = query1.Descend("type1Name").Constrain(EntitiesUtilities.GetShortType(entityType.Name)).Equal().And( query1.Descend("type2Name").Constrain(EntitiesUtilities.GetShortType(referenceType.Name)).Equal()); if (entityID != Guid.Empty) constraint1.And(query1.Descend("entity1ID").Constrain(entityID).Equal()); IQuery query2 = dataStore.ObjectContainer.Query(); query2.Constrain(typeof(EntityReference)); IConstraint constraint2 = query2.Descend("type2Name").Constrain(EntitiesUtilities.GetShortType(entityType.Name)).Equal().And( query2.Descend("type1Name").Constrain(EntitiesUtilities.GetShortType(referenceType.Name)).Equal()); if (entityID != Guid.Empty) constraint2.And(query2.Descend("entity2ID").Constrain(entityID).Equal()); IObjectSet os1 = query1.Execute(); while (os1.HasNext()) { EntityReference reference = (EntityReference)os1.Next(); list.Add(reference); } IObjectSet os2 = query2.Execute(); while (os2.HasNext()) { EntityReference reference = (EntityReference)os2.Next(); list.Add(reference); } if (list.Count == 0) { LogWriter.Debug("No references loaded from the data store."); } else { LogWriter.Debug("Count: " + list.Count); foreach (EntityReference r in list) { using (LogGroup logGroup2 = LogGroup.StartDebug("Processing reference.")) { EntityReference reference = (EntityReference)r.SwitchFor(entityType, entityID); LogWriter.Debug("Loaded reference - Entity ID 1: " + reference.Entity1ID); LogWriter.Debug("Loaded reference - Entity ID 2: " + reference.Entity2ID); LogWriter.Debug("Loaded reference - Property 1 name: " + reference.Property1Name); LogWriter.Debug("Loaded reference - Property 2 name: " + reference.Property2Name); LogWriter.Debug("Loaded reference - Type name 1: " + reference.Type1Name); LogWriter.Debug("Loaded reference - Type name 2: " + reference.Type2Name); if (reference.Entity1ID != Guid.Empty && reference.Entity2ID != Guid.Empty) { // LogWriter.Debug("Adding to the collection."); collection.Add(reference); } else { LogWriter.Error("Reference not added to the collection. IDs are empty. This shouldn't happen but the system can ignore it and continue. Invalid references like these should probably be deleted."); } } } } } LogWriter.Debug("References #: " + collection.Count.ToString()); if (activateAll) { LogWriter.Debug("Activating references."); foreach (EntityReference reference in collection) { Provider.Activator.ActivateReference(reference); } } LogWriter.Debug("References #: " + collection.Count.ToString()); } return collection; }
internal void ApplySelectedFiltersToUsers(bool applyToActiveUsers = false) { if (lvViews.SelectedItems.Count == 0) { return; } var templates = new EntityReferenceCollection(); foreach (ListViewItem item in lvViews.SelectedItems) { templates.Add(new EntityReference(entityName, ((Entity)item.Tag).Id)); } List<Entity> users = null; if (!applyToActiveUsers) { var usDialog = new UserSelectionDialog(service); if (usDialog.ShowDialog(this) == DialogResult.OK) { users = usDialog.SelectedUsers; } else { return; } } if (users == null || users.Count > 0) { loadingPanel = InformationPanel.GetInformationPanel(this, "Processing...", 340, 120); var bwApplyFiltersToUsers = new BackgroundWorker {WorkerReportsProgress = true}; bwApplyFiltersToUsers.DoWork += bwApplyFiltersToUsers_DoWork; bwApplyFiltersToUsers.ProgressChanged += bwApplyFiltersToUsers_ProgressChanged; bwApplyFiltersToUsers.RunWorkerCompleted += bwApplyFiltersToUsers_RunWorkerCompleted; bwApplyFiltersToUsers.RunWorkerAsync(new object[] {templates, users}); } }
private void ApplyTemplateToUsers(List<Guid> rulesIds, string question, RuleManager rm, BackgroundWorker worker) { worker.ReportProgress(0, "Waiting for input..."); if ( MessageBox.Show(this, question, "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { var usDialog = new UserSelectionDialog(service); if (usDialog.ShowDialog() == DialogResult.OK) { foreach (var user in usDialog.SelectedUsers) { worker.ReportProgress(0, string.Format("Applying rule(s) to user(s) '{0}'", user.GetAttributeValue<string>("fullname"))); var erc = new EntityReferenceCollection(); foreach (var ruleId in rulesIds) { erc.Add(new EntityReference("savedquery", ruleId)); } rm.ApplyRulesToUser(erc, user.Id); } } } }