/// <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>
  /// Create a custom entity.
  /// Update 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();


     // Create the custom entity.
     //<snippetCreateUpdateEntityMetadata1>
     CreateEntityRequest createrequest = new CreateEntityRequest
     {

      //Define the entity
      Entity = new EntityMetadata
      {
       SchemaName = _customEntityName,
       DisplayName = new Label("Bank Account", 1033),
       DisplayCollectionName = new Label("Bank Accounts", 1033),
       Description = new Label("An entity to store information about customer bank accounts", 1033),
       OwnershipType = OwnershipTypes.UserOwned,
       IsActivity = false,

      },

      // Define the primary attribute for the entity
      PrimaryAttribute = new StringAttributeMetadata
      {
       SchemaName = "new_accountname",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       MaxLength = 100,
       FormatName = StringFormatName.Text,
       DisplayName = new Label("Account Name", 1033),
       Description = new Label("The primary attribute for the Bank Account entity.", 1033)
      }

     };
     _serviceProxy.Execute(createrequest);
     Console.WriteLine("The bank account entity has been created.");
     //</snippetCreateUpdateEntityMetadata1>


     // Add some attributes to the Bank Account entity
     //<snippetCreateUpdateEntityMetadata2>
     CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new StringAttributeMetadata
      {
       SchemaName = "new_bankname",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       MaxLength = 100,
       FormatName = StringFormatName.Text,
       DisplayName = new Label("Bank Name", 1033),
       Description = new Label("The name of the bank.", 1033)
      }
     };

     _serviceProxy.Execute(createBankNameAttributeRequest);
     //</snippetCreateUpdateEntityMetadata2>
     Console.WriteLine("An bank name attribute has been added to the bank account entity.");

     //<snippetCreateUpdateEntityMetadata3>
     CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new MoneyAttributeMetadata
      {
       SchemaName = "new_balance",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       PrecisionSource = 2,
       DisplayName = new Label("Balance", 1033),
       Description = new Label("Account Balance at the last known date", 1033),

      }
     };

     _serviceProxy.Execute(createBalanceAttributeRequest);
     //</snippetCreateUpdateEntityMetadata3>
     Console.WriteLine("An account balance attribute has been added to the bank account entity.");

     //<snippetCreateUpdateEntityMetadata4>
     CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new DateTimeAttributeMetadata
      {
       SchemaName = "new_checkeddate",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       Format = DateTimeFormat.DateOnly,
       DisplayName = new Label("Date", 1033),
       Description = new Label("The date the account balance was last confirmed", 1033)

      }
     };

     _serviceProxy.Execute(createCheckedDateRequest);
     Console.WriteLine("An date attribute has been added to the bank account entity.");
     //</snippetCreateUpdateEntityMetadata4>
     //Create a lookup attribute to link the bank account with a contact record.

     //<snippetCreateUpdateEntityMetadata5>
     CreateOneToManyRequest req = new CreateOneToManyRequest()
     {
      Lookup = new LookupAttributeMetadata()
      {
       Description = new Label("The owner of the bank account", 1033),
       DisplayName = new Label("Account Owner", 1033),
       LogicalName = "new_parent_contactid",
       SchemaName = "New_Parent_ContactId",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired)
      },
      OneToManyRelationship = new OneToManyRelationshipMetadata()
      {
       AssociatedMenuConfiguration = new AssociatedMenuConfiguration()
       {
        Behavior = AssociatedMenuBehavior.UseCollectionName,
        Group = AssociatedMenuGroup.Details,
        Label = new Label("Bank Accounts", 1033),
        Order = 10000
       },
       CascadeConfiguration = new CascadeConfiguration()
       {
        Assign = CascadeType.Cascade,
        Delete = CascadeType.Cascade,
        Merge = CascadeType.Cascade,
        Reparent = CascadeType.Cascade,
        Share = CascadeType.Cascade,
        Unshare = CascadeType.Cascade
       },
       ReferencedEntity = Contact.EntityLogicalName,
       ReferencedAttribute = "contactid",
       ReferencingEntity = _customEntityName,
       SchemaName = "new_contact_new_bankaccount"
      }
     };
     _serviceProxy.Execute(req);
     //</snippetCreateUpdateEntityMetadata5>
     Console.WriteLine("A lookup attribute has been added to the bank account entity to link it with the Contact entity.");

     //<snippetCreateUpdateEntityMetadata11>
     //Create an Image attribute for the custom entity
     // Only one Image attribute can be added to an entity that doesn't already have one.
     CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new ImageAttributeMetadata
      {
       SchemaName = "EntityImage", //The name is always EntityImage
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       DisplayName = new Label("Image", 1033),
       Description = new Label("An image to represent the bank account.", 1033)

      }
     };

     _serviceProxy.Execute(createEntityImageRequest);
     Console.WriteLine("An image attribute has been added to the bank account entity.");
     //</snippetCreateUpdateEntityMetadata11>

     //<snippetCreateUpdateEntityMetadata9>

     //<snippetCreateUpdateEntityMetadata.RetrieveEntity>
     RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest
     {
      EntityFilters = EntityFilters.Entity,
      LogicalName = _customEntityName
     };
     RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest);
     //</snippetCreateUpdateEntityMetadata.RetrieveEntity>
     //<snippetCreateUpdateEntityMetadata8>
     EntityMetadata BankAccountEntity = retrieveBankAccountEntityResponse.EntityMetadata;

     // Disable Mail merge
     BankAccountEntity.IsMailMergeEnabled = new BooleanManagedProperty(false);
     // Enable Notes
     UpdateEntityRequest updateBankAccountRequest = new UpdateEntityRequest
     {
      Entity = BankAccountEntity,
      HasNotes = true
     };



     _serviceProxy.Execute(updateBankAccountRequest);
     //</snippetCreateUpdateEntityMetadata8>
     //</snippetCreateUpdateEntityMetadata9>

     Console.WriteLine("The bank account entity has been updated");


     //Update the entity form so the new fields are visible
     UpdateEntityForm(_customEntityName);

     // Customizations must be published after an entity is updated.
     //<snippetCreateUpdateEntityMetadata6>
     PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
     _serviceProxy.Execute(publishRequest);
     //</snippetCreateUpdateEntityMetadata6>
     Console.WriteLine("Customizations were published.");

     //Provides option to view the entity in the default solution
     ShowEntityInBrowser(promptForDelete, BankAccountEntity);
     //Provides option to view the entity form with the fields added
     ShowEntityFormInBrowser(promptForDelete, BankAccountEntity);

     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 async Task <TEntity> Handle(CreateEntityRequest <TEntity> request, CancellationToken cancellationToken)
        {
            var resultToReturn = (await innerDataContext.Set <TEntity>().AddAsync(request.Entity)).Entity;
            await innerDataContext.SaveChangesAsync(cancellationToken);

            return(resultToReturn);
        }
Пример #4
0
        public void AddNewEntity()
        {
            using (var svc = new CrmServiceClient(connection))
            {
                CreateEntityRequest createrequest = new CreateEntityRequest
                {
                    Entity = new EntityMetadata
                    {
                        SchemaName            = "test_entity",
                        DisplayName           = new Label("Test entity", 1033),
                        DisplayCollectionName = new Label("Test Entities", 1033),
                        Description           = new Label("An entity to store test information", 1033),
                        OwnershipType         = OwnershipTypes.UserOwned,
                        IsActivity            = false
                    },
                    PrimaryAttribute = new StringAttributeMetadata
                    {
                        SchemaName    = "name",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        MaxLength     = 100,
                        FormatName    = StringFormatName.Text,
                        DisplayName   = new Label("Test", 1033),
                        Description   = new Label("The primary attribute for the Test entity.", 1033)
                    },
                    SolutionUniqueName = "samplesolution"
                };

                svc.Execute(createrequest);
                Console.WriteLine("The entity has been created.");
            }
        }
Пример #5
0
        static void CriarEntidade(OrganizationServiceProxy serviceProxy)
        {
            CreateEntityRequest createRequest = new CreateEntityRequest
            {
                Entity = new EntityMetadata
                {
                    SchemaName            = "new_bankaccount",
                    DisplayName           = new Label("Bank Account", 1033),
                    DisplayCollectionName = new Label("Bank Accounts", 1033),
                    Description           = new Label("An Entity to store information about customer bank accounts", 1033),
                    OwnershipType         = OwnershipTypes.UserOwned,
                    IsActivity            = false
                },
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = "new_accountname",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    FormatName    = StringFormatName.Text,
                    DisplayName   = new Label("Account Name", 1033),
                    Description   = new Label("The primary attribute for the ank Account entity", 1033),
                }
            };

            try
            {
                serviceProxy.Execute(createRequest);
                Console.WriteLine("Entidade criada com sucesso!!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao criar Entidade:" + ex.Message.ToString());
                throw;
            }
        }
        public void Create(EntityMetadata entity, string primaryFieldName)
        {
            if (entity.SchemaName == null)
            {
                return;
            }

            var em = this._cdsConnection.GetEntityMetadata(entity.SchemaName);

            if (em == null)
            {
                var createRequest = new CreateEntityRequest();
                createRequest.Entity = entity;

                StringAttributeMetadata atr = new StringAttributeMetadata();
                atr.SchemaName    = primaryFieldName;
                atr.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                atr.MaxLength     = 100;
                atr.FormatName    = StringFormatName.Text;
                atr.DisplayName   = new Label("Name", 1033);
                createRequest.PrimaryAttribute = atr;

                Console.WriteLine("Creating entity...");
                this._cdsConnection.Execute(createRequest);
                Console.WriteLine("Entity created.");
            }
        }
Пример #7
0
 /// <summary>
 /// 创建Entity
 /// </summary>
 /// <param name="entityName">Entity的逻辑名称</param>
 /// <param name="entityDisplayName">Entity的显示名称</param>
 /// <param name="entityPluralName">Entity的复数显示名称</param>
 /// <param name="primaryAttrName">Primary Field的逻辑名称</param>
 /// <param name="primaryAttrDisplayName">Primary Field的显示名称</param>
 public OrganizationResponse CreateEntity(
     string entityName,
     string entityDisplayName,
     string entityPluralName,
     string primaryAttrName,
     string primaryAttrDisplayName)
 {
     if (CheckCreateEntity(entityName, primaryAttrName))
     {
         var request = new CreateEntityRequest()
         {
             // 定义EntityMetadata
             Entity = new EntityMetadata()
             {
                 SchemaName            = entityName,
                 DisplayName           = new Label(entityDisplayName, 1033),
                 DisplayCollectionName = new Label(entityPluralName, 1033),
                 OwnershipType         = OwnershipTypes.OrganizationOwned,
             },
             // 定义Entity的Primary Field
             PrimaryAttribute = new StringAttributeMetadata
             {
                 SchemaName    = primaryAttrName,
                 RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                 MaxLength     = 100,
                 Format        = StringFormat.Text,
                 DisplayName   = new Label(primaryAttrDisplayName, 1033)
             },
         };
         return(Service.Execute(request));
     }
     return(null);
 }
Пример #8
0
        public void CreateEntity(CustomEntityMetaData newEntityMetaData)
        {
            using (var crmSvc = new CrmServiceClient(cnString))
            {
                var CreateRequest = new CreateEntityRequest
                {
                    Entity = new emd.EntityMetadata
                    {
                        SchemaName            = (SchemaPrefix + newEntityMetaData.PrimaryAttributeSchemaName).ToLower(),
                        DisplayName           = new Label(newEntityMetaData.EntityDisplayName, 1033),
                        DisplayCollectionName = new Label(newEntityMetaData.EntityDisplayCollectionName, 1033),
                        Description           = new Label("New entity created via code", 1033),
                        OwnershipType         = emd.OwnershipTypes.UserOwned,
                        IsActivity            = false,
                    },
                    PrimaryAttribute = new emd.StringAttributeMetadata
                    {
                        SchemaName    = (SchemaPrefix + newEntityMetaData.PrimaryAttributeSchemaName).ToLower(),
                        RequiredLevel = new emd.AttributeRequiredLevelManagedProperty(emd.AttributeRequiredLevel.None),
                        MaxLength     = 100,
                        FormatName    = emd.StringFormatName.Text,
                        DisplayName   = new Label(newEntityMetaData.PrimaryAttributeDisplayName, 1033),
                        Description   = new Label("The primary created via code", 1033)
                    }
                };

                var result = crmSvc.OrganizationServiceProxy.Execute(CreateRequest);
            }
        }
Пример #9
0
        public static void DotsEventCalendarEntity()
        {
            // Create the custom entity.
            CreateEntityRequest createRequest = new CreateEntityRequest
            {
                //Define the entity
                Entity = new EntityMetadata
                {
                    SchemaName            = _customEntityName,
                    DisplayName           = new Label("DS EventsCalendar", 1033),
                    DisplayCollectionName = new Label("Events Calendar", 1033),
                    Description           = new Label("An entity to store information about EventsCalendar for particular entity.", 1033),
                    OwnershipType         = OwnershipTypes.UserOwned,
                    IsActivity            = false,
                    CanCreateViews        = new BooleanManagedProperty(false)



                                            //CanCreateForms = new BooleanManagedProperty(true),
                },

                // Define the primary attribute for the entity
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = "dots_name",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    FormatName    = StringFormatName.Text,
                    DisplayName   = new Label("Name", 1033),
                    Description   = new Label("The primary attribute for the dots_eventscalendar entity.", 1033),
                }
            };

            _serviceProxy.Execute(createRequest);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            CreateEntityRequest request;

            try
            {
                request = new CreateEntityRequest
                {
                    CatalogId           = CatalogId,
                    DataAssetKey        = DataAssetKey,
                    CreateEntityDetails = CreateEntityDetails,
                    OpcRequestId        = OpcRequestId,
                    OpcRetryToken       = OpcRetryToken
                };

                response = client.CreateEntity(request).GetAwaiter().GetResult();
                WriteOutput(response, response.Entity);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
Пример #11
0
        public CreateEntityRequest ToCreateEntityRequest()
        {
            // Create the entity and then add in aatributes.
            var createrequest = new CreateEntityRequest();

            createrequest.Entity           = Entity;
            createrequest.PrimaryAttribute = PrimaryAttribute;
            return(createrequest);
        }
Пример #12
0
        public Task <TEntity> Handle(CreateEntityRequest <TEntity> request, CancellationToken cancellationToken)
        {
            var keyProperty = typeof(TEntity).GetProperties().FirstOrDefault(p => p.GetCustomAttribute <KeyAttribute>() != null);

            return(Task.Run(() =>
            {
                _entities.Add(request.Entity);
                return request.Entity;
            }));
        }
Пример #13
0
        public static void DotsTwitterPublisher()
        {
            // Create the custom entity.
            CreateEntityRequest createRequest = new CreateEntityRequest
            {
                //Define the entity
                Entity = new EntityMetadata
                {
                    SchemaName            = _custom_PublisherEntityName,
                    DisplayName           = new Label("DS Twitter Publisher", 1033),
                    DisplayCollectionName = new Label("Twitter Publisher", 1033),
                    Description           = new Label("An entity to store information about Publisher a entity.", 1033),
                    OwnershipType         = OwnershipTypes.UserOwned,
                    IsActivity            = false,
                    //CanCreateForms = new BooleanManagedProperty(true),
                },

                // Define the primary attribute for the entity
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = "dots_alias",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.SystemRequired),
                    MaxLength     = 100,
                    FormatName    = StringFormatName.Text,
                    DisplayName   = new Label("Alias", 1033),
                    Description   = new Label("The primary attribute for the dots_twitterpublisher entity.", 1033),
                }
            };

            _serviceProxy.Execute(createRequest);

            // Add some attributes to the  entity
            CreateAttributeRequest createMediaAttributeRequest = new CreateAttributeRequest
            {
                EntityName = _custom_PublisherEntityName,
                Attribute  = new PicklistAttributeMetadata
                {
                    SchemaName    = "dots_media",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.SystemRequired),
                    OptionSet     = new OptionSetMetadata
                    {
                        IsGlobal      = false,
                        OptionSetType = OptionSetType.Picklist,
                        Options       =
                        {
                            new OptionMetadata(new Label("Twitter", 1033), 1),
                        }
                    },
                    DisplayName = new Label("Media", 1033),
                    Description = new Label("The Media type like twitter.", 1033),
                }
            };

            _serviceProxy.Execute(createMediaAttributeRequest);
        }
Пример #14
0
 public override CreateEntityResponse CreateEntity(CreateEntityRequest request)
 {
     try
     {
         var pair = new Tuple <string, string>(request.EnglishEntity, request.SerbianEntity);
         _writer.AddEntity(pair, _entityToDictionaryTypeMap[request.Type]);
         return(new CreateEntityResponse(ResponseResult.OK, null));
     }
     catch (Exception e)
     {
         return(new CreateEntityResponse(ResponseResult.FAILED, e.Message));
     }
 }
Пример #15
0
        public async Task <IActionResult> Post([FromBody] TEntity value)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(new { Errors = ModelState.Values, Payload = value }));
            }
            var request = new CreateEntityRequest <TEntity>(value);
            var result  = await _mediator.Send(request);

            return(new OkObjectResult(result)
            {
                StatusCode = 201
            });
        }
Пример #16
0
        public async Task CreatePhoneCategory(Guid contactId, [FromBody] CreateEntityRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var newPhoneCategoryDb = new PhoneCategoryDb
            {
                ContactId = contactId,
                Name      = request.Name
            };

            await _dbService.Insert(newPhoneCategoryDb);
        }
Пример #17
0
        public static void DotsAutoNumberConfigurationEntity()
        {
            // Create the custom entity.
            CreateEntityRequest createRequest = new CreateEntityRequest
            {
                //Define the entity
                Entity = new EntityMetadata
                {
                    SchemaName            = _customConfigurationEntityName,
                    DisplayName           = new Label("DS AutoSMS Configuration", 1033),
                    DisplayCollectionName = new Label("Auto SMS Configuration", 1033),
                    Description           = new Label("An entity to store information about autosms configuration for particular entity.", 1033),
                    OwnershipType         = OwnershipTypes.UserOwned,
                    IsActivity            = false,
                    //CanCreateForms = new BooleanManagedProperty(true),
                },

                // Define the primary attribute for the entity
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = "dots_type",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    FormatName    = StringFormatName.Text,
                    DisplayName   = new Label("Type", 1033),
                    Description   = new Label("The primary attribute for the dots_autonumber configuration entity.", 1033),
                }
            };

            _serviceProxy.Execute(createRequest);

            // Add some attributes to the dots_autonumber entity
            CreateAttributeRequest createPlaceHolderAttributeRequest = new CreateAttributeRequest
            {
                EntityName = _customConfigurationEntityName,
                Attribute  = new StringAttributeMetadata
                {
                    SchemaName    = "dots_value",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 500,
                    FormatName    = StringFormatName.Text,
                    DisplayName   = new Label("Value", 1033),
                    Description   = new Label("The Value for Security", 1033),
                }
            };

            _serviceProxy.Execute(createPlaceHolderAttributeRequest);
        }
        private void addCreateRequest(string[] row, List <CrmOperation> crmop)
        {
            bool   parseresult;
            String reqLevelstring = row[ExcelColumsDefinition.ENTITYPRIMARYATTRIBUTEREQUIREMENTLEVEL];
            AttributeRequiredLevel attributeRequiredLevel = AttributeRequiredLevel.None;

            if (Enum.IsDefined(typeof(AttributeRequiredLevel), reqLevelstring))
            {
                attributeRequiredLevel = (AttributeRequiredLevel)Enum.Parse(typeof(AttributeRequiredLevel), reqLevelstring, true);
            }
            CreateEntityRequest createrequest = new CreateEntityRequest
            {
                Entity = new EntityMetadata
                {
                    SchemaName                  = Utils.addOrgPrefix(row[ExcelColumsDefinition.ENTITYSCHEMANAMEEXCELCOL], entitySheet.orgPrefix, true),
                    DisplayName                 = new Label(row[ExcelColumsDefinition.ENTITYDISPLAYNAMEEXCELCOL], languageCode),
                    DisplayCollectionName       = new Label(row[ExcelColumsDefinition.ENTITYPLURALNAME], languageCode),
                    Description                 = new Label(row[ExcelColumsDefinition.ENTITYDESCRIPTIONEXCELCOL], languageCode),
                    OwnershipType               = Enum.IsDefined(typeof(OwnershipTypes), row[ExcelColumsDefinition.ENTITYOWNERSHIP]) ? (OwnershipTypes)Enum.Parse(typeof(OwnershipTypes), row[ExcelColumsDefinition.ENTITYOWNERSHIP], true) : OwnershipTypes.UserOwned,
                    IsActivity                  = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYDEFINEACTIVITY], out parseresult) ? parseresult : false,
                    IsConnectionsEnabled        = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYCONNECTION], out parseresult) ? new BooleanManagedProperty(parseresult) : new BooleanManagedProperty(true),
                    IsActivityParty             = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYSENDMAIL], out parseresult) ? parseresult : false,
                    IsMailMergeEnabled          = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYMAILMERGE], out parseresult) ? new BooleanManagedProperty(parseresult) : new BooleanManagedProperty(true),
                    IsDocumentManagementEnabled = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYDOCUMENTMANAGEMENT], out parseresult) ? parseresult : false,
                    IsValidForQueue             = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYQUEUES], out parseresult) ? new BooleanManagedProperty(parseresult) : new BooleanManagedProperty(false),
                    AutoRouteToOwnerQueue       = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYMOVEOWNERDEFAULTQUEUE], out parseresult) ? parseresult : false,
                    IsDuplicateDetectionEnabled = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYDUPLICATEDETECTION], out parseresult) ? new BooleanManagedProperty(parseresult) : new BooleanManagedProperty(true),
                    IsAuditEnabled              = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYAUDITING], out parseresult) ? new BooleanManagedProperty(parseresult) : new BooleanManagedProperty(false),
                    IsVisibleInMobile           = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYMOBILEEXPRESS], out parseresult) ? new BooleanManagedProperty(parseresult) : new BooleanManagedProperty(false),
                    IsAvailableOffline          = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYOFFLINEOUTLOOK], out parseresult) ? parseresult : false,
                },
                HasNotes      = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYNOTE], out parseresult) ? parseresult : true,
                HasActivities = Boolean.TryParse(row[ExcelColumsDefinition.ENTITYACTIVITIES], out parseresult) ? parseresult : true,

                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = row[ExcelColumsDefinition.ENTITYPRIMARYATTRIBUTEDISPLAYNAME] != string.Empty ? row[ExcelColumsDefinition.ENTITYPRIMARYATTRIBUTENAME] : Utils.addOrgPrefix("name", entitySheet.orgPrefix, true),
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(attributeRequiredLevel),
                    MaxLength     = 100,
                    Format        = StringFormat.Text,
                    DisplayName   = row[ExcelColumsDefinition.ENTITYPRIMARYATTRIBUTEDISPLAYNAME] != string.Empty ? new Label(row[ExcelColumsDefinition.ENTITYPRIMARYATTRIBUTEDISPLAYNAME], languageCode) : new Label("Name", languageCode),
                    Description   = new Label(row[ExcelColumsDefinition.ENTITYPRIMARYATTRIBUTEDESCRIPTION], languageCode)
                }
            };
            string strPreview = string.Format("Create new Enity : {0}", createrequest.Entity.SchemaName);

            crmop.Add(new CrmOperation(CrmOperation.CrmOperationType.create, CrmOperation.CrmOperationTarget.entity, createrequest, strPreview));
        }
Пример #19
0
        /// <summary>
        /// Method to create custom entity
        /// </summary>
        /// <param name="Name"></param>
        public void CreateCustomEntity(string Name, bool isActivity, int NumberOfRecords)
        {
            string _primaryAttributeSchemaName  = "new_name";
            string _primaryAttributeLogicalName = "name";

            if (isActivity)
            {
                _primaryAttributeSchemaName  = "Subject";
                _primaryAttributeLogicalName = "subject";
            }
            // Create custom entity.
            CreateEntityRequest _entity = new CreateEntityRequest()
            {
                Entity = new EntityMetadata()
                {
                    LogicalName                  = "new_" + Name,
                    DisplayName                  = new Label(Name, 1033),
                    DisplayCollectionName        = new Label(Name, 1033),
                    OwnershipType                = OwnershipTypes.UserOwned,
                    SchemaName                   = "new_" + Name,
                    IsActivity                   = isActivity,
                    IsAvailableOffline           = true,
                    IsAuditEnabled               = new BooleanManagedProperty(true),
                    IsMailMergeEnabled           = new BooleanManagedProperty(false),
                    IsVisibleInMobileClient      = new BooleanManagedProperty(true),
                    IsVisibleInMobile            = new BooleanManagedProperty(true),
                    IsReadOnlyInMobileClient     = new BooleanManagedProperty(true),
                    IsKnowledgeManagementEnabled = true,
                    IsValidForQueue              = new BooleanManagedProperty(true)
                },
                HasActivities    = true,
                HasNotes         = true,
                PrimaryAttribute = new StringAttributeMetadata()
                {
                    SchemaName    = _primaryAttributeSchemaName,
                    LogicalName   = _primaryAttributeLogicalName,
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    DisplayName   = new Label("Name", 1033)
                }
            };

            Console.WriteLine("\n Creating entity {0}", Name);
            CRM.CreateSampleData.ConnectionToServer._service.Execute(_entity);
            Console.WriteLine("\n Creating {0} records to entity {1}", NumberOfRecords, Name);
            AddRecordsToCustomEntity(Name, isActivity, NumberOfRecords);
        }
Пример #20
0
        public async Task Test_CreateEntityRequest_Handler()
        {
            var mediatr = IoC.ServiceProvider.GetRequiredService <IMediator>();

            var request = new CreateEntityRequest <TestModel>(new TestModel()
            {
                Name        = "test name 1",
                Description = "test description 1"
            });

            var result = await mediatr.Send(request);

            var getPersistedValue = new ReadEntityRequest <int, TestModel>(request.Entity.Id);
            var persistedValue    = await mediatr.Send(getPersistedValue);

            Assert.AreEqual(result, persistedValue);
        }
Пример #21
0
        public async Task CreateContact([FromBody] CreateEntityRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var userId = User.Claims.GetUserId();

            var contactDb = new ContactDb
            {
                Name              = request.Name,
                UserId            = userId,
                Notes             = "[]",
                Gender            = Gender.Undefined,
                AddressCategories = DefaultAddressCategories(),
                PhoneCategories   = DefaultPhoneCategories()
            };

            await _dbService.Insert(contactDb);
        }
Пример #22
0
        public async Task <Entity> CreateEntityAsync(CreateEntityRequest request, CancellationToken cancellationToken = new CancellationToken())
        {
            var fields = request.Fields ?? new Field[] { };

            //Attempt to get the entity definition.
            var entityDefinition = await _storage.GetEntityDefinitionAsync(request.EntityDefinitionId, cancellationToken);

            if (entityDefinition == null)
            {
                throw new EntityDefinitionNotFoundException($"Entity definition '{request.EntityDefinitionId}' not found.");
            }

            foreach (var field in fields)
            {
                //Attempt to get the field definition
                var fieldDefinition = entityDefinition.Fields.FirstOrDefault(f => f.Id == field.FieldDefinitionId);

                if (fieldDefinition == null)
                {
                    throw new FieldDefinitionNotFoundException($"Unable to find field definition '{field.FieldDefinitionId}'.");
                }

                //TODO: Validate the data type.
            }

            //Create the entity
            var entity = new Entity()
            {
                Id = Guid.NewGuid(),
                EntityDefinitionId = request.EntityDefinitionId,
                Name       = request.Name,
                Fields     = fields,
                CreatedUtc = DateTime.UtcNow
            };

            //Add the entity to the backing store.
            await _storage.AddEntityAsync(entity, cancellationToken);

            return(entity);
        }
Пример #23
0
        public void ExtractEntities(XrmActivityContext context)
        {
            var destinationService = context.XrmServices[Destination];
            var sourceService = context.XrmServices[Source];

            var sourceEntitities = XrmMetadataHelperFunctions.GetAllEntityMetadataDictionary(sourceService,
                EntityFilters.Attributes);
            var destinationEntities = XrmMetadataHelperFunctions.GetAllEntityMetadataDictionary(destinationService,
                EntityFilters.Attributes);

            XrmMetadataHelperFunctions.ProcessTask(sourceEntitities,
                () => new XrmConnectionManager().GetConnection(context.Configuration.DataSources[Destination]),
                sourceEntity =>
                {
                    if (sourceEntity.IsCustomEntity != null && !sourceEntity.IsCustomEntity.Value) return;
                    if (sourceEntity.IsIntersect != null && sourceEntity.IsIntersect.Value) return;
                    if (sourceEntity.MetadataId != null &&
                        XrmHelperFunctions.IsExcemptedFromProcessing(sourceEntity.LogicalName,
                            sourceEntity.MetadataId.Value,
                            context.Configuration.Exceptions)) return;

                    "create entity {0}".Trace(sourceEntity.LogicalName);

                    var destinationEntity = destinationEntities.ContainsKey(sourceEntity.LogicalName)
                        ? destinationEntities[sourceEntity.LogicalName]
                        : null;


                    if (destinationEntity != null) return;
                    var request = new CreateEntityRequest()
                    {
                        Entity = sourceEntity,
                        PrimaryAttribute = (StringAttributeMetadata)  sourceEntity.Attributes.FirstOrDefault(c => c.IsPrimaryName != null && c.IsPrimaryName.Value)
                    };

                    destinationService.Execute(request);
                },
                null,
                context.Configuration.Threads);
        }
Пример #24
0
        public void CreateEntity(CrmServiceClient services, DxEntity entity)
        {
            try
            {
                CreateEntityRequest createrequest = new CreateEntityRequest
                {
                    Entity = new EntityMetadata
                    {
                        SchemaName            = entity.PSchema,
                        DisplayName           = new Microsoft.Xrm.Sdk.Label(entity.PName, 3082),
                        DisplayCollectionName = new Microsoft.Xrm.Sdk.Label(entity.PNamePlural, 3082),
                        Description           = new Microsoft.Xrm.Sdk.Label(entity.PDescription, 3082),
                        OwnershipType         = entity.POwnershipType,
                        IsActivity            = entity.IsActivity,
                        IsConnectionsEnabled  = entity.IsConnectionsEnabled,
                        // IsActivityParty = true envio de correo
                    },

                    PrimaryAttribute = new StringAttributeMetadata
                    {
                        SchemaName    = entity.DxAttribute.PSchemaName,
                        RequiredLevel = entity.DxAttribute.PRequiredLevel,
                        MaxLength     = 100,
                        FormatName    = entity.DxAttribute.PFormatName,
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(entity.DxAttribute.PDisplayName, 3082),
                        Description   = new Microsoft.Xrm.Sdk.Label(entity.PDescription, 3082)
                    }
                };
                OrganizationResponse organizationResponse = services.ExecuteCrmOrganizationRequest(createrequest);
                new Util().CreateLog(string.Format("Entity created at {0} {1} with id {2}",
                                                   DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(),
                                                   ((CreateEntityResponse)organizationResponse).EntityId));
            }
            catch (System.Exception exception)
            {
                var error = exception.Message;
                throw;
            }
        }
Пример #25
0
        public bool CreateEntity(IOrganizationService service, XRMSpeedyEntity entity, int languageCode)
        {
            try
            {
                CreateEntityRequest createRequest = new CreateEntityRequest
                {
                    Entity = new EntityMetadata
                    {
                        SchemaName            = entity.EntityMetadata.SchemaName,
                        DisplayName           = entity.EntityMetadata.DisplayName,
                        DisplayCollectionName = entity.EntityMetadata.DisplayCollectionName,
                        Description           = entity.EntityMetadata.Description,
                        OwnershipType         = entity.EntityMetadata.OwnershipType,
                        IsActivity            = false
                    },

                    // Define the primary attribute for the entity
                    PrimaryAttribute = new StringAttributeMetadata
                    {
                        SchemaName = entity.ShortPrimaryAttributeName
                            ? entity.EntityMetadata.SchemaName.Split('_')[0] + "_" + "name"
                            : entity.EntityMetadata.SchemaName + "name",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired),
                        MaxLength     = entity.PrimaryAttributeSize,
                        Format        = StringFormat.Text,
                        DisplayName   = new Label("Name", languageCode),
                        Description   = new Label("The primary attribute for the entity.", languageCode)
                    }
                };

                CreateEntityResponse response = (CreateEntityResponse)service.Execute(createRequest);

                return(CreateAttributes(service, entity, languageCode));
            }
            catch (FaultException <OrganizationServiceFault> )
            {
                throw;
            }
        }
        public void CreateEntity <T>() where T : CrmPlusPlusEntity, new()
        {
            var entityName = EntityNameAttribute.GetFromType <T>();
            var entityInfo = EntityInfoAttribute.GetFromType <T>();

            var createEntityRequest = new CreateEntityRequest
            {
                Entity = new EntityMetadata
                {
                    SchemaName            = entityName,
                    DisplayName           = entityInfo.DisplayName.ToLabel(),
                    DisplayCollectionName = entityInfo.PluralDisplayName.ToLabel(),
                    Description           = entityInfo.Description.ToLabel(),
                    OwnershipType         = entityInfo.OwnershipType,
                    IsActivity            = false
                },
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = entityName + "primary",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    FormatName    = Microsoft.Xrm.Sdk.Metadata.StringFormatName.Text,
                    DisplayName   = "Primary attribute".ToLabel(),
                    Description   = string.Format("The primary attribute for the {0} entity", entityInfo.DisplayName).ToLabel()
                }
            };

            var response = (CreateEntityResponse)service.Execute(createEntityRequest);

            var addReq = new AddSolutionComponentRequest()
            {
                ComponentType      = (int)SolutionComponentTypes.Entity,
                ComponentId        = response.EntityId,
                SolutionUniqueName = Solution.Name
            };

            service.Execute(addReq);
        }
Пример #27
0
        /// <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;
            }
        }
Пример #28
0
        /// <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;
            }
        }
 public async Task <TEntity> Handle(CreateEntityRequest <TEntity> request, CancellationToken cancellationToken)
 {
     return(await _innerHandler.Handle(request, cancellationToken));
 }
Пример #30
0
        /// <summary>
        /// Create a custom entity.
        /// Update 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();


                    // Create the custom entity.
                    //<snippetCreateUpdateEntityMetadata1>
                    CreateEntityRequest createrequest = new CreateEntityRequest
                    {
                        //Define the entity
                        Entity = new EntityMetadata
                        {
                            SchemaName            = _customEntityName,
                            DisplayName           = new Label("Bank Account", 1033),
                            DisplayCollectionName = new Label("Bank Accounts", 1033),
                            Description           = new Label("An entity to store information about customer bank accounts", 1033),
                            OwnershipType         = OwnershipTypes.UserOwned,
                            IsActivity            = false,
                        },

                        // Define the primary attribute for the entity
                        PrimaryAttribute = new StringAttributeMetadata
                        {
                            SchemaName    = "new_accountname",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength     = 100,
                            FormatName    = StringFormatName.Text,
                            DisplayName   = new Label("Account Name", 1033),
                            Description   = new Label("The primary attribute for the Bank Account entity.", 1033)
                        }
                    };
                    _serviceProxy.Execute(createrequest);
                    Console.WriteLine("The bank account entity has been created.");
                    //</snippetCreateUpdateEntityMetadata1>


                    // Add some attributes to the Bank Account entity
                    //<snippetCreateUpdateEntityMetadata2>
                    CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute  = new StringAttributeMetadata
                        {
                            SchemaName    = "new_bankname",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength     = 100,
                            FormatName    = StringFormatName.Text,
                            DisplayName   = new Label("Bank Name", 1033),
                            Description   = new Label("The name of the bank.", 1033)
                        }
                    };

                    _serviceProxy.Execute(createBankNameAttributeRequest);
                    //</snippetCreateUpdateEntityMetadata2>
                    Console.WriteLine("An bank name attribute has been added to the bank account entity.");

                    //<snippetCreateUpdateEntityMetadata3>
                    CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute  = new MoneyAttributeMetadata
                        {
                            SchemaName      = "new_balance",
                            RequiredLevel   = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            PrecisionSource = 2,
                            DisplayName     = new Label("Balance", 1033),
                            Description     = new Label("Account Balance at the last known date", 1033),
                        }
                    };

                    _serviceProxy.Execute(createBalanceAttributeRequest);
                    //</snippetCreateUpdateEntityMetadata3>
                    Console.WriteLine("An account balance attribute has been added to the bank account entity.");

                    //<snippetCreateUpdateEntityMetadata4>
                    CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute  = new DateTimeAttributeMetadata
                        {
                            SchemaName    = "new_checkeddate",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            Format        = DateTimeFormat.DateOnly,
                            DisplayName   = new Label("Date", 1033),
                            Description   = new Label("The date the account balance was last confirmed", 1033)
                        }
                    };

                    _serviceProxy.Execute(createCheckedDateRequest);
                    Console.WriteLine("An date attribute has been added to the bank account entity.");
                    //</snippetCreateUpdateEntityMetadata4>
                    //Create a lookup attribute to link the bank account with a contact record.

                    //<snippetCreateUpdateEntityMetadata5>
                    CreateOneToManyRequest req = new CreateOneToManyRequest()
                    {
                        Lookup = new LookupAttributeMetadata()
                        {
                            Description   = new Label("The owner of the bank account", 1033),
                            DisplayName   = new Label("Account Owner", 1033),
                            LogicalName   = "new_parent_contactid",
                            SchemaName    = "New_Parent_ContactId",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired)
                        },
                        OneToManyRelationship = new OneToManyRelationshipMetadata()
                        {
                            AssociatedMenuConfiguration = new AssociatedMenuConfiguration()
                            {
                                Behavior = AssociatedMenuBehavior.UseCollectionName,
                                Group    = AssociatedMenuGroup.Details,
                                Label    = new Label("Bank Accounts", 1033),
                                Order    = 10000
                            },
                            CascadeConfiguration = new CascadeConfiguration()
                            {
                                Assign   = CascadeType.Cascade,
                                Delete   = CascadeType.Cascade,
                                Merge    = CascadeType.Cascade,
                                Reparent = CascadeType.Cascade,
                                Share    = CascadeType.Cascade,
                                Unshare  = CascadeType.Cascade
                            },
                            ReferencedEntity    = Contact.EntityLogicalName,
                            ReferencedAttribute = "contactid",
                            ReferencingEntity   = _customEntityName,
                            SchemaName          = "new_contact_new_bankaccount"
                        }
                    };
                    _serviceProxy.Execute(req);
                    //</snippetCreateUpdateEntityMetadata5>
                    Console.WriteLine("A lookup attribute has been added to the bank account entity to link it with the Contact entity.");

                    //<snippetCreateUpdateEntityMetadata11>
                    //Create an Image attribute for the custom entity
                    // Only one Image attribute can be added to an entity that doesn't already have one.
                    CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute  = new ImageAttributeMetadata
                        {
                            SchemaName    = "EntityImage", //The name is always EntityImage
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            DisplayName   = new Label("Image", 1033),
                            Description   = new Label("An image to represent the bank account.", 1033)
                        }
                    };

                    _serviceProxy.Execute(createEntityImageRequest);
                    Console.WriteLine("An image attribute has been added to the bank account entity.");
                    //</snippetCreateUpdateEntityMetadata11>

                    //<snippetCreateUpdateEntityMetadata9>

                    //<snippetCreateUpdateEntityMetadata.RetrieveEntity>
                    RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.Entity,
                        LogicalName   = _customEntityName
                    };
                    RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest);
                    //</snippetCreateUpdateEntityMetadata.RetrieveEntity>
                    //<snippetCreateUpdateEntityMetadata8>
                    EntityMetadata BankAccountEntity = retrieveBankAccountEntityResponse.EntityMetadata;

                    // Disable Mail merge
                    BankAccountEntity.IsMailMergeEnabled = new BooleanManagedProperty(false);
                    // Enable Notes
                    UpdateEntityRequest updateBankAccountRequest = new UpdateEntityRequest
                    {
                        Entity   = BankAccountEntity,
                        HasNotes = true
                    };



                    _serviceProxy.Execute(updateBankAccountRequest);
                    //</snippetCreateUpdateEntityMetadata8>
                    //</snippetCreateUpdateEntityMetadata9>

                    Console.WriteLine("The bank account entity has been updated");


                    //Update the entity form so the new fields are visible
                    UpdateEntityForm(_customEntityName);

                    // Customizations must be published after an entity is updated.
                    //<snippetCreateUpdateEntityMetadata6>
                    PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(publishRequest);
                    //</snippetCreateUpdateEntityMetadata6>
                    Console.WriteLine("Customizations were published.");

                    //Provides option to view the entity in the default solution
                    ShowEntityInBrowser(promptForDelete, BankAccountEntity);
                    //Provides option to view the entity form with the fields added
                    ShowEntityFormInBrowser(promptForDelete, BankAccountEntity);

                    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;
            }
        }
Пример #31
0
        /// <summary>
        /// Create a custom entity that can be used in the To field of an email activity.
        /// Update 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();


                    //<snippetCreateUpdateEmailableEntity1>

                    // Create the custom entity.
                    CreateEntityRequest createrequest = new CreateEntityRequest
                    {
                        // Define an entity to enable for emailing. In order to do so,
                        // IsActivityParty must be set.
                        Entity = new EntityMetadata
                        {
                            SchemaName            = _customEntityName,
                            DisplayName           = new Label("Agent", 1033),
                            DisplayCollectionName = new Label("Agents", 1033),
                            Description           = new Label("Insurance Agents", 1033),
                            OwnershipType         = OwnershipTypes.UserOwned,
                            IsActivity            = false,

                            // Unless this flag is set, this entity cannot be party to an
                            // activity.
                            IsActivityParty = true
                        },

                        // As with built-in emailable entities, the Primary Attribute will
                        // be used in the activity party screens. Be sure to choose descriptive
                        // attributes.
                        PrimaryAttribute = new StringAttributeMetadata
                        {
                            SchemaName    = "new_fullname",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength     = 100,
                            FormatName    = StringFormatName.Text,
                            DisplayName   = new Label("Agent Name", 1033),
                            Description   = new Label("Agent Name", 1033)
                        }
                    };

                    _serviceProxy.Execute(createrequest);
                    Console.WriteLine("The emailable entity has been created.");

                    // The entity will not be selectable as an activity party until its customizations
                    // have been published. Otherwise, the e-mail activity dialog cannot find
                    // a correct default view.
                    PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(publishRequest);

                    // Before any emails can be created for this entity, an Email attribute
                    // must be defined.
                    CreateAttributeRequest createFirstEmailAttributeRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute  = new StringAttributeMetadata
                        {
                            SchemaName    = "new_emailaddress",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength     = 100,
                            FormatName    = StringFormatName.Email,
                            DisplayName   = new Label("Email Address", 1033),
                            Description   = new Label("Email Address", 1033)
                        }
                    };

                    _serviceProxy.Execute(createFirstEmailAttributeRequest);
                    Console.WriteLine("An email attribute has been added to the emailable entity.");

                    // Create a second, alternate email address. Since there is already one
                    // email attribute on the entity, this will never be used for emailing
                    // even if the first one is not populated.
                    CreateAttributeRequest createSecondEmailAttributeRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute  = new StringAttributeMetadata
                        {
                            SchemaName    = "new_secondaryaddress",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength     = 100,
                            FormatName    = StringFormatName.Email,
                            DisplayName   = new Label("Secondary Email Address", 1033),
                            Description   = new Label("Secondary Email Address", 1033)
                        }
                    };

                    _serviceProxy.Execute(createSecondEmailAttributeRequest);

                    Console.WriteLine("A second email attribute has been added to the emailable entity.");
                    //</snippetCreateUpdateEmailableEntity1>

                    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>
        /// 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;
            }
        }
Пример #33
0
        [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>
        /// 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;
            }
        }
Пример #35
0
  //</snippetremoveOptionLabelsFromCache>
  
  protected void addCustomEntityWithOptionSet()
  {
   String primaryAttributeSchemaName = "sample_SampleEntityForMetadataQueryName";

   CreateEntityRequest createEntityRequest = new CreateEntityRequest
   {

    //Define the entity
    Entity = new EntityMetadata
    {
     SchemaName = _customEntitySchemaName,
     LogicalName = _customEntitySchemaName.ToLower(),
     DisplayName = new Label("Entity for MetadataQuery Sample", _languageCode),
     DisplayCollectionName = new Label("Entity for MetadataQuery Sample", _languageCode),
     Description = new Label("An entity created for the MetadataQuery Sample", _languageCode),
     OwnershipType = OwnershipTypes.UserOwned,
     IsVisibleInMobile = new BooleanManagedProperty(true),
     IsActivity = false,

    },

    // Define the primary attribute for the entity


    PrimaryAttribute = new StringAttributeMetadata
    {
     SchemaName = primaryAttributeSchemaName,
     LogicalName = primaryAttributeSchemaName.ToLower(),
     RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
     MaxLength = 100,
     Format = StringFormat.Text,
     DisplayName = new Label("Entity for MetadataQuery Sample Name", _languageCode),
     Description = new Label("The primary attribute for the Bank Account entity.", _languageCode)
    }

   };
_service.Execute(createEntityRequest);


   //PublishXmlRequest publishXmlRequest = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", _customEntitySchemaName.ToLower()) };
   //_service.Execute(publishXmlRequest);

   //Add an optionset attribute

   CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
   {
    EntityName = _customEntitySchemaName.ToLower(),
    Attribute = new PicklistAttributeMetadata
    {
     SchemaName = _customAttributeSchemaName,
     DisplayName = new Label("Example OptionSet for MetadataQuery Sample", _languageCode),
     RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

     OptionSet = new OptionSetMetadata
     {
      IsGlobal = false,
      OptionSetType = OptionSetType.Picklist,
      Options =  { 
       new OptionMetadata(new Label("First Option",_languageCode),null),
       new OptionMetadata(new Label("Second Option",_languageCode),null),
       new OptionMetadata(new Label("Third Option",_languageCode),null),
       new OptionMetadata(new Label("Fourth Option",_languageCode),null)
      }
     }
    }
   };

   _service.Execute(createAttributeRequest);

  }
Пример #36
0
        /// <summary>
        ///     DOESN'T UPDATE PRIMARY FIELD - CALL THE CREATEORUPDATESTRING METHOD
        /// </summary>
        public void CreateOrUpdateEntity(string schemaName, string displayName, string displayCollectionName,
            string description, bool audit, string primaryFieldSchemaName,
            string primaryFieldDisplayName, string primaryFieldDescription,
            int primaryFieldMaxLength, bool primaryFieldIsMandatory, bool primaryFieldAudit, bool isActivityType,
            bool notes, bool activities, bool connections, bool mailMerge, bool queues)
        {
            lock (LockObject)
            {
                var metadata = new EntityMetadata();

                var exists = EntityExists(schemaName);
                if (exists)
                    metadata = GetEntityMetadata(schemaName);

                metadata.SchemaName = schemaName;
                metadata.LogicalName = schemaName;
                metadata.DisplayName = new Label(displayName, 1033);
                metadata.DisplayCollectionName = new Label(displayCollectionName, 1033);
                metadata.IsAuditEnabled = new BooleanManagedProperty(audit);
                metadata.IsActivity = isActivityType;
                metadata.IsValidForQueue = new BooleanManagedProperty(queues);
                metadata.IsMailMergeEnabled = new BooleanManagedProperty(mailMerge);
                metadata.IsConnectionsEnabled = new BooleanManagedProperty(connections);
                metadata.IsActivity = isActivityType;
                if (!String.IsNullOrWhiteSpace(description))
                    metadata.Description = new Label(description, 1033);

                if (exists)
                {
                    var request = new UpdateEntityRequest
                    {
                        Entity = metadata,
                        HasActivities = activities,
                        HasNotes = notes
                    };
                    Execute(request);
                }
                else
                {
                    metadata.OwnershipType = OwnershipTypes.UserOwned;

                    var primaryFieldMetadata = new StringAttributeMetadata();
                    SetCommon(primaryFieldMetadata, primaryFieldSchemaName, primaryFieldDisplayName,
                        primaryFieldDescription,
                        primaryFieldIsMandatory, primaryFieldAudit, true);
                    primaryFieldMetadata.MaxLength = primaryFieldMaxLength;

                    var request = new CreateEntityRequest
                    {
                        Entity = metadata,
                        PrimaryAttribute = primaryFieldMetadata,
                        HasActivities = activities,
                        HasNotes = notes
                    };
                    Execute(request);
                    RefreshFieldMetadata(primaryFieldSchemaName, schemaName);
                }
                RefreshEntityMetadata(schemaName);
            }
        }
        /// <summary>
        /// Create a custom entity that can be used in the To field of an email activity.
        /// Update 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();


                    //<snippetCreateUpdateEmailableEntity1>

                    // Create the custom entity.
                    CreateEntityRequest createrequest = new CreateEntityRequest
                    {
                        // Define an entity to enable for emailing. In order to do so,
                        // IsActivityParty must be set.
                        Entity = new EntityMetadata
                        {
                            SchemaName = _customEntityName,
                            DisplayName = new Label("Agent", 1033),
                            DisplayCollectionName = new Label("Agents", 1033),
                            Description = new Label("Insurance Agents", 1033),
                            OwnershipType = OwnershipTypes.UserOwned,
                            IsActivity = false,

                            // Unless this flag is set, this entity cannot be party to an
                            // activity.
                            IsActivityParty = true
                        },

                        // As with built-in emailable entities, the Primary Attribute will
                        // be used in the activity party screens. Be sure to choose descriptive
                        // attributes.
                        PrimaryAttribute = new StringAttributeMetadata
                        {
                            SchemaName = "new_fullname",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength = 100,
                            FormatName = StringFormatName.Text,
                            DisplayName = new Label("Agent Name", 1033),
                            Description = new Label("Agent Name", 1033)
                        }
                    };

                    _serviceProxy.Execute(createrequest);
                    Console.WriteLine("The emailable entity has been created.");

                    // The entity will not be selectable as an activity party until its customizations
                    // have been published. Otherwise, the e-mail activity dialog cannot find
                    // a correct default view.
                    PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(publishRequest);

                    // Before any emails can be created for this entity, an Email attribute
                    // must be defined.
                    CreateAttributeRequest createFirstEmailAttributeRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute = new StringAttributeMetadata
                        {
                            SchemaName = "new_emailaddress",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength = 100,                            
                            FormatName = StringFormatName.Email,
                            DisplayName = new Label("Email Address", 1033),
                            Description = new Label("Email Address", 1033)
                        }
                    };

                    _serviceProxy.Execute(createFirstEmailAttributeRequest);
                    Console.WriteLine("An email attribute has been added to the emailable entity.");

                    // Create a second, alternate email address. Since there is already one 
                    // email attribute on the entity, this will never be used for emailing
                    // even if the first one is not populated.
                    CreateAttributeRequest createSecondEmailAttributeRequest = new CreateAttributeRequest
                    {
                        EntityName = _customEntityName,
                        Attribute = new StringAttributeMetadata
                        {
                            SchemaName = "new_secondaryaddress",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength = 100,                            
                            FormatName = StringFormatName.Email,
                            DisplayName = new Label("Secondary Email Address", 1033),
                            Description = new Label("Secondary Email Address", 1033)
                        }
                    };

                    _serviceProxy.Execute(createSecondEmailAttributeRequest);

                    Console.WriteLine("A second email attribute has been added to the emailable entity.");
                    //</snippetCreateUpdateEmailableEntity1>

                    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;
            }
        }
Пример #38
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateImageAttributeDemoEntity()
        {
            //Create a Custom entity
            CreateEntityRequest createrequest = new CreateEntityRequest
            {
                //Define the entity
                Entity = new EntityMetadata
                {
                    SchemaName            = _customEntityName,
                    DisplayName           = new Label("Image Attribute Demo", 1033),
                    DisplayCollectionName = new Label("Image Attribute Demos", 1033),
                    Description           = new Label("An entity created by an SDK sample to demonstrate how to upload and retrieve entity images.", 1033),
                    OwnershipType         = OwnershipTypes.UserOwned,
                    IsActivity            = false,
                },

                // Define the primary attribute for the entity
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = "sample_Name",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    FormatName    = StringFormatName.Text,
                    DisplayName   = new Label("Name", 1033),
                    Description   = new Label("The primary attribute for the Image Attribute Demo entity.", 1033)
                }
            };

            _serviceProxy.Execute(createrequest);
            Console.WriteLine("The Image Attribute Demo entity has been created.");

            //Create an Image attribute for the custom entity
            // Only one Image attribute can be added to an entity that doesn't already have one.
            CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest
            {
                EntityName = _customEntityName.ToLower(),
                Attribute  = new ImageAttributeMetadata
                {
                    SchemaName = "EntityImage", //The name is always EntityImage
                    //Required level must be AttributeRequiredLevel.None
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    DisplayName   = new Label("Image", 1033),
                    Description   = new Label("An image to show with this demonstration.", 1033)
                }
            };

            _serviceProxy.Execute(createEntityImageRequest);
            Console.WriteLine("The Image attribute has been created.");

            //<snippetEntityImages5>
            QueryExpression qe = new QueryExpression("systemform");

            qe.Criteria.AddCondition("type", ConditionOperator.Equal, 2); //main form
            qe.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, _customEntityName.ToLower());
            qe.ColumnSet.AddColumn("formxml");

            SystemForm ImageAttributeDemoMainForm = (SystemForm)_serviceProxy.RetrieveMultiple(qe).Entities[0];

            XDocument ImageAttributeDemoMainFormXml = XDocument.Parse(ImageAttributeDemoMainForm.FormXml);

            //Set the showImage attribute so the entity image will be displayed
            ImageAttributeDemoMainFormXml.Root.SetAttributeValue("showImage", true);

            //Updating the entity form definition
            ImageAttributeDemoMainForm.FormXml = ImageAttributeDemoMainFormXml.ToString();

            _serviceProxy.Update(ImageAttributeDemoMainForm);
            //</snippetEntityImages5>
            Console.WriteLine("The Image Attribute Demo main form has been updated to show images.");


            PublishXmlRequest pxReq1 = new PublishXmlRequest {
                ParameterXml = String.Format(@"
   <importexportxml>
    <entities>
     <entity>{0}</entity>
    </entities>
   </importexportxml>", _customEntityName.ToLower())
            };

            _serviceProxy.Execute(pxReq1);

            Console.WriteLine("The Image Attribute Demo entity was published");
        }
Пример #39
0
        public void CreateEntity(string excelFile, EntityTemplate entityTemplate, Action<string> setMessageOfTheDayLabel)
        {
            errorList = new List<Exception>();
            warningList = new List<Exception>();
            createAttributeRequestList = new List<CreateAttributeRequest>();
            createdGlobalOptionSetList = new List<string>();
            createWebResourcesRequestList = new List<CreateRequest>();

            if (entityTemplate == null)
            {
                errorList.Add(
                    new Exception(string.Format("CreateEntity method EntityTemplate reference is null. File: {0}",
                        excelFile)));
                entityTemplate=new EntityTemplate(){Errors = new List<Exception>()};
                entityTemplate.Errors.AddRange(errorList);
                return;
            }
            if (entityTemplate.WillCreateEntity)
            {
                var createrequest = new CreateEntityRequest();
                var entityMetadata = new EntityMetadata
                {
                    SchemaName = entityTemplate.LogicalName,
                    DisplayName = GetLabelWithLocalized(entityTemplate.DisplayName),
                    DisplayCollectionName = GetLabelWithLocalized(entityTemplate.DisplayNamePlural),
                    Description = GetLabelWithLocalized(entityTemplate.Description),
                    OwnershipType = DefaultConfiguration.DefaultOwnershipType,
                    IsActivity = false
                };
                createrequest.PrimaryAttribute = GetPrimaryAttribute(entityTemplate);
                createrequest.Entity = entityMetadata;
                ExecuteOperation(GetSharedOrganizationService(), createrequest,
                    string.Format("An error occured while creating the entity: {0}", entityTemplate.LogicalName));
                //setMessageOfTheDayLabel("1");
                if (entityTemplate.AttributeList == null)
                {
                    entityTemplate.Warnings.AddRange(warningList);
                    entityTemplate.Errors.AddRange(errorList);
                }

                foreach (var attributeTemplate in entityTemplate.AttributeList)
                {
                    CreateAttribute(entityTemplate.LogicalName, attributeTemplate);
                }
            }

            var requests = new ExecuteMultipleRequest
            {
                Requests = new OrganizationRequestCollection()
            };
            if (entityTemplate.WebResource != null)
            {
                for (var i = 0; i < entityTemplate.WebResource.Count; i++)
                {
                    var webresourceRequest = GetCreateWebResourceRequest(entityTemplate.WebResource[i]);
                    requests.Requests.Add(webresourceRequest);
                    if (i % DefaultConfiguration.ExecuteMultipleSize == 0 || createAttributeRequestList.Count - i < 10)
                    {
                        ExecuteMultipleWebresourceRequests(requests);
                        //setMessageOfTheDayLabel(requests.Requests.Count);
                        requests = new ExecuteMultipleRequest
                        {
                            Requests = new OrganizationRequestCollection()
                        };
                    }
                }
            }

            ExecuteMultipleOperation("Execute multiple error occured.", setMessageOfTheDayLabel);
            entityTemplate.Warnings.AddRange(warningList);
            entityTemplate.Errors.AddRange(errorList);
        }
Пример #40
0
 public CreateEntityRequest ToCreateEntityRequest()
 {
     // Create the entity and then add in aatributes.
     var createrequest = new CreateEntityRequest();
     createrequest.Entity = Entity;
     createrequest.PrimaryAttribute = PrimaryAttribute;
     return createrequest;
 }
Пример #41
0
  /// <summary>
  /// Creates any entity records that this sample requires.
  /// </summary>
  public void CreateImageAttributeDemoEntity()
  {
   //Create a Custom entity
   CreateEntityRequest createrequest = new CreateEntityRequest
   {

    //Define the entity
    Entity = new EntityMetadata
    {
     SchemaName = _customEntityName,
     DisplayName = new Label("Image Attribute Demo", 1033),
     DisplayCollectionName = new Label("Image Attribute Demos", 1033),
     Description = new Label("An entity created by an SDK sample to demonstrate how to upload and retrieve entity images.", 1033),
     OwnershipType = OwnershipTypes.UserOwned,
     IsActivity = false,

    },

    // Define the primary attribute for the entity
    PrimaryAttribute = new StringAttributeMetadata
    {
     SchemaName = "sample_Name",
     RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
     MaxLength = 100,
     FormatName = StringFormatName.Text,
     DisplayName = new Label("Name", 1033),
     Description = new Label("The primary attribute for the Image Attribute Demo entity.", 1033)
    }

   };
   _serviceProxy.Execute(createrequest);
   Console.WriteLine("The Image Attribute Demo entity has been created.");

   //Create an Image attribute for the custom entity
   // Only one Image attribute can be added to an entity that doesn't already have one.
   CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest
   {
    EntityName = _customEntityName.ToLower(),
    Attribute = new ImageAttributeMetadata
    {
     SchemaName = "EntityImage", //The name is always EntityImage
     //Required level must be AttributeRequiredLevel.None
     RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), 
     DisplayName = new Label("Image", 1033),
     Description = new Label("An image to show with this demonstration.", 1033)

    }
   };
   _serviceProxy.Execute(createEntityImageRequest);
   Console.WriteLine("The Image attribute has been created.");

   //<snippetEntityImages5>
   QueryExpression qe = new QueryExpression("systemform");
   qe.Criteria.AddCondition("type", ConditionOperator.Equal, 2); //main form
   qe.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, _customEntityName.ToLower()); 
   qe.ColumnSet.AddColumn("formxml");

   SystemForm ImageAttributeDemoMainForm = (SystemForm)_serviceProxy.RetrieveMultiple(qe).Entities[0];

   XDocument ImageAttributeDemoMainFormXml = XDocument.Parse(ImageAttributeDemoMainForm.FormXml);
   //Set the showImage attribute so the entity image will be displayed
   ImageAttributeDemoMainFormXml.Root.SetAttributeValue("showImage", true);

   //Updating the entity form definition
   ImageAttributeDemoMainForm.FormXml = ImageAttributeDemoMainFormXml.ToString();

   _serviceProxy.Update(ImageAttributeDemoMainForm);
   //</snippetEntityImages5>
   Console.WriteLine("The Image Attribute Demo main form has been updated to show images.");


   PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format(@"
   <importexportxml>
    <entities>
     <entity>{0}</entity>
    </entities>
   </importexportxml>", _customEntityName.ToLower()) };
   _serviceProxy.Execute(pxReq1);

   Console.WriteLine("The Image Attribute Demo entity was published");
  }