/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create custom fields in account entity // Create secure custom field #1 CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "secret_home", DisplayName = new Label("SecretHome", 1033), SchemaName = "Secret_Home", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = Account.EntityLogicalName }; CreateAttributeResponse attributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _secretHomeId = attributeResponse.AttributeId; Console.WriteLine("Secret_Home custom field created."); // Create secure custom field #2 attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "secret_phone", DisplayName = new Label("SecretPhone", 1033), SchemaName = "Secret_Phone", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = Account.EntityLogicalName }; attributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _secretPhoneId = attributeResponse.AttributeId; Console.WriteLine("Secret_Phone custom field created."); #endregion Create custom fields in account entity Console.WriteLine(); }
private bool CreateAttributes(IOrganizationService service, XRMSpeedyEntity entity, int languageCode) { try { foreach (XRMSpeedyField field in entity.Fields.Where(f => f.Import == true)) { CreateAttributeRequest request = new CreateAttributeRequest { EntityName = entity.EntityMetadata.SchemaName, Attribute = field.AttributeMetadata }; CreateAttributeResponse response = (CreateAttributeResponse)service.Execute(request); } return(true); } catch (FaultException <OrganizationServiceFault> ) { throw; } }
[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 // The custom prefix would typically be passed in as an argument or // determined by the publisher of the custom solution. String prefix = "new_"; String customEntityName = prefix + "sampleentity"; // Create the custom activity entity. CreateEntityRequest request = new CreateEntityRequest { HasNotes = true, HasActivities = false, PrimaryAttribute = new StringAttributeMetadata { SchemaName = "Subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Microsoft.Xrm.Sdk.Label("Subject", 1033) }, Entity = new EntityMetadata { IsActivity = true, SchemaName = customEntityName, DisplayName = new Microsoft.Xrm.Sdk.Label("Sample Entity", 1033), DisplayCollectionName = new Microsoft.Xrm.Sdk.Label("Sample Entity", 1033), OwnershipType = OwnershipTypes.UserOwned, IsAvailableOffline = true, } }; service.Execute(request); //Entity must be published // Add few attributes to the custom activity entity. CreateAttributeRequest fontFamilyAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontfamily", DisplayName = new Microsoft.Xrm.Sdk.Label("Font Family", 1033), MaxLength = 100 } }; CreateAttributeResponse fontFamilyAttributeResponse = (CreateAttributeResponse)service.Execute( fontFamilyAttributeRequest); CreateAttributeRequest fontColorAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontcolor", DisplayName = new Microsoft.Xrm.Sdk.Label("Font Color", 1033), MaxLength = 50 } }; CreateAttributeResponse fontColorAttributeResponse = (CreateAttributeResponse)service.Execute( fontColorAttributeRequest); CreateAttributeRequest fontSizeAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new IntegerAttributeMetadata { SchemaName = prefix + "fontSize", DisplayName = new Microsoft.Xrm.Sdk.Label("Font Size", 1033) } }; CreateAttributeResponse fontSizeAttributeResponse = (CreateAttributeResponse)service.Execute( fontSizeAttributeRequest); Console.WriteLine("The custom activity has been created."); #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> /// Create the custom entity. /// Optionally delete the custom 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 { // 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(); //<snippetCreateCustomActivityEntity1> // The custom prefix would typically be passed in as an argument or // determined by the publisher of the custom solution. //<snippetCreateCustomActivityEntity2> String prefix = "new_"; String customEntityName = prefix + "instantmessage"; // Create the custom activity entity. CreateEntityRequest request = new CreateEntityRequest { HasNotes = true, HasActivities = false, PrimaryAttribute = new StringAttributeMetadata { SchemaName = "Subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) }, Entity = new EntityMetadata { IsActivity = true, SchemaName = customEntityName, DisplayName = new Label("Instant Message", 1033), DisplayCollectionName = new Label("Instant Messages", 1033), OwnershipType = OwnershipTypes.UserOwned, IsAvailableOffline = true, } }; _serviceProxy.Execute(request); //Entity must be published //</snippetCreateCustomActivityEntity2> // Add few attributes to the custom activity entity. CreateAttributeRequest fontFamilyAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontfamily", DisplayName = new Label("Font Family", 1033), MaxLength = 100 } }; CreateAttributeResponse fontFamilyAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontFamilyAttributeRequest); CreateAttributeRequest fontColorAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontcolor", DisplayName = new Label("Font Color", 1033), MaxLength = 50 } }; CreateAttributeResponse fontColorAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontColorAttributeRequest); CreateAttributeRequest fontSizeAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new IntegerAttributeMetadata { SchemaName = prefix + "fontSize", DisplayName = new Label("Font Size", 1033) } }; CreateAttributeResponse fontSizeAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontSizeAttributeRequest); //</snippetCreateCustomActivityEntity1> Console.WriteLine("The custom activity has been created."); DeleteCustomEntity(prefix, promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// 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; } }
[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 a custom string attribute for the appointment instance StringAttributeMetadata customAppointmentInstanceAttribute = new StringAttributeMetadata { LogicalName = "new_customAppInstanceAttribute", DisplayName = new Microsoft.Xrm.Sdk.Label("CustomAppInstanceAttribute", 1033), Description = new Microsoft.Xrm.Sdk.Label("Sample Custom Appointment Instance Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppInstanceAttribute" }; CreateAttributeRequest instanceAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentInstanceAttribute, EntityName = "appointment" }; CreateAttributeResponse instanceAttributeResponse = (CreateAttributeResponse)service.Execute(instanceAttributeRequest); _instanceAttributeID = instanceAttributeResponse.AttributeId; // Create a custom string attribute for the recurring appointment master (series) StringAttributeMetadata customAppointmentSeriesAttribute = new StringAttributeMetadata { LogicalName = "new_customAppSeriesAttribute", DisplayName = new Microsoft.Xrm.Sdk.Label("CustomAppSeriesAttribute", 1033), Description = new Microsoft.Xrm.Sdk.Label("Sample Custom Appointment Series Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppSeriesAttribute", LinkedAttributeId = _instanceAttributeID // Link the custom attribute to the appointment’s custom attribute. }; CreateAttributeRequest seriesAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentSeriesAttribute, EntityName = "recurringappointmentmaster" }; CreateAttributeResponse seriesAttributeResponse = (CreateAttributeResponse)service.Execute(seriesAttributeRequest); _seriesAttributeID = seriesAttributeResponse.AttributeId; // Publish all the changes to the solution. PublishAllXmlRequest createRequest = new PublishAllXmlRequest(); service.Execute(createRequest); Console.WriteLine("Created a custom string attribute, {0}, for the appointment.", customAppointmentInstanceAttribute.LogicalName); Console.WriteLine("Created a custom string attribute, {0}, for the recurring appointment, and linked it with {1}.", customAppointmentSeriesAttribute.LogicalName, customAppointmentInstanceAttribute.LogicalName); #region Clean up CleanUpSample(service); #endregion Clean up } #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; } } } #endregion Sample Code catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <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 { // 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, "); // 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); // 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); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Link the custom attributes. /// 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(); //<snippetLinkCustomAttributesBetweenSeriesandInstances1> // Create a custom string attribute for the appointment instance StringAttributeMetadata customAppointmentInstanceAttribute = new StringAttributeMetadata { LogicalName = "new_customAppInstanceAttribute", DisplayName = new Label("CustomAppInstanceAttribute", 1033), Description = new Label("Sample Custom Appointment Instance Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppInstanceAttribute" }; CreateAttributeRequest instanceAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentInstanceAttribute, EntityName = "appointment" }; CreateAttributeResponse instanceAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(instanceAttributeRequest); _instanceAttributeID = instanceAttributeResponse.AttributeId; // Create a custom string attribute for the recurring appointment master (series) StringAttributeMetadata customAppointmentSeriesAttribute = new StringAttributeMetadata { LogicalName = "new_customAppSeriesAttribute", DisplayName = new Label("CustomAppSeriesAttribute", 1033), Description = new Label("Sample Custom Appointment Series Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppSeriesAttribute", LinkedAttributeId = _instanceAttributeID // Link the custom attribute to the appointment’s custom attribute. }; CreateAttributeRequest seriesAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentSeriesAttribute, EntityName = "recurringappointmentmaster" }; CreateAttributeResponse seriesAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(seriesAttributeRequest); _seriesAttributeID = seriesAttributeResponse.AttributeId; // Publish all the changes to the solution. PublishAllXmlRequest createRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(createRequest); Console.WriteLine("Created a custom string attribute, {0}, for the appointment.", customAppointmentInstanceAttribute.LogicalName); Console.WriteLine("Created a custom string attribute, {0}, for the recurring appointment, and linked it with {1}.", customAppointmentSeriesAttribute.LogicalName, customAppointmentInstanceAttribute.LogicalName); //</snippetLinkCustomAttributesBetweenSeriesandInstances1> 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; } }
[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 Microsoft Dataverse"; 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> /// Create a custom activity /// </summary> /// <returns></returns> public static void CreateCustomActivity() { Console.WriteLine("###### Creating Custom Activity"); // Create the custom activity entity. CreateEntityRequest request = new CreateEntityRequest { HasNotes = true, HasActivities = false, PrimaryAttribute = new StringAttributeMetadata { SchemaName = "Subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) }, Entity = new EntityMetadata { IsActivity = true, SchemaName = _customActivityName, DisplayName = new Label("Custom Activity", 1033), DisplayCollectionName = new Label("Custom Activities", 1033), OwnershipType = OwnershipTypes.UserOwned, IsAvailableOffline = true, } }; service.Execute(request); // Customizations must be published after an entity is updated. PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); service.Execute(publishRequest); // Add few attributes to the custom activity entity. //Add string type attribute CreateAttributeRequest stringAttributeRequest = new CreateAttributeRequest { EntityName = _customActivityName, Attribute = new StringAttributeMetadata { SchemaName = "new_teststring", DisplayName = new Label("Test String", 1033), MaxLength = 50 } }; CreateAttributeResponse fontColorAttributeResponse = (CreateAttributeResponse)service.Execute( stringAttributeRequest); CreateAttributeRequest integerAttributeRequest = new CreateAttributeRequest { EntityName = _customActivityName, Attribute = new IntegerAttributeMetadata { SchemaName = "new_testinteger", DisplayName = new Label("Test Integer", 1033) } }; CreateAttributeResponse fontSizeAttributeResponse = (CreateAttributeResponse)service.Execute( integerAttributeRequest); // Customizations must be published after an entity is updated. publishRequest = new PublishAllXmlRequest(); service.Execute(publishRequest); Console.WriteLine("Created Custom Activity"); }