public void When_execute_is_called_with_a_null_target_exception_is_thrown() { var context = new XrmFakedContext(); var executor = new AssociateRequestExecutor(); var req = new AssociateRequest() { Target = null, Relationship = new Relationship("fakeRelationship") }; context.AddRelationship("fakeRelationship", new XrmFakedRelationship()); Assert.Throws<Exception>(() => executor.Execute(req, context)); }
//public void AssignSecurityRole(Guid prmUserId, Guid prmSecurityRoleId, IOrganizationService prmCrmWebService) public void AssignSecurityRole(SecurityRoleBase mySecurityRoleBase, IOrganizationService prmCrmWebService) { // Create new Associate Request object for creating a N:N link between User and Security AssociateRequest wod_AssosiateRequest = new AssociateRequest(); // Create related entity reference object for associating relationship // In our case we will pass (SystemUser) record reference wod_AssosiateRequest.RelatedEntities = new EntityReferenceCollection(); wod_AssosiateRequest.RelatedEntities.Add(new EntityReference("systemuser", this.guidUserId)); // Create new Relationship object for System User & Security Role entity schema and assigning it // to request relationship property wod_AssosiateRequest.Relationship = new Relationship("systemuserroles_association"); // Create target entity reference object for associating relationship mySecurityRoleBase.getSecurityRoleGuidBySecurityRoleName(prmCrmWebService); wod_AssosiateRequest.Target = new EntityReference("role", mySecurityRoleBase.guidSecurityRoleId); // Passing AssosiateRequest object to Crm Service Execute method for assigning Security Role to User prmCrmWebService.Execute(wod_AssosiateRequest); }
private static Guid CreateSystemUser(String userName, String firstName, String lastName, String domain, String roleStr, OrganizationServiceProxy serviceProxy, ref String ldapPath) { CreateADAccount(userName, firstName, lastName, serviceProxy, ref ldapPath); // Retrieve the default business unit needed to create the user. QueryExpression businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple( businessUnitQuery).Entities[0].ToEntity<BusinessUnit>(); //Create a new system user. SystemUser user = new SystemUser { DomainName = domain + userName, FirstName = firstName, LastName = lastName, BusinessUnitId = new EntityReference { LogicalName = BusinessUnit.EntityLogicalName, Name = BusinessUnit.EntityLogicalName, Id = defaultBusinessUnit.Id } }; Guid userId = serviceProxy.Create(user); if (!String.IsNullOrWhiteSpace(roleStr)) { // Retrieve the specified security role. Role role = RetrieveRoleByName(serviceProxy, roleStr); // Assign the security role to the newly created Microsoft Dynamics CRM user. AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, role.Id), }, Relationship = new Relationship("systemuserroles_association") }; serviceProxy.Execute(associate); } return userId; }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a new connectionrole instance. /// Create related Connection Role Object Type Code records /// for the account and the contact entities. /// </summary> public static void CreateRequiredRecords(CrmServiceClient service) { // Create a Connection Role for account and contact var newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue((int)connectionrole_category.Business) }; _connectionRoleId = service.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account var newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; service.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact var newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; service.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact." ); // Associate the connection role with itself. var associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId) }, // The name of the relationship connection role association // relationship in MS CRM. Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; service.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection role with itself."); // Create an Account var setupAccount = new Account { Name = "Example Account" }; _accountId = service.Create(setupAccount); Console.WriteLine("Created {0}.", setupAccount.Name); // Create a Contact var setupContact = new Contact { LastName = "Example Contact" }; _contactId = service.Create(setupContact); Console.WriteLine("Created {0}.", setupContact.LastName); return; }
internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef) { var request = MakeRequest <CreateRequest>(orgRequest); var resp = new CreateResponse(); var settings = MockupExecutionContext.GetSettings(request); var entity = request.Target; if (entity.LogicalName == null) { throw new MockupException("Entity needs a logical name"); } var entityMetadata = metadata.EntityMetadata.GetMetadata(entity.LogicalName); var clonedEntity = entity.CloneEntity(entityMetadata, new ColumnSet(true)); var validAttributes = clonedEntity.Attributes.Where(x => x.Value != null); clonedEntity.Attributes = new AttributeCollection(); clonedEntity.Attributes.AddRange(validAttributes); if (userRef != null && userRef.Id != Guid.Empty && !security.HasPermission(clonedEntity, AccessRights.CreateAccess, userRef)) { throw new FaultException($"Trying to create entity '{entity.LogicalName}'" + $", but the calling user with id '{userRef.Id}' does not have create access for that entity"); } if (Utility.HasCircularReference(metadata.EntityMetadata, clonedEntity)) { throw new FaultException($"Trying to create entity '{clonedEntity.LogicalName}', but the attributes had a circular reference"); } var transactioncurrencyId = "transactioncurrencyid"; var exchangerate = "exchangerate"; if (!clonedEntity.Attributes.ContainsKey(transactioncurrencyId) && Utility.IsSettableAttribute(transactioncurrencyId, entityMetadata) && entityMetadata.Attributes.Any(m => m is MoneyAttributeMetadata) && (settings.ServiceRole == MockupServiceSettings.Role.UI || (settings.ServiceRole == MockupServiceSettings.Role.SDK && clonedEntity.Attributes.Any( attr => entityMetadata.Attributes.Where(a => a is MoneyAttributeMetadata).Any(m => m.LogicalName == attr.Key))))) { var user = db.GetEntityOrNull(userRef); if (user.Attributes.ContainsKey(transactioncurrencyId)) { clonedEntity.Attributes[transactioncurrencyId] = user[transactioncurrencyId]; } else { clonedEntity.Attributes[transactioncurrencyId] = Utility.GetBaseCurrency(metadata); } } if (!clonedEntity.Attributes.ContainsKey(exchangerate) && Utility.IsSettableAttribute(exchangerate, entityMetadata) && clonedEntity.Attributes.ContainsKey(transactioncurrencyId)) { var currencyId = clonedEntity.GetAttributeValue <EntityReference>(transactioncurrencyId); var currency = db.GetEntityOrNull(currencyId); clonedEntity.Attributes[exchangerate] = currency["exchangerate"]; Utility.HandleCurrencies(metadata, db, clonedEntity); } var attributes = entityMetadata.Attributes; if (!clonedEntity.Attributes.ContainsKey("statecode") && Utility.IsSettableAttribute("statecode", entityMetadata)) { var stateMeta = attributes.First(a => a.LogicalName == "statecode") as StateAttributeMetadata; clonedEntity["statecode"] = stateMeta.DefaultFormValue.HasValue ? new OptionSetValue(stateMeta.DefaultFormValue.Value) : new OptionSetValue(0); } if (!clonedEntity.Attributes.ContainsKey("statuscode") && Utility.IsSettableAttribute("statuscode", entityMetadata)) { var statusMeta = attributes.FirstOrDefault(a => a.LogicalName == "statuscode") as StatusAttributeMetadata; clonedEntity["statuscode"] = statusMeta.DefaultFormValue.HasValue ? new OptionSetValue(statusMeta.DefaultFormValue.Value) : new OptionSetValue(1); } if (Utility.IsSettableAttribute("createdon", entityMetadata)) { clonedEntity["createdon"] = DateTime.Now.Add(core.TimeOffset); } if (Utility.IsSettableAttribute("createdby", entityMetadata)) { clonedEntity["createdby"] = userRef; } if (Utility.IsSettableAttribute("modifiedon", entityMetadata) && Utility.IsSettableAttribute("modifiedby", entityMetadata)) { clonedEntity["modifiedon"] = clonedEntity["createdon"]; clonedEntity["modifiedby"] = clonedEntity["createdby"]; } var owner = userRef; if (clonedEntity.Attributes.ContainsKey("ownerid")) { owner = clonedEntity.GetAttributeValue <EntityReference>("ownerid"); } Utility.SetOwner(db, security, metadata, clonedEntity, owner); if (!clonedEntity.Attributes.ContainsKey("businessunitid") && clonedEntity.LogicalName == LogicalNames.SystemUser || clonedEntity.LogicalName == LogicalNames.Team) { clonedEntity["businessunitid"] = metadata.RootBusinessUnit.ToEntityReference(); } if (clonedEntity.LogicalName == LogicalNames.BusinessUnit && !clonedEntity.Attributes.ContainsKey("parentbusinessunitid")) { clonedEntity["parentbusinessunitid"] = metadata.RootBusinessUnit.ToEntityReference(); } if (settings.ServiceRole == MockupServiceSettings.Role.UI) { foreach (var attr in entityMetadata.Attributes.Where(a => (a as BooleanAttributeMetadata)?.DefaultValue != null).ToList()) { if (!clonedEntity.Attributes.Any(a => a.Key == attr.LogicalName)) { clonedEntity[attr.LogicalName] = (attr as BooleanAttributeMetadata).DefaultValue; } } foreach (var attr in entityMetadata.Attributes.Where(a => (a as PicklistAttributeMetadata)?.DefaultFormValue != null && (a as PicklistAttributeMetadata)?.DefaultFormValue.Value != -1).ToList()) { if (!clonedEntity.Attributes.Any(a => a.Key == attr.LogicalName)) { clonedEntity[attr.LogicalName] = new OptionSetValue((attr as PicklistAttributeMetadata).DefaultFormValue.Value); } } } if (clonedEntity.LogicalName == LogicalNames.Contact || clonedEntity.LogicalName == LogicalNames.Lead || clonedEntity.LogicalName == LogicalNames.SystemUser) { Utility.SetFullName(metadata, clonedEntity); } db.Add(clonedEntity); if (clonedEntity.LogicalName == LogicalNames.BusinessUnit) { security.AddRolesForBusinessUnit(db, clonedEntity.ToEntityReference()); } if (entity.RelatedEntities.Count > 0) { foreach (var relatedEntities in entity.RelatedEntities) { if (Utility.GetRelationshipMetadataDefaultNull(metadata.EntityMetadata, relatedEntities.Key.SchemaName, Guid.Empty, userRef) == null) { throw new FaultException($"Relationship with schemaname '{relatedEntities.Key.SchemaName}' does not exist in metadata"); } foreach (var relatedEntity in relatedEntities.Value.Entities) { var req = new CreateRequest() { Target = relatedEntity }; core.Execute(req, userRef); } var associateReq = new AssociateRequest { Target = entity.ToEntityReference(), Relationship = relatedEntities.Key, RelatedEntities = new EntityReferenceCollection(relatedEntities.Value.Entities.Select(e => e.ToEntityReference()).ToList()) }; core.Execute(associateReq, userRef); } } resp.Results.Add("id", clonedEntity.Id); return(resp); }
/// <summary> /// Create and configure the organization service proxy. /// Create the connection role instances. /// Associate the connection roles. /// 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(); // Create the Connection Role 1 ConnectionRole newConnectionRole1 = new ConnectionRole { Name = "Example Connection Role 1", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole1Id = _serviceProxy.Create(newConnectionRole1); Console.WriteLine("Created {0}.", newConnectionRole1.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Contact." ); // Create the Connection Role 2 ConnectionRole newConnectionRole2 = new ConnectionRole { Name = "Example Connection Role 2", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole2Id = _serviceProxy.Create(newConnectionRole2); Console.WriteLine("Created {0}.", newConnectionRole2.Name); // Create a related Connection Role 2 Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Account." ); // Create a related Connection Role 2 Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Contact." ); //<snippetAssociateReciprocalConnectionRoles> // Associate the connection roles AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole1Id), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole2Id) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection roles."); //</snippetAssociateReciprocalConnectionRoles> 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 static void Should_Only_Find_Correct_Faked_N_To_N_Records() { var fakedContext = new XrmFakedContext(); var fakedService = fakedContext.GetFakedOrganizationService(); var userId = new Guid("11111111-7982-4276-A8FE-7CE05FABEAB4"); var businessId = Guid.NewGuid(); var testUser = new SystemUser { Id = userId }; var testRole = new Role { Id = new Guid("22222222-7982-4276-A8FE-7CE05FABEAB4"), Name = "Test Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId) }; var testUser2 = new SystemUser { Id = Guid.NewGuid() }; var testRole2 = new Role { Id = Guid.NewGuid(), Name = "Test Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId) }; fakedContext.Initialize(new Entity[] { testUser, testRole, testUser2, testRole2 }); fakedContext.AddRelationship("systemuserroles_association", new XrmFakedRelationship { IntersectEntity = "systemuserroles", Entity1LogicalName = SystemUser.EntityLogicalName, Entity1Attribute = "systemuserid", Entity2LogicalName = Role.EntityLogicalName, Entity2Attribute = "roleid" }); var request = new AssociateRequest() { Target = testUser.ToEntityReference(), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, testRole.Id), }, Relationship = new Relationship("systemuserroles_association") }; fakedService.Execute(request); var request2 = new AssociateRequest() { Target = testUser2.ToEntityReference(), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, testRole2.Id), }, Relationship = new Relationship("systemuserroles_association") }; fakedService.Execute(request2); var query = new QueryExpression() { EntityName = "role", ColumnSet = new ColumnSet("name"), LinkEntities = { new LinkEntity { LinkFromEntityName = Role.EntityLogicalName, LinkFromAttributeName = "roleid", LinkToEntityName = SystemUserRoles.EntityLogicalName, LinkToAttributeName = "roleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression { AttributeName = "systemuserid", Operator = ConditionOperator.Equal, Values = { userId} } } } } } }; var result = fakedService.RetrieveMultiple(query); Assert.NotEmpty(result.Entities); Assert.Equal(1, result.Entities.Count); }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// authorization profile is created, and associated to a team. Then an entity /// is created and permissions for the entity are assigned to the profile. These /// permissions are then retrieved. /// </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 { //<snippetRetrieveSecuredFieldsForAUser1> // 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(); CreateRequiredRecords(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; _serviceProxy.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; _serviceProxy.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)_serviceProxy.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List<Guid> profileIds = new List<Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection<Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = _serviceProxy.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveSecuredFieldsForAUser1> } // 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> /// This method creates any entity records that this sample requires. /// Create a primary connection role instance. /// Create a reciprocal connection role instance. /// Associate the connection roles. /// </summary> public void CreateRequiredRecords() { // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create the Connection Roles. // Create the primary connection Role instance. ConnectionRole setupPrimaryConnectionRole = new ConnectionRole { Name = "Example Primary Connection Role", Category = new OptionSetValue(Categories.Business), }; _primaryConnectionRoleId = _serviceProxy.Create(setupPrimaryConnectionRole); Console.WriteLine("Created {0}.", setupPrimaryConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account // on the primary role. ConnectionRoleObjectTypeCode accountPrimaryConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _primaryConnectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(accountPrimaryConnectionRoleTypeCode); Console.WriteLine(@"Created a related Connection Role Object Type Code record for Account on the primary role."); // Create another Connection Role. ConnectionRole setupReciprocalConnectionRole = new ConnectionRole { Name = "Example Reciprocal Connection Role", Category = new OptionSetValue(Categories.Business), }; _reciprocalConnectionRoleId = _serviceProxy.Create(setupReciprocalConnectionRole); Console.WriteLine("Created {0}.", setupReciprocalConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account // on the related role. ConnectionRoleObjectTypeCode accountReciprocalConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _reciprocalConnectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(accountReciprocalConnectionRoleTypeCode); Console.WriteLine(@"Created a related Connection Role Object Type Code record for Account on the related role."); // Associate the connection roles. AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _primaryConnectionRoleId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _reciprocalConnectionRoleId) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); return; }
public void ValidMessageTest() { this.request = new AssociateUnencryptedRequest(Protocol.V20.Version, this.secureRecipient); this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.EnsureValidMessage(); }
internal static void Associate(OrganizationServiceContext serviceContext, EntityReference related) { var targetEntityLogicalName = HttpContext.Current.Request["refentity"]; var targetEntityId = HttpContext.Current.Request["refid"]; var relationshipName = HttpContext.Current.Request["refrel"]; var relationshipRole = HttpContext.Current.Request["refrelrole"]; Guid targetId; if (string.IsNullOrWhiteSpace(targetEntityLogicalName) || string.IsNullOrWhiteSpace(targetEntityId) || string.IsNullOrWhiteSpace(relationshipName) || related == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Request did not contain parameters 'refentity', 'refid', 'refrel'"); return; } if (!Guid.TryParse(targetEntityId, out targetId)) { ADXTrace.Instance.TraceError(TraceCategory.Application, "Request did not contain a valid guid 'refid'"); return; } try { var relationship = new Relationship(relationshipName); if (!string.IsNullOrWhiteSpace(relationshipRole)) { switch (relationshipRole) { case "Referenced": relationship.PrimaryEntityRole = EntityRole.Referenced; break; case "Referencing": relationship.PrimaryEntityRole = EntityRole.Referencing; return; break; default: ADXTrace.Instance.TraceError(TraceCategory.Application, "Relationship Primary Entity Role provided by parameter named 'refrelrole' is not valid."); break; } } var associateRequest = new AssociateRequest { Target = new EntityReference(targetEntityLogicalName, targetId), Relationship = relationship, RelatedEntities = new EntityReferenceCollection { related } }; serviceContext.Execute(associateRequest); } catch (Exception ex) { ADXTrace.Instance.TraceError(TraceCategory.Application, ex.ToString()); } }
public void Import() { using (var reader = new StreamReader(filePath, Encoding.Default)) { string line; int lineNumber = 0; while ((line = reader.ReadLine()) != null) { lineNumber++; try { var data = line.Split(','); Guid firstGuid = Guid.Empty; Guid secondGuid = Guid.Empty; if (settings.FirstAttributeIsGuid) { firstGuid = new Guid(data[0]); } else { var records = service.RetrieveMultiple(new QueryExpression(settings.FirstEntity) { Criteria = { Conditions = { new ConditionExpression(settings.FirstAttributeName, ConditionOperator.Equal, data[0]) } } }); if (records.Entities.Count == 1) { firstGuid = records.Entities.First().Id; } else if (records.Entities.Count > 1) { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("More than one record ({0}) were found with the value specified", settings.FirstEntity) }); continue; } else { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("No record ({0}) was found with the value specified", settings.FirstEntity) }); continue; } } if (settings.SecondAttributeIsGuid) { secondGuid = new Guid(data[1]); } else { var records = service.RetrieveMultiple(new QueryExpression(settings.SecondEntity) { Criteria = { Conditions = { new ConditionExpression(settings.SecondAttributeName, ConditionOperator.Equal, data[1]) } } }); if (records.Entities.Count == 1) { secondGuid = records.Entities.First().Id; } else if (records.Entities.Count > 1) { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("More than one record ({0}) were found with the value specified", settings.SecondEntity) }); continue; } else { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("No record ({0}) was found with the value specified", settings.SecondEntity) }); continue; } } var request = new AssociateRequest { Target = new EntityReference(settings.FirstEntity, firstGuid), Relationship = new Relationship(settings.Relationship), RelatedEntities = new EntityReferenceCollection { new EntityReference(settings.SecondEntity, secondGuid) } }; if (request.Target.LogicalName == request.RelatedEntities.First().LogicalName) { request.Relationship.PrimaryEntityRole = EntityRole.Referenced; } service.Execute(request); OnRaiseSuccess(new ResultEventArgs { LineNumber = lineNumber }); } catch (FaultException<OrganizationServiceFault> error) { if (error.Detail.ErrorCode.ToString("X") == "80040237") { OnRaiseError(new ResultEventArgs { LineNumber = lineNumber, Message = "Relationship was not created because it already exists" }); } else { OnRaiseError(new ResultEventArgs { LineNumber = lineNumber, Message = error.Message }); } } } } }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Create the Connection Role 1 ConnectionRole newConnectionRole1 = new ConnectionRole { Name = "Example Connection Role 1", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole1Id = service.Create(newConnectionRole1); Console.WriteLine("Created {0}.", newConnectionRole1.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; service.Create(newAccountConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; service.Create(newContactConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Contact." ); // Create the Connection Role 2 ConnectionRole newConnectionRole2 = new ConnectionRole { Name = "Example Connection Role 2", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole2Id = service.Create(newConnectionRole2); Console.WriteLine("Created {0}.", newConnectionRole2.Name); // Create a related Connection Role 2 Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; service.Create(newAccountConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Account." ); // Create a related Connection Role 2 Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; service.Create(newContactConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Contact." ); // Associate the connection roles AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole1Id), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole2Id) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; service.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection roles."); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
protected internal void CreateEntity(Entity e) { if (e == null) { throw new InvalidOperationException("The entity must not be null"); } if (e.Id == Guid.Empty) { e.Id = Guid.NewGuid(); //Add default guid if none present ValidateEntity(e); //Hack for Dynamic Entities where the Id property doesn't populate the "entitynameid" primary key if (!e.GetType().IsSubclassOf(typeof(Entity))) { var primaryKeyAttribute = string.Format("{0}id", e.LogicalName); e[primaryKeyAttribute] = e.Id; } } else { ValidateEntity(e); } //Create specific validations if (e.Id != Guid.Empty && Data.ContainsKey(e.LogicalName) && Data[e.LogicalName].ContainsKey(e.Id)) { throw new InvalidOperationException(string.Format("There is already a record of entity {0} with id {1}, can't create with this Id.", e.LogicalName, e.Id)); } AddEntityWithDefaults(e); if (e.RelatedEntities.Count > 0) { foreach (var relationshipSet in e.RelatedEntities) { Relationship relationship = relationshipSet.Key; foreach (var relatedEntity in relationshipSet.Value.Entities) { CreateEntity(relatedEntity); } if (FakeMessageExecutors.ContainsKey(typeof(AssociateRequest))) { var entityReferenceCollection = new EntityReferenceCollection(relationshipSet.Value.Entities.Select(en => en.ToEntityReference()).ToList()); var request = new AssociateRequest() { Target = new EntityReference() { Id = e.Id, LogicalName = e.LogicalName }, Relationship = relationship, RelatedEntities = entityReferenceCollection }; FakeMessageExecutors[typeof(AssociateRequest)].Execute(request, this); } else throw PullRequestException.NotImplementedOrganizationRequest(typeof(AssociateRequest)); } } }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a new connectionrole instance. /// Create related Connection Role Object Type Code records /// for the account and the contact entities. /// </summary> public void CreateRequiredRecords() { // Create a Connection Role for account and contact ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue((int)connectionrole_category.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact." ); // Associate the connection role with itself. AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId) }, // The name of the relationship connection role association // relationship in MS CRM. Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection role with itself."); // Create an Account Account setupAccount = new Account { Name = "Example Account" }; _accountId = _serviceProxy.Create(setupAccount); Console.WriteLine("Created {0}.", setupAccount.Name); // Create a Contact Contact setupContact = new Contact { LastName = "Example Contact" }; _contactId = _serviceProxy.Create(setupContact); Console.WriteLine("Created {0}.", setupContact.LastName); return; }
protected override string GetRequestDescription(OrganizationRequest request) { AssociateRequest associateRequest = (AssociateRequest)request; return(string.Format(Properties.Resources.Dynamics365AssociateOperationRequestDescription, Entity.DisplayName, associateRequest.Target.Id, AssociatedEntity.DisplayName, associateRequest.RelatedEntities[0].Id)); }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// authorization profile is created, and associated to a team. Then an entity /// is created and permissions for the entity are assigned to the profile. These /// permissions are then retrieved. /// </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 { //<snippetRetrieveSecuredFieldsForAUser1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; _serviceProxy.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; _serviceProxy.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)_serviceProxy.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List <Guid> profileIds = new List <Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection <Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = _serviceProxy.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveSecuredFieldsForAUser1> } // 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> /// This method first connects to the Organization service. Afterwards, /// a FieldSecurityProfile object is created and tied to an existing team. Then a /// custom entity and several attributes are created and FieldPermission is /// assigned to the Identity attribute of the new entity. /// </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 { //<snippetEnableFieldSecurityForAnEntity1> // 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(); CreateRequiredRecords(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); //<snippetEnableFieldSecurityForAnEntity2> // Create the request object and set the monikers with the // teamprofiles_association relationship. AssociateRequest teamToProfile = new AssociateRequest { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; // Execute the request. _serviceProxy.Execute(teamToProfile); //</snippetEnableFieldSecurityForAnEntity2> // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false) }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; // Execute the request. _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Create custom attributes. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; // Execute the request. CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; // Execute the request. CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create the field permission for the Identity attribute. FieldPermission identityPermission = new FieldPermission() { AttributeLogicalName = "new_identity", EntityName = "new_tweet", CanRead = new OptionSetValue(FieldPermissionType.Allowed), FieldSecurityProfileId = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId) }; // Execute the request _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created. "); DeleteRequiredRecords(promptforDelete); } //</snippetEnableFieldSecurityForAnEntity1> } // 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; } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate // // Create a Connection Role for account and contact ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue((int)connectionrole_category.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact." ); // Associate the connection role with itself. AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId) }, // The name of the relationship connection role association // relationship in MS CRM. Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection role with itself."); // Create an Account Account setupAccount = new Account { Name = "Example Account" }; _accountId = _serviceProxy.Create(setupAccount); Console.WriteLine("Created {0}.", setupAccount.Name); // Create a Contact Contact setupContact = new Contact { LastName = "Example Contact" }; _contactId = _serviceProxy.Create(setupContact); Console.WriteLine("Created {0}.", setupContact.LastName); return; #endregion Demonstrate } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public void Setup() { this.request = new AssociateUnencryptedRequest(this.protocol.Version, this.secureRecipient); }
/// <summary> /// Create and configure the organization service proxy. /// Create the connection role instances. /// Associate the connection roles. /// 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)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the Connection Role 1 ConnectionRole newConnectionRole1 = new ConnectionRole { Name = "Example Connection Role 1", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole1Id = _serviceProxy.Create(newConnectionRole1); Console.WriteLine("Created {0}.", newConnectionRole1.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Contact." ); // Create the Connection Role 2 ConnectionRole newConnectionRole2 = new ConnectionRole { Name = "Example Connection Role 2", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole2Id = _serviceProxy.Create(newConnectionRole2); Console.WriteLine("Created {0}.", newConnectionRole2.Name); // Create a related Connection Role 2 Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Account." ); // Create a related Connection Role 2 Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Contact." ); //<snippetAssociateReciprocalConnectionRoles> // Associate the connection roles AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole1Id), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole2Id) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection roles."); //</snippetAssociateReciprocalConnectionRoles> 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 InvalidMessageTest() { this.request = new AssociateUnencryptedRequest(Protocol.V20.Version, this.insecureRecipient); this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.EnsureValidMessage(); // no-encryption only allowed for secure channels. }
internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef) { var request = MakeRequest <CreateRequest>(orgRequest); var resp = new CreateResponse(); var settings = MockupExecutionContext.GetSettings(request); var entity = request.Target; if (entity.LogicalName == null) { throw new MockupException("Entity needs a logical name"); } var entityMetadata = metadata.EntityMetadata.GetMetadata(entity.LogicalName); var clonedEntity = entity.CloneEntity(entityMetadata, new ColumnSet(true)); var validAttributes = clonedEntity.Attributes.Where(x => x.Value != null); clonedEntity.Attributes = new AttributeCollection(); clonedEntity.Attributes.AddRange(validAttributes); if (userRef != null && userRef.Id != Guid.Empty) { if (!security.HasPermission(clonedEntity, AccessRights.CreateAccess, userRef)) { throw new FaultException($"Trying to create entity '{entity.LogicalName}'" + $", but the calling user with id '{userRef.Id}' does not have Create access for that entity (SecLib::AccessCheckEx2 failed)"); } if (core.GetMockupSettings().AppendAndAppendToPrivilegeCheck.GetValueOrDefault(true)) { var references = clonedEntity.Attributes .Where(x => x.Value is EntityReference && x.Key != "ownerid") .ToArray(); if (references.Any()) { if (!security.HasPermission(clonedEntity, AccessRights.AppendAccess, userRef)) { throw new FaultException($"Trying to create entity '{entity.LogicalName}' with references" + $", but the calling user with id '{userRef.Id}' does not have Append access for that entity"); } } foreach (var attr in references) { var reference = attr.Value as EntityReference; if (settings.ServiceRole == MockupServiceSettings.Role.UI && !security.HasPermission(reference, AccessRights.ReadAccess, userRef)) { throw new FaultException($"Trying to create entity '{entity.LogicalName}'" + $", but the calling user with id '{userRef.Id}' does not have read access for referenced entity '{reference.LogicalName}' on attribute '{attr.Key}'"); } if (!security.HasPermission(reference, AccessRights.AppendToAccess, userRef)) { throw new FaultException($"Trying to create entity '{entity.LogicalName}'" + $", but the calling user with id '{userRef.Id}' does not have AppendTo access for referenced entity '{reference.LogicalName}' on attribute '{attr.Key}'"); } } } } if (Utility.HasCircularReference(metadata.EntityMetadata, clonedEntity)) { throw new FaultException($"Trying to create entity '{clonedEntity.LogicalName}', but the attributes had a circular reference"); } var transactioncurrencyId = "transactioncurrencyid"; var exchangerate = "exchangerate"; if (!clonedEntity.Attributes.ContainsKey(transactioncurrencyId) && Utility.IsValidAttribute(transactioncurrencyId, entityMetadata) && entityMetadata.Attributes.Any(m => m is MoneyAttributeMetadata) && (settings.ServiceRole == MockupServiceSettings.Role.UI || (settings.ServiceRole == MockupServiceSettings.Role.SDK && clonedEntity.Attributes.Any( attr => entityMetadata.Attributes.Where(a => a is MoneyAttributeMetadata).Any(m => m.LogicalName == attr.Key))))) { var user = db.GetEntityOrNull(userRef); if (user.Attributes.ContainsKey(transactioncurrencyId)) { clonedEntity.Attributes[transactioncurrencyId] = user[transactioncurrencyId]; } else { clonedEntity.Attributes[transactioncurrencyId] = Utility.GetBaseCurrency(metadata); } } if (!clonedEntity.Attributes.ContainsKey(exchangerate) && Utility.IsValidAttribute(exchangerate, entityMetadata) && clonedEntity.Attributes.ContainsKey(transactioncurrencyId)) { var currencyId = clonedEntity.GetAttributeValue <EntityReference>(transactioncurrencyId); var currency = db.GetEntityOrNull(currencyId); clonedEntity.Attributes[exchangerate] = currency["exchangerate"]; Utility.HandleCurrencies(metadata, db, clonedEntity); } if (Utility.IsValidAttribute("statecode", entityMetadata) && Utility.IsValidAttribute("statuscode", entityMetadata)) { var defaultState = 0; try { var defaultStateStatus = metadata.DefaultStateStatus[clonedEntity.LogicalName]; if (!clonedEntity.Attributes.ContainsKey("statecode") && !clonedEntity.Attributes.ContainsKey("statuscode")) { clonedEntity["statecode"] = new OptionSetValue(defaultState); clonedEntity["statuscode"] = new OptionSetValue(defaultStateStatus[defaultState]); } else { var statusmeta = (entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == "statuscode") as StatusAttributeMetadata) ?.OptionSet.Options .Cast <StatusOptionMetadata>() .FirstOrDefault(o => o.Value == clonedEntity.GetAttributeValue <OptionSetValue>("statuscode")?.Value); if (clonedEntity.LogicalName != "opportunityclose" && // is allowed to be created inactive ((clonedEntity.Attributes.ContainsKey("statecode") && clonedEntity.GetAttributeValue <OptionSetValue>("statecode")?.Value != defaultState) || (clonedEntity.Attributes.ContainsKey("statuscode") && statusmeta?.State != defaultState))) { clonedEntity["statecode"] = new OptionSetValue(defaultState); clonedEntity["statuscode"] = new OptionSetValue(defaultStateStatus[defaultState]); } else if (!clonedEntity.Contains("statecode") || clonedEntity.GetAttributeValue <OptionSetValue>("statecode") == null) { clonedEntity["statecode"] = new OptionSetValue(statusmeta.State.Value); } else if (!clonedEntity.Contains("statuscode") || clonedEntity.GetAttributeValue <OptionSetValue>("statuscode") == null) { clonedEntity["statuscode"] = new OptionSetValue(defaultStateStatus[defaultState]); } } } catch (KeyNotFoundException) { throw new KeyNotFoundException($"Unable to get default status reason for the state {defaultState.ToString()} in {clonedEntity.LogicalName} entity. " + $"This might be due to unsaved default status reason changes. Please update, save, and publish the relevant status reason field on {clonedEntity.LogicalName} and generate new metadata"); } } if (Utility.IsValidAttribute("createdon", entityMetadata)) { clonedEntity["createdon"] = DateTime.UtcNow.Add(core.TimeOffset); } if (Utility.IsValidAttribute("createdby", entityMetadata)) { clonedEntity["createdby"] = userRef; } if (Utility.IsValidAttribute("modifiedon", entityMetadata) && Utility.IsValidAttribute("modifiedby", entityMetadata)) { clonedEntity["modifiedon"] = clonedEntity["createdon"]; clonedEntity["modifiedby"] = clonedEntity["createdby"]; } var owner = userRef; if (clonedEntity.Attributes.ContainsKey("ownerid")) { owner = clonedEntity.GetAttributeValue <EntityReference>("ownerid"); } Utility.SetOwner(db, security, metadata, clonedEntity, owner); if (!clonedEntity.Attributes.ContainsKey("businessunitid") && (clonedEntity.LogicalName == LogicalNames.SystemUser || clonedEntity.LogicalName == LogicalNames.Team)) { clonedEntity["businessunitid"] = metadata.RootBusinessUnit.ToEntityReference(); } if (clonedEntity.LogicalName == LogicalNames.BusinessUnit) { CheckBusinessUnitAttributes(clonedEntity, settings); } foreach (var attr in entityMetadata.Attributes.Where(a => (a as BooleanAttributeMetadata)?.DefaultValue != null).ToList()) { if (!clonedEntity.Attributes.Any(a => a.Key == attr.LogicalName)) { clonedEntity[attr.LogicalName] = (attr as BooleanAttributeMetadata).DefaultValue; } } foreach (var attr in entityMetadata.Attributes.Where(a => (a as PicklistAttributeMetadata)?.DefaultFormValue != null && (a as PicklistAttributeMetadata)?.DefaultFormValue.Value != -1).ToList()) { if (!clonedEntity.Attributes.Any(a => a.Key == attr.LogicalName)) { clonedEntity[attr.LogicalName] = new OptionSetValue((attr as PicklistAttributeMetadata).DefaultFormValue.Value); } } if (clonedEntity.LogicalName == LogicalNames.Contact || clonedEntity.LogicalName == LogicalNames.Lead || clonedEntity.LogicalName == LogicalNames.SystemUser) { Utility.SetFullName(metadata, clonedEntity); } clonedEntity.Attributes .Where(x => x.Value is string && x.Value != null && string.IsNullOrEmpty((string)x.Value)) .ToList() .ForEach(x => clonedEntity[x.Key] = null); if (Utility.Activities.Contains(clonedEntity.LogicalName)) { clonedEntity["activitytypecode"] = Utility.ActivityTypeCode[clonedEntity.LogicalName]; var req = new CreateRequest { Target = clonedEntity.ToActivityPointer() }; core.Execute(req, userRef); } db.Add(clonedEntity); if (clonedEntity.LogicalName == LogicalNames.BusinessUnit) { security.AddRolesForBusinessUnit(db, clonedEntity.ToEntityReference()); CreateDefaultTeamForBusinessUnit(clonedEntity, userRef); } if (entity.RelatedEntities.Count > 0) { foreach (var relatedEntities in entity.RelatedEntities) { if (Utility.GetRelationshipMetadataDefaultNull(metadata.EntityMetadata, relatedEntities.Key.SchemaName, Guid.Empty, userRef) == null) { throw new FaultException($"Relationship with schemaname '{relatedEntities.Key.SchemaName}' does not exist in metadata"); } foreach (var relatedEntity in relatedEntities.Value.Entities) { var req = new CreateRequest() { Target = relatedEntity }; core.Execute(req, userRef); } var associateReq = new AssociateRequest { Target = entity.ToEntityReference(), Relationship = relatedEntities.Key, RelatedEntities = new EntityReferenceCollection(relatedEntities.Value.Entities.Select(e => e.ToEntityReference()).ToList()) }; core.Execute(associateReq, userRef); } } resp.Results.Add("id", clonedEntity.Id); return(resp); }
/// <summary> /// Called to create the Association based on a request previously given by the Relying Party. /// </summary> /// <param name="request">The prior request for an association.</param> /// <returns> /// The created association. /// </returns> Association IAssociateSuccessfulResponseRelyingParty.CreateAssociationAtRelyingParty(AssociateRequest request) { Requires.NotNull(request, "request"); throw new NotImplementedException(); }
protected internal Guid CreateEntity(Entity e) { if (e == null) { throw new InvalidOperationException("The entity must not be null"); } var clone = e.Clone(e.GetType()); if (clone.Id == Guid.Empty) { clone.Id = Guid.NewGuid(); // Add default guid if none present } // Hack for Dynamic Entities where the Id property doesn't populate the "entitynameid" primary key var primaryKeyAttribute = $"{e.LogicalName}id"; if (!clone.Attributes.ContainsKey(primaryKeyAttribute)) { clone[primaryKeyAttribute] = clone.Id; } ValidateEntity(clone); // Create specific validations if (clone.Id != Guid.Empty && Data.ContainsKey(clone.LogicalName) && Data[clone.LogicalName].ContainsKey(clone.Id)) { throw new InvalidOperationException($"There is already a record of entity {clone.LogicalName} with id {clone.Id}, can't create with this Id."); } // Create specific validations if (clone.Attributes.ContainsKey("statecode")) { throw new InvalidOperationException($"When creating an entity with logical name '{clone.LogicalName}', or any other entity, it is not possible to create records with the statecode property. Statecode must be set after creation."); } AddEntityWithDefaults(clone, false, this.UsePipelineSimulation); if (e.RelatedEntities.Count > 0) { foreach (var relationshipSet in e.RelatedEntities) { var relationship = relationshipSet.Key; var entityReferenceCollection = new EntityReferenceCollection(); foreach (var relatedEntity in relationshipSet.Value.Entities) { var relatedId = CreateEntity(relatedEntity); entityReferenceCollection.Add(new EntityReference(relatedEntity.LogicalName, relatedId)); } if (FakeMessageExecutors.ContainsKey(typeof(AssociateRequest))) { var request = new AssociateRequest { Target = clone.ToEntityReference(), Relationship = relationship, RelatedEntities = entityReferenceCollection }; FakeMessageExecutors[typeof(AssociateRequest)].Execute(request, this); } else { throw PullRequestException.NotImplementedOrganizationRequest(typeof(AssociateRequest)); } } } return(clone.Id); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Retrieve the default business unit needed to create the team. QueryExpression queryDefaultBusinessUnit = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression() }; // Execute the request. queryDefaultBusinessUnit.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); BusinessUnit defaultBusinessUnit = (BusinessUnit)_serviceProxy.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Get the GUID of the current user. WhoAmIRequest who = new WhoAmIRequest(); WhoAmIResponse whoResp = (WhoAmIResponse)_serviceProxy.Execute(who); _userId = whoResp.UserId; // Instantiate a role entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Role setupRole = new Role { Name = "ABC Management Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; //Create a role record. _roleId = _serviceProxy.Create(setupRole); Console.WriteLine("Created Role."); // Assign User to Managers role. AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, _userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId), }, Relationship = new Relationship("systemuserroles_association") }; // Execute the request. _serviceProxy.Execute(associate); }
public static void Should_Only_Find_Correct_Faked_N_To_N_Records() { var fakedContext = new XrmFakedContext(); var fakedService = fakedContext.GetFakedOrganizationService(); var userId = new Guid("11111111-7982-4276-A8FE-7CE05FABEAB4"); var businessId = Guid.NewGuid(); var testUser = new SystemUser { Id = userId }; var testRole = new Role { Id = new Guid("22222222-7982-4276-A8FE-7CE05FABEAB4"), Name = "Test Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId) }; var testUser2 = new SystemUser { Id = Guid.NewGuid() }; var testRole2 = new Role { Id = Guid.NewGuid(), Name = "Test Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId) }; fakedContext.Initialize(new Entity[] { testUser, testRole, testUser2, testRole2 }); fakedContext.AddRelationship("systemuserroles_association", new XrmFakedRelationship { IntersectEntity = "systemuserroles", Entity1LogicalName = SystemUser.EntityLogicalName, Entity1Attribute = "systemuserid", Entity2LogicalName = Role.EntityLogicalName, Entity2Attribute = "roleid" }); var request = new AssociateRequest() { Target = testUser.ToEntityReference(), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, testRole.Id), }, Relationship = new Relationship("systemuserroles_association") }; fakedService.Execute(request); var request2 = new AssociateRequest() { Target = testUser2.ToEntityReference(), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, testRole2.Id), }, Relationship = new Relationship("systemuserroles_association") }; fakedService.Execute(request2); var query = new QueryExpression() { EntityName = "role", ColumnSet = new ColumnSet("name"), LinkEntities = { new LinkEntity { LinkFromEntityName = Role.EntityLogicalName, LinkFromAttributeName = "roleid", LinkToEntityName = SystemUserRoles.EntityLogicalName, LinkToAttributeName = "roleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression { AttributeName = "systemuserid", Operator = ConditionOperator.Equal, Values = { userId } } } } } } }; var result = fakedService.RetrieveMultiple(query); Assert.NotEmpty(result.Entities); Assert.Equal(1, result.Entities.Count); }
public void Reproduce_issue_125() { Account account = new Account(); account.Id = Guid.NewGuid(); account.Name = "Goggle ltd"; Contact contact = new Contact(); contact.Id = Guid.NewGuid(); contact.FirstName = "Test"; contact.LastName = "Contact 1"; contact.ParentCustomerId = account.ToEntityReference(); PhoneCall phonecall = new PhoneCall(); phonecall.Id = Guid.NewGuid(); phonecall["statecode"] = PhoneCallState.Open; //phonecall.To = new List<ActivityParty>() { contact.ToEntityReference() }; phonecall.StatusCode = new OptionSetValue(1); phonecall.Subject = "Test phone call"; gbp_globecountry Country = new gbp_globecountry() { Id = Guid.NewGuid(), gbp_name = "United Kingdom", gbp_code = "GB" }; gbp_customaddress customerA = new gbp_customaddress() { Id = Guid.NewGuid(), gbp_addresstype = new OptionSetValue(3), gbp_country = new EntityReference(gbp_globecountry.EntityLogicalName, Country.Id), }; var context = new XrmFakedContext(); context.AddRelationship("gbp_gbp_customaddress_contact_assosciation", new XrmFakedRelationship() { IntersectEntity = "gbp_gbp_customaddress_contact", Entity1LogicalName = gbp_customaddress.EntityLogicalName, Entity1Attribute = "gbp_customaddressid", Entity2LogicalName = Contact.EntityLogicalName, Entity2Attribute = "contactid" }); context.Initialize(new List <Entity>() { contact, customerA }); var fakedService = context.GetOrganizationService(); var request = new AssociateRequest() { Target = customerA.ToEntityReference(), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Contact.EntityLogicalName, contact.Id), }, Relationship = new Relationship("gbp_gbp_customaddress_contact_assosciation") }; fakedService.Execute(request); string fetchQuery = string.Format(@"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0' > <entity name='gbp_customaddress' > <attribute name='gbp_country' /> <link-entity name='gbp_gbp_customaddress_contact' from='gbp_customaddressid' to='gbp_customaddressid' alias='NtoN' intersect='true' > <link-entity name='contact' from='contactid' to='contactid' alias='Contact' > <filter> <condition attribute='contactid' operator='eq' value='{0}' /> </filter> </link-entity> </link-entity> </entity> </fetch> ", contact.Id); EntityCollection result = fakedService.RetrieveMultiple(new FetchExpression(fetchQuery)); Assert.Equal(1, result.Entities.Count); }
/// <summary> /// Retrieves the requested SystemUser record. If the record does not exist, a new /// Microsoft Dynamics CRM SystemUser record is created and an associated Active /// Directory account is created, if it doesn't currently exist. /// </summary> /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param> /// <param name="firstName">The first name of the system user to be retrieved</param> /// <param name="lastName">The last name of the system user to be retrieved</param> /// <param name="roleStr">The string representing the Microsoft Dynamics CRM security /// role for the user</param> /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft /// Dynamics CRM environment</param> /// <param name="ldapPath">The LDAP path for your network - you can either call /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param> /// <returns></returns> public static Guid RetrieveSystemUser(String userName, String firstName, String lastName, String roleStr, OrganizationServiceProxy serviceProxy, ref String ldapPath) { String domain; Guid userId = Guid.Empty; if (serviceProxy == null) throw new ArgumentNullException("serviceProxy"); if (String.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException("UserName"); if (String.IsNullOrWhiteSpace(firstName)) throw new ArgumentNullException("FirstName"); if (String.IsNullOrWhiteSpace(lastName)) throw new ArgumentNullException("LastName"); // Obtain the current user's information. WhoAmIRequest who = new WhoAmIRequest(); WhoAmIResponse whoResp = (WhoAmIResponse)serviceProxy.Execute(who); Guid currentUserId = whoResp.UserId; SystemUser currentUser = serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new ColumnSet("domainname")).ToEntity<SystemUser>(); // Extract the domain and create the LDAP object. String[] userPath = currentUser.DomainName.Split(new char[] { '\\' }); if (userPath.Length > 1) domain = userPath[0] + "\\"; else domain = String.Empty; SystemUser existingUser = GetUserIdIfExist(serviceProxy, domain, userName, firstName, lastName); if (existingUser != null) { userId = existingUser.SystemUserId.Value; if (!String.IsNullOrWhiteSpace(roleStr)) { // Check to make sure the user is assigned the correct role. Role role = RetrieveRoleByName(serviceProxy, roleStr); // Associate the user with the role when needed. if (!UserInRole(serviceProxy, userId, role.Id)) { AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, role.Id) }, Relationship = new Relationship("systemuserroles_association") }; serviceProxy.Execute(associate); } } } else { // Create the system user in Microsoft Dynamics CRM if the user doesn't // already exist. userId = CreateSystemUser(userName, firstName, lastName, domain, roleStr, serviceProxy, ref ldapPath); } return userId; }
/// <summary> /// Creates a new association with a given Provider. /// </summary> /// <param name="provider">The provider to create an association with.</param> /// <param name="associateRequest">The associate request. May be <c>null</c>, which will always result in a <c>null</c> return value..</param> /// <param name="retriesRemaining">The number of times to try the associate request again if the Provider suggests it.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The newly created association, or null if no association can be created with /// the given Provider given the current security settings. /// </returns> /// <exception cref="ProtocolException">Create if an error occurs while creating the new association.</exception> private async Task <Association> CreateNewAssociationAsync(IProviderEndpoint provider, AssociateRequest associateRequest, int retriesRemaining, CancellationToken cancellationToken) { Requires.NotNull(provider, "provider"); if (associateRequest == null || retriesRemaining < 0) { // this can happen if security requirements and protocol conflict // to where there are no association types to choose from. return(null); } Exception exception = null; try { var associateResponse = await this.channel.RequestAsync(associateRequest, cancellationToken); var associateSuccessfulResponse = associateResponse as IAssociateSuccessfulResponseRelyingParty; var associateUnsuccessfulResponse = associateResponse as AssociateUnsuccessfulResponse; if (associateSuccessfulResponse != null) { Association association = associateSuccessfulResponse.CreateAssociationAtRelyingParty(associateRequest); this.associationStore.StoreAssociation(provider.Uri, association); return(association); } else if (associateUnsuccessfulResponse != null) { if (string.IsNullOrEmpty(associateUnsuccessfulResponse.AssociationType)) { Logger.OpenId.Debug("Provider rejected an association request and gave no suggestion as to an alternative association type. Giving up."); return(null); } if (!this.securitySettings.IsAssociationInPermittedRange(Protocol.Lookup(provider.Version), associateUnsuccessfulResponse.AssociationType)) { Logger.OpenId.DebugFormat("Provider rejected an association request and suggested '{0}' as an association to try, which this Relying Party does not support. Giving up.", associateUnsuccessfulResponse.AssociationType); return(null); } if (retriesRemaining <= 0) { Logger.OpenId.Debug("Unable to agree on an association type with the Provider in the allowed number of retries. Giving up."); return(null); } // Make sure the Provider isn't suggesting an incompatible pair of association/session types. Protocol protocol = Protocol.Lookup(provider.Version); ErrorUtilities.VerifyProtocol( HmacShaAssociation.IsDHSessionCompatible(protocol, associateUnsuccessfulResponse.AssociationType, associateUnsuccessfulResponse.SessionType), OpenIdStrings.IncompatibleAssociationAndSessionTypes, associateUnsuccessfulResponse.AssociationType, associateUnsuccessfulResponse.SessionType); associateRequest = AssociateRequestRelyingParty.Create(this.securitySettings, provider, associateUnsuccessfulResponse.AssociationType, associateUnsuccessfulResponse.SessionType); return(await this.CreateNewAssociationAsync(provider, associateRequest, retriesRemaining - 1, cancellationToken)); } else { throw new ProtocolException(MessagingStrings.UnexpectedMessageReceivedOfMany); } } catch (ProtocolException ex) { exception = ex; } Assumes.NotNull(exception); // If the association failed because the remote server can't handle Expect: 100 Continue headers, // then our web request handler should have already accomodated for future calls. Go ahead and // immediately make one of those future calls now to try to get the association to succeed. if (UntrustedWebRequestHandler.IsExceptionFrom417ExpectationFailed(exception)) { return(await this.CreateNewAssociationAsync(provider, associateRequest, retriesRemaining - 1, cancellationToken)); } // Since having associations with OPs is not totally critical, we'll log and eat // the exception so that auth may continue in dumb mode. Logger.OpenId.ErrorFormat("An error occurred while trying to create an association with {0}. {1}", provider.Uri, exception); return(null); }
public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { if (relatedEntities.Count > 0) { var request = new AssociateRequest { Target = CreateLookup(entityName, entityId), Relationship = relationship, RelatedEntities = relatedEntities }; Execute(request); } }
protected override void Execute(CodeActivityContext executionContext) { //Build the connection IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); string contactId = this.inputContact.Get(executionContext).Id.ToString(); // Guid of primary entity to be used in fetch string accountId = this.inputAccount.Get(executionContext).Id.ToString(); // Guid of secondary entity to be used in fetch { //The fetch to be used if disassociating string fetchxml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'> <entity name='contact'> <attribute name='contactid' /> <order attribute='contactid' descending='false' /> <filter type='and'> <condition attribute='contactid' operator='eq' uitype='contact' value='{" + contactId + @"}' /> </filter> <link-entity name='gg_contact_account_entitypermission' from='contactid' to='contactid' visible='false' intersect='true'> <link-entity name='account' from='accountid' to='accountid' alias='ac'> <filter type='and'> <condition attribute='accountid' operator='eq' uitype='account' value='{" + accountId + @"}' /> </filter> </link-entity> </link-entity> </entity> </fetch>"; bool TrueFalse = this.Bool.Get(executionContext); //result of the yes no input determing whether to associate or disaasociate EntityCollection collRecords = service.RetrieveMultiple(new FetchExpression(fetchxml)); if (TrueFalse) //Logic for disassociate { if (collRecords != null && collRecords.Entities != null && collRecords.Entities.Count > 0) { EntityReferenceCollection collection = new EntityReferenceCollection(); foreach (var entity in collRecords.Entities) { var reference = new EntityReference("list", entity.Id); collection.Add(reference); //Create a collection of entity references } Relationship relationship = new Relationship("gg_contact_account_entitypermission"); //schema name of N:N relationship service.Disassociate("account", this.inputAccount.Get(executionContext).Id, relationship, collection); //Pass the entity reference collections to be disassociated from the specific Email Send record } } else //Logic for associate { if (collRecords.Entities.Count == 0) { AssociateRequest request = new AssociateRequest { Target = new EntityReference("account", this.inputAccount.Get(executionContext).Id), RelatedEntities = new EntityReferenceCollection { new EntityReference("list", this.inputContact.Get(executionContext).Id) }, Relationship = new Relationship("gg_contact_account_entitypermission") }; service.Execute(request); } } } }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code //////////////////////////////////////// #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = service.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; service.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; service.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_message", DisplayName = new Label("Message", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Message", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; service.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)service.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)service.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_picture", DisplayName = new Label("Picture", 1033), SchemaName = "New_Picture", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)service.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = service.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List <Guid> profileIds = new List <Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)service.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection <Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = service.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// Retrieves the requested SystemUser record. If the record does not exist, a new /// Microsoft Dynamics CRM SystemUser record is created and an associated Active /// Directory account is created, if it doesn't currently exist. /// </summary> /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param> /// <param name="firstName">The first name of the system user to be retrieved</param> /// <param name="lastName">The last name of the system user to be retrieved</param> /// <param name="roleStr">The string representing the Microsoft Dynamics CRM security /// role for the user</param> /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft /// Dynamics CRM environment</param> /// <param name="ldapPath">The LDAP path for your network - you can either call /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param> /// <returns></returns> public static Guid RetrieveSystemUser(String userName, String firstName, String lastName, String roleStr, CrmServiceClient service, ref String ldapPath) { String domain; Guid userId = Guid.Empty; if (service == null) { throw new ArgumentNullException("service"); } if (String.IsNullOrWhiteSpace(userName)) { throw new ArgumentNullException("UserName"); } if (String.IsNullOrWhiteSpace(firstName)) { throw new ArgumentNullException("FirstName"); } if (String.IsNullOrWhiteSpace(lastName)) { throw new ArgumentNullException("LastName"); } // Obtain the current user's information. WhoAmIRequest who = new WhoAmIRequest(); WhoAmIResponse whoResp = (WhoAmIResponse)service.Execute(who); Guid currentUserId = whoResp.UserId; SystemUser currentUser = service.Retrieve(SystemUser.EntityLogicalName, currentUserId, new ColumnSet("domainname")).ToEntity <SystemUser>(); // Extract the domain and create the LDAP object. String[] userPath = currentUser.DomainName.Split(new char[] { '\\' }); if (userPath.Length > 1) { domain = userPath[0] + "\\"; } else { domain = String.Empty; } SystemUser existingUser = GetUserIdIfExist(service, domain, userName, firstName, lastName); if (existingUser != null) { userId = existingUser.SystemUserId.Value; if (!String.IsNullOrWhiteSpace(roleStr)) { // Check to make sure the user is assigned the correct role. Role role = RetrieveRoleByName(service, roleStr); // Associate the user with the role when needed. if (!UserInRole(service, userId, role.Id)) { AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, role.Id) }, Relationship = new Relationship("systemuserroles_association") }; service.Execute(associate); } } } else { Console.WriteLine("User Not Found. Manually create user in office 365"); } return(userId); }
/// <summary> /// Create a CRM <c>AssociationRequest and executes it.</c> /// </summary> /// <param name="relationshipName">The name of the relationship to be created.</param> /// <param name="entity1Name">The name of the first entity to create the relationship from.</param> /// <param name="entity1Guid">The unique identifier for the first entity instance.</param> /// <param name="entity2Name">The name of the related entity.</param> /// <param name="entity2Guid">The unique identifier of the related entity instance.</param> private void CreateAssociatedRequest(string relationshipName, string entity1Name, string entity1Guid, string entity2Name, string entity2Guid) { AssociateRequest areq = new AssociateRequest(); // Target is the entity that you are associating your entities to. areq.Target = new EntityReference(entity1Name, new Guid(entity1Guid)); // RelatedEntities are the entities you are associating to your target (can be more than 1) areq.RelatedEntities = new EntityReferenceCollection(); areq.RelatedEntities.Add(new EntityReference(entity2Name, new Guid(entity2Guid))); // The relationship schema name in CRM you are using to associate the entities. // Found in settings - customization - entity - relationships areq.Relationship = new Relationship(relationshipName); // Execute the request this.CrmAdapter.OrganizationService.Execute(areq); }
public void Import() { using (var reader = new StreamReader(filePath, Encoding.Default)) { string line; int lineNumber = 0; while ((line = reader.ReadLine()) != null) { lineNumber++; try { var data = line.Split(','); Guid firstGuid = Guid.Empty; Guid secondGuid = Guid.Empty; if (settings.FirstAttributeIsGuid) { firstGuid = new Guid(data[0]); } else { var records = service.RetrieveMultiple(new QueryExpression(settings.FirstEntity) { Criteria = { Conditions = { new ConditionExpression(settings.FirstAttributeName, ConditionOperator.Equal, data[0]) } } }); if (records.Entities.Count == 1) { firstGuid = records.Entities.First().Id; } else if (records.Entities.Count > 1) { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("More than one record ({0}) were found with the value specified", settings.FirstEntity) }); continue; } else { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("No record ({0}) was found with the value specified", settings.FirstEntity) }); continue; } } if (settings.SecondAttributeIsGuid) { secondGuid = new Guid(data[1]); } else { var records = service.RetrieveMultiple(new QueryExpression(settings.SecondEntity) { Criteria = { Conditions = { new ConditionExpression(settings.SecondAttributeName, ConditionOperator.Equal, data[1]) } } }); if (records.Entities.Count == 1) { secondGuid = records.Entities.First().Id; } else if (records.Entities.Count > 1) { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("More than one record ({0}) were found with the value specified", settings.SecondEntity) }); continue; } else { RaiseError(this, new ResultEventArgs { LineNumber = lineNumber, Message = string.Format("No record ({0}) was found with the value specified", settings.SecondEntity) }); continue; } } var request = new AssociateRequest { Target = new EntityReference(settings.FirstEntity, firstGuid), Relationship = new Relationship(settings.Relationship), RelatedEntities = new EntityReferenceCollection { new EntityReference(settings.SecondEntity, secondGuid) } }; if (request.Target.LogicalName == request.RelatedEntities.First().LogicalName) { request.Relationship.PrimaryEntityRole = EntityRole.Referenced; } service.Execute(request); OnRaiseSuccess(new ResultEventArgs { LineNumber = lineNumber }); } catch (FaultException <OrganizationServiceFault> error) { if (error.Detail.ErrorCode.ToString("X") == "80040237") { OnRaiseError(new ResultEventArgs { LineNumber = lineNumber, Message = "Relationship was not created because it already exists" }); } else { OnRaiseError(new ResultEventArgs { LineNumber = lineNumber, Message = error.Message }); } } } } }