Пример #1
0
        public void LoadEntities()
        {
            // Loads listview header column for entities
            ListViewColumnHelper.AddColumnsHeader(entityListView, typeof(EntityMetadataInfo), ListViewColumnsSettings.EntityFirstColumns, lvcSettings.EntitySelectedAttributes, ListViewColumnsSettings.EntityAttributesToIgnore);

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading Entities...",
                Work = (bw, e) =>
                {
                    // Search for all entities metadata
                    var request = new RetrieveAllEntitiesRequest { EntityFilters = EntityFilters.Entity };
                    var response = (RetrieveAllEntitiesResponse)Service.Execute(request);

                    currentAllMetadata = response.EntityMetadata;

                    // return listview items
                    e.Result = BuildEntityItems(currentAllMetadata.ToList());
                },
                PostWorkCallBack = e =>
                {
                    entityListView.Items.Clear();
                    // Add listview items to listview
                    entityListView.Items.AddRange(((List<ListViewItem>)e.Result).ToArray());
                }
            });
        }
        public List<RibbonItem> GetListOfRibbonItems()
        {
            List<RibbonItem> ribbonItems = new List<RibbonItem>();
            // This statement is required to enable early-bound type support.
            _serviceProxy.EnableProxyTypes();
            // First build the system entities
            String[] entitiesWithRibbons = {"account", "activitymimeattachment","activitypointer","appointment",
                                                "bulkoperation","campaign","campaignactivity","campaignresponse",
                                                "competitor","connection","contact","contract","contractdetail",
                                                "customeraddress","discount","discounttype","email","fax","goal",
                                                "importfile","incident","invoice","invoicedetail","kbarticle",
                                                "kbarticlecomment","lead","letter","list","listmember", "metric",
                                                "opportunity","opportunityproduct","phonecall","pricelevel","product",
                                                "productpricelevel","queueitem","quote","quotedetail",
                                                "recurringappointmentmaster","report","salesliterature","salesorder",
                                                "salesorderdetail","service","serviceappointment","sharepointdocumentlocation",
                                                "sharepointsite","systemuser","task","team","territory","uom","uomschedule",
                                                "userquery"};

            foreach (String entity in entitiesWithRibbons) {
                ribbonItems.Add(new RibbonItem { EntityName = entity, IsSystemEntity = true });
            }

            // Next add the custom entities
            RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity };
            RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer);

            foreach (EntityMetadata em in resp.EntityMetadata) {
                if (em.IsCustomEntity == true && em.IsIntersect == false)
                    ribbonItems.Add(new RibbonItem { EntityName = em.LogicalName, IsSystemEntity = false });
            }

            return ribbonItems;
        }
Пример #3
0
        public void Find()
        {
            var request = new RetrieveAllEntitiesRequest {EntityFilters = EntityFilters.Entity | EntityFilters.Attributes};
            var response = (RetrieveAllEntitiesResponse) service.Execute(request);

            foreach (var emd in response.EntityMetadata.Where(x =>(x.IsCustomizable.Value || x.IsManaged.Value == false) && x.DisplayName.UserLocalizedLabel != null))
            {
                LoadScripts(emd);
                LoadRibbonCommands(emd);
            }
        }
Пример #4
0
        /// <summary>
        /// Gets all entities metadata with specified informations
        /// </summary>
        /// <param name="service">Organization service</param>
        /// <param name="filters">Information to retrieve</param>
        /// <returns>List of entities metadata</returns>
        public static List<EntityMetadata> GetEntitiesMetadata(IOrganizationService service, EntityFilters filters)
        {
            var request = new RetrieveAllEntitiesRequest
            {
                EntityFilters = filters
            };

            var response = (RetrieveAllEntitiesResponse)service.Execute(request);

            return response.EntityMetadata.ToList();
        }
Пример #5
0
        /// <summary>
        /// Gets the list of entities metadata (only Entity Items)
        /// </summary>
        /// <returns>List of entities metadata</returns>
        public static List<EntityMetadata> RetrieveEntities(IOrganizationService oService)
        {
            var request = new RetrieveAllEntitiesRequest
            {
                EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
            };

            var response = (RetrieveAllEntitiesResponse)oService.Execute(request);

            return response.EntityMetadata.ToList();
        }
Пример #6
0
        public List<EntityMetadata> GetEntitiesWithPrivileges()
        {
            var request = new RetrieveAllEntitiesRequest
                              {
                                  EntityFilters =
                                      EntityFilters.Entity | EntityFilters.Privileges
                              };
            var response = (RetrieveAllEntitiesResponse) service.Execute(request);

            return response.EntityMetadata.ToList();
        }
Пример #7
0
        public void LoadCrmItems()
        {
            EnableControls(false);

            WorkAsync("Loading Entities...",
                (bw, e) =>
                {
                    // Recherche des métadonnées
                    entityCache = new List<EntityMetadata>();
                    webResourcesHtmlCache = new List<Entity>();

                    var request = new RetrieveAllEntitiesRequest
                    {
                        EntityFilters = EntityFilters.Entity
                    };

                    var response = (RetrieveAllEntitiesResponse)Service.Execute(request);

                    foreach (var emd in response.EntityMetadata)
                    {
                        entityCache.Add(emd);
                    }
                    // Fin Recherche des métadonnées

                    bw.ReportProgress(0, "Loading web resources...");
                    // Rercherche des images

                    webResourcesImageCache = new List<Entity>();

                    var wrQuery = new QueryExpression("webresource");
                    wrQuery.Criteria.AddCondition("webresourcetype", ConditionOperator.In, new object[] { 2, 5, 6, 7 });
                    wrQuery.ColumnSet.AllColumns = true;

                    EntityCollection results = Service.RetrieveMultiple(wrQuery);

                    foreach (Entity webresource in results.Entities)
                    {
                        if (webresource.GetAttributeValue<OptionSetValue>("webresourcetype").Value == 2)
                        {
                            webResourcesHtmlCache.Add(webresource);
                        }
                        else
                        {
                            webResourcesImageCache.Add(webresource);
                        }
                    }
                },
                e =>
                {
                    DisplaySiteMap();
                    EnableControls(true);
                },
                e => SetWorkingMessage(e.UserState.ToString()));
        }
Пример #8
0
        /// <summary>
        /// 全てのエンティティの名前と表示名を取得します。
        /// </summary>
        /// <returns></returns>
        public EntityMetadata[] getAllEntity()
        {
            RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
            {
                EntityFilters = EntityFilters.Entity,
                RetrieveAsIfPublished = true
            };
            RetrieveAllEntitiesResponse entityResponse = (RetrieveAllEntitiesResponse)_service.Execute(request);

            return entityResponse.EntityMetadata;
        }
Пример #9
0
        /// <summary>
        /// Recupere la liste des EntityMetadata presente dans la CRM
        /// </summary>
        /// <param name="service">CRM Service</param>
        /// <returns>Liste des entites retrouvees</returns>
        public static List<EntityMetadata> GetEntitiesList(IOrganizationService service)
        {
            var req = new RetrieveAllEntitiesRequest
            {
                EntityFilters = EntityFilters.Entity
            };

            var resp = (RetrieveAllEntitiesResponse)service.Execute(req);
            //resp.EntityMetadata[0].icon

            return resp.EntityMetadata.Where(ent => ent.IsCustomEntity != null && (ent.DisplayName.UserLocalizedLabel != null && ent.IsCustomEntity.Value)).ToList();
        }
        public OrganizationData(IOrganizationService orgService)
        {
            var optionSetRequest = new RetrieveAllOptionSetsRequest();
            var entityRequest = new RetrieveAllEntitiesRequest
            {
                EntityFilters = EntityFilters.Entity | EntityFilters.Attributes,
                RetrieveAsIfPublished = false
            };

            OptionSets = ((RetrieveAllOptionSetsResponse)orgService.Execute(optionSetRequest))
                .OptionSetMetadata.OrderBy(o => o.Name).ToArray();

            Entities = ((RetrieveAllEntitiesResponse)orgService.Execute(entityRequest))
                .EntityMetadata.OrderBy(e => e.LogicalName).ToArray();
        }
Пример #11
0
        /// <summary>
        /// Get forms
        /// </summary>
        /// <param name="service">Microsoft Dynamics CRM organization service</param>
        /// <param name="worker"></param>
        /// <returns>List of forms</returns>
        public static IEnumerable<CrmForm> GetForms(IOrganizationService service, BackgroundWorker worker = null)
        {
            if (worker != null && worker.WorkerReportsProgress)
            {
                worker.ReportProgress(0, "Retrieving entities metadata...");
            }

            var request = new RetrieveAllEntitiesRequest { EntityFilters = EntityFilters.Entity };
            var response = (RetrieveAllEntitiesResponse)service.Execute(request);
            entitiesMetadatas = response.EntityMetadata;

            if (worker != null && worker.WorkerReportsProgress)
            {
                worker.ReportProgress(0, "Retrieving forms...");
            }

            var qe = new QueryExpression("systemform")
            {
                ColumnSet = new ColumnSet(new[] { "name", "formxml", "objecttypecode" }),
                Criteria = new FilterExpression
                {
                    Filters =
                    {
                        new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression("type", ConditionOperator.Equal, 2)
                            }
                        },
                        new FilterExpression
                        {
                            FilterOperator = LogicalOperator.Or,
                            Conditions =
                            {
                                new ConditionExpression("iscustomizable", ConditionOperator.Equal, true),
                                new ConditionExpression("ismanaged", ConditionOperator.Equal, false)
                            }
                        }
                    }
                }
            };

            return service.RetrieveMultiple(qe).Entities.Select(e => new CrmForm(e));
        }
Пример #12
0
        /// <summary>
        /// Gets the list of entities metadata (only Entity Items)
        /// </summary>
        /// <returns>List of entities metadata</returns>
        public static List<EntityMetadata> RetrieveEntities(IOrganizationService oService)
        {
            List<EntityMetadata> entities = new List<EntityMetadata>();

            RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest
                                                     {
                                                         EntityFilters = EntityFilters.Entity
                                                     };

            RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)oService.Execute(request);

            foreach (EntityMetadata emd in response.EntityMetadata)
            {
                if (emd.DisplayName.UserLocalizedLabel != null && (emd.IsCustomizable.Value || emd.IsManaged.Value == false))
                {
                    entities.Add(emd);
                }
            }

            return entities;
        }
Пример #13
0
        /// <summary>
        /// Downloads the env structure.
        /// </summary>
        /// <param name="connectionName">Name of the connection.</param>
        /// <returns></returns>
        private List<List<string>> downloadEnvStructure(string connectionName)
        {
            try
            {
                toolStripStatusLabel1.Text = "Loading entities from source. Please wait...";
                Application.DoEvents();
                this.entitiesNames = new List<List<string>>();
                MSCRMConnection connection = cm.getConnection(connectionName);
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters = EntityFilters.Entity,
                    RetrieveAsIfPublished = true
                };

                // Retrieve the MetaData.
                RetrieveAllEntitiesResponse AllEntitiesResponse = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                IOrderedEnumerable<EntityMetadata> EMD = AllEntitiesResponse.EntityMetadata.OrderBy(ee => ee.LogicalName);

                foreach (EntityMetadata currentEntity in EMD)
                {
                    if (currentEntity.IsIntersect.Value == false && currentEntity.IsValidForAdvancedFind.Value)
                    {
                        entitiesNames.Add(new List<string> { currentEntity.LogicalName, currentEntity.PrimaryIdAttribute });
                    }
                }

                WriteEnvStructure(connectionName, entitiesNames);
                toolStripStatusLabel1.Text = "Entities loaded from source.";
                return entitiesNames;
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                toolStripStatusLabel1.Text = "Error.";
                MessageBox.Show("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                toolStripStatusLabel1.Text = "Error.";
                if (ex.InnerException != null)
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("Error:" + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return null;
        }
Пример #14
0
        private static void Initialize()
        {
            const string        fetchXml      = "__fetchXml__";
            const string        schemaName    = "__schemaName__";
            const string        entityName    = "__entityName__";
            const string        logicalName   = "__logicalName__";
            const string        attributeName = "__attributeName__";
            const EntityFilters filters       = EntityFilters.All;
            var id = new Guid("ffffffff-ffff-ffff-ffff-ffffffffffff");

            var retrieveRequest = new RetrieveRequest {
                ColumnSet = new ColumnSet(true), Target = new EntityReference(logicalName, id)
            };

            _serializedRetrieveRequestFormat = SerializeForFormat(retrieveRequest)
                                               .Replace(logicalName, @"{0}")
                                               .Replace(id.ToString(), @"{1}");

            var relationship = new Relationship(schemaName)
            {
                PrimaryEntityRole = EntityRole.Referencing
            };
            var query = new RelationshipQueryCollection {
                { relationship, new QueryExpression(entityName)
                  {
                      ColumnSet = new ColumnSet(true)
                  } }
            };
            var retrieveRequestWithRelatedQuery = new RetrieveRequest {
                ColumnSet = new ColumnSet(), Target = new EntityReference(logicalName, id), RelatedEntitiesQuery = query
            };

            _serializedRetrieveRequestWithRelatedQueryFormat = SerializeForFormat(retrieveRequestWithRelatedQuery)
                                                               .Replace(logicalName, @"{0}")
                                                               .Replace(id.ToString(), @"{1}")
                                                               .Replace(schemaName, @"{2}")
                                                               .Replace(@"""PrimaryEntityRole"":0", @"""PrimaryEntityRole"":{3}")
                                                               .Replace(entityName, @"{4}");

            var retrieveAllEntitiesRequest = new RetrieveAllEntitiesRequest {
                EntityFilters = filters, RetrieveAsIfPublished = true
            };

            _serializedRetrieveAllEntitiesRequestFormat = SerializeForFormat(retrieveAllEntitiesRequest)
                                                          .Replace(((int)filters).ToString(), @"{0}")
                                                          .Replace("true", @"{1}");

            var retrieveEntityRequest = new RetrieveEntityRequest {
                EntityFilters = filters, LogicalName = logicalName, RetrieveAsIfPublished = true
            };

            _serializedRetrieveEntityRequestFormat = SerializeForFormat(retrieveEntityRequest)
                                                     .Replace(((int)filters).ToString(), @"{0}")
                                                     .Replace(logicalName, @"{1}")
                                                     .Replace("true", @"{2}");

            var retrieveMultipleRequest = new RetrieveMultipleRequest {
                Query = new QueryExpression(logicalName)
                {
                    Distinct = true
                }
            };

            _serializedRetrieveMultipleRequestFormat = SerializeForFormat(retrieveMultipleRequest)
                                                       .Replace(logicalName, @"{0}")
                                                       .Replace("true", @"{1}");

            var retrieveMultipleFetchExpressionRequest = new RetrieveMultipleRequest {
                Query = new FetchExpression(fetchXml)
            };

            _serializedRetrieveMultipleFetchExpressionFormat = SerializeForFormat(retrieveMultipleFetchExpressionRequest)
                                                               .Replace(fetchXml, @"{0}");

            var retrieveRelationshipRequest = new RetrieveRelationshipRequest {
                Name = logicalName, RetrieveAsIfPublished = true
            };

            _serializedRetrieveRelationshipRequestFormat = SerializeForFormat(retrieveRelationshipRequest)
                                                           .Replace(logicalName, @"{0}")
                                                           .Replace("true", @"{1}");

            var retrieveLocLabelsRequest = new RetrieveLocLabelsRequest
            {
                EntityMoniker      = new EntityReference(logicalName, id),
                AttributeName      = attributeName,
                IncludeUnpublished = true
            };

            _serializedRetrieveLocLabelsRequestFormat =
                SerializeForFormat(retrieveLocLabelsRequest)
                .Replace(logicalName, @"{0}")
                .Replace(id.ToString(), @"{1}")
                .Replace(attributeName, @"{2}")
                .Replace("true", @"{3}");

            var retrieveProvLangsRequest = new RetrieveProvisionedLanguagesRequest();

            _serializedRetrieveProvisionedLanguagesRequestFormat = SerializeForFormat(retrieveProvLangsRequest);
        }
Пример #15
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Privileges,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Defaulted setting is to false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("EntityPrivileges.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());


                                metadataWriter.WriteStartElement("Privileges");

                                foreach (SecurityPrivilegeMetadata privilege in currentEntity.Privileges)
                                {
                                    metadataWriter.WriteStartElement("Privilege");
                                    metadataWriter.WriteElementString("PrivilegeName", privilege.Name.ToString());
                                    metadataWriter.WriteElementString("Id", privilege.PrivilegeId.ToString());
                                    metadataWriter.WriteElementString("Type", privilege.PrivilegeType.ToString());
                                    metadataWriter.WriteElementString("CanBeBasic", privilege.CanBeBasic.ToString());
                                    metadataWriter.WriteElementString("CanBeDeep", privilege.CanBeDeep.ToString());
                                    metadataWriter.WriteElementString("CanBeGlobal", privilege.CanBeGlobal.ToString());
                                    metadataWriter.WriteElementString("CanBeLocal", privilege.CanBeLocal.ToString());

                                    metadataWriter.WriteEndElement();
                                }

                                metadataWriter.WriteEndElement();


                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    Console.WriteLine("Done.");
                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Пример #16
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.
                    String filename = String.Concat("AllAttributeDesc.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }
                                if (currentEntity.IsIntersect.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsIntersect", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsIntersect", "no");
                                }



                                #region Attributes


                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("LogicalName", currentAttribute.LogicalName);
                                        // Write the Description if it is set.
                                        if (currentAttribute.Description.UserLocalizedLabel != null)
                                        {
                                            metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocalizedLabel.Label.ToString());
                                        }

                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());
                                        if (currentAttribute.DisplayName.UserLocalizedLabel != null)
                                        {
                                            metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocalizedLabel.Label.ToString());
                                        }
                                        if (currentAttribute.SchemaName != null)
                                        {
                                            metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName.ToString());
                                        }
                                        if (currentAttribute.IntroducedVersion != null)
                                        {
                                            metadataWriter.WriteElementString("IntroducedVersion", currentAttribute.IntroducedVersion.ToString());
                                        }
                                        if (currentAttribute.DeprecatedVersion != null)
                                        {
                                            metadataWriter.WriteElementString("DeprecatedVersion", currentAttribute.DeprecatedVersion.ToString());
                                        }
                                        if (currentAttribute.IsCustomAttribute != null)
                                        {
                                            metadataWriter.WriteElementString("IsCustomAttribute", currentAttribute.IsCustomAttribute.Value.ToString());
                                        }
                                        if (currentAttribute.IsCustomizable != null)
                                        {
                                            metadataWriter.WriteElementString("IsCustomizable", currentAttribute.IsCustomizable.Value.ToString());
                                        }
                                        if (currentAttribute.RequiredLevel != null)
                                        {
                                            metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForCreate != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForCreate", currentAttribute.IsValidForCreate.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForRead != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForRead", currentAttribute.IsValidForRead.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForUpdate != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForUpdate", currentAttribute.IsValidForUpdate.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForCreate != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForCreate", currentAttribute.CanBeSecuredForCreate.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForRead != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForRead", currentAttribute.CanBeSecuredForRead.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForUpdate != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForUpdate", currentAttribute.CanBeSecuredForUpdate.Value.ToString());
                                        }
                                        if (currentAttribute.IsAuditEnabled != null)
                                        {
                                            metadataWriter.WriteElementString("IsAuditEnabled", currentAttribute.IsAuditEnabled.Value.ToString());
                                        }
                                        if (currentAttribute.IsManaged != null)
                                        {
                                            metadataWriter.WriteElementString("IsManaged", currentAttribute.IsManaged.Value.ToString());
                                        }
                                        if (currentAttribute.IsPrimaryId != null)
                                        {
                                            metadataWriter.WriteElementString("IsPrimaryId", currentAttribute.IsPrimaryId.Value.ToString());
                                        }
                                        if (currentAttribute.IsPrimaryName != null)
                                        {
                                            metadataWriter.WriteElementString("IsPrimaryName", currentAttribute.IsPrimaryName.Value.ToString());
                                        }
                                        if (currentAttribute.IsRenameable != null)
                                        {
                                            metadataWriter.WriteElementString("IsRenameable", currentAttribute.IsRenameable.Value.ToString());
                                        }
                                        if (currentAttribute.IsSecured != null)
                                        {
                                            metadataWriter.WriteElementString("IsSecured", currentAttribute.IsSecured.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForAdvancedFind != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForAdvancedFind", currentAttribute.IsValidForAdvancedFind.Value.ToString());
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion Attributes

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    Console.WriteLine("Done.");
                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Пример #17
0
 void worker_DoWork(object sender, DoWorkEventArgs e)
 {
     var request = new RetrieveAllEntitiesRequest{EntityFilters = EntityFilters.All};
     var response = (RetrieveAllEntitiesResponse) service.Execute(request);
     e.Result = response.EntityMetadata.ToList();
 }
        private void buttonLoadEntitiesFromSource_Click(object sender, EventArgs e)
        {
            DialogResult dResTest = MessageBox.Show("Loading the structure may take some time. The application will become unresponsive during this time.\n\nAre you sure you want to load the structure from the Source?", "Confirm Structure Load", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dResTest == DialogResult.No)
            {
                return;
            }

            setStateAllControls(false);
            try
            {
                toolStripStatusLabel1.Text = "Loading MetaData from source. Please wait...";
                Application.DoEvents();
                MSCRMConnection connection = cm.MSCRMConnections[comboBoxSource.SelectedIndex];
                if (_serviceProxy == null)
                    _serviceProxy = cm.connect(connection);

                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships,
                    RetrieveAsIfPublished = true
                };

                //Make sure the EntityExport folder exists
                if (!Directory.Exists(EntitesStructureFolderName))
                    Directory.CreateDirectory(EntitesStructureFolderName);

                // Retrieve the MetaData.
                environmentStructure = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                string structureFileName = EntitesStructureFolderName + "\\" + comboBoxSource.SelectedItem + ".xml";
                WriteMetadata(structureFileName, environmentStructure);
                DateTime structureRefreshedOn = File.GetLastWriteTime(structureFileName);
                labelStructureLoadedDate.Text = structureRefreshedOn.ToString();
                IOrderedEnumerable<EntityMetadata> EMD = environmentStructure.EntityMetadata.OrderBy(em => em.LogicalName);
                foreach (EntityMetadata currentEntity in EMD)
                {
                    if (currentEntity.IsIntersect.Value == false)
                    {
                        checkedListBoxEntities.Items.AddRange(new object[] { currentEntity.LogicalName });
                    }
                }
                toolStripStatusLabel1.Text = "MetaData loaded from source.";
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                toolStripStatusLabel1.Text = "Error.";
                MessageBox.Show("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                toolStripStatusLabel1.Text = "Error.";
                if (ex.InnerException != null)
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("Error:" + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            setStateAllControls(true);
            buttonOpenInExcel.Visible = false;
        }
Пример #19
0
        /// <summary>
        /// Main entry point for the application.
        /// </summary>
        /// <param name="CmdArgs">Entities to place on the diagram</param>
        public static int Main(string[] args)
        {
            String filename = String.Empty;
            VisioApi.Application application;
            VisioApi.Document document;
            DiagramBuilder builder = new DiagramBuilder();

            try
            {
                // Obtain the target organization's Web address and client logon 
                // credentials from the user.
                ServerConnection serverConnect = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(config))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Load Visio and create a new document.
                    application = new VisioApi.Application();
                    application.Visible = false; // Not showing the UI increases rendering speed  
                    builder.VersionName = application.Version;
                    document = application.Documents.Add(String.Empty);
                    builder._application = application;
                    builder._document = document;

                    // Load the metadata.
                    Console.WriteLine("Loading Metadata...");
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships,
                        RetrieveAsIfPublished = true,

                    };
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                    builder._metadataResponse = response;

                    // Diagram all entities if given no command-line parameters, otherwise diagram
                    // those entered as command-line parameters.
                    if (args.Length < 1)
                    {
                        ArrayList entities = new ArrayList();

                        foreach (EntityMetadata entity in response.EntityMetadata)
                        {
                            // Only draw an entity if it does not exist in the excluded entity table.
                            if (!_excludedEntityTable.ContainsKey(entity.LogicalName.GetHashCode()))
                            {
                                entities.Add(entity.LogicalName);
                            }
                            else
                            {
                                Console.WriteLine("Excluding entity: {0}", entity.LogicalName);
                            }
                        }

                        builder.BuildDiagram((string[])entities.ToArray(typeof(string)), "All Entities");
                        filename = "AllEntities.vsd";
                    }
                    else
                    {
                        builder.BuildDiagram(args, String.Join(", ", args));
                        filename = String.Concat(args[0], ".vsd");
                    }

                    // Save the diagram in the current directory using the name of the first
                    // entity argument or "AllEntities" if none were given. Close the Visio application. 
                    document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                    application.Quit();
                }
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                    null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                    null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> fe
                        = ex.InnerException
                        as FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                            null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                //Console.WriteLine("Rendering complete.");
                Console.WriteLine("Rendering complete.  Press any key to continue.");
                Console.ReadLine();
            }
            return 0;
        }
        public CRMEntityList CRMGetAllEntities(CRMEntityList EntityList)
        {
            OrganizationServiceProxy _serviceProxy;
            List<CRMEntityMetadata> Results = new List<CRMEntityMetadata>();

            using (_serviceProxy = GetCRMConnection())
            {
                try
                {
                    RetrieveAllEntitiesRequest retrieveAllEntitiesRequest = new RetrieveAllEntitiesRequest
                    {
                        EntityFilters = EntityFilters.Entity,
                    };

                    RetrieveAllEntitiesResponse retrieveAllEntitiesResponse = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(retrieveAllEntitiesRequest);
                    
                    foreach (EntityMetadata Metadata in retrieveAllEntitiesResponse.EntityMetadata)
                    {
                        try
                        {
                            CRMEntityMetadata Entity = new CRMEntityMetadata();
                            Entity.DisplayName = Metadata.DisplayName.UserLocalizedLabel != null ? Metadata.DisplayName.UserLocalizedLabel.Label.ToString() : Metadata.LogicalName;
                            Entity.ObjectTypeCode = Metadata.ObjectTypeCode.HasValue ? Metadata.ObjectTypeCode.Value : 0;
                            Entity.LogicalName = Metadata.LogicalName;
                            Entity.PrimaryIdAttribute = Metadata.PrimaryIdAttribute;
                            Entity.PrimaryNameAttribute = Metadata.PrimaryNameAttribute;
                            Entity.IsCustomEntity = Metadata.IsCustomEntity.HasValue ? Metadata.IsCustomEntity.Value : false;
                            Entity.Attributes = new List<CRMAttribute>();
                            Results.Add(Entity);
                        }
                        catch (Exception e)
                        {
                            throw;
                        }
                    }
                    //EntityList.Entities = new List<CRMEntityMetadata>();
                    EntityList.Entities = Results;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            return EntityList;
        }
Пример #21
0
        /// <summary>
        /// </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();

                    //<snippetDumpEntityPrivileges1>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Privileges,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("EntityPrivileges.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());


                                metadataWriter.WriteStartElement("Privileges");

                                foreach (SecurityPrivilegeMetadata privilege in currentEntity.Privileges)
                                {
                                    metadataWriter.WriteStartElement("Privilege");
                                    metadataWriter.WriteElementString("PrivilegeName", privilege.Name.ToString());
                                    metadataWriter.WriteElementString("Id", privilege.PrivilegeId.ToString());
                                    metadataWriter.WriteElementString("Type", privilege.PrivilegeType.ToString());
                                    metadataWriter.WriteElementString("CanBeBasic", privilege.CanBeBasic.ToString());
                                    metadataWriter.WriteElementString("CanBeDeep", privilege.CanBeDeep.ToString());
                                    metadataWriter.WriteElementString("CanBeGlobal", privilege.CanBeGlobal.ToString());
                                    metadataWriter.WriteElementString("CanBeLocal", privilege.CanBeLocal.ToString());

                                    metadataWriter.WriteEndElement();
                                }

                                metadataWriter.WriteEndElement();


                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");
                    //</snippetDumpEntityPrivileges1>

                    //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;
            }
        }
Пример #22
0
        /// <summary>
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetDumpRelationshipInfo1>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Relationships,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("RelationshipInfo.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);

                                // Start OneToManyRelationships Node
                                metadataWriter.WriteStartElement("OneToManyRelationships");

                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.OneToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("OtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("OtoM_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("OtoM_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End OneToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToManyRelationships Node
                                metadataWriter.WriteStartElement("ManyToManyRelationships");


                                foreach (ManyToManyRelationshipMetadata currentRelationship in currentEntity.ManyToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoM_Entity1", currentRelationship.Entity1LogicalName);
                                    metadataWriter.WriteElementString("MtoM_Entity2", currentRelationship.Entity2LogicalName);
                                    metadataWriter.WriteElementString("IntersectEntity", currentRelationship.IntersectEntityName);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToOneRelationships Node
                                metadataWriter.WriteStartElement("ManyToOneRelationships");


                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.ManyToOneRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoO_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoO_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("MtoO_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToOneRelationships Node
                                metadataWriter.WriteEndElement();

                                // End Relationships Node
                                // metadataWriter.WriteEndElement();



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");
                    //</snippetDumpRelationshipInfo1>

                    //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,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </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 export folder for ribbon xml files if not already exist.
                    if (!Directory.Exists(exportFolder))
                    {
                        Directory.CreateDirectory(exportFolder);
                    }

                    //Retrieve the Appliation Ribbon
                    RetrieveApplicationRibbonRequest  appribReq  = new RetrieveApplicationRibbonRequest();
                    RetrieveApplicationRibbonResponse appribResp = (RetrieveApplicationRibbonResponse)_serviceProxy.Execute(appribReq);

                    System.String applicationRibbonPath = Path.GetFullPath(exportFolder + "\\applicationRibbon.xml");
                    File.WriteAllBytes(applicationRibbonPath, unzipRibbon(appribResp.CompressedApplicationRibbonXml));
                    //Write the path where the file has been saved.
                    Console.WriteLine(applicationRibbonPath);
                    //Retrieve system Entity Ribbons
                    RetrieveEntityRibbonRequest entRibReq = new RetrieveEntityRibbonRequest()
                    {
                        RibbonLocationFilter = RibbonLocationFilters.All
                    };

                    foreach (System.String entityName in entitiesWithRibbons)
                    {
                        entRibReq.EntityName = entityName;
                        RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                        System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml");
                        File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                        //Write the path where the file has been saved.
                        Console.WriteLine(entityRibbonPath);
                    }

                    //Check for custom entities
                    RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Entity
                    };

                    RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer);

                    foreach (EntityMetadata em in resp.EntityMetadata)
                    {
                        if (em.IsCustomEntity == true & amp; &amp; em.IsIntersect == false)
                        {
                            entRibReq.EntityName = em.LogicalName;
                            RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                            System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml");
                            File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                            //Write the path where the file has been saved.
                            Console.WriteLine(entityRibbonPath);
                        }
                    }
                }
            }

            // 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;
            }
        }
Пример #24
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </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
            {
                //<snippetExportRibbonXml1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //Create export folder for ribbon xml files if not already exist.
                    if (!Directory.Exists(exportFolder))
                    {
                        Directory.CreateDirectory(exportFolder);
                    }

                    //<snippetExportRibbonXml3>
                    //Retrieve the Appliation Ribbon
                    RetrieveApplicationRibbonRequest  appribReq  = new RetrieveApplicationRibbonRequest();
                    RetrieveApplicationRibbonResponse appribResp = (RetrieveApplicationRibbonResponse)_serviceProxy.Execute(appribReq);

                    System.String applicationRibbonPath = Path.GetFullPath(exportFolder + "\\applicationRibbon.xml");
                    File.WriteAllBytes(applicationRibbonPath, unzipRibbon(appribResp.CompressedApplicationRibbonXml));
                    //</snippetExportRibbonXml3>
                    //Write the path where the file has been saved.
                    Console.WriteLine(applicationRibbonPath);
                    //<snippetExportRibbonXml4>
                    //Retrieve system Entity Ribbons
                    RetrieveEntityRibbonRequest entRibReq = new RetrieveEntityRibbonRequest()
                    {
                        RibbonLocationFilter = RibbonLocationFilters.All
                    };

                    #region retrieval code

                    bool isDone = false;
                    while (!isDone)
                    {
                        Console.WriteLine("\nRetrieve all ribbons or specific ribbons? (a)ll/(s)pecific: ");
                        string input = Console.ReadLine();

                        if (input == "a")
                        {
                            foreach (System.String entityName in entitiesWithRibbons)
                            {
                                entRibReq.EntityName = entityName;
                                RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                                System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml");
                                File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                                //Write the path where the file has been saved.
                                Console.WriteLine(entityRibbonPath);
                            }

                            //</snippetExportRibbonXml4>

                            //<snippetExportRibbonXml5>
                            //Check for custom entities
                            RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest()
                            {
                                EntityFilters = EntityFilters.Entity
                            };

                            RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer);

                            foreach (EntityMetadata em in resp.EntityMetadata)
                            {
                                if (em.IsCustomEntity == true && em.IsIntersect == false)
                                {
                                    entRibReq.EntityName = em.LogicalName;
                                    RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                                    System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml");
                                    File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                                    //Write the path where the file has been saved.
                                    Console.WriteLine(entityRibbonPath);
                                }
                            }

                            isDone = true;
                        }
                        else if (input == "s")
                        {
                            // first do system entities
                            int i = 0;
                            foreach (System.String entityName in entitiesWithRibbons)
                            {
                                Console.WriteLine("[{0}] {1}", i++, entityName);
                            }
                            Console.WriteLine("Enter the numbers of the entities to download, separated by commas: ");
                            string   entityNums    = Console.ReadLine();
                            string[] entityNumsArr = entityNums.Split(new char[] { ',' });

                            foreach (string numStr in entityNumsArr)
                            {
                                int num;
                                if (Int32.TryParse(numStr, out num))
                                {
                                    if (num >= 0 && num < entitiesWithRibbons.Length)
                                    {
                                        string entityName = entitiesWithRibbons[num];
                                        entRibReq.EntityName = entityName;
                                        RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                                        System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml");
                                        File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                                        //Write the path where the file has been saved.
                                        Console.WriteLine(entityRibbonPath);
                                    }
                                    else
                                    {
                                        Console.WriteLine("No element index {0} in entitiesWithRibbons, skipping...", num);
                                    }
                                }
                            }

                            // next check for custom entities
                            RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest()
                            {
                                EntityFilters = EntityFilters.Entity
                            };
                            RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer);

                            i = 0;
                            foreach (EntityMetadata em in resp.EntityMetadata)
                            {
                                if (em.IsCustomEntity == true && em.IsIntersect == false)
                                {
                                    Console.WriteLine("[{0}] {1}", i, em.LogicalName);
                                }
                                i++;
                            }
                            Console.WriteLine("Enter the numbers of the entities to download, separated by commas: ");
                            entityNums    = Console.ReadLine();
                            entityNumsArr = entityNums.Split(new char[] { ',' });

                            //foreach (EntityMetadata em in resp.EntityMetadata)
                            foreach (string numStr in entityNumsArr)
                            {
                                int index;
                                if (Int32.TryParse(numStr, out index))
                                {
                                    if (index >= 0 && index < resp.EntityMetadata.Length)
                                    {
                                        EntityMetadata em = resp.EntityMetadata[index];
                                        if (em.IsCustomEntity == true && em.IsIntersect == false)
                                        {
                                            entRibReq.EntityName = em.LogicalName;
                                            RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                                            System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml");
                                            File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                                            //Write the path where the file has been saved.
                                            Console.WriteLine(entityRibbonPath);
                                        }
                                    }
                                }
                            }
                            Console.WriteLine("");


                            isDone = true;
                        }
                    }
                    #endregion
                }
                //</snippetExportRibbonXml5>
                //</snippetExportRibbonXml1>
            }

            // 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;
            }
        }
Пример #25
0
        private void ToolStripButtonLoadSiteMapFromDiskClick(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                Title  = "Select a Xml file representing a SiteMap",
                Filter = "Xml file (*.xml)|*.xml"
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                EnableControls(false);

                siteMapDoc = new XmlDocument();
                siteMapDoc.Load(ofd.FileName);

                if (siteMapDoc.DocumentElement.Name != "SiteMap" ||
                    siteMapDoc.DocumentElement.ChildNodes.Count > 0 &&
                    siteMapDoc.DocumentElement.ChildNodes[0].Name == "SiteMap")
                {
                    MessageBox.Show(this, "Invalid Xml: SiteMap Xml root must be SiteMap!", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                    tsbMainOpenSiteMap.Enabled = true;
                    toolStripButtonLoadSiteMapFromDisk.Enabled = true;
                }
                else
                {
                    if (Service != null && entityCache == null)
                    {
                        WorkAsync(new WorkAsyncInfo
                        {
                            Message = "Loading Entities...",
                            Work    = (bw, evt) =>
                            { // Recherche des métadonnées
                                entityCache           = new List <EntityMetadata>();
                                webResourcesHtmlCache = new List <Entity>();

                                var request = new RetrieveAllEntitiesRequest
                                {
                                    EntityFilters = EntityFilters.Entity
                                };

                                var response = (RetrieveAllEntitiesResponse)Service.Execute(request);

                                foreach (var emd in response.EntityMetadata)
                                {
                                    entityCache.Add(emd);
                                }
                                // Fin Recherche des métadonnées

                                bw.ReportProgress(0, "Loading web resources...");
                                // Rercherche des images

                                webResourcesImageCache = new List <Entity>();

                                var wrQuery = new QueryExpression("webresource");
                                wrQuery.Criteria.AddCondition("webresourcetype", ConditionOperator.In,
                                                              new object[] { 1, 5, 6, 7 });
                                wrQuery.ColumnSet.AllColumns = true;

                                EntityCollection results = Service.RetrieveMultiple(wrQuery);

                                foreach (Entity webresource in results.Entities)
                                {
                                    if (webresource.GetAttributeValue <OptionSetValue>("webresourcetype").Value == 1)
                                    {
                                        webResourcesHtmlCache.Add(webresource);
                                    }
                                    else
                                    {
                                        webResourcesImageCache.Add(webresource);
                                    }
                                }
                            },
                            PostWorkCallBack = evt =>
                            {
                                DisplaySiteMap();
                                EnableControls(true);
                            },
                            ProgressChanged = evt => { SetWorkingMessage(evt.UserState.ToString()); }
                        });
                    }
                    else
                    {
                        DisplaySiteMap();
                        EnableControls(true);
                    }
                }
            }
        }
Пример #26
0
        /// <summary>
        /// </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();

                    //<snippetDumpEntityInfo1>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                    

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
		    // To view this file, right click the file and choose open with Excel. 
		    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("EntityInfo.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());
                                metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString());
                                if (currentEntity.DisplayName.UserLocalizedLabel != null)
                                    metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label);
                                if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null)
                                    metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label);

                                metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString());
                                metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString());
                                metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString());
                                metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString());
                                metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString());

                                metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString());
                                //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString());

                                metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString());

                                metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString());
                                metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString());
                                metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString());
                                metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString());
                                metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString());

                                metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString());
                                if (currentEntity.IsEnabledForCharts != null)
                                    metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString());
                                metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString());
                                metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString());

                                metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString());
                                metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString());

                                metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString()); 
                                metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString());
                                metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString());

                                metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute);
                                metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute);
                                metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
                                metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName);
                                if (currentEntity.Description.UserLocalizedLabel != null)
                                    metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label);



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }




                   Console.WriteLine("Done.");
                    //</snippetDumpEntityInfo1>

                    //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;
            }
        }
Пример #27
0
 public List<EntityMetadata> GetAllEntityMetadata()
 {
     lock (LockObject)
     {
         if (!_loadedAllEntities)
         {
             var request = new RetrieveAllEntitiesRequest
             {
                 EntityFilters = EntityFilters.Entity,
             };
             var response = (RetrieveAllEntitiesResponse) Execute(request);
             _entityMetadata.Clear();
             _entityMetadata.AddRange(response.EntityMetadata);
             _loadedAllEntities = true;
         }
         return _entityMetadata;
     }
 }
Пример #28
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Demonstrate
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Relationships,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("RelationshipInfo.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);

                                // Start OneToManyRelationships Node
                                metadataWriter.WriteStartElement("OneToManyRelationships");

                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.OneToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("OtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("OtoM_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("OtoM_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End OneToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToManyRelationships Node
                                metadataWriter.WriteStartElement("ManyToManyRelationships");


                                foreach (ManyToManyRelationshipMetadata currentRelationship in currentEntity.ManyToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoM_Entity1", currentRelationship.Entity1LogicalName);
                                    metadataWriter.WriteElementString("MtoM_Entity2", currentRelationship.Entity2LogicalName);
                                    metadataWriter.WriteElementString("IntersectEntity", currentRelationship.IntersectEntityName);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToOneRelationships Node
                                metadataWriter.WriteStartElement("ManyToOneRelationships");


                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.ManyToOneRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoO_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoO_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("MtoO_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToOneRelationships Node
                                metadataWriter.WriteEndElement();

                                // End Relationships Node
                                // metadataWriter.WriteEndElement();



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");

                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        /// <summary>
        /// Downloads the env structure.
        /// </summary>
        /// <param name="connectionName">Name of the connection.</param>
        /// <returns>The Environment Structure</returns>
        public EnvStructure downloadEnvStructure(string connectionName)
        {
            try
            {
                MSCRMConnection connection = cm.getConnection(connectionName);
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                EnvStructure         es      = new EnvStructure();
                es.Entities = new List <EnvEntity>();

                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters         = EntityFilters.Attributes,
                    RetrieveAsIfPublished = true
                };

                // Retrieve the MetaData.
                RetrieveAllEntitiesResponse         AllEntitiesResponse = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                IOrderedEnumerable <EntityMetadata> EMD = AllEntitiesResponse.EntityMetadata.OrderBy(ee => ee.LogicalName);

                List <string> AdditionalEntities = new List <string> {
                    "duplicaterule",
                    "duplicaterulecondition",
                    "incidentresolution",
                    "kbarticlecomment",
                    "opportunityclose",
                    "orderclose",
                    "postcomment",
                    "postlike",
                    "quoteclose",
                    "subject",
                    "uom"
                };

                List <string> IgnoredEntities = new List <string> {
                    "activitypointer",
                    "asyncoperation",
                    "fieldsecurityprofile",
                    "importjob",
                    "pluginassembly",
                    "plugintype",
                    "processsession",
                    "recurringappointmentmaster",
                    "sdkmessage",
                    "sdkmessagefilter",
                    "sdkmessageprocessingstep",
                    "sdkmessageprocessingstepimage",
                    "sdkmessageprocessingstepsecureconfig",
                    "workflow"
                };

                List <string> IgnoredAttributes = new List <string> {
                    "importsequencenumber",
                    //"statuscode",
                    "timezoneruleversionnumber",
                    "utcconversiontimezonecode",
                    //"overriddencreatedon"//,
                    //"ownerid"
                };

                foreach (EntityMetadata currentEntity in EMD)
                {
                    if (currentEntity.IsIntersect.Value == false &&
                        IgnoredEntities.IndexOf(currentEntity.LogicalName) < 0 &&
                        (currentEntity.IsValidForAdvancedFind.Value || AdditionalEntities.IndexOf(currentEntity.LogicalName) >= 0)
                        )
                    {
                        EnvEntity ee = new EnvEntity();
                        ee.EntityName = currentEntity.LogicalName;
                        ee.Attributes = new List <string>();
                        IOrderedEnumerable <AttributeMetadata> AMD = currentEntity.Attributes.OrderBy(a => a.LogicalName);

                        foreach (AttributeMetadata currentAttribute in AMD)
                        {
                            // Only write out main attributes enabled for reading and creation, or the statecode
                            if ((((currentAttribute.AttributeOf == null) &&
                                  currentAttribute.IsValidForRead.Value &&
                                  currentAttribute.IsValidForCreate.Value &&
                                  IgnoredAttributes.IndexOf(currentAttribute.LogicalName) < 0) || currentAttribute.LogicalName.Equals("statecode")))
                            {
                                ee.Attributes.Add(currentAttribute.LogicalName);
                            }
                        }
                        //ee.Attributes.Add("statecode");
                        //Dont export entitites for which only the ID is retrieved
                        if (ee.Attributes.Count > 1)
                        {
                            es.Entities.Add(ee);
                        }
                    }
                }

                es.connectionName = connectionName;
                WriteEnvStructure(es);

                return(es);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #30
0
        public void GetAllEntity()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();



            Console.WriteLine("Starting Fetch Methods");
            DateTime startTime  = DateTime.Now;
            var      properties = new MetadataPropertiesExpression();

            properties.PropertyNames.AddRange("LogicalName", "DisplayName", "PrimaryIdAttribute", "PrimaryNameAttribute");

            //An entity query expression to combine the filter expressions and property expressions for the query.
            var entityQueryExpression = new EntityQueryExpression {
                Properties = properties,
            };

            //Retrieve the metadata for the query without a ClientVersionStamp
            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            List <string> NameList  = new List <string>();
            List <string> emptyList = new List <string>();

            foreach (EntityMetadata item in response.EntityMetadata)
            {
                string name = item.DisplayName.UserLocalizedLabel != null ? item.DisplayName.UserLocalizedLabel.Label : item.SchemaName;

                NameList.Add(name);

                if (string.IsNullOrEmpty(name))
                {
                    emptyList.Add(item.LogicalName);
                }
            }

            NameList.Sort();

            DateTime endTime = DateTime.Now;

            Console.WriteLine("Time Taken with entityQueryExpress Method is :" + (endTime - startTime).TotalSeconds);

            startTime = DateTime.Now;

            RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
            {
                EntityFilters         = EntityFilters.Entity,
                RetrieveAsIfPublished = true
            };

            // Retrieve the MetaData
            RetrieveAllEntitiesResponse response1 = (RetrieveAllEntitiesResponse)service.Execute(request);

            endTime = DateTime.Now;
            Console.WriteLine("Time Taken with RetrieveAllEntitiesRequest Method is :" + (endTime - startTime).TotalSeconds);

            foreach (EntityMetadata item in response1.EntityMetadata)
            {
                if (emptyList.Contains(item.LogicalName))
                {
                    Console.ReadLine();
                }
            }

            Console.ReadLine();
        }
Пример #31
0
 public virtual OrganizationResponse UseRetrieveAllEntitiesRequest(RetrieveAllEntitiesRequest retrieveAllEntitiesRequest)
 {
     return(new RetrieveAllEntitiesResponse {
         ["EntityMetadata"] = EntitiesMetadata.ToArray()
     });
 }
Пример #32
0
        private void menuLoadEntities_Click(object sender, EventArgs e)
        {
            List <Tuple <int, string, string> > data = new List <Tuple <int, string, string> >();

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading entities with auditing enabled...",
                Work    = (w, ev) =>
                {
                    RetrieveAllEntitiesRequest metaDataRequest = new RetrieveAllEntitiesRequest();
                    metaDataRequest.EntityFilters = EntityFilters.Attributes;

                    var metaDataResponse = (RetrieveAllEntitiesResponse)Service.Execute(metaDataRequest);

                    var entities = metaDataResponse.EntityMetadata;
                    foreach (var item in entities)
                    {
                        if (item.IsAuditEnabled.Value)
                        {
                            data.Add(new Tuple <int, string, string>(item.ObjectTypeCode.Value, item.DisplayName.UserLocalizedLabel.Label, item.PrimaryNameAttribute));
                            entityMetadataList.Add(item);
                        }
                    }

                    ev.Result = data.OrderBy(x => (x.Item2)).ToList();
                },
                ProgressChanged = ev =>
                {
                    // If progress has to be notified to user, use the following method:
                    SetWorkingMessage("Loading entities with auditing enabled...");
                },
                PostWorkCallBack = ev =>
                {
                    ddlEntities.DataSource    = ev.Result;
                    ddlEntities.DisplayMember = "Item2";
                    ddlEntities.ValueMember   = "Item1";
                },
                AsyncArgument = null,
                IsCancelable  = true,
                MessageWidth  = 340,
                MessageHeight = 150
            });

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading users...",
                Work    = (w, ev) =>
                {
                    List <KeyValuePair <Guid, string> > users = new List <KeyValuePair <Guid, string> >();

                    FetchExpression query = new FetchExpression(FetchXml.LicencedUsers);
                    var queryResult       = Service.RetrieveMultiple(query);
                    users.Add(new KeyValuePair <Guid, string>(Guid.Empty, "All Users"));
                    foreach (var item in queryResult.Entities)
                    {
                        users.Add(new KeyValuePair <Guid, string>(item.Id, item.Attributes["fullname"] != null ? item.Attributes["fullname"].ToString() : string.Empty));
                    }

                    ev.Result = users;
                },
                ProgressChanged = ev =>
                {
                    // If progress has to be notified to user, use the following method:
                    SetWorkingMessage("Loading users...");
                },
                PostWorkCallBack = ev =>
                {
                    ddlUsers.DataSource    = (List <KeyValuePair <Guid, string> >)ev.Result;
                    ddlUsers.DisplayMember = "Value";
                    ddlUsers.ValueMember   = "Key";
                },
                AsyncArgument = null,
                IsCancelable  = true,
                MessageWidth  = 340,
                MessageHeight = 150
            });
        }
Пример #33
0
        /// <summary>
        /// </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();

                    //<snippetDumpEntityInfo1>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("EntityInfo.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());
                                metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString());
                                if (currentEntity.DisplayName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label);
                                }
                                if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label);
                                }

                                metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString());
                                metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString());
                                metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString());
                                metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString());
                                metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString());

                                metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString());
                                //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString());

                                metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString());

                                metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString());
                                metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString());
                                metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString());
                                metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString());
                                metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString());

                                metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString());
                                if (currentEntity.IsEnabledForCharts != null)
                                {
                                    metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString());
                                }
                                metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString());
                                metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString());

                                metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString());
                                metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString());

                                metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString());
                                metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString());

                                metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute);
                                metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute);
                                metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
                                metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName);
                                if (currentEntity.Description.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label);
                                }



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");
                    //</snippetDumpEntityInfo1>

                    //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;
            }
        }
Пример #34
0
        public static void LoadAllEntities()
        {
            CrmConnManager.Connect();

            RetrieveAllEntitiesRequest req = new RetrieveAllEntitiesRequest
            {
                RetrieveAsIfPublished = true,
                EntityFilters         = EntityFilters.Attributes
            };

            RetrieveAllEntitiesResponse res = (RetrieveAllEntitiesResponse)CrmConnManager.LService.Execute(req);

            foreach (var em in res.EntityMetadata)
            {
                if (em.ObjectTypeCode != null)
                {
                    var mige = new CrmEntity()
                    {
                        Code        = (int)em.ObjectTypeCode,
                        LogicalName = em.LogicalName,
                        DisplayName = em.DisplayName?.UserLocalizedLabel?.Label
                    };

                    AllEntities.Add(mige);
                    App.MigEntities.Add(mige);

                    foreach (var attr in em.Attributes)
                    {
                        if (attr.AttributeType.Value == AttributeTypeCode.Picklist)
                        {
                            mige.OptionAttributes.Add(new CrmOptionAttribute()
                            {
                                Name = attr.LogicalName
                            });
                        }
                        else if (attr.AttributeType.Value == AttributeTypeCode.Lookup)
                        {
                            var am = attr as LookupAttributeMetadata;

                            if (am.Targets.Count() > 0)
                            {
                                var target = am.Targets[0];
                                if (target.StartsWith("tri_") || target.StartsWith("kc_"))
                                {
                                    var lookupEntity = App.CrmLookupEntities.Where(e => e.LogicalName == target).FirstOrDefault();
                                    if (lookupEntity == null)
                                    {
                                        lookupEntity = new CrmLookupEntity()
                                        {
                                            LogicalName = target
                                        };

                                        App.CrmLookupEntities.Add(lookupEntity);
                                    }
                                    mige.LookupAttributes.Add(new CrmLookupAttribute()
                                    {
                                        Name         = attr.LogicalName,
                                        LookupEntity = lookupEntity
                                    });
                                }
                            }
                        }
                    }
                }
            }

            foreach (var e in res.EntityMetadata)
            {
                var lookupEntity = App.CrmLookupEntities.Where(x => x.LogicalName == e.LogicalName).FirstOrDefault();
                if (lookupEntity != null)
                {
                    lookupEntity.PrimaryNameAttribute = e.PrimaryNameAttribute;
                    if (lookupEntity.LogicalName == "tri_state")
                    {
                        lookupEntity.PrimaryNameAttribute = "tri_statename";
                    }
                }
            }
        }
Пример #35
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                {
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                }
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    Console.WriteLine("Done.");
                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Пример #36
0
        /// <summary>
        /// Button to login to CRM and create a CrmService Client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            List <EntityObj> lst = new List <EntityObj>();

            List <SystemUser> lstActiveUsr = new List <SystemUser>();


            #region Login Control
            // Establish the Login control
            CrmLogin ctrl = new CrmLogin();
            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            // Handel return.
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                MessageBox.Show("Good Connect");
            }
            else
            {
                MessageBox.Show("BadConnect");
            }

            #endregion

            #region CRMServiceClient
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                svcClient = ctrl.CrmConnectionMgr.CrmSvc;
                ctrl.Close();
                this.loginbutton.Visibility = Visibility.Hidden;


                if (svcClient.IsReady)
                {
                    this.label.Visibility    = Visibility.Visible;
                    this.comboBox.Visibility = Visibility.Visible;

                    //RetrieveEntityRequest req = new RetrieveEntityRequest()
                    //{
                    //    EntityFilters = EntityFilters.All,
                    //    RetrieveAsIfPublished=true,
                    //    LogicalName="account"
                    //};

                    //RetrieveEntityResponse res = (RetrieveEntityResponse)svcClient.OrganizationServiceProxy.Execute(req);



                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)svcClient.OrganizationServiceProxy.Execute(request);

                    foreach (EntityMetadata currentEntity in response.EntityMetadata)
                    {
                        //if (currentEntity.DisplayName.UserLocalizedLabel!=null)
                        //{
                        EntityObj obj = new EntityObj();
                        obj.EntityName = currentEntity.LogicalName;
                        obj.EntityOC   = currentEntity.ObjectTypeCode.ToString();

                        lst.Add(obj);
                        //}
                    }

                    lst = lst.OrderBy(o => o.EntityName).ToList();
                    this.comboBox.DisplayMemberPath = "EntityName";
                    this.comboBox.SelectedValuePath = "EntityOC";
                    this.comboBox.ItemsSource       = lst;
                    this.comboBox.Text = "Select Entity Name";

                    this.label3.Visibility    = Visibility.Visible;
                    this.comboBox2.Visibility = Visibility.Visible;

                    DataCollection <Entity> activeUsrsColl = MainWindow.FindEnabledUsers(svcClient.OrganizationServiceProxy);

                    foreach (Entity user in activeUsrsColl)
                    {
                        SystemUser sysUser = new SystemUser();
                        sysUser.FullName     = user["fullname"].ToString();
                        sysUser.SystemUserID = user["systemuserid"].ToString();

                        lstActiveUsr.Add(sysUser);
                    }

                    lstActiveUsr = lstActiveUsr.OrderBy(o => o.FullName).ToList();
                    this.comboBox2.DisplayMemberPath = "FullName";
                    this.comboBox2.SelectedValuePath = "SystemUserID";
                    this.comboBox2.ItemsSource       = lstActiveUsr;
                    this.comboBox2.Text = "Select Active User Name";

                    // Get data from CRM .
                    //string FetchXML =
                    //    @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                    //                    <entity name='account'>
                    //                        <attribute name='name' />
                    //                        <attribute name='primarycontactid' />
                    //                        <attribute name='telephone1' />
                    //                        <attribute name='accountid' />
                    //                        <order attribute='name' descending='false' />
                    //                      </entity>
                    //                    </fetch>";

                    //var Result = svcClient.GetEntityDataByFetchSearchEC(FetchXML);
                    //if (Result != null)
                    //{
                    //    MessageBox.Show(string.Format("Found {0} records\nFirst Record name is {1}", Result.Entities.Count, Result.Entities.FirstOrDefault().GetAttributeValue<string>("name")));
                    //}


                    //// Core API using SDK OOTB
                    //CreateRequest req = new CreateRequest();
                    //Entity accENt = new Entity("account");
                    //accENt.Attributes.Add("name", "TESTFOO");
                    //req.Target = accENt;
                    //CreateResponse res = (CreateResponse)svcClient.OrganizationServiceProxy.Execute(req);
                    ////CreateResponse res = (CreateResponse)svcClient.ExecuteCrmOrganizationRequest(req, "MyAccountCreate");
                    //MessageBox.Show(res.id.ToString());



                    //// Using Xrm.Tooling helpers.
                    //Dictionary<string, CrmDataTypeWrapper> newFields = new Dictionary<string, CrmDataTypeWrapper>();
                    //// Create a new Record. - Account
                    //newFields.Add("name", new CrmDataTypeWrapper("CrudTestAccount", CrmFieldType.String));
                    //Guid guAcctId = svcClient.CreateNewRecord("account", newFields);

                    //MessageBox.Show(string.Format("New Record Created {0}", guAcctId));
                }
            }
            #endregion
        }
Пример #37
0
        /// <summary>
        /// </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();

                    #region How to dump attribute info
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Attributes,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                {
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                }
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    #endregion How to dump attribute info



                    Console.WriteLine("Done.");

                    //DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("EntityInfo.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());
                                metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString());
                                if (currentEntity.DisplayName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label);
                                }
                                if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label);
                                }
                                metadataWriter.WriteElementString("IntroducedVersion", currentEntity.IntroducedVersion.ToString());
                                metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString());
                                metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString());
                                metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString());
                                metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString());
                                metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString());

                                metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString());
                                //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString());

                                metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString());

                                metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString());
                                metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString());
                                metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString());
                                metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString());
                                metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString());

                                metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString());
                                if (currentEntity.IsEnabledForCharts != null)
                                {
                                    metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString());
                                }
                                metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString());
                                metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString());

                                metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString());
                                metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString());

                                metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString());
                                metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString());

                                metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute);
                                metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute);
                                metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
                                metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName);
                                if (currentEntity.Description.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label);
                                }



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Пример #39
0
        /// <summary>
        /// </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();

                    //<snippetDumpPicklistInfo1>
                    #region How to dump attribute info
                    //<snippetDumpPicklistInfo2>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                    
                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
		    // To view this file, right click the file and choose open with Excel. 
		    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                else
                                    metadataWriter.WriteElementString("IsCustomizable", "no");

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {

                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();

                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    //</snippetDumpPicklistInfo2>
                    #endregion How to dump attribute info



                   Console.WriteLine("Done.");
                    //</snippetDumpPicklistInfo1>

                    //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;
            }
        }
        private void loadEntities()
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Retrieving Entity Metadata...",
                Work    = (w, e) =>
                {
                    #region Reset Variables

                    allEntityMetadata.Clear();// = new EntityMetadataCollection();
                    ExecutionRecordSet.Entities.Clear();
                    views.Entities.Clear();
                    ExecutionRecordSet.Entities.Clear();
                    EntityNameMap.Clear();
                    emrBatchSize = 200;

                    //_selectedWorkflow = null;
                    //_selectedView = null;

                    this.Invoke((MethodInvoker) delegate()
                    {
                        cmbEntities.Items.Clear();
                        lstViews.Items.Clear();
                        radFetchXML.Checked = false;
                        radViews.Checked    = true;
                        tsbCount.Enabled    = tsbExecute.Enabled = false;
                        txtBatchSize.Text   = "200";
                        txtInterval.Text    = "0";
                        txtRecordCount.Clear();
                        rtxtFetchXML.Clear();
                        rtxtFetchXML.Enabled        = false;
                        toolStripSeparator5.Visible = tsbtnFetchBuilder.Visible = false;
                    });

                    #endregion Reset Variables

                    #region Get Entity Metadata

                    RetrieveAllEntitiesRequest _getAllEntities = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };

                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)Service.Execute(_getAllEntities);

                    e.Result = response;

                    #endregion Get Entity Metadata
                },
                ProgressChanged = e =>
                {
                    // If progress has to be notified to user, use the following method:
                    SetWorkingMessage("Metadata retrieved!");
                },
                PostWorkCallBack = e =>
                {
                    allEntityMetadata.AddRange(((RetrieveAllEntitiesResponse)e.Result).EntityMetadata);

                    foreach (var item in allEntityMetadata)
                    {
                        if (item.IsValidForAdvancedFind == true)//item.DisplayName.LocalizedLabels.Count() > 0 &&  // && item.IsCustomizable.Value == true)
                        {
                            cmbEntities.Items.Add(string.Format("{0} ({1})", item.DisplayName.UserLocalizedLabel.Label.ToString(), item.LogicalName.ToLower()));
                            EntityNameMap.Add(string.Format("{0} ({1})", item.DisplayName.UserLocalizedLabel.Label.ToString(), item.LogicalName.ToLower()), item.LogicalName.ToLower());
                        }
                        //else
                        //{
                        //    cmbEntities.Items.Add(item.SchemaName);
                        //}
                    }

                    cmbEntities.Sorted = true;
                    cmbEntities.Text   = "Select an Entity";
                },
                AsyncArgument = null,
                IsCancelable  = true,
                MessageWidth  = 340,
                MessageHeight = 150
            });
        }
        private void LoadMetadata(bool initalLoad = false)
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = initalLoad ? "Retrieving Entity Metadata" : "Updating and Publishing to CRM",
                Work    = (worker, args) =>
                {
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
                    request.EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity;
                    var response          = Service.Execute(request) as RetrieveAllEntitiesResponse;

                    List <SlimEntityMetadata> metadata = new List <SlimEntityMetadata>();
                    foreach (var ent in response.EntityMetadata
                             .Where(x => x.DisplayName != null && x.DisplayName.UserLocalizedLabel != null
                                    //&& x.IsValidForAdvancedFind != null && x.IsValidForAdvancedFind.Value
                                    && x.CanChangeTrackingBeEnabled != null && x.CanChangeTrackingBeEnabled.Value)
                             .OrderBy(x => x.DisplayName.UserLocalizedLabel.Label))
                    {
                        metadata.Add(new SlimEntityMetadata()
                        {
                            EntityName            = ent.DisplayName.UserLocalizedLabel.Label,
                            ChangeTrackingEnabled = ent.ChangeTrackingEnabled.HasValue && ent.ChangeTrackingEnabled.Value,
                            SchemaName            = ent.SchemaName,
                            LogicalName           = ent.LogicalName
                        });
                    }
                    args.Result = metadata;
                },
                // Work is completed, results can be shown to user
                PostWorkCallBack = (args) =>
                {
                    if (args.Error != null)
                    {
                        MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        // Binding result data to ListBox Control
                        entityDataGrid.Visible    = true;
                        entityDataGrid.DataSource = null;
                        this.unmanagedSolutionsList.DataSource = this.Solutions;

                        var lstResults            = (args.Result as List <SlimEntityMetadata>);
                        entityDataGrid.DataSource = lstResults;

                        for (int index = 0; index < lstResults.Count; index++)
                        {
                            var item = lstResults[index];
                            if (item.ChangeTrackingEnabled)
                            {
                                entityDataGrid.Rows[index].ReadOnly = true;

                                foreach (var cell in entityDataGrid.Rows[index].Cells)
                                {
                                    (cell as DataGridViewCell).Style.BackColor = Color.LightGray;
                                }
                            }
                        }
                    }

                    submitUpdateBtn.Visible        = true;
                    unmanagedSolutionsList.Visible = true;
                    unmanagedSolutionLabel.Visible = true;
                    loadMetadataButton.Visible     = false;
                },
                IsCancelable = false
            });
        }
Пример #42
0
        public static void saveEntityIntomationToXml()
        {
            try
            {
                // Establish a connection to the organization web service using CrmConnection.
                // Obtain an organization service proxy.
                // The using statement assures that the service proxy will be properly disposed.
                 using (OrganizationService orgService = new OrganizationService(getCrmConnection()))
                {
                    StringBuilder entityList = new StringBuilder();
                    StringBuilder filedList = new StringBuilder();
                    string headTemplate = "<?xml version=\"1.0\"?>";
                    string entityTemplate = "<entity LogicalName =\"{0}\" DisplayName=\"{1}\"></entity>";
                    // string attrTemplate = "<attribute name=\"{0}\" type=\"{1}\"/>";

                    RetrieveAllEntitiesRequest req = new RetrieveAllEntitiesRequest();
                    req.EntityFilters = EntityFilters.Privileges;
                    req.RetrieveAsIfPublished = true;
                    RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)orgService.Execute(req);

                    for (int i = 0; i < resp.EntityMetadata.Length; i++)
                    {
                        EntityMetadata ent = resp.EntityMetadata[i];
                        string entName = ent.LogicalName;

                        if (ent.DisplayName.UserLocalizedLabel != null)
                        {
                            entityList.Append(string.Format(entityTemplate, ent.LogicalName, ent.DisplayName.UserLocalizedLabel.Label));
                        }
                    }
                    string strxml = headTemplate + "<data>" + entityList.ToString() + "</data>";

                    string fileName = "{0}Entities_{1}_{2}.xml";
                    string xmlFloder = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "EntityInfoXml\\";

                    XmlDocument xml = new XmlDocument();

                    fileName = string.Format(fileName, xmlFloder, "http1921681222", "dropnml");
                    if (!File.Exists(fileName))
                    {
                        File.Create(fileName).Close();

                    }

                    xml.LoadXml(strxml);
                    xml.Save(fileName);
                }
            }

               // 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;
            }
        }
        private void UpdateCrm(string solutionName)
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Updating CRM",
                Work    = (worker, args) =>
                {
                    bool publishRequired = false;
                    foreach (DataGridViewRow row in this.entityDataGrid.Rows)
                    {
                        SlimEntityMetadata metaData = row.DataBoundItem as SlimEntityMetadata;

                        if (metaData.ChangeTrackingEnabled)
                        {
                            bool selectedForChangeTrackingUpdate = false;
                            foreach (DataGridViewCell cell in row.Cells)
                            {
                                if (cell is DataGridViewCheckBoxCell && !(cell as DataGridViewCheckBoxCell).ReadOnly)
                                {
                                    selectedForChangeTrackingUpdate = true;
                                }
                            }

                            if (selectedForChangeTrackingUpdate)
                            {
                                publishRequired = true;
                                UpdateEntityRequest entrequest = new UpdateEntityRequest()
                                {
                                    Entity = new Microsoft.Xrm.Sdk.Metadata.EntityMetadata()
                                    {
                                        ChangeTrackingEnabled = true,
                                        LogicalName           = metaData.LogicalName,
                                    },
                                    SolutionUniqueName = solutionName
                                };

                                Service.Execute(entrequest);
                            }
                        }
                    }

                    if (publishRequired)
                    {
                        PublishAllXmlRequest pubCustomizationRequest = new PublishAllXmlRequest();
                        Service.Execute(pubCustomizationRequest);
                    }

                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
                    request.EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity;
                    var response          = Service.Execute(request) as RetrieveAllEntitiesResponse;

                    List <SlimEntityMetadata> metadata = new List <SlimEntityMetadata>();
                    foreach (var ent in response.EntityMetadata
                             .Where(x => x.DisplayName != null && x.DisplayName.UserLocalizedLabel != null
                                    //&& x.IsValidForAdvancedFind != null && x.IsValidForAdvancedFind.Value
                                    && x.CanChangeTrackingBeEnabled != null && x.CanChangeTrackingBeEnabled.Value)
                             .OrderBy(x => x.DisplayName.UserLocalizedLabel.Label))
                    {
                        metadata.Add(new SlimEntityMetadata()
                        {
                            EntityName            = ent.DisplayName.UserLocalizedLabel.Label,
                            ChangeTrackingEnabled = ent.ChangeTrackingEnabled.HasValue && ent.ChangeTrackingEnabled.Value,
                            SchemaName            = ent.SchemaName,
                            LogicalName           = ent.LogicalName
                        });
                    }

                    args.Result = metadata;
                },
                // Work is completed, results can be shown to user
                PostWorkCallBack = (args) =>
                {
                    if (args.Error != null)
                    {
                        MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        // Binding result data to ListBox Control
                        entityDataGrid.Visible    = true;
                        entityDataGrid.DataSource = null;
                        this.unmanagedSolutionsList.DataSource = this.Solutions;

                        var lstResults            = (args.Result as List <SlimEntityMetadata>);
                        entityDataGrid.DataSource = lstResults;

                        for (int index = 0; index < lstResults.Count; index++)
                        {
                            var item = lstResults[index];
                            if (item.ChangeTrackingEnabled)
                            {
                                entityDataGrid.Rows[index].ReadOnly = true;

                                foreach (var cell in entityDataGrid.Rows[index].Cells)
                                {
                                    (cell as DataGridViewCell).Style.BackColor = Color.LightGray;
                                }
                            }
                        }
                    }

                    submitUpdateBtn.Visible        = true;
                    unmanagedSolutionsList.Visible = true;
                    unmanagedSolutionLabel.Visible = true;
                    loadMetadataButton.Visible     = false;
                },
                IsCancelable = false
            });
        }
Пример #44
0
        private Task<List<EntityMetadata>> LoadEntityMetadata()
        {
            return Task.Run(() =>
            {
                var req = new RetrieveAllEntitiesRequest
                {
                    EntityFilters = EntityFilters.Entity,
                    RetrieveAsIfPublished = false
                };

                var result = (RetrieveAllEntitiesResponse)_service.Execute(req);

                return result.EntityMetadata.ToList();
            });
        }
        private void SearchByIdFindButton_Click(object sender, EventArgs ee)
        {
            SearchByIdEntityLogicalName.Text = "";
            SearchByIdEntityDisplayName.Text = "";
            SearchByIdName.Text = "";
            SearchByIdOpenInCrmButton.Enabled = false;

            var guid = SearchByIdString.Text.Replace("{", "").Replace("}", "").Trim();

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Retrieve entitity list...",
                Work    = (w, e) =>
                {
                    if (_systemEntities == null)
                    {
                        var request = new RetrieveAllEntitiesRequest {
                            EntityFilters = EntityFilters.Entity
                        };
                        var response    = (RetrieveAllEntitiesResponse)Service.Execute(request);
                        var entities    = response.EntityMetadata.Where(em => !string.IsNullOrWhiteSpace(em.DisplayName?.UserLocalizedLabel?.Label) && !_excludedEntities.Contains(em.LogicalName)).ToArray();
                        _systemEntities = entities.Where(em => !em.IsCustomEntity.HasValue || em.IsCustomEntity != true).ToArray();
                        _customEntities = entities.Where(em => em.IsCustomEntity.HasValue && em.IsCustomEntity == true).ToArray();
                    }

                    var count              = (decimal)((SearchByIdFindSystem.Checked ? _systemEntities.Length : 0) + (SearchByIdFindCustom.Checked ? _customEntities.Length : 0));
                    var processUnit        = count == 0 ? 0 : 100 / count;
                    decimal processPercent = 0;

                    if (SearchByIdFindSystem.Checked)
                    {
                        foreach (var entityMetadata in _systemEntities)
                        {
                            processPercent += processUnit;
                            w.ReportProgress((int)processPercent, entityMetadata.DisplayName.UserLocalizedLabel.Label);
                            string[] data;
                            if (!FingById(entityMetadata, guid, out data))
                            {
                                continue;
                            }
                            e.Result = data;
                            return;
                        }
                    }
                    if (SearchByIdFindCustom.Checked)
                    {
                        foreach (var entityMetadata in _customEntities)
                        {
                            processPercent += processUnit;
                            w.ReportProgress((int)processPercent, entityMetadata.DisplayName.UserLocalizedLabel.Label);
                            string[] data;
                            if (!FingById(entityMetadata, guid, out data))
                            {
                                continue;
                            }
                            e.Result = data;
                            return;
                        }
                    }
                    e.Result = null;
                },
                ProgressChanged = e =>
                {
                    SetWorkingMessage($"{e.ProgressPercentage}%{Environment.NewLine}{e.UserState}");
                },
                PostWorkCallBack = e =>
                {
                    var data = e.Result as string[];
                    if (data == null)
                    {
                        MessageBox.Show("Nothing found", "Search by ID", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    SearchByIdResult.Visible          = true;
                    SearchByIdOpenInCrmButton.Enabled = true;
                    SearchByIdOpenInCrmButton.Tag     = guid;
                    SearchByIdEntityLogicalName.Text  = data[0];
                    SearchByIdEntityDisplayName.Text  = data[1];
                    SearchByIdName.Text = data[2];
                },
                MessageWidth  = 340,
                MessageHeight = 150
            });
        }
Пример #46
0
 /// <summary>
 /// Retrieve the list of all CRM entities
 /// </summary>
 /// <returns>List of all CRM entities</returns>
 public RetrieveAllEntitiesResponse RetrieveEntitiesList()
 {
     var request = new RetrieveAllEntitiesRequest { EntityFilters = EntityFilters.Entity };
     return (RetrieveAllEntitiesResponse)service.Execute(request);
 }
Пример #47
0
 private void LoadEntities(Action AfterLoad)
 {
     if (working)
     {
         return;
     }
     entities = null;
     entityShitList = new List<string>();
     working = true;
     WorkAsync("Loading entities metadata...",
         (eventargs) =>
         {
             EnableControls(false);
             var req = new RetrieveAllEntitiesRequest()
             {
                 EntityFilters = EntityFilters.Entity,
                 RetrieveAsIfPublished = true
             };
             eventargs.Result = Service.Execute(req);
         },
         (completedargs) =>
         {
             working = false;
             if (completedargs.Error != null)
             {
                 MessageBox.Show(completedargs.Error.Message);
             }
             else
             {
                 if (completedargs.Result is RetrieveAllEntitiesResponse)
                 {
                     entities = new Dictionary<string, EntityMetadata>();
                     foreach (var entity in ((RetrieveAllEntitiesResponse)completedargs.Result).EntityMetadata)
                     {
                         entities.Add(entity.LogicalName, entity);
                     }
                 }
             }
             EnableControls(true);
             if (AfterLoad != null)
             {
                 AfterLoad();
             }
         });
 }
Пример #48
0
        static void Main()
        {
            var serviceUrl = "http://crmdevapp01/DEV01/XRMServices/2011/Organization.svc";

            var credentials = new ClientCredentials();

            credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            using (var service = new OrganizationServiceProxy(new Uri(serviceUrl), null, credentials, null))
            {
                #region All Entities
                {
                    // Получение списка всех сущностей, включая атрибуты этих сущностей
                    var request = new RetrieveAllEntitiesRequest
                    {
                        EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                    };
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);
                    foreach (var entityMetadata in response.EntityMetadata)
                    {
                        Console.WriteLine(
                            entityMetadata.LogicalName + " - " +
                            (entityMetadata.DisplayName?.UserLocalizedLabel == null ? "" : entityMetadata.DisplayName.UserLocalizedLabel.Label) +
                            " (атрибутов " + entityMetadata.Attributes.Length + ")");
                    }
                }
                #endregion


                #region One Entity
                {
                    // Получаем метаданные сущности "contact", включая данные самой сущности и ее атрибутов
                    var request = new RetrieveEntityRequest
                    {
                        LogicalName           = "contact",
                        EntityFilters         = EntityFilters.Entity | EntityFilters.Attributes,
                        RetrieveAsIfPublished = false
                    };
                    var response        = (RetrieveEntityResponse)service.Execute(request);
                    var contactMetadata = response.EntityMetadata;

                    Console.WriteLine("Contact entity");
                    // Вывод данных о сущности
                    Console.WriteLine($"   Logical Name = {contactMetadata.LogicalName}");
                    Console.WriteLine($"   Display Name = {contactMetadata.DisplayName.UserLocalizedLabel.Label}");
                    Console.WriteLine($"   Primary ID Attribute = {contactMetadata.PrimaryIdAttribute}");
                    Console.WriteLine($"   Primary Name Attribute = {contactMetadata.PrimaryNameAttribute}");
                    Console.WriteLine("Attributes");
                    // Вывод данных об атрибутах сущности
                    foreach (var attributeMetadata in contactMetadata.Attributes.Where(a => a.AttributeType.HasValue && a.DisplayName.UserLocalizedLabel != null))
                    {
                        // вывод данных, общих для всех атрибутов
                        Console.WriteLine($"   {attributeMetadata.DisplayName.UserLocalizedLabel.Label} ({attributeMetadata.LogicalName})");
                        // вывод данных, специфических для разных типов атрибутов
                        switch (attributeMetadata.AttributeType.Value)
                        {
                        case AttributeTypeCode.Picklist:
                            var picklistAttributeMetadata = attributeMetadata as PicklistAttributeMetadata;
                            foreach (var option in picklistAttributeMetadata.OptionSet.Options)
                            {
                                Console.WriteLine($"      {option.Label.UserLocalizedLabel.Label} = {option.Value}");
                            }
                            break;

                        case AttributeTypeCode.Lookup:
                            var lookupAttributeMetadata = attributeMetadata as LookupAttributeMetadata;
                            foreach (var target in lookupAttributeMetadata.Targets)
                            {
                                Console.WriteLine($"      {target}");
                            }
                            break;
                        }
                    }
                }
                #endregion
            }

            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
Пример #49
0
        /// <summary>
        /// Reads entities into memory
        /// </summary>
        public void ReadEntitiesFromCRM()
        {
            LogInfo("Reading CRM metadata from CRM");
            CRMEntitySet = new clEntities(); //initialise
            string[] Tags = { "", "", "", "", "", "", "", "", "", "" };

            RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
            {
                EntityFilters = EntityFilters.All
            };

            request.RetrieveAsIfPublished = cxReadasIfPublished.Checked;

            RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)Service.Execute(request);

            LogInfo2("Entity data read from CRM");

            foreach (EntityMetadata currentEntity in response.EntityMetadata)
            {
                LogInfo2("Processsing entity " + currentEntity.LogicalName);

                if (currentEntity.IsCustomizable.Value) //only output items for customisable entities
                {
                    string sDescription;
                    //Get attributes
                    SortedDictionary <string, clOneAttribute> attributes = new SortedDictionary <string, clOneAttribute>();
                    foreach (AttributeMetadata att in currentEntity.Attributes)
                    {
                        LogInfo2("Processsing attribute " + att.LogicalName);
                        sDescription = att.Description.LocalizedLabels.Where(l => l.LanguageCode == mySettings.LanguageCode).FirstOrDefault() != null?att.Description.LocalizedLabels.Where(l => l.LanguageCode == mySettings.LanguageCode).FirstOrDefault().Label : "";

                        if (mySettings.UseTags)
                        {
                            ExtractTags(sDescription, out Tags, out sDescription);
                        }
                        attributes.Add(att.LogicalName, new clOneAttribute(att.LogicalName, att.SchemaName, att.AttributeType.Value.ToString(), sDescription, mySettings.LanguageCode, Tags, (att.SourceType != null && att.SourceType > 0)));
                        if (att.AttributeType.Value.ToString() == "Picklist")
                        {
                            attributes[att.LogicalName].DefaultOptionSetValue = ((PicklistAttributeMetadata)att).DefaultFormValue;
                        }
                    }

                    sDescription = currentEntity.Description.LocalizedLabels.Where(l => l.LanguageCode == mySettings.LanguageCode).FirstOrDefault() != null?currentEntity.Description.LocalizedLabels.Where(l => l.LanguageCode == mySettings.LanguageCode).FirstOrDefault().Label : "";

                    if (mySettings.UseTags)
                    {
                        ExtractTags(sDescription, out Tags, out sDescription);
                    }

                    //Flag linked rollup fields _state and _date as these are hidden and cannot be updated
                    foreach (string sKey in attributes.Keys)
                    {
                        if (attributes[sKey].IsRollupField)                                       //is this a rollup
                        {
                            if (attributes.Keys.Contains(attributes[sKey].logicalName + "_date")) //if so and if the _date fields exists then flag it
                            {
                                attributes[attributes[sKey].logicalName + "_date"].NotUpdateAble = true;
                            }
                            if (attributes.Keys.Contains(attributes[sKey].logicalName + "_state")) //if so and if the _state fields exists then flag it
                            {
                                attributes[attributes[sKey].logicalName + "_state"].NotUpdateAble = true;
                            }
                        }
                    }

                    //Add entity to set
                    CRMEntitySet.AddEntity(currentEntity.LogicalName, currentEntity.SchemaName, sDescription, mySettings.LanguageCode, attributes, Tags);
                    if (!currentEntity.IsRenameable.Value)
                    {
                        CRMEntitySet.entities[currentEntity.LogicalName].NotUpdateAble = true; //flag if cannot be updated
                    }
                }
            }
        }
Пример #50
0
        private void ToolStripButtonLoadSiteMapFromDiskClick(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                Title = "Select a Xml file representing a SiteMap",
                Filter = "Xml file (*.xml)|*.xml"
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                EnableControls(false);

                siteMapDoc = new XmlDocument();
                siteMapDoc.Load(ofd.FileName);

                if (siteMapDoc.DocumentElement.Name != "SiteMap" ||
                    siteMapDoc.DocumentElement.ChildNodes.Count > 0 &&
                    siteMapDoc.DocumentElement.ChildNodes[0].Name == "SiteMap")
                {
                    MessageBox.Show(this, "Invalid Xml: SiteMap Xml root must be SiteMap!", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);

                    tsbMainOpenSiteMap.Enabled = true;
                    toolStripButtonLoadSiteMapFromDisk.Enabled = true;
                }
                else
                {
                    if (Service != null && entityCache == null)
                    {
                        WorkAsync("Loading Entities...",
                            (bw, evt) =>
                            {
                                // Recherche des métadonnées
                                entityCache = new List<EntityMetadata>();
                                webResourcesHtmlCache = new List<Entity>();

                                var request = new RetrieveAllEntitiesRequest
                                {
                                    EntityFilters = EntityFilters.Entity
                                };

                                var response = (RetrieveAllEntitiesResponse)Service.Execute(request);

                                foreach (var emd in response.EntityMetadata)
                                {
                                    entityCache.Add(emd);
                                }
                                // Fin Recherche des métadonnées

                                bw.ReportProgress(0, "Loading web resources...");
                                // Rercherche des images

                                webResourcesImageCache = new List<Entity>();

                                var wrQuery = new QueryExpression("webresource");
                                wrQuery.Criteria.AddCondition("webresourcetype", ConditionOperator.In,
                                    new object[] { 2, 5, 6, 7 });
                                wrQuery.ColumnSet.AllColumns = true;

                                EntityCollection results = Service.RetrieveMultiple(wrQuery);

                                foreach (Entity webresource in results.Entities)
                                {
                                    if (webresource.GetAttributeValue<OptionSetValue>("webresourcetype").Value == 2)
                                    {
                                        webResourcesHtmlCache.Add(webresource);
                                    }
                                    else
                                    {
                                        webResourcesImageCache.Add(webresource);
                                    }
                                }
                            },
                            evt =>
                            {
                                DisplaySiteMap();
                                EnableControls(true);
                            },
                            evt => SetWorkingMessage(evt.UserState.ToString()));
                    }
                    else
                    {
                        DisplaySiteMap();
                        EnableControls(true);
                    }
                }
            }
        }
Пример #51
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            var request = new RetrieveAllEntitiesRequest{EntityFilters = EntityFilters.Entity};
            var response = (RetrieveAllEntitiesResponse) service.Execute(request);

            var settings =
                service.RetrieveMultiple(new QueryExpression("usersettings") {ColumnSet = new ColumnSet("localeid")});
            localeId = settings.Entities.First().GetAttributeValue<int>("localeid");

            e.Result = response.EntityMetadata.Select(emd => new EntityInfo { Metadata = emd });
        }
        /// <summary>
        /// </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();

                    #region How to dump attribute info
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Attributes,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.
                    String filename = String.Concat("AllAttributeDesc.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }
                                if (currentEntity.IsIntersect.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsIntersect", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsIntersect", "no");
                                }



                                #region Attributes


                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("LogicalName", currentAttribute.LogicalName);
                                        // Write the Description if it is set.
                                        if (currentAttribute.Description.UserLocalizedLabel != null)
                                        {
                                            metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocalizedLabel.Label.ToString());
                                        }

                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());
                                        if (currentAttribute.DisplayName.UserLocalizedLabel != null)
                                        {
                                            metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocalizedLabel.Label.ToString());
                                        }
                                        if (currentAttribute.SchemaName != null)
                                        {
                                            metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName.ToString());
                                        }
                                        if (currentAttribute.IntroducedVersion != null)
                                        {
                                            metadataWriter.WriteElementString("IntroducedVersion", currentAttribute.IntroducedVersion.ToString());
                                        }
                                        if (currentAttribute.DeprecatedVersion != null)
                                        {
                                            metadataWriter.WriteElementString("DeprecatedVersion", currentAttribute.DeprecatedVersion.ToString());
                                        }
                                        if (currentAttribute.IsCustomAttribute != null)
                                        {
                                            metadataWriter.WriteElementString("IsCustomAttribute", currentAttribute.IsCustomAttribute.Value.ToString());
                                        }
                                        if (currentAttribute.IsCustomizable != null)
                                        {
                                            metadataWriter.WriteElementString("IsCustomizable", currentAttribute.IsCustomizable.Value.ToString());
                                        }
                                        if (currentAttribute.RequiredLevel != null)
                                        {
                                            metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForCreate != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForCreate", currentAttribute.IsValidForCreate.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForRead != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForRead", currentAttribute.IsValidForRead.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForUpdate != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForUpdate", currentAttribute.IsValidForUpdate.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForCreate != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForCreate", currentAttribute.CanBeSecuredForCreate.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForRead != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForRead", currentAttribute.CanBeSecuredForRead.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForUpdate != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForUpdate", currentAttribute.CanBeSecuredForUpdate.Value.ToString());
                                        }
                                        if (currentAttribute.IsAuditEnabled != null)
                                        {
                                            metadataWriter.WriteElementString("IsAuditEnabled", currentAttribute.IsAuditEnabled.Value.ToString());
                                        }
                                        if (currentAttribute.IsManaged != null)
                                        {
                                            metadataWriter.WriteElementString("IsManaged", currentAttribute.IsManaged.Value.ToString());
                                        }
                                        if (currentAttribute.IsPrimaryId != null)
                                        {
                                            metadataWriter.WriteElementString("IsPrimaryId", currentAttribute.IsPrimaryId.Value.ToString());
                                        }
                                        if (currentAttribute.IsPrimaryName != null)
                                        {
                                            metadataWriter.WriteElementString("IsPrimaryName", currentAttribute.IsPrimaryName.Value.ToString());
                                        }
                                        if (currentAttribute.IsRenameable != null)
                                        {
                                            metadataWriter.WriteElementString("IsRenameable", currentAttribute.IsRenameable.Value.ToString());
                                        }
                                        if (currentAttribute.IsSecured != null)
                                        {
                                            metadataWriter.WriteElementString("IsSecured", currentAttribute.IsSecured.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForAdvancedFind != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForAdvancedFind", currentAttribute.IsValidForAdvancedFind.Value.ToString());
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    #endregion How to dump attribute info



                    Console.WriteLine("Done.");

                    //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;
            }
        }
Пример #53
0
        public void testService()
        {
            ClientCredentials Credentials = new ClientCredentials();
            //Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            //Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("crmadmin", "CRMP@ssw0rd");
            Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(
                Settings.Default.CRMUSerName,
                Settings.Default.CRMPassword, Settings.Default.CRMDomain);

            //This URL needs to be updated to match the servername and Organization for the environment.
            Uri OrganizationUri = new Uri(Settings.Default.CRMURL);
            Uri HomeRealmUri = null;

            //OrganizationServiceProxy serviceProxy;
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                service = (IOrganizationService)serviceProxy;
                //QueryByAttribute query = new QueryByAttribute("am_project");
                //query.ColumnSet = new ColumnSet(true);
                //query.AddAttributeValue("am_name", "Project Test BOQ 20130623");
                //EntityCollection collection = service.RetrieveMultiple(query);
                //foreach(Entity e in collection.Entities){
                //    Console.WriteLine(e.Id);
                //    Console.WriteLine(e["am_optservicearea"]);
                //}

                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters = EntityFilters.Attributes,
                    RetrieveAsIfPublished = true
                };
                RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(request);
                foreach (EntityMetadata currentEntity in response.EntityMetadata)
                {
                    if (currentEntity.LogicalName != "am_so") continue;
                    foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                    {
                        Console.WriteLine("LogicalName: " + currentAttribute.LogicalName);
                    }
                }

                //Entity so = new Entity("am_so");
                //service.
                //so.Co

                //Entity unit = new Entity("am_project");

                //unit["am_name"] = "Test am_so";

                //Guid unitId = service.Create(unit);
                //Console.WriteLine(unitId.ToString());
                service = null;
            }
        }
Пример #54
0
        /// <summary>
        /// Main entry point for the application.
        /// </summary>
        /// <param name="CmdArgs">Entities to place on the diagram</param>
        public static int Main(string[] args)
        {
            String filename = String.Empty;

            VisioApi.Application application;
            VisioApi.Document    document;
            DiagramBuilder       builder = new DiagramBuilder();

            try
            {
                // Obtain the target organization's Web address and client logon
                // credentials from the user.
                ServerConnection serverConnect        = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(config))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Load Visio and create a new document.
                    application          = new VisioApi.Application();
                    application.Visible  = false; // Not showing the UI increases rendering speed
                    builder.VersionName  = application.Version;
                    document             = application.Documents.Add(String.Empty);
                    builder._application = application;
                    builder._document    = document;

                    // Load the metadata.
                    Console.WriteLine("Loading Metadata...");
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships,
                        RetrieveAsIfPublished = true,
                    };
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                    builder._metadataResponse = response;

                    // Diagram all entities if given no command-line parameters, otherwise diagram
                    // those entered as command-line parameters.
                    if (args.Length < 1)
                    {
                        ArrayList entities = new ArrayList();

                        foreach (EntityMetadata entity in response.EntityMetadata)
                        {
                            // Only draw an entity if it does not exist in the excluded entity table.
                            if (!_excludedEntityTable.ContainsKey(entity.LogicalName.GetHashCode()))
                            {
                                entities.Add(entity.LogicalName);
                            }
                            else
                            {
                                Console.WriteLine("Excluding entity: {0}", entity.LogicalName);
                            }
                        }

                        builder.BuildDiagram((string[])entities.ToArray(typeof(string)), "All Entities");
                        filename = "AllEntities.vsd";
                    }
                    else
                    {
                        builder.BuildDiagram(args, String.Join(", ", args));
                        filename = String.Concat(args[0], ".vsd");
                    }

                    // Save the diagram in the current directory using the name of the first
                    // entity argument or "AllEntities" if none were given. Close the Visio application.
                    document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                    application.Quit();
                }
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe
                        = ex.InnerException
                          as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                                          null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                //Console.WriteLine("Rendering complete.");
                Console.WriteLine("Rendering complete.  Press any key to continue.");
                Console.ReadLine();
            }
            return(0);
        }
Пример #55
0
        private void ProcessRetrieveEntities()
        {
            cBoxEntities.Items.Clear();

            WorkAsync("Retrieving Entities...",
              e =>
              {
                  var request = new RetrieveAllEntitiesRequest { EntityFilters = EntityFilters.Entity };
                  var response = (RetrieveAllEntitiesResponse)Service.Execute(request);

                  e.Result = response.EntityMetadata;
              },
              e =>
              {
                  if (e.Error != null)
                  {
                      MessageBox.Show(this, "An error occured: " + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                  }
                  else
                  {
                      var emds = (EntityMetadata[])e.Result;

                      foreach (var emd in emds)
                      {
                          cBoxEntities.Items.Add(new EntityInfo(emd.LogicalName, emd.DisplayName != null && emd.DisplayName.UserLocalizedLabel != null ? emd.DisplayName.UserLocalizedLabel.Label : "N/A", emd.PrimaryNameAttribute));
                      }

                      cBoxEntities.DrawMode = DrawMode.OwnerDrawFixed;
                      cBoxEntities.DrawItem += cbbEntity_DrawItem;

                      cBoxEntities.SelectedIndex = 0;
                  }
              });
        }
 private void ConnectToCrmAndGetEntities()
 {
     string textFile = string.Empty;
     using (StreamReader textReader = new StreamReader(txtFileLocation.Text))
     {
         textFile = textReader.ReadToEnd();
     }
     string pattern = @"\b(?=(public partial class\s+\w+)\b)";
     string[] classes = Regex.Matches(textFile, pattern)
                            .Cast<Match>()
                            .Select(match => match.Groups[1].Value.Replace("public partial class ", string.Empty))
                            .ToArray();
     RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
     {
         EntityFilters = EntityFilters.Entity,
         RetrieveAsIfPublished = true,
     };
     // Retrieve the MetaData.
     RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_service.Execute(request);
     List<EntityMetadata> listEntityMetaData = response.EntityMetadata.OrderBy(s => s.SchemaName).ToList();
     foreach (var item in listEntityMetaData)
     {
         cbxListEntities.Items.Add(item.SchemaName);
         //Check if exist in the class
         if (classes.Contains(item.SchemaName))
         {
             cbxListEntities.SetItemCheckState(cbxListEntities.Items.Count - 1, CheckState.Indeterminate);
         }
     }
 }
Пример #57
0
        private void LoadMetadata()
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading metadata...",
                Work = (bw, e) =>
                {
                    var request = new RetrieveAllEntitiesRequest { EntityFilters = EntityFilters.All };
                    var response = (RetrieveAllEntitiesResponse)Service.Execute(request);
                    e.Result = response.EntityMetadata.ToList();
                },
                PostWorkCallBack = e =>
                {
                    if (e.Error == null)
                    {
                        emds = (List<EntityMetadata>)e.Result;

                        cbbFirstEntity.Items.Clear();

                        foreach (var emd in emds)
                        {
                            cbbFirstEntity.Items.Add(new EntityInfo { Metadata = emd });
                        }

                        if (cbbFirstEntity.Items.Count > 0)
                        {
                            cbbFirstEntity.SelectedIndex = 0;
                        }

                        cbbFirstEntity.DrawMode = DrawMode.OwnerDrawFixed;
                        cbbFirstEntity.DrawItem += cbbEntity_DrawItem;

                        tsbExport.Enabled = true;
                        tsbImportNN.Enabled = true;
                        tsbDelete.Enabled = true;
                    }
                    else
                    {
                        tsbExport.Enabled = false;
                        tsbImportNN.Enabled = false;
                        tsbDelete.Enabled = false;

                        MessageBox.Show(ParentForm, "An error occured: " + e.Error.Message, "Error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                }
            });
        }
        [STAThread] // Added to support UX
        public static void Main(string[] args)
        {
            CrmServiceClient service  = null;
            String           filename = String.Empty;

            VisioApi.Application application;
            VisioApi.Document    document;
            DiagramBuilder       builder = new DiagramBuilder(service);

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate
                    // Load Visio and create a new document.
                    application          = new VisioApi.Application();
                    application.Visible  = false; // Not showing the UI increases rendering speed
                    builder.VersionName  = application.Version;
                    document             = application.Documents.Add(String.Empty);
                    builder._application = application;
                    builder._document    = document;

                    // Load the metadata.
                    Console.WriteLine("Loading Metadata...");
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships,
                        RetrieveAsIfPublished = false,
                    };
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(request);
                    builder._metadataResponse = response;

                    // Diagram all entities if given no command-line parameters, otherwise diagram
                    // those entered as command-line parameters.
                    if (args.Length < 1)
                    {
                        ArrayList entities = new ArrayList();

                        foreach (EntityMetadata entity in response?.EntityMetadata)
                        {
                            // Only draw an entity if it does not exist in the excluded entity table.
                            if (!_excludedEntityTable.ContainsKey(entity.LogicalName.GetHashCode()))
                            {
                                entities.Add(entity.LogicalName);
                            }
                            else
                            {
                                Console.WriteLine("Excluding entity: {0}", entity.LogicalName);
                            }
                        }

                        builder.BuildDiagram(service, (string[])entities.ToArray(typeof(string)), "All Entities");
                        filename = "AllEntities.vsd";
                    }
                    else
                    {
                        builder.BuildDiagram(service, args, String.Join(", ", args));
                        filename = String.Concat(args[0], ".vsd");
                    }

                    // Save the diagram in the current directory using the name of the first
                    // entity argument or "AllEntities" if none were given. Close the Visio application.
                    document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                    application.Quit();
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var bw = (BackgroundWorker)sender;

            bw.ReportProgress(0, _retrievingMetadataStatus);

            //1. retrieve teamtemplate entity metadata
            //set attributes to exclude from the query
            List <string> IgnoredAttributes = new List <string> {
                "issystem"
            };

            //execute the teamtemplate entitymetadata request
            RetrieveEntityRequest entityreq = new RetrieveEntityRequest
            {
                LogicalName   = "teamtemplate",
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
            };
            RetrieveEntityResponse entityres = (RetrieveEntityResponse)_service.Execute(entityreq);

            //2. build and execute fetchxml to retrieve teamtemplate records
            string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";

            fetchXml += "<entity name='teamtemplate'>";

            foreach (AttributeMetadata amd in entityres.EntityMetadata.Attributes)
            {
                //only include attributes not in the ignore list
                if (!IgnoredAttributes.Contains(amd.LogicalName))
                {
                    fetchXml += "<attribute name='" + amd.LogicalName + "' />";
                }
            }
            fetchXml += "</entity></fetch>";

            bw.ReportProgress(0, _exportingStatus);
            EntityCollection exported = _service.RetrieveMultiple(new FetchExpression(fetchXml));


            //if we have any results
            if (exported.Entities.Count > 0)
            {
                bw.ReportProgress(0, _enablingAccessTeamStatus);

                //3. get list of unique objecttypecodes with access teams from source org
                List <int> objecttypeList = new List <int>();
                foreach (Entity entity in exported.Entities)
                {
                    if (!objecttypeList.Contains((int)entity["objecttypecode"]))
                    {
                        objecttypeList.Add((int)entity["objecttypecode"]);
                    }
                }

                //4. retrieve all entity metadata from target org so we can check whether to enable access teams
                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters         = EntityFilters.Entity,
                    RetrieveAsIfPublished = false
                };
                RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_targetService.Execute(request);

                //5. loop through target entitymetadata results
                //create a list to store entities that are enabled for access teams
                List <int> enabledEntities = new List <int>();
                foreach (EntityMetadata emd in response.EntityMetadata)
                {
                    //if objecttypecode is in list from source org AND AutoCreateAccessTeams == false, set AutoCreateAccessTeams = true
                    //AutoCreateAccessTeams is nullable, so need to set separate enabled flag
                    bool enabled = false;
                    if (emd.AutoCreateAccessTeams.HasValue)
                    {
                        if ((bool)emd.AutoCreateAccessTeams)
                        {
                            //set the flag so we don't try to update it later
                            enabled = true;

                            //add it to the list of entities that are enabled for access teams
                            enabledEntities.Add((int)emd.ObjectTypeCode);
                        }
                    }

                    //6. update target entities to enable access teams if requested
                    if (objecttypeList.Contains((int)emd.ObjectTypeCode) && !enabled && enableTargetAccessTeamsCheckBox.Checked)
                    {
                        //6a. set the entity metadata AutoCreateAccessTeams value
                        emd.AutoCreateAccessTeams = true;
                        UpdateEntityRequest updateReq = new UpdateEntityRequest
                        {
                            Entity = emd,
                        };

                        //update the entity metadata
                        _targetService.Execute(updateReq);

                        //add it to the list of entities that are enabled for access teams
                        enabledEntities.Add((int)emd.ObjectTypeCode);
                    }
                }

                bw.ReportProgress(0, _importingStatus);

                //7. do the access team migration
                foreach (Entity entity in exported.Entities)
                {
                    //only copy team templates for entities that are enabled for access teams
                    if (enabledEntities.Contains((int)entity["objecttypecode"]))
                    {
                        try
                        {
                            //7a. try to update first
                            try
                            {
                                _targetService.Update(entity);
                            }
                            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
                            {
                                //7b. if update fails, then create
                                _targetService.Create(entity);
                            }

                            //8. update our success counter
                            Interlocked.Increment(ref _counter);
                        }
                        catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                        {
                            //7c. if everything fails, return error
                            throw new Exception(string.Format(_rowErrorMessage, ex.Message, entity["teamtemplatename"]));
                        }
                    }
                }
            }
        }
Пример #60
0
        /// <summary>
        /// Main entry point for the application.
        /// </summary>
        /// <param name="CmdArgs">Entities to place on the diagram</param>
        public static int Main(string[] args)
        {
            String filename = String.Empty;

            VisioApi.Application application;
            VisioApi.Document    document;
            DiagramBuilder       builder = new DiagramBuilder();

            try
            {
                // Load Visio and create a new document.
                application         = new VisioApi.Application();
                application.Visible = false; // Not showing the UI increases rendering speed
                document            = application.Documents.Add(String.Empty);

                builder._application = application;
                builder._document    = document;

                // Load the metadata.
                Console.WriteLine("Loading Metadata {0} ...", DateTime.Now.ToLongTimeString());
                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters         = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships,
                    RetrieveAsIfPublished = true
                };

                var response = builder.RetrieveMetadata();
                Console.WriteLine("Metadata Loaded {0} ...", DateTime.Now.ToLongTimeString());
                builder._metadataResponse = response;

                // Diagram all entities if given no command-line parameters, otherwise diagram
                // those entered as command-line parameters.
                if (args.Length < 1)
                {
                    ArrayList entities = new ArrayList();

                    foreach (EntityMetadata entity in response.EntityMetadata)
                    {
                        entities.Add(entity.LogicalName);
                    }

                    builder.BuildDiagram((string[])entities.ToArray(typeof(string)), "All Entities");
                    filename = "AllEntities.vsd";
                }
                else
                {
                    builder.BuildDiagram(args, String.Join(", ", args));
                    filename = String.Concat(args[0], ".vsd");
                }

                // Save the diagram in the current directory using the name of the first
                // entity argument or "AllEntities" if none were given. Close the Visio application.
                document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                application.Quit();
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe
                        = ex.InnerException
                          as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                                          null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                //Console.WriteLine("Rendering complete.");
                Console.WriteLine("Rendering complete.  Press any key to continue.");
                Console.ReadLine();
            }

            return(0);
        }