/// <summary>
        /// Downloads the env structure.
        /// </summary>
        /// <param name="connectionName">Name of the connection.</param>
        /// <returns>The N to N Relationships Structure</returns>
        public NtoNRelationshipsStructure downloadEnvStructure(string connectionName)
        {
            try
            {
                MSCRMConnection connection = cm.getConnection(connectionName);
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                NtoNRelationshipsStructure es = new NtoNRelationshipsStructure();
                es.NtoNRelationships = new List<NtoNRelationship>();

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

                // Retrieve the MetaData.
                RetrieveAllEntitiesResponse AllEntitiesResponse = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                List<string> TreatedRelationships = new List<string>();

                foreach (EntityMetadata currentEntity in AllEntitiesResponse.EntityMetadata)
                {
                    List<ManyToManyRelationshipMetadata> ManyToManyRelationships = currentEntity.ManyToManyRelationships.ToList();
                    foreach (ManyToManyRelationshipMetadata relationship in ManyToManyRelationships)
                    {
                        if (!relationship.IsValidForAdvancedFind.Value)
                            continue;

                        if (relationship.IntersectEntityName == "subscriptionmanuallytrackedobject")
                            continue;

                        if (TreatedRelationships.Find(r => r == relationship.SchemaName) != null)
                            continue;

                        NtoNRelationship ee = new NtoNRelationship();
                        // Start Entity Node
                        ee.RelationshipSchemaName = relationship.SchemaName;
                        ee.IntersectEntityName = relationship.IntersectEntityName;
                        ee.Entity1LogicalName = relationship.Entity1LogicalName;
                        ee.Entity1IntersectAttribute = relationship.Entity1IntersectAttribute;
                        ee.Entity2LogicalName = relationship.Entity2LogicalName;
                        ee.Entity2IntersectAttribute = relationship.Entity2IntersectAttribute;

                        // End Entity Node
                        TreatedRelationships.Add(relationship.SchemaName);
                        es.NtoNRelationships.Add(ee);
                    }
                }

                //Order by SchemaName
                IOrderedEnumerable<NtoNRelationship> orderedNtoNRelationships = es.NtoNRelationships.OrderBy(se => se.RelationshipSchemaName);
                es.NtoNRelationships = orderedNtoNRelationships.ToList<NtoNRelationship>();

                es.connectionName = connectionName;
                WriteEnvStructure(es);

                return es;
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void populateCheckedEntities()
        {
            dataGridView1.DataSource = null;

            //If Structure already downloaded display entities list
            if (comboBoxConnectionSource.SelectedItem == null)
                return;

            try
            {
                es = man.ReadEnvStructure(comboBoxConnectionSource.SelectedItem.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while reading the struction of connection " + comboBoxConnectionSource.SelectedItem.ToString() + ". The structure file may be corrupted.\r\n\r\n" + ex.Message);
                return;
            }
            labelStructureLastLoadedDate.Text = "never";
            if (es != null)
            {
                string structureFileName = man.Folder + "\\" + comboBoxConnectionSource.SelectedItem + ".xml";
                DateTime structureRefreshedOn = File.GetLastWriteTime(structureFileName);
                labelStructureLastLoadedDate.Text = structureRefreshedOn.ToString();
                SortableBindingList<NtoNRelationship> sortedNToNRelationships = new SortableBindingList<NtoNRelationship>(es.NtoNRelationships);
                dataGridView1.DataSource = sortedNToNRelationships;

                if (currentProfile != null && currentProfile.SelectedNtoNRelationships != null && currentProfile.SelectedNtoNRelationships.Count > 0)
                {
                    foreach (DataGridViewRow row in this.dataGridView1.Rows)
                    {
                        DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)row.Cells[0];
                        string RelationshipSchemaName = (string)row.Cells[1].Value;
                        bool c = currentProfile.SelectedNtoNRelationships.FindIndex(r => r.RelationshipSchemaName == RelationshipSchemaName) > -1;
                        ((DataGridViewCheckBoxCell)row.Cells[0]).Value = c;
                    }
                }
            }
        }
 /// <summary>
 /// Writes the env structure.
 /// </summary>
 /// <param name="str">The string.</param>
 private void WriteEnvStructure(NtoNRelationshipsStructure str)
 {
     string filename = Folder + "\\" + str.connectionName + ".xml";
     FileStream writer = new FileStream(filename, FileMode.Create);
     DataContractSerializer ser = new DataContractSerializer(typeof(NtoNRelationshipsStructure));
     ser.WriteObject(writer, str);
     writer.Close();
 }
        private void buttonLoadEntities_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;
            }

            toolStripStatusLabel.Text = "Loading structure. Please wait...";
            Application.DoEvents();

            try
            {
                es = man.downloadEnvStructure(comboBoxConnectionSource.SelectedItem.ToString());
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                MessageBox.Show("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                else
                {
                    MessageBox.Show("Error:" + ex.Message);
                }
            }

            if (es == null)
                return;

            string structureFileName = man.Folder + "\\" + comboBoxConnectionSource.SelectedItem.ToString() + ".xml";
            DateTime structureRefreshedOn = File.GetLastWriteTime(structureFileName);
            labelStructureLastLoadedDate.Text = structureRefreshedOn.ToString();
            //Display Relationships
            dataGridView1.DataSource = es.NtoNRelationships;

            if (currentProfile != null && currentProfile.SelectedNtoNRelationships != null && currentProfile.SelectedNtoNRelationships.Count > 0)
            {
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)row.Cells[0];
                    string RelationshipSchemaName = (string)row.Cells[1].Value;
                    bool c = currentProfile.SelectedNtoNRelationships.FindIndex(r => r.RelationshipSchemaName == RelationshipSchemaName) > -1;
                    ((DataGridViewCheckBoxCell)row.Cells[0]).Value = c;
                }
            }

            toolStripStatusLabel.Text = "Structure successfully loaded";
        }