Example #1
0
        private static async Task RunAsync(EntityMetadataCollection entities)
        {
            try
            {
                var webApiClient   = new WebApiClient();
                var webApiMetadata = await webApiClient.GetWebApiMetadata();

                IEdmModel metadataModel;
                IEnumerable <EdmError> errors;
                bool parseSuccess = EdmxReader.TryParse(XmlReader.Create(new StringReader(webApiMetadata)), out metadataModel, out errors);

                if (parseSuccess)
                {
                    var edmSchemaElements = metadataModel.SchemaElements.Where(se =>
                                                                               se.SchemaElementKind == EdmSchemaElementKind.TypeDefinition &&
                                                                               ExcludedEntities.All(ee => ee.ToLowerInvariant() != se.Name.ToLowerInvariant()));

                    foreach (IEdmSchemaElement schemaElement in edmSchemaElements)
                    {
                        var entity = entities.FirstOrDefault(e => e.LogicalName == schemaElement.Name);
                        if (entity != null)
                        {
                            WriteEntityTsFile(schemaElement as IEdmEntityType, entity);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("Error in RunAsync(): " + e.Message);
            }
            Console.WriteLine("Done! Press any key to close the application");
            Console.Read();
        }
Example #2
0
        /// <summary>
        /// Modify to mock CRM Organization Service actions
        /// </summary>
        /// <param name="serviceMock">The Organization Service to mock</param>
        /// <returns>Configured Organization Service</returns>
        private static Mock <IOrganizationService> CopyToNewRecordSetup(Mock <IOrganizationService> serviceMock)
        {
            Entity note = new Entity("annotation");

            note["objectid"] = new EntityReference("contact", Guid.NewGuid());

            serviceMock.Setup(t =>
                              t.Retrieve(It.IsAny <string>(), It.IsAny <Guid>(), It.IsAny <ColumnSet>()))
            .ReturnsInOrder(note);

            OrganizationResponse     response           = new OrganizationResponse();
            EntityMetadataCollection metadataCollection = new EntityMetadataCollection();
            EntityMetadata           entityMetadata     = new EntityMetadata();

            entityMetadata.LogicalName = "account";
            metadataCollection.Add(entityMetadata);
            ParameterCollection results = new ParameterCollection {
                { "EntityMetadata", metadataCollection }
            };

            response.Results = results;

            serviceMock.Setup(t =>
                              t.Execute(It.IsAny <OrganizationRequest>()))
            .ReturnsInOrder(response);

            return(serviceMock);
        }
        /// <summary>
        /// Find the Logical Name from the entity type code - this needs a reference to the Organization Service to look up metadata
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public string GetEntityLogicalName(IOrganizationService service)
        {
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, this.EntityTypeCode));
            var propertyExpression = new MetadataPropertiesExpression {
                AllProperties = false
            };

            propertyExpression.PropertyNames.Add("LogicalName");
            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria   = entityFilter,
                Properties = propertyExpression
            };

            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };

            var response = service.Execute(retrieveMetadataChangesRequest);

            EntityMetadataCollection metadataCollection = (EntityMetadataCollection)response.Results["EntityMetadata"];

            if (metadataCollection.Count == 1)
            {
                return(metadataCollection[0].LogicalName);
            }
            return(null);
        }
Example #4
0
        /// <summary>
        /// Loads the entity metadata for all the entities in the Aptify database
        /// </summary>
        /// <returns>A collection of the metadata from the Aptify entities</returns>
        internal EntityMetadataCollection LoadEntityMetadata( )
        {
            using (this.connection)
            {
                try
                {
                    this.connection.Open( );

                    // Load all the basic entity information
                    EntityMetadataCollection entities = LoadAptifyEntityInformation(this.connection);

                    // Load the underlying table information
                    LoadAptifyTableMetadata(this.connection, entities);

                    Log.DebugFormat("Successfully loaded {0} entities from Aptify database", entities.Count( ));

                    return(entities);
                }
                catch (DbException ex)
                {
                    Log.Fatal("Could not load aptify entities", ex);
                    throw;
                }
            }
        }
Example #5
0
        public static void StoreChangedMetaData(DeletedMetadataCollection deletedMD, EntityMetadataCollection changedMD)
        {
            int deletedAmount = deletedMD.Count;
            int changedAmount = changedMD.Count;

            Console.WriteLine("*Changed Metadata* \n" + deletedAmount + " deletes found. \n" + changedAmount + " changes found.");

            log("\n* CRM: " + URL + " \n*Changed Metadata* \n" + deletedAmount + " deletes found. \n" + changedAmount + " changes found.", "Results", true, false);
            string[,] _deletedMD  = new string[deletedAmount, 2];
            string[,] _modifiedMD = new string[changedAmount, 2];

            //Parse into Arrays
            //deletes
            int i = 0;

            foreach (var _key in deletedMD.Keys)
            {
                DataCollection <Guid> _tmpGUID;

                if (deletedMD.TryGetValue(_key, out _tmpGUID))
                {
                    Console.WriteLine(_tmpGUID);
                }
                else
                {
                    Console.WriteLine(_key + " not found i deleted metadata!");
                }
            }
            //changes
            for (i = 0; i < changedMD.Count; i++)
            {
                Console.WriteLine("change found to: '" + changedMD[i].SchemaName.ToString() + "' since " + _ClientVersionStamp);
                log("change found to: '" + changedMD[i].SchemaName.ToString() + "' since " + _ClientVersionStamp, "Results", true, false);
            }
        }
Example #6
0
        private static EntityMetadataCollection LoadAptifyEntityInformation(IDbConnection connection)
        {
            var entities  = new EntityMetadataCollection( );
            var parentIDs = new List <int>( );

            using (IDbCommand command = connection.CreateCommand( ))
            {
                command.CommandText = Queries.GetAllEntities;
                command.CommandType = CommandType.Text;

                using (IDataReader reader = command.ExecuteReader( ))
                {
                    while (reader.Read( ))
                    {
                        var entity = new AptifyEntityMetadata(
                            ( int )reader["ID"], ( string )reader["Name"]);

                        entities.Add(entity);
                        parentIDs.Add(reader.GetInt32(1));
                    }
                }

                MapParents(entities, parentIDs);
            }

            return(entities);
        }
Example #7
0
        public void LoadEntities()
        {
            lvEntities.Items.Clear();
            lvEntities.Enabled       = false;
            tsbLoadEntities.Enabled  = false;
            tsbExportToExcel.Enabled = false;

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading Entities...",
                Work    = (w, e) =>
                {
                    e.Result = MetadataHelper.LoadEntities(Service);
                },
                PostWorkCallBack = e =>
                {
                    if (e.Error != null)
                    {
                        MessageBox.Show(e.Error.ToString());
                    }

                    var items = new List <ListViewItem>();

                    entities = (EntityMetadataCollection)e.Result;

                    foreach (var emd in entities)
                    {
                        var item = new ListViewItem(emd.DisplayName.UserLocalizedLabel != null
                            ? emd.DisplayName.UserLocalizedLabel.Label
                            : "N/A");
                        item.SubItems.Add(emd.LogicalName);
                        item.Tag = emd;

                        allItems.Add(item);

                        if (txtSearch.Text.Length == 0 || txtSearch.Text.Length > 0 &&
                            (emd.LogicalName.IndexOf(txtSearch.Text.ToLower(), StringComparison.Ordinal) >= 0 ||
                             emd.DisplayName?.UserLocalizedLabel?.Label.ToLower()
                             .IndexOf(txtSearch.Text.ToLower(), StringComparison.Ordinal) >= 0))
                        {
                            items.Add(item);
                        }
                    }

                    lvEntities.Items.AddRange(items.ToArray());
                    lvEntities.Enabled       = true;
                    tsbLoadEntities.Enabled  = true;
                    tsbExportToExcel.Enabled = true;
                },
                ProgressChanged = e =>
                {
                    SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(e.UserState.ToString()));
                }
            });
        }
 private void LoadAttributes()
 {
     if (Service == null)
     {
         return;
     }
     Enabled = false;
     if (metadata == null)
     {
         var asyncinfo = new WorkAsyncInfo()
         {
             Message = "Loading entities and attributes",
             Work    = (a, args) =>
             {
                 var eqe = new EntityQueryExpression();
                 eqe.Properties = new MetadataPropertiesExpression("DisplayName", "Attributes");
                 eqe.Criteria.Conditions.Add(new MetadataConditionExpression("IsCustomizable", MetadataConditionOperator.Equals, true));
                 var aqe = new AttributeQueryExpression();
                 aqe.Properties = new MetadataPropertiesExpression();
                 aqe.Properties.AllProperties = true;
                 aqe.Criteria.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.DateTime));
                 //aqe.Criteria.Conditions.Add(new MetadataConditionExpression("CanChangeDateTimeBehavior", MetadataConditionOperator.Equals, true));
                 eqe.AttributeQuery = aqe;
                 var req = new RetrieveMetadataChangesRequest()
                 {
                     Query = eqe,
                     ClientVersionStamp = null
                 };
                 args.Result = Service.Execute(req) as RetrieveMetadataChangesResponse;
             },
             PostWorkCallBack = (args) =>
             {
                 if (args.Error != null)
                 {
                     MessageBox.Show($"Failed to load metadata:\n{args.Error.Message}", "Load", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     return;
                 }
                 if (!(args.Result is RetrieveMetadataChangesResponse))
                 {
                     MessageBox.Show($"Unexpected result:\n{args.Result}", "Load", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     return;
                 }
                 metadata = ((RetrieveMetadataChangesResponse)args.Result).EntityMetadata;
                 PopulateAttributes();
             }
         };
         WorkAsync(asyncinfo);
     }
     else
     {
         PopulateAttributes();
     }
 }
Example #9
0
        /// <summary>
        /// Find the parents of a collection of entities
        /// </summary>
        /// <param name="entities">Collection of entity metadata</param>
        /// <param name="parentIDs">Parent IDs that correlate to the entities</param>
        private static void MapParents(EntityMetadataCollection entities, IEnumerable <int> parentIDs)
        {
            using (var e1 = entities.GetEnumerator( ))
                using (var e2 = parentIDs.GetEnumerator( ))
                {
                    while (e1.MoveNext( ))
                    {
                        if (!e2.MoveNext( ))
                        {
                            throw new Exception("Mapping of parents requires the same number of parentIDs as entities");
                        }

                        e1.Current.Parent = entities.GetById(e2.Current);
                    }
                }
        }
        internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef)
        {
            var request = MakeRequest <RetrieveMetadataChangesRequest>(orgRequest);

            var q = request.Query;
            var c = q.Criteria.Conditions.First();

            var m = metadata.EntityMetadata.Where(x => x.Value.ObjectTypeCode.Value == (int)c.Value);

            var resp = new RetrieveMetadataChangesResponse();
            var col  = new EntityMetadataCollection();

            col.Add(m.Single().Value);
            resp.Results["EntityMetadata"] = col;

            return(resp);
        }
        private void DateTimeBehaviorUtility_ConnectionUpdated(object sender, ConnectionUpdatedEventArgs e)
        {
            var orgver = new Version(e.ConnectionDetail.OrganizationVersion);
            var orgok  = orgver >= new Version(7, 1);

            btnLoadAttributes.Enabled = orgok;
            if (orgok)
            {
                listAttributes.Items.Clear();
                listAttributes.Groups.Clear();
                metadata = null;
            }
            else
            {
                MessageBox.Show("DateTime Behavior was introduced in\nMicrosoft Dynamics CRM 2015 Update 1 (7.1.0.0)\n\nPlease connect to a newer organization to use this cool tool.", "Organization too old", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Example #12
0
        public void Clone_default_addCloneLabel_Adds_Clone_Label()
        {
            var metadata       = AccountMetadata.GetEntityMetadata();
            var entityMetadata = new EntityMetadataCollection()
            {
                metadata
            };

            _context.AddFakeMessageExecutor <RetrieveMetadataChangesRequest>(new RetrieveMetadataChangesRequestExecutor(entityMetadata));

            var clone = new Entity("account")
            {
                ["name"] = "Your Company"
            }.Clone(_service);

            Assert.Equal("Your Company (clone)", clone.GetAttributeValue <string>("name"));
        }
            public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
            {
                OrganizationResponse     response           = new OrganizationResponse();
                EntityMetadataCollection metadataCollection = new EntityMetadataCollection();
                EntityMetadata           entityMetadata     = new EntityMetadata {
                    LogicalName = "account"
                };

                metadataCollection.Add(entityMetadata);
                ParameterCollection results = new ParameterCollection {
                    { "EntityMetadata", metadataCollection }
                };

                response.Results = results;

                return(response);
            }
Example #14
0
        public void LoadEntities()
        {
            lvEntities.Items.Clear();

            tsbCreateRecords.Enabled = false;
            tsbDeleteEntity.Enabled  = false;
            tsbLoadEntities.Enabled  = false;

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading Entities...",
                Work    = (bw, evt) =>
                {
                    var mm     = new MetadataManager(Service);
                    evt.Result = mm.GetEntitiesMetadata();
                },
                PostWorkCallBack = evt =>
                {
                    emc = (EntityMetadataCollection)evt.Result;

                    var list = new List <ListViewItem>();

                    foreach (var em in emc.Where(e => e.Attributes.Any(
                                                     a => a.AttributeType.Value == AttributeTypeCode.Picklist ||
                                                     a.AttributeType.Value == AttributeTypeCode.State ||
                                                     a.AttributeType.Value == AttributeTypeCode.Status)))
                    {
                        var item =
                            new ListViewItem(em.DisplayName == null || em.DisplayName.UserLocalizedLabel == null
                                ? "N/A"
                                : em.DisplayName.UserLocalizedLabel.Label);
                        item.SubItems.Add(em.LogicalName);
                        item.Tag = em;

                        list.Add(item);
                    }

                    lvEntities.Items.AddRange(list.ToArray());

                    tsbCreateRecords.Enabled = true;
                    tsbDeleteEntity.Enabled  = true;
                    tsbLoadEntities.Enabled  = true;
                }
            });
        }
Example #15
0
        public void LoadEntities()
        {
            lvEntities.Items.Clear();

            tsbCreateRecords.Enabled = false;
            tsbDeleteEntity.Enabled = false;
            tsbLoadEntities.Enabled = false;

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading Entities...",
                Work = (bw, evt) =>
                {
                    var mm = new MetadataManager(Service);
                    evt.Result = mm.GetEntitiesMetadata();
                },
                PostWorkCallBack = evt =>
                {
                    emc = (EntityMetadataCollection)evt.Result;

                    var list = new List<ListViewItem>();

                    foreach (var em in emc.Where(e => e.Attributes.Any(
                        a => a.AttributeType.Value == AttributeTypeCode.Picklist
                             || a.AttributeType.Value == AttributeTypeCode.State
                             || a.AttributeType.Value == AttributeTypeCode.Status)))
                    {
                        var item =
                            new ListViewItem(em.DisplayName == null || em.DisplayName.UserLocalizedLabel == null
                                ? "N/A"
                                : em.DisplayName.UserLocalizedLabel.Label);
                        item.SubItems.Add(em.LogicalName);
                        item.Tag = em;

                        list.Add(item);
                    }

                    lvEntities.Items.AddRange(list.ToArray());

                    tsbCreateRecords.Enabled = true;
                    tsbDeleteEntity.Enabled = true;
                    tsbLoadEntities.Enabled = true;
                }
            });
        }
Example #16
0
        public void Clone_Ignores_Uniqueidentifier_Columns()
        {
            var metadata       = AccountMetadata.GetEntityMetadata();
            var entityMetadata = new EntityMetadataCollection()
            {
                metadata
            };

            _context.AddFakeMessageExecutor <RetrieveMetadataChangesRequest>(new RetrieveMetadataChangesRequestExecutor(entityMetadata));

            var clone = new Entity("account")
            {
                ["name"]      = "Your Company",
                ["processid"] = Guid.NewGuid()
            }.Clone(_service);

            Assert.Null(clone.GetAttributeValue <Guid?>("processid"));
        }
Example #17
0
        public void Clone_Correctly_Clones_Record_Without_columnsToRemove()
        {
            var metadata       = AccountMetadata.GetEntityMetadata();
            var entityMetadata = new EntityMetadataCollection()
            {
                metadata
            };

            _context.AddFakeMessageExecutor <RetrieveMetadataChangesRequest>(new RetrieveMetadataChangesRequestExecutor(entityMetadata));

            var clone = new Entity("account")
            {
                ["name"]             = "Your Company",
                ["primarycontactid"] = new EntityReference("contact", Guid.NewGuid())
            }.Clone(_service);

            Assert.NotNull(clone.GetAttributeValue <EntityReference>("primarycontactid"));
        }
Example #18
0
        public static EntityMetadataCollection GetAllMetaData(this IOrganizationService service, EntityQueryExpression queryExp)
        {
            var entityCol = new EntityMetadataCollection();

            try
            {
                var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
                {
                    Query = queryExp,
                    ClientVersionStamp = null
                };
                entityCol = ((RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest)).EntityMetadata;
            }
            catch
            {
                throw;
            }
            return(entityCol);
        }
Example #19
0
        private static void LoadAptifyTableMetadata(IDbConnection connection, EntityMetadataCollection entities)
        {
            using (IDbCommand command = connection.CreateCommand( ))
            {
                command.CommandText = Queries.GetAllColumns;
                command.CommandType = CommandType.Text;

                using (IDataReader reader = command.ExecuteReader( ))
                {
                    while (reader.Read( ))
                    {
                        // Load the required fields to simplify the latter code
                        var entityId = ( int )reader["EntityID"];
                        AptifyEntityMetadata parent = entities.GetByName(reader["LinkedEntity"] as string);
                        var tableName  = ( string )reader["BaseTable"];
                        var columnName = ( string )reader["Name"];
                        var nullable   = ( bool )reader["SQLAllowNull"];
                        var embedded   = (( string )reader["LinkType"] ?? String.Empty).Trim( ) == "Embedded";

                        AptifyEntityMetadata entity = entities.GetById(entityId);

                        if (entity == null)
                        {
                            throw new InvalidOperationException("No entity found with ID " + entityId);
                        }

                        AptifyTableMetadata table = entity.Tables.FirstOrDefault(t => t.Name == tableName);

                        // This is the first time the table was found
                        if (table == null)
                        {
                            // Add the table to the entity
                            table = new AptifyTableMetadata(entity, tableName);
                            entity.AddTable(table);
                        }

                        var column = new AptifyColumnMetadata(columnName, nullable, parent, embedded);

                        table.AddColumn(column);
                    }
                }
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            try
            {
                var _languageCode = 1033;

                CrmServiceClient connection =
                    new CrmServiceClient(ConfigurationManager.ConnectionStrings["crm"].ConnectionString);
                var service = (IOrganizationService)connection.OrganizationWebProxyClient ??
                              (IOrganizationService)connection.OrganizationServiceProxy;
                var entities = new EntityMetadataCollection();
                entities = GetEntityMetadata(service);

                var task = RunAsync(entities);
                task.Wait();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("Error in Main(): " + e.Message);
            }
            var d = 0;
        }
        public void Find(Version crmVersion)
        {
            worker.ReportProgress(0, "Loading User language...");
            GetCurrentUserLcid();

            worker.ReportProgress(0, "Loading Entities metadata...");
            emds = GetEntities();

            worker.ReportProgress(0, "Loading Scripts...");
            foreach (var emd in emds.Where(x => x.DisplayName.UserLocalizedLabel != null))
            {
                LoadScripts(emd);
                LoadRibbonCommands(emd);

                // Grid events are only available since CRM 8.2
                if (crmVersion >= new Version(8, 2, 0, 0))
                {
                    LoadCustomControls(emd);
                }
            }

            LoadRibbonCustomRule();
        }
Example #22
0
        public void LoadFls()
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading Field Security profiles...",
                Work = (bw, e) =>
                {
                    var flsManager = new FlsManager(Service);
                    profiles = flsManager.LoadSecureProfiles();

                    bw.ReportProgress(0, "Loading Secured fields...");
                    fields = flsManager.LoadSecureFields();

                    var dico = new Dictionary<string, List<string>>();

                    foreach (var field in fields)
                    {
                        if (!dico.ContainsKey(field.Entity))
                        {
                            dico.Add(field.Entity, new List<string>());
                        }

                        if (!dico[field.Entity].Contains(field.Attribute))
                        {
                            dico[field.Entity].Add(field.Attribute);
                        }
                    }

                    metadata = MetadataHelper.LoadMetadata(dico, Service);
                },
                PostWorkCallBack = e =>
                {
                    var fieldsList = new List<ListViewItem>();
                    var profilesList = new List<ListViewItem>();

                    foreach (var field in fields)
                    {
                        var entityDislayName =
                            metadata.First(m => m.LogicalName == field.Entity).DisplayName.UserLocalizedLabel.Label;
                        var attributeDisplayName =
                            metadata.First(m => m.LogicalName == field.Entity)
                                .Attributes.First(a => a.LogicalName == field.Attribute)
                                .DisplayName.UserLocalizedLabel.Label;

                        var item = new ListViewItem(attributeDisplayName);
                        item.SubItems.Add(field.Attribute);
                        item.SubItems.Add(entityDislayName);
                        item.SubItems.Add(field.Entity);
                        item.SubItems.Add(string.Empty);
                        item.SubItems.Add(string.Empty);
                        item.SubItems.Add(string.Empty);
                        fieldsList.Add(item);
                    }

                    foreach (var profile in profiles)
                    {
                        var item = new ListViewItem(profile.GetAttributeValue<string>("name")) { Tag = profile };
                        profilesList.Add(item);
                    }

                    lvFlsRoles.Items.Clear();
                    LvSecuredAttributes.Items.Clear();

                    lvFlsRoles.Items.AddRange(profilesList.ToArray());
                    LvSecuredAttributes.Items.AddRange(fieldsList.ToArray());
                },
                ProgressChanged = e => { SetWorkingMessage(e.UserState.ToString()); }
            });
        }
Example #23
0
        //</snippetupdateOptionLabelList>
        //<snippetaddOptionLabelsToCache>
        protected void addOptionLabelsToCache(EntityMetadataCollection entityMetadataCollection, Boolean showChanges)
        {
            List <OptionSetOption> changes = new List <OptionSetOption>();

            foreach (EntityMetadata em in entityMetadataCollection)
            {
                foreach (AttributeMetadata am in em.Attributes)
                {
                    switch (am.AttributeType)
                    {
                    case AttributeTypeCode.Boolean:
                        BooleanAttributeMetadata booleanAttribute = (BooleanAttributeMetadata)am;
                        //Labels will not be included if they aren't new
                        if (booleanAttribute.OptionSet.FalseOption.Label.UserLocalizedLabel != null)
                        {
                            changes.Add(new OptionSetOption(
                                            (Guid)booleanAttribute.OptionSet.MetadataId,
                                            0,
                                            booleanAttribute.OptionSet.FalseOption.Label.UserLocalizedLabel.Label)
                                        );
                        }
                        //Labels will not be included if they aren't new
                        if (booleanAttribute.OptionSet.TrueOption.Label.UserLocalizedLabel != null)
                        {
                            changes.Add(new OptionSetOption(
                                            (Guid)booleanAttribute.OptionSet.MetadataId,
                                            1,
                                            booleanAttribute.OptionSet.TrueOption.Label.UserLocalizedLabel.Label));
                        }
                        break;

                    default:
                        EnumAttributeMetadata optionsetAttribute = (EnumAttributeMetadata)am;
                        foreach (OptionMetadata option in optionsetAttribute.OptionSet.Options)
                        {
                            //Labels will not be included if they aren't new
                            if (option.Label.UserLocalizedLabel != null)
                            {
                                changes.Add(new OptionSetOption(
                                                (Guid)optionsetAttribute.OptionSet.MetadataId,
                                                (int)option.Value,
                                                option.Label.UserLocalizedLabel.Label));
                            }
                        }
                        break;
                    }
                }
            }

            _optionLabelList.AddRange(changes);

            if (showChanges)
            {
                if (changes.Count > 0)
                {
                    Console.WriteLine("{0} option labels for {1} entities were added to the cache.", changes.Count, entityMetadataCollection.Count);
                    Console.WriteLine("{0} Option Labels cached", _optionLabelList.Count);
                }
                else
                {
                    Console.WriteLine("No option labels were added to the cache.");
                }
            }
        }
Example #24
0
        public void LoadEntities()
        {
            lvEntities.Items.Clear();

            tsbCreateRecords.Enabled = false;
            tsbDeleteEntity.Enabled  = false;
            tsbLoadEntities.Enabled  = false;

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading Entities...",
                Work    = (bw, evt) =>
                {
                    var mm     = new MetadataManager(Service);
                    evt.Result = mm.GetEntitiesMetadata();

                    if (mm.EntityExists("gap_powerbioptionsetref"))
                    {
                        var records = Service.RetrieveMultiple(new QueryExpression("gap_powerbioptionsetref")
                        {
                            ColumnSet = new ColumnSet("gap_optionsetschemaname", "gap_entityschemaname")
                        });
                        var items = records.Entities.ToList().Select(e => new { optionSet = e.GetAttributeValue <string>("gap_optionsetschemaname"), entity = e.GetAttributeValue <string>("gap_entityschemaname") });
                        foreach (var item in items)
                        {
                            if (selectedOptionSets.FirstOrDefault(so => so.Item1 == item.entity && so.Item2 == item.optionSet) == null)
                            {
                                selectedOptionSets.Add(new Tuple <string, string>(item.entity, item.optionSet));
                            }
                        }
                    }
                },
                PostWorkCallBack = evt =>
                {
                    emc = (EntityMetadataCollection)evt.Result;

                    var list = new List <ListViewItem>();

                    foreach (var em in emc.Where(e => e.Attributes.Any(
                                                     a => a.AttributeType.HasValue && a.AttributeType.Value == AttributeTypeCode.Picklist ||
                                                     a.AttributeType.HasValue && a.AttributeType.Value == AttributeTypeCode.Boolean ||
                                                     a.AttributeType.HasValue && a.AttributeType.Value == AttributeTypeCode.State ||
                                                     a.AttributeType.HasValue && a.AttributeType.Value == AttributeTypeCode.Status)))
                    {
                        var item =
                            new ListViewItem(em.DisplayName == null || em.DisplayName.UserLocalizedLabel == null
                                ? "N/A"
                                : em.DisplayName.UserLocalizedLabel.Label);
                        item.SubItems.Add(em.LogicalName);
                        item.Tag     = em;
                        item.Checked = selectedOptionSets.Any(so => so.Item1 == em.SchemaName);

                        list.Add(item);
                    }

                    lvEntities.Items.AddRange(list.ToArray());

                    tsbCreateRecords.Enabled = true;
                    tsbDeleteEntity.Enabled  = emc.ToList().FirstOrDefault(emd => emd.LogicalName == "gap_powerbioptionsetref") != null;
                    tsbLoadEntities.Enabled  = true;
                }
            });
        }
Example #25
0
        static void Main(string[] args)
        {
            var _languageCode = 1033;

            CrmServiceClient connection = new CrmServiceClient(ConfigurationManager.ConnectionStrings["crm"].ConnectionString);
            var service = (IOrganizationService)connection.OrganizationWebProxyClient ?? (IOrganizationService)connection.OrganizationServiceProxy;


            //To reduce the number of classes generated to those which are most useful,
            // the following entities will be excluded. If necessary, you can comment out
            // items from this array so that class files will be generated for the entity
            String[] excludedEntities =
            {
                "ApplicationFile",
                "AsyncOperation",
                "AttributeMap",
                "AuthorizationServer",
                "BulkDeleteFailure",
                "BulkDeleteOperation",
                "BulkOperation",
                "BulkOperationLog",
                "BusinessProcessFlowInstance",
                "BusinessUnitMap",
                "BusinessUnitNewsArticle",
                "ChildIncidentCount",
                "ClientUpdate",
                "ColumnMapping",
                "Commitment",
                "ComplexControl",
                "ConvertRule",
                "ConvertRuleItem",
                "Dependency",
                "DependencyFeature",
                "DependencyNode",
                "DisplayString",
                "DisplayStringMap",
                "DocumentIndex",
                "DuplicateRecord",
                "DuplicateRule",
                "DuplicateRuleCondition",
                "EmailHash",
                "EmailSearch",
                "EmailServerProfile",
                "EntityMap",
                "ExchangeSyncIdMapping",
                "FieldPermission",
                "FieldSecurityProfile",
                "FilterTemplate",
                "FixedMonthlyFiscalCalendar",
                "ImageDescriptor",
                "Import",
                "ImportData",
                "ImportEntityMapping",
                "ImportFile",
                "ImportJob",
                "ImportLog",
                "ImportMap",
                "IntegrationStatus",
                "InternalAddress",
                "InterProcessLock",
                "InvalidDependency",
                "IsvConfig",
                "License",
                "LookUpMapping",
                "Mailbox",
                "MailboxStatistics",
                "MetadataDifference",
                "MultiEntitySearch",
                "MultiEntitySearchEntities",
                "Notification",
                "OrganizationStatistic",
                "OrganizationUI",
                "OwnerMapping",
                "PartnerApplication",
                "PickListMapping",
                "PluginAssembly",
                "PluginType",
                "PluginTypeStatistic",
                "PrincipalObjectAccess",
                "PrincipalObjectAccessReadSnapshot",
                "PrincipalObjectAttributeAccess",
                "Privilege",
                "PrivilegeObjectTypeCodes",
                "ProcessSession",
                "ProcessStage",
                "ProcessTrigger",
                "Publisher",
                "PublisherAddress",
                "RecordCountSnapshot",
                "RelationshipRole",
                "RelationshipRoleMap",
                "ReplicationBacklog",
                "Report",
                "ReportCategory",
                "ReportEntity",
                "ReportLink",
                "ReportVisibility",
                "RibbonCommand",
                "RibbonContextGroup",
                "RibbonCustomization",
                "RibbonDiff",
                "RibbonRule",
                "RibbonTabToCommandMap",
                "RoutingRule",
                "RoutingRuleItem",
                "SalesProcessInstance",
                "SdkMessage",
                "SdkMessageFilter",
                "SdkMessagePair",
                "SdkMessageProcessingStep",
                "SdkMessageProcessingStepImage",
                "SdkMessageProcessingStepSecureConfig",
                "SdkMessageRequest",
                "SdkMessageRequestField",
                "SdkMessageResponse",
                "SdkMessageResponseField",
                "ServiceEndpoint",
                "SiteMap",
                "SLA",
                "SLAItem",
                "Solution",
                "SolutionComponent",
                "SqlEncryptionAudit",
                "StatusMap",
                "StringMap",
                "Subscription",
                "SubscriptionClients",
                "SubscriptionSyncInfo",
                "SubscriptionTrackingDeletedObject",
                "SystemApplicationMetadata",
                "SystemForm",
                "SystemUserBusinessUnitEntityMap",
                "SystemUserPrincipals",
                "TraceAssociation",
                "TraceLog",
                "TraceRegarding",
                "TransformationMapping",
                "TransformationParameterMapping",
                "UnresolvedAddress",
                "UserApplicationMetadata",
                "UserEntityInstanceData",
                "UserEntityUISettings",
                "WebWizard",
                "WizardAccessPrivilege",
                "WizardPage",
                "WorkflowWaitSubscription"
            };
            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            // No classes for intersect entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));
            // Do not retrieve excluded entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn, excludedEntities));


            //A properties expression to limit the properties to be included with entities
            MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            EntityProperties.PropertyNames.AddRange(new string[] {
                "Attributes",
                "Description",
                "DisplayName",
                "OneToManyRelationships",
                "SchemaName"
            });


            MetadataConditionExpression[] attributesToReturn = new MetadataConditionExpression[] {
                //No virtual attributes
                new MetadataConditionExpression("AttributeType", MetadataConditionOperator.NotEquals, AttributeTypeCode.Virtual),
                // No child attributes
                new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null)
            };


            MetadataFilterExpression AttributeFilter = new MetadataFilterExpression(LogicalOperator.And);

            AttributeFilter.Conditions.AddRange(attributesToReturn);


            MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            AttributeProperties.PropertyNames.Add("AttributeTypeName");
            AttributeProperties.PropertyNames.Add("MaxLength");
            AttributeProperties.PropertyNames.Add("OptionSet");
            AttributeProperties.PropertyNames.Add("Description");
            AttributeProperties.PropertyNames.Add("DisplayName");
            AttributeProperties.PropertyNames.Add("RequiredLevel");
            AttributeProperties.PropertyNames.Add("SchemaName");
            AttributeProperties.PropertyNames.Add("Targets");
            AttributeProperties.PropertyNames.Add("IsValidForCreate");
            AttributeProperties.PropertyNames.Add("IsValidForRead");
            AttributeProperties.PropertyNames.Add("IsValidForUpdate");


            MetadataFilterExpression relationshipFilter = new MetadataFilterExpression(LogicalOperator.And);

            MetadataPropertiesExpression relationshipProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            relationshipProperties.PropertyNames.Add("SchemaName");
            relationshipProperties.PropertyNames.Add("ReferencingEntity");
            relationshipProperties.PropertyNames.Add("ReferencingAttribute");



            //A label query expression to limit the labels returned to only those for the user's preferred language
            LabelQueryExpression labelQuery = new LabelQueryExpression();
            //labelQuery.FilterLanguages.Add(_languageCode);


            //An entity query expression to combine the filter expressions and property expressions for the query.
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = EntityFilter,
                Properties     = EntityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria   = AttributeFilter,
                    Properties = AttributeProperties
                },
                RelationshipQuery = new RelationshipQueryExpression()
                {
                    Criteria   = relationshipFilter,
                    Properties = relationshipProperties
                },
                LabelQuery = labelQuery
            };

            RetrieveMetadataChangesRequest rmdcr = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };
            RetrieveMetadataChangesResponse resp = (RetrieveMetadataChangesResponse)service.Execute(rmdcr);

            EntityMetadataCollection entities = resp.EntityMetadata;

            foreach (EntityMetadata entity in entities)
            {
                writeEntityTSFile(entity);
            }
            Console.WriteLine("Done!");
        }
Example #26
0
        private static EntityMetadataCollection GetEntityMetadata(IOrganizationService service)
        {
            //To reduce the number of classes generated to those which are most useful,
            // the following entities will be excluded. If necessary, you can comment out
            // items from this array so that class files will be generated for the entity

            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            // No classes for intersect entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));
            // Do not retrieve excluded entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn,
                                                                        ExcludedEntities));


            //A properties expression to limit the properties to be included with entities
            MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            EntityProperties.PropertyNames.AddRange(new string[]
            {
                "Attributes",
                "Description",
                "DisplayName",
                "OneToManyRelationships",
                "SchemaName"
            });


            MetadataConditionExpression[] attributesToReturn = new MetadataConditionExpression[]
            {
                //No virtual attributes
                new MetadataConditionExpression("AttributeType", MetadataConditionOperator.NotEquals, AttributeTypeCode.Virtual),
                // No child attributes
                new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null)
            };


            MetadataFilterExpression AttributeFilter = new MetadataFilterExpression(LogicalOperator.And);

            AttributeFilter.Conditions.AddRange(attributesToReturn);


            MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            AttributeProperties.PropertyNames.Add("AttributeTypeName");
            AttributeProperties.PropertyNames.Add("MaxLength");
            AttributeProperties.PropertyNames.Add("OptionSet");
            AttributeProperties.PropertyNames.Add("Description");
            AttributeProperties.PropertyNames.Add("DisplayName");
            AttributeProperties.PropertyNames.Add("RequiredLevel");
            AttributeProperties.PropertyNames.Add("SchemaName");
            AttributeProperties.PropertyNames.Add("Targets");
            AttributeProperties.PropertyNames.Add("IsValidForCreate");
            AttributeProperties.PropertyNames.Add("IsValidForRead");
            AttributeProperties.PropertyNames.Add("IsValidForUpdate");


            MetadataFilterExpression relationshipFilter = new MetadataFilterExpression(LogicalOperator.And);

            MetadataPropertiesExpression relationshipProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            relationshipProperties.PropertyNames.Add("SchemaName");
            relationshipProperties.PropertyNames.Add("ReferencingEntity");
            relationshipProperties.PropertyNames.Add("ReferencingAttribute");


            //A label query expression to limit the labels returned to only those for the user's preferred language
            LabelQueryExpression labelQuery = new LabelQueryExpression();
            //labelQuery.FilterLanguages.Add(_languageCode);


            //An entity query expression to combine the filter expressions and property expressions for the query.
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = EntityFilter,
                Properties     = EntityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria   = AttributeFilter,
                    Properties = AttributeProperties
                },
                RelationshipQuery = new RelationshipQueryExpression()
                {
                    Criteria   = relationshipFilter,
                    Properties = relationshipProperties
                },
                LabelQuery = labelQuery
            };

            RetrieveMetadataChangesRequest rmdcr = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };
            RetrieveMetadataChangesResponse resp = (RetrieveMetadataChangesResponse)service.Execute(rmdcr);

            EntityMetadataCollection entities = resp.EntityMetadata;

            return(entities);
        }
Example #27
0
        public void LoadFls()
        {
            WorkAsync("Loading Field Security profiles...",
                      (w, e) =>
            {
                var flsManager = new FlsManager(Service);
                profiles       = flsManager.LoadSecureProfiles();

                w.ReportProgress(0, "Loading Secured fields...");
                fields = flsManager.LoadSecureFields();

                var dico = new Dictionary <string, List <string> >();

                foreach (var field in fields)
                {
                    if (!dico.ContainsKey(field.Entity))
                    {
                        dico.Add(field.Entity, new List <string>());
                    }

                    if (!dico[field.Entity].Contains(field.Attribute))
                    {
                        dico[field.Entity].Add(field.Attribute);
                    }
                }

                metadata = MetadataHelper.LoadMetadata(dico, Service);
            },
                      e =>
            {
                var fieldsList   = new List <ListViewItem>();
                var profilesList = new List <ListViewItem>();

                foreach (var field in fields)
                {
                    var entityDislayName =
                        metadata.First(m => m.LogicalName == field.Entity).DisplayName.UserLocalizedLabel.Label;
                    var attributeDisplayName =
                        metadata.First(m => m.LogicalName == field.Entity)
                        .Attributes.First(a => a.LogicalName == field.Attribute)
                        .DisplayName.UserLocalizedLabel.Label;

                    var item = new ListViewItem(attributeDisplayName);
                    item.SubItems.Add(field.Attribute);
                    item.SubItems.Add(entityDislayName);
                    item.SubItems.Add(field.Entity);
                    item.SubItems.Add(string.Empty);
                    item.SubItems.Add(string.Empty);
                    item.SubItems.Add(string.Empty);
                    fieldsList.Add(item);
                }

                foreach (var profile in profiles)
                {
                    var item = new ListViewItem(profile.GetAttributeValue <string>("name"))
                    {
                        Tag = profile
                    };
                    profilesList.Add(item);
                }

                lvFlsRoles.Items.Clear();
                LvSecuredAttributes.Items.Clear();

                lvFlsRoles.Items.AddRange(profilesList.ToArray());
                LvSecuredAttributes.Items.AddRange(fieldsList.ToArray());
            },
                      e => SetWorkingMessage(e.UserState.ToString()));
        }
Example #28
0
  //</snippetupdateOptionLabelList>
  //<snippetaddOptionLabelsToCache>
  protected void addOptionLabelsToCache(EntityMetadataCollection entityMetadataCollection, Boolean showChanges)
  {

   List<OptionSetOption> changes = new List<OptionSetOption>();

   foreach (EntityMetadata em in entityMetadataCollection)
   {
    foreach (AttributeMetadata am in em.Attributes)
    {
     switch (am.AttributeType)
     {
      case AttributeTypeCode.Boolean:
       BooleanAttributeMetadata booleanAttribute = (BooleanAttributeMetadata)am;
       //Labels will not be included if they aren't new
       if (booleanAttribute.OptionSet.FalseOption.Label.UserLocalizedLabel != null)
       {
        changes.Add(new OptionSetOption(
        (Guid)booleanAttribute.OptionSet.MetadataId,
        0, 
        booleanAttribute.OptionSet.FalseOption.Label.UserLocalizedLabel.Label)
        );
       }
       //Labels will not be included if they aren't new
       if (booleanAttribute.OptionSet.TrueOption.Label.UserLocalizedLabel != null)
       {
        changes.Add(new OptionSetOption(
        (Guid)booleanAttribute.OptionSet.MetadataId,
        1, 
        booleanAttribute.OptionSet.TrueOption.Label.UserLocalizedLabel.Label));
       }
       break;
      default:
       EnumAttributeMetadata optionsetAttribute = (EnumAttributeMetadata)am;
       foreach (OptionMetadata option in optionsetAttribute.OptionSet.Options)
       {
        //Labels will not be included if they aren't new
        if (option.Label.UserLocalizedLabel != null)
        {
         changes.Add(new OptionSetOption(
          (Guid)optionsetAttribute.OptionSet.MetadataId,
         (int)option.Value, 
         option.Label.UserLocalizedLabel.Label));
        }        
       }
       break;
     }
    }
   }

   _optionLabelList.AddRange(changes);

   if (showChanges)
   {

    if (changes.Count > 0)
    {
     Console.WriteLine("{0} option labels for {1} entities were added to the cache.", changes.Count, entityMetadataCollection.Count);
     Console.WriteLine("{0} Option Labels cached", _optionLabelList.Count);
    }
    else
    { Console.WriteLine("No option labels were added to the cache."); }

   }
  }
Example #29
0
        public void GenerateClassFile(EntityMetadataCollection entityMetaDataCollection)
        {
            var w = new CodeWriter.CodeWriter(CodeWriterSettings.CSharpDefault);

            w._("using System;");
            w._("using System.Collections.Generic;");
            w._("using System.Linq;");
            w._("using System.Text;");
            w._("using System.Threading.Tasks;");
            w._("using Microsoft.Xrm.Sdk;");
            w._("");

            using (w.B("namespace Xrm"))
            {
                foreach (EntityMetadata entityMetaData in entityMetaDataCollection)
                {
                    using (w.B("public class " + entityMetaData.LogicalName + ": Entity"))
                    {
                        var attributes = entityMetaData.Attributes.Where(filter => filter.AttributeType.ToString() != "Virtual").ToList();
                        foreach (var att in attributes)
                        {
                            w._("public " + GetAttributeTypeName(att.AttributeType.ToString()) + " " + att.LogicalName + "{ get; set;}");
                        }
                        using (w.B("public Entity ToEntity()"))
                        {
                            w._("Entity ent = new Entity(this.GetType().Name);");

                            using (w.B("try"))
                            {
                                using (w.B("foreach (var att in this.GetType().GetProperties())"))
                                {
                                    using (w.B("if (att.Name != \"KeyAttributes\" && att.Name != \"Item\" && att.Name  != \"ExtensionData\" && att.Name != \"entityimageid\" && att.Name != \"Attributes\" && att.Name != \"FormattedValues\" && att.Name != \"RelatedEntities\")"))
                                    {
                                        using (w.B("if (att.GetValue(this) != null)"))
                                        {
                                            using (w.B("if (att.GetValue(this).GetType().Name != \"Guid\")"))
                                            {
                                                w._("ent[att.Name] = att.GetValue(this);");
                                            }
                                            using (w.B("else if(att.GetValue(this).GetType().Name == \"Guid\" && (Guid)att.GetValue(this) != Guid.Empty)"))
                                            {
                                                w._("ent[att.Name] = att.GetValue(this);");
                                            }
                                        }
                                    }
                                }
                            }
                            using (w.B("catch (Exception ex)"))
                            {
                                w._("throw new Exception(ex.Message);");
                            }
                        }
                        using (w.B("public string ToJsonString()"))
                        {
                            w._("string returnString = string.Empty;");
                            w._("returnString = new JavaScriptSerializer().Serialize(this);");
                            w._("return returnString;");
                        }
                    }
                }
            }
            string executableLocation = Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location);
            string csLocation = Path.Combine(executableLocation, "Xrm.cs");

            File.WriteAllText(csLocation, w.ToString());
            Console.WriteLine(csLocation);
        }
Example #30
0
        public FetchXMLDialog(IOrganizationService service, Settings settings, EntityMetadata selectedEntity, EntityMetadataCollection entities)
            : this()
        {
            this._service        = service;
            this._selectedEntity = selectedEntity;

            Task.Run(() => LoadSystemViews(selectedEntity));
            Task.Run(() => LoadUserViews(selectedEntity));
        }
Example #31
0
 public RetrieveMetadataChangesRequestExecutor(EntityMetadataCollection entityMetadata)
 {
     this.entityMetadata = entityMetadata;
 }