private void AuditExportDetails_Load(object sender, EventArgs e)
        {
            Control[] ComboBoxes = au.Controls.Find("comboBoxConnectionSource", true);
            if (ComboBoxes.Length != 1)
            {
                return;
            }
            ComboBox              sourceCB = (ComboBox)ComboBoxes[0];
            EnvAuditStructure     es       = au.man.ReadEnvStructure(sourceCB.SelectedItem.ToString());
            List <EnvAuditEntity> eeList   = es.Entities;
            EnvAuditEntity        ee       = eeList.Find(eP => eP.LogicalName == this.entity);
            SelectedAuditEntity   se       = null;

            if (au.currentProfile != null)
            {
                se = au.currentProfile.SelectedEntities.Find(eP => eP.LogicalName == this.entity);
            }

            foreach (string Attribute in ee.Attributes)
            {
                checkedListBoxAttributes.Items.AddRange(new object[] { Attribute });
                checkedListBoxAttributes.SetItemChecked(checkedListBoxAttributes.Items.Count - 1, au.AuditType != "Attribute Change History");
                //Enable all Attributes selection for Audit Summary Export type
                //if (au.AuditType != "Attribute Change History")
                //    continue;
                if (se == null)
                {
                    continue;
                }
                if (se.SelectedAttributes == null)
                {
                    continue;
                }
                string selectedAttribute = se.SelectedAttributes.Find(a => a == Attribute);
                if (selectedAttribute == null)
                {
                    checkedListBoxAttributes.SetItemChecked(checkedListBoxAttributes.Items.Count - 1, false);
                }
                else
                {
                    checkedListBoxAttributes.SetItemChecked(checkedListBoxAttributes.Items.Count - 1, true);
                }
            }

            //Disable Attributes selection for Audit Summary Export type
            if (au.AuditType != "Attribute Change History")
            {
                checkedListBoxAttributes.Enabled = false;
            }

            //Display Export Filter
            if (se != null && se.Filter != null && se.Filter != "")
            {
                xmlEditor1.Text = se.Filter;
            }
        }
        /// <summary>
        /// Downloads the env audit structure.
        /// </summary>
        /// <param name="connectionName">Name of the connection.</param>
        /// <returns>The Environment Audit Structure.</returns>
        public EnvAuditStructure downloadEnvAuditStructure(string connectionName)
        {
            try
            {
                MSCRMConnection connection = cm.getConnection(connectionName);
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                EnvAuditStructure es = new EnvAuditStructure();
                es.Entities = new List<EnvAuditEntity>();
                es.Users = new List<AuditUser>();

                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.IsAuditEnabled.Value && currentEntity.LogicalName != "audit")
                        continue;

                    EnvAuditEntity ee = new EnvAuditEntity();
                    ee.LogicalName = currentEntity.LogicalName;
                    ee.ObjectTypeCode = currentEntity.ObjectTypeCode.Value;
                    ee.PrimaryNameAttribute = currentEntity.PrimaryNameAttribute;
                    ee.Attributes = new List<string>();
                    IOrderedEnumerable<AttributeMetadata> AMD = currentEntity.Attributes.OrderBy(a => a.LogicalName);

                    if (currentEntity.LogicalName == "audit")
                    {
                        es.Operations = new List<KeyValuePair<int, string>>();
                    }
                    foreach (AttributeMetadata currentAttribute in AMD)
                    {
                        if (!currentAttribute.IsAuditEnabled.Value && currentEntity.LogicalName != "audit")
                            continue;

                        // Only write out main attributes enabled for reading and creation.
                        if ((currentAttribute.AttributeOf == null) &&
                            currentAttribute.IsValidForRead.Value &&
                            currentAttribute.IsValidForCreate.Value &&
                            IgnoredAttributes.IndexOf(currentAttribute.LogicalName) < 0)
                        {
                            ee.Attributes.Add(currentAttribute.LogicalName);
                        }

                        if (currentEntity.LogicalName == "audit")
                        {
                            if (currentAttribute.LogicalName == "operation")
                            {
                                var typedAttribute = (PicklistAttributeMetadata)currentAttribute;
                                foreach (var option in typedAttribute.OptionSet.Options)
                                {
                                    es.Operations.Add(new KeyValuePair<int, string>(option.Value.Value, option.Label.UserLocalizedLabel.Label));
                                }
                            }
                            else if (currentAttribute.LogicalName == "action")
                            {
                                var typedAttribute = (PicklistAttributeMetadata)currentAttribute;
                                foreach (var option in typedAttribute.OptionSet.Options)
                                {
                                    es.Actions.Add(new KeyValuePair<int, string>(option.Value.Value, option.Label.UserLocalizedLabel.Label));
                                }
                            }
                        }
                    }
                    //Dont export entitites for which only the ID is retrieved
                    if (ee.Attributes.Count > 1)
                        es.Entities.Add(ee);
                }

                //Get users
                string usersQuery = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='systemuser'>";
                usersQuery += "<attribute name='fullname' /><attribute name='systemuserid' /><order attribute='fullname' descending='false' />";
                usersQuery += "</entity></fetch>";

                RetrieveMultipleRequest UsersRequest = new RetrieveMultipleRequest()
                {
                    Query = new FetchExpression(usersQuery)
                };

                EntityCollection Users = ((RetrieveMultipleResponse)_serviceProxy.Execute(UsersRequest)).EntityCollection;

                foreach (Entity User in Users.Entities)
                {
                    es.Users.Add(new AuditUser { Id = User.Id, FullName = (string)User["fullname"] });
                }

                es.connectionName = connectionName;
                WriteEnvStructure(es);
                return es;
            }
            catch (Exception)
            {
                throw;
            }
        }