private static void Main(string[] args)
        {
            //Set the application directory as the current directory
            string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

            appPath = appPath.Replace("file:\\", "");
            Directory.SetCurrentDirectory(appPath);

            MSCRMNtoNAssociationsTransportManager man = new MSCRMNtoNAssociationsTransportManager();
            string selectedProfileName = "";

            if (args.Length == 0)
            {
                if (man.Profiles.Count == 0)
                {
                    Console.WriteLine("\nNo profiles found.");
                    return;
                }

                //Display all profiles for selection
                Console.WriteLine("\nSpecify the Profile to run (1-{0}) [1] : ", man.Profiles.Count);
                int tpCpt = 1;
                foreach (NtoNAssociationsTransportProfile profile in man.Profiles)
                {
                    Console.WriteLine(tpCpt + ". " + profile.ProfileName);
                    tpCpt++;
                }

                String input = Console.ReadLine();
                if (input == String.Empty)
                {
                    input = "1";
                }
                int depNumber;
                Int32.TryParse(input, out depNumber);
                if (depNumber > 0 && depNumber <= man.Profiles.Count)
                {
                    selectedProfileName = man.Profiles[depNumber - 1].ProfileName;
                }
                else
                {
                    Console.WriteLine("The specified Profile does not exist.");
                    return;
                }
            }
            else
            {
                //Check that the Profile name is provided
                if (string.IsNullOrEmpty(args[0]))
                {
                    return;
                }
                selectedProfileName = args[0];
            }

            NtoNAssociationsTransportProfile p = man.GetProfile(selectedProfileName);

            if (p == null)
            {
                Console.WriteLine("The specified Profile does not exist.");
                return;
            }

            man.RunProfile(p);
        }
        /// <summary>
        /// Exports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="transportReportFileName">Name of the transport report file.</param>
        private void Export(NtoNAssociationsTransportProfile profile, string transportReportFileName)
        {
            NtoNTransportReport report = null;
            try
            {
                report = new NtoNTransportReport(transportReportFileName);
                //Get Transport Report
                if (File.Exists(transportReportFileName))
                {
                    report = ReadTransportReport(transportReportFileName);
                }

                //Clean Data folder
                string dataExportFolder = Folder + "\\" + profile.ProfileName + "\\Data";
                if (Directory.Exists(dataExportFolder))
                {
                    Directory.Delete(dataExportFolder, true);
                }
                Directory.CreateDirectory(dataExportFolder);

                MSCRMConnection connection = profile.getSourceConneciton();
                NtoNRelationshipsStructure es = ReadEnvStructure(profile.SourceConnectionName);
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                List<NtoNTransportReportLine> TransportReport = new List<NtoNTransportReportLine>();
                profile.TotalExportedRecords = 0;
                //Mesure export time
                DateTime exportStartDT = DateTime.Now;

                LogManager.WriteLog("Start exporting data from " + connection.ConnectionName);

                int recordCount = 0;
                if (es != null)
                {
                    foreach (SelectedNtoNRelationship ee in profile.SelectedNtoNRelationships)
                    {
                        LogManager.WriteLog("Exporting data for relationship " + ee.RelationshipSchemaName);
                        DateTime entityExportStartDT = DateTime.Now;
                        string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                        fetchXml += "<entity name='" + ee.IntersectEntityName + "'>";
                        //Get Entity structure
                        NtoNRelationship strE = new NtoNRelationship();
                        foreach (NtoNRelationship envE in es.NtoNRelationships)
                        {
                            if (envE.IntersectEntityName == ee.IntersectEntityName)
                            {
                                strE = envE;
                                fetchXml += "<attribute name='" + strE.Entity1IntersectAttribute + "' />";
                                fetchXml += "<attribute name='" + strE.Entity2IntersectAttribute + "' />";
                                if (ee.IntersectEntityName == "listmember" || ee.IntersectEntityName == "campaignitem")
                                    fetchXml += "<attribute name='entitytype' />";
                                else if (ee.IntersectEntityName == "campaignactivityitem")
                                    fetchXml += "<attribute name='itemobjecttypecode' />";

                                break;
                            }
                        }

                        //Add Query filter
                        int objectTypeCode = 0;
                        if (ee.Entity2LogicalName == "account") objectTypeCode = 1;
                        else if (ee.Entity2LogicalName == "campaign") objectTypeCode = 4400;
                        else if (ee.Entity2LogicalName == "contact") objectTypeCode = 2;
                        else if (ee.Entity2LogicalName == "lead") objectTypeCode = 4;
                        else if (ee.Entity2LogicalName == "list") objectTypeCode = 4300;
                        else if (ee.Entity2LogicalName == "product") objectTypeCode = 1024;
                        else if (ee.Entity2LogicalName == "salesliterature") objectTypeCode = 1038;

                        if (ee.IntersectEntityName == "campaignitem")
                            fetchXml += "<filter type='and'><condition attribute='entitytype' operator='eq' value='" + objectTypeCode + "' /></filter>";
                        else if (ee.IntersectEntityName == "campaignactivityitem")
                            fetchXml += "<filter type='and'><condition attribute='itemobjecttypecode' operator='eq' value='" + objectTypeCode + "' /></filter>";

                        fetchXml += "</entity></fetch>";
                        int recordCountPerEntity = ExportEntity(profile, fetchXml, ee.RelationshipSchemaName);
                        recordCount += recordCountPerEntity;
                        DateTime entityExportEndDT = DateTime.Now;
                        TimeSpan ts = entityExportEndDT - entityExportStartDT;
                        NtoNTransportReportLine transportReportLine = new NtoNTransportReportLine();
                        transportReportLine.RelationshipSchemaName = ee.RelationshipSchemaName;
                        transportReportLine.ExportedRecords = recordCountPerEntity;
                        report.TotalExportedRecords += recordCountPerEntity;
                        transportReportLine.ExportedIn = ts.ToString().Substring(0, 10);
                        transportReportLine.ExportStartedAt = entityExportStartDT.ToString();
                        transportReportLine.ExportFinishedAt = entityExportEndDT.ToString();
                        report.ReportLines.Add(transportReportLine);
                        WriteTransportReport(report, transportReportFileName);
                    }
                }

                TimeSpan exportTimeSpan = DateTime.Now - exportStartDT;
                LogManager.WriteLog("Export finished for " + profile.SourceConnectionName + ". Exported " + recordCount + " records in " + exportTimeSpan.ToString().Substring(0, 10));
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                }
            }
        }
        /// <summary>
        /// Imports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="transportReportFileName">Name of the transport report file.</param>
        private void Import(NtoNAssociationsTransportProfile profile, string transportReportFileName)
        {
            int totalTreatedRecords = 0;
            int totalImportFailures = 0;
            int totalImportSuccess = 0;
            int ReconnectionRetryCount = 5;

            try
            {
                NtoNTransportReport report = new NtoNTransportReport(transportReportFileName);
                //Get Transport Report
                if (File.Exists(transportReportFileName))
                {
                    report = ReadTransportReport(transportReportFileName);
                }

                MSCRMConnection connection = profile.getTargetConneciton(); ;
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                LogManager.WriteLog("Start importing data in " + connection.ConnectionName);

                //Mesure import time
                DateTime importStartDT = DateTime.Now;

                //es = ReadEnvStructure(profile.SourceConnectionName);

                foreach (SelectedNtoNRelationship ee in profile.SelectedNtoNRelationships)
                {
                    //Check if there are any records to import
                    if (ee.ExportedRecords == 0)
                    {
                        continue;
                    }

                    //Mesure import time
                    DateTime entityImportStartDT = DateTime.Now;

                    string entityFolderPath = Folder + "\\" + profile.ProfileName + "\\Data\\" + ee.RelationshipSchemaName;
                    string[] filePaths = Directory.GetFiles(entityFolderPath, "*.xml");

                    LogManager.WriteLog("Importing " + ee.RelationshipSchemaName + " records.");
                    int treatedRecordsForEntity = 0;
                    int importedRecordsForEntity = 0;
                    int importFailuresForEntity = 0;

                    foreach (string filePath in filePaths)
                    {
                        List<Type> knownTypes = new List<Type>();
                        knownTypes.Add(typeof(Entity));

                        XmlDictionaryReaderQuotas XRQ = new XmlDictionaryReaderQuotas();
                        XRQ.MaxStringContentLength = int.MaxValue;

                        using(FileStream fs = new FileStream(filePath, FileMode.Open))
                        using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, XRQ))
                        {
                            DataContractSerializer ser = new DataContractSerializer(typeof(EntityCollection), knownTypes);
                            EntityCollection fromDisk = (EntityCollection)ser.ReadObject(reader, true);

                            foreach (Entity en in fromDisk.Entities)
                            {
                                EntityReference relatedEntity1 = new EntityReference();
                                EntityReference relatedEntity2 = new EntityReference();

                                try
                                {
                                    Guid relatedEntity1Id = getRelatedEntityGuid(en[ee.Entity1IntersectAttribute]);
                                    Guid relatedEntity2Id = getRelatedEntityGuid(en[ee.Entity2IntersectAttribute]);

                                    relatedEntity1 = new EntityReference { LogicalName = ee.Entity1LogicalName, Id = relatedEntity1Id };
                                    relatedEntity2 = new EntityReference { LogicalName = ee.Entity2LogicalName, Id = relatedEntity2Id };

                                    if (!AlreadyAssociated(_serviceProxy, ee, relatedEntity1Id, relatedEntity2Id))
                                    {
                                        if (ee.IntersectEntityName == "listmember")
                                        {
                                            Guid entity_id = Guid.Empty;
                                            Guid list_id = Guid.Empty;

                                            if (ee.Entity1LogicalName == "list")
                                            {
                                                entity_id = relatedEntity2Id;
                                                list_id = relatedEntity1Id;
                                            }
                                            else
                                            {
                                                entity_id = relatedEntity1Id;
                                                list_id = relatedEntity2Id;
                                            }

                                            AddMemberListRequest request = new AddMemberListRequest();
                                            request.EntityId = entity_id;
                                            request.ListId = list_id;
                                            AddMemberListResponse response = (AddMemberListResponse)service.Execute(request);
                                        }
                                        else if (ee.IntersectEntityName == "campaignitem")
                                        {
                                            Guid entity_id = Guid.Empty;
                                            Guid list_id = Guid.Empty;
                                            string EntityName = "";

                                            if (ee.Entity1LogicalName == "campaign")
                                            {
                                                entity_id = relatedEntity2Id;
                                                list_id = relatedEntity1Id;
                                                EntityName = (string)en["entitytype"];
                                                relatedEntity2.LogicalName = EntityName;
                                            }
                                            else
                                            {
                                                entity_id = relatedEntity1Id;
                                                list_id = relatedEntity2Id;
                                                EntityName = (string)en["entitytype"];
                                                relatedEntity1.LogicalName = EntityName;
                                            }

                                            AddItemCampaignRequest req = new AddItemCampaignRequest();
                                            req.CampaignId = relatedEntity1Id;
                                            req.EntityName = EntityName;
                                            req.EntityId = entity_id;
                                            AddItemCampaignResponse resp = (AddItemCampaignResponse)service.Execute(req);
                                        }
                                        else if (ee.IntersectEntityName == "campaignactivityitem")
                                        {
                                            Guid entity_id = Guid.Empty;
                                            Guid list_id = Guid.Empty;
                                            string EntityName = "";

                                            if (ee.Entity1LogicalName == "campaignactivity")
                                            {
                                                entity_id = relatedEntity2Id;
                                                list_id = relatedEntity1Id;
                                                EntityName = (string)en["itemobjecttypecode"];
                                                relatedEntity2.LogicalName = EntityName;
                                            }
                                            else
                                            {
                                                entity_id = relatedEntity1Id;
                                                list_id = relatedEntity2Id;
                                                EntityName = (string)en["itemobjecttypecode"];
                                                relatedEntity1.LogicalName = EntityName;
                                            }

                                            AddItemCampaignActivityRequest req = new AddItemCampaignActivityRequest();
                                            req.CampaignActivityId = relatedEntity1Id;
                                            req.EntityName = EntityName;
                                            req.ItemId = entity_id;
                                            AddItemCampaignActivityResponse resp = (AddItemCampaignActivityResponse)service.Execute(req);
                                        }
                                        else
                                        {
                                            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
                                            relatedEntities.Add(relatedEntity2);
                                            Relationship relationship = new Relationship(ee.RelationshipSchemaName);
                                            relationship.PrimaryEntityRole = EntityRole.Referencing;
                                            service.Associate(relatedEntity1.LogicalName, relatedEntity1.Id, relationship, relatedEntities);
                                        }
                                    }

                                    importedRecordsForEntity++;
                                    totalImportSuccess++;
                                }
                                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                                {
                                    totalImportFailures++;
                                    importFailuresForEntity++;
                                    NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure
                                    {
                                        CreatedOn = DateTime.Now.ToString(),
                                        NtoNRelationshipName = ee.RelationshipSchemaName,
                                        Reason = ex.Detail.Message,
                                        UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(),
                                        UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString()
                                    };
                                    report.TotalImportFailures += 1;
                                    //Insert the Failure line in the Failures Report
                                    WriteNewImportFailureLine(failure, importFailuresReportFileName);
                                }
                                catch (Exception ex)
                                {
                                    //Check if the authentification session is expired
                                    if (ex.InnerException != null && ex.InnerException.Message.StartsWith("ID3242"))
                                    {
                                        LogManager.WriteLog("Error:The CRM authentication session expired. Reconnection attempt n° " + ReconnectionRetryCount);
                                        ReconnectionRetryCount--;
                                        //On 5 failed reconnections exit
                                        if (ReconnectionRetryCount == 0)
                                            throw;

                                        _serviceProxy = cm.connect(connection);
                                        service = (IOrganizationService)_serviceProxy;
                                        LogManager.WriteLog("Error:The CRM authentication session expired.");
                                        totalImportFailures++;
                                        importFailuresForEntity++;
                                        NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure
                                        {
                                            CreatedOn = DateTime.Now.ToString(),
                                            NtoNRelationshipName = ee.RelationshipSchemaName,
                                            Reason = ex.InnerException.Message,
                                            UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(),
                                            UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString()
                                        };
                                        report.TotalImportFailures += 1;
                                        //Insert the Failure line in the Failures Report
                                        WriteNewImportFailureLine(failure, importFailuresReportFileName);
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                                totalTreatedRecords++;
                                treatedRecordsForEntity++;
                                updateTransportReport(report, ee, importedRecordsForEntity, importFailuresForEntity, entityImportStartDT);
                            }
                        }
                    }
                    LogManager.WriteLog("Treated " + treatedRecordsForEntity + " " + ee.RelationshipSchemaName + " records with " + importedRecordsForEntity + " successfully imported records and " + importFailuresForEntity + " failures.");
                }

                TimeSpan importTimeSpan = DateTime.Now - importStartDT;
                LogManager.WriteLog("Import finished for " + connection.ConnectionName + ". Treated " + totalTreatedRecords + " records in " + importTimeSpan.ToString().Substring(0, 10) + ". Successfuly imported " + totalImportSuccess + " records and " + totalImportFailures + " failures.");
                WriteTransportReport(report, transportReportFileName);
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                }
            }
        }
        /// <summary>
        /// Runs the profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <returns>The Execution Report File Name</returns>
        public string RunProfile(NtoNAssociationsTransportProfile profile)
        {
            LogManager.WriteLog("Running N*N Transportation Profile: " + profile.ProfileName);

            //Check if there are selected Relationships to transport
            if (profile.SelectedNtoNRelationships == null || profile.SelectedNtoNRelationships.Count == 0)
            {
                LogManager.WriteLog("No Relationships selected for transport. Select the Relationships and then run the profile");
                return "";
            }

            DateTime now = DateTime.Now;
            ReportFileName = Folder + "\\" + profile.ProfileName + "\\ExecutionReports\\TransportReport" + now.Year + "-" + now.Month + "-" + now.Day + "-" + now.Hour + "-" + now.Minute + "-" + now.Second + ".xml";
            importFailuresReportFileName = Folder + "\\" + profile.ProfileName + "\\ExecutionReports\\ImportFailuresReport" + now.Year + "-" + now.Month + "-" + now.Day + "-" + now.Hour + "-" + now.Minute + "-" + now.Second + ".xml";

            //Initialize Execution Reports folder
            string executionReportsFolder = Folder + "\\" + profile.ProfileName + "\\ExecutionReports";
            if (!Directory.Exists(executionReportsFolder))
            {
                Directory.CreateDirectory(executionReportsFolder);
            }

            //Create Transport Report
            NtoNTransportReport tr = new NtoNTransportReport(profile.ProfileName);
            WriteTransportReport(tr, ReportFileName);

            //Check for the Operation to execute
            if (profile.Operation == 0)
            {
                //Export data
                Export(profile, ReportFileName);
            }
            else if (profile.Operation == 1)
            {
                //Import Data
                Import(profile, ReportFileName);
            }
            else if (profile.Operation == 2)
            {
                //Transport data => Export + Import
                Export(profile, ReportFileName);
                Import(profile, ReportFileName);
            }

            NtoNTransportReport report = ReadTransportReport(ReportFileName);
            report.TransportFinishedAt = DateTime.Now.ToString();
            report.TransportCompleted = true;
            TimeSpan TransportTimeSpan = DateTime.Now - Convert.ToDateTime(report.TransportStartedAt);
            report.TransportedIn = TransportTimeSpan.ToString().Substring(0, 10);
            WriteTransportReport(report, ReportFileName);

            return ReportFileName;
        }
        /// <summary>
        /// Updates the profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        public void UpdateProfile(NtoNAssociationsTransportProfile profile)
        {
            if (!Directory.Exists(Folder + "\\" + profile.ProfileName))
                Directory.CreateDirectory(Folder + "\\" + profile.ProfileName);

            //Refresh Profiles  in case some other instance is updating the profiles
            ReadProfiles();

            for (int i = 0; i < Profiles.Count; i++)
            {
                if (Profiles[i].ProfileName == profile.ProfileName)
                {
                    Profiles[i] = profile;
                    break;
                }
            }
            WriteProfiles();
        }
        /// <summary>
        /// Deletes the profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        public void DeleteProfile(NtoNAssociationsTransportProfile profile)
        {
            //Refresh Profiles in case some other instance is updating the profiles
            ReadProfiles();

            for (int i = 0; i < Profiles.Count; i++)
            {
                if (Profiles[i].ProfileName == profile.ProfileName)
                {
                    Profiles.RemoveAt(i);
                }
            }

            //Delete Profile folder
            try
            {
                if (Directory.Exists(Folder + "\\" + profile.ProfileName))
                    Directory.Delete(Folder + "\\" + profile.ProfileName, true);
            }
            catch (Exception)
            {
                throw;
            }

            //Save Profiles
            WriteProfiles();
        }
        /// <summary>
        /// Exports the entity.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="fetchXml">The fetch fetchXML query.</param>
        /// <param name="RelationshipSchemaName">Name of the relationship schema.</param>
        /// <returns>The number of exported record for the Entity</returns>
        public int ExportEntity(NtoNAssociationsTransportProfile profile, string fetchXml, string RelationshipSchemaName)
        {
            //Set the number of records per page to retrieve.
            //This value should not be bigger than 5000 as this is the limit of records provided by the CRM
            int fetchCount = 5000;
            // Initialize the file number.
            int fileNumber = 1;
            // Initialize the number of records.
            int recordCount = 0;
            // Specify the current paging cookie. For retrieving the first page, pagingCookie should be null.
            string pagingCookie = null;
            string entityName = "";

            while (true)
            {
                // Build fetchXml string with the placeholders.
                string xml = CreateXml(fetchXml, pagingCookie, fileNumber, fetchCount);

                // Execute the fetch query and get the xml result.

                RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

                EntityCollection returnCollection = ((RetrieveMultipleResponse)_serviceProxy.Execute(fetchRequest)).EntityCollection;
                recordCount += returnCollection.Entities.Count;
                if (recordCount > 0)
                {
                    string entityFolderName = Folder + "\\" + profile.ProfileName + "\\Data\\" + RelationshipSchemaName;
                    entityName = returnCollection.EntityName;
                    if (!Directory.Exists(entityFolderName))
                        Directory.CreateDirectory(entityFolderName);
                    List<Type> knownTypes = new List<Type>();
                    knownTypes.Add(typeof(Entity));
                    int fileCpt = 1000000 + fileNumber;
                    string filename = entityFolderName + "\\" + fileCpt + ".xml";
                    FileStream writer = new FileStream(filename, FileMode.Create);
                    DataContractSerializer ser = new DataContractSerializer(typeof(EntityCollection), knownTypes);
                    ser.WriteObject(writer, returnCollection);
                    writer.Close();
                }
                // Check for more records, if it returns 1.
                if (returnCollection.MoreRecords)
                {
                    // Increment the page number to retrieve the next page.
                    fileNumber++;
                    pagingCookie = returnCollection.PagingCookie;
                }
                else
                {
                    // If no more records in the result nodes, exit the loop.
                    break;
                }
            }

            if (recordCount > 0)
            {
                //Save Exported Entites number
                foreach (SelectedNtoNRelationship ee in profile.SelectedNtoNRelationships)
                {
                    if (RelationshipSchemaName == ee.RelationshipSchemaName)
                    {
                        ee.ExportedRecords = recordCount;
                    }
                }

                profile.TotalExportedRecords += recordCount;
                UpdateProfile(profile);
            }
            LogManager.WriteLog("Exported " + recordCount + " " + entityName + " records.");

            return recordCount;
        }
        /// <summary>
        /// Creates the profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        public void CreateProfile(NtoNAssociationsTransportProfile profile)
        {
            if (!Directory.Exists(Folder + "\\" + profile.ProfileName))
                Directory.CreateDirectory(Folder + "\\" + profile.ProfileName);

            //Refresh Profiles in case some other instance is updating the profiles
            ReadProfiles();

            //Creating new Profile
            Profiles.Add(profile);
            WriteProfiles();
        }
        private bool SaveProfile()
        {
            bool result = true;
            //Check that all fields are provided
            if (string.IsNullOrEmpty(textBoxTransportationProfileName.Text))
            {
                MessageBox.Show("Profile Name is mandatory!");
                return false;
            }

            //Check that the name of the profile is valid
            if (textBoxTransportationProfileName.Text.Contains(" ") ||
                    textBoxTransportationProfileName.Text.Contains("\\") ||
                    textBoxTransportationProfileName.Text.Contains("/") ||
                    textBoxTransportationProfileName.Text.Contains(">") ||
                    textBoxTransportationProfileName.Text.Contains("<") ||
                    textBoxTransportationProfileName.Text.Contains("?") ||
                    textBoxTransportationProfileName.Text.Contains("*") ||
                    textBoxTransportationProfileName.Text.Contains(":") ||
                    textBoxTransportationProfileName.Text.Contains("|") ||
                    textBoxTransportationProfileName.Text.Contains("\"") ||
                    textBoxTransportationProfileName.Text.Contains("'")
                    )
            {
                MessageBox.Show("You shouldn't use spaces nor the following characters (\\/<>?*:|\"') in the Profile Name as it will be used to create folders and files.");
                return false;
            }

            if (comboBoxConnectionSource.SelectedItem == null)
            {
                MessageBox.Show("You must select a Source for the Profile");
                return false;
            }

            if (comboBoxConnectionTarget.SelectedItem == null && comboBoxOperation.SelectedItem.ToString() != "Export Data")
            {
                MessageBox.Show("You must select a Target for the Profile");
                return false;
            }

            //Check if this is a creation
            if (currentProfile == null)
            {
                //Check if a Connection having the same name exist already
                foreach (NtoNAssociationsTransportProfile tp in man.Profiles)
                {
                    if (tp.ProfileName.ToLower() == textBoxTransportationProfileName.Text.ToLower())
                    {
                        MessageBox.Show("Profile with the name " + textBoxTransportationProfileName.Text + " exist already. Please select another name");
                        return false;
                    }
                }

                NtoNAssociationsTransportProfile newProfile = new NtoNAssociationsTransportProfile();
                newProfile.ProfileName = textBoxTransportationProfileName.Text;
                //newProfile.ImportMode = comboBoxImportMode.SelectedIndex;
                newProfile.SourceConnectionName = comboBoxConnectionSource.SelectedItem.ToString();
                newProfile.setSourceConneciton();
                if (comboBoxOperation.SelectedItem.ToString() != "Export Data")
                {
                    newProfile.TargetConnectionName = comboBoxConnectionTarget.SelectedItem.ToString();
                    newProfile.setTargetConneciton();
                }
                newProfile.SelectedNtoNRelationships = new List<SelectedNtoNRelationship>();

                dataGridView1.EndEdit();
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)row.Cells[0];

                    if (check.Value != null && (bool)check.Value)
                    {
                        NtoNRelationship nnr = es.NtoNRelationships.Find(r => r.RelationshipSchemaName == (string)row.Cells[1].Value);
                        SelectedNtoNRelationship ee = new SelectedNtoNRelationship();
                        ee.RelationshipSchemaName = nnr.RelationshipSchemaName;
                        ee.IntersectEntityName = nnr.IntersectEntityName;
                        ee.Entity1IntersectAttribute = nnr.Entity1IntersectAttribute;
                        ee.Entity1LogicalName = nnr.Entity1LogicalName;
                        ee.Entity2IntersectAttribute = nnr.Entity2IntersectAttribute;
                        ee.Entity2LogicalName = nnr.Entity2LogicalName;
                        ee.ExportedRecords = 0;
                        newProfile.SelectedNtoNRelationships.Add(ee);
                    }
                }

                newProfile.Operation = comboBoxOperation.SelectedIndex;
                man.CreateProfile(newProfile);
                comboBoxTransportationProfiles.Items.AddRange(new object[] { newProfile.ProfileName });
                comboBoxTransportationProfiles.SelectedItem = newProfile.ProfileName;
                currentProfile = newProfile;
            }
            else
            {
                currentProfile.ProfileName = textBoxTransportationProfileName.Text;
                //currentProfile.ImportMode = comboBoxImportMode.SelectedIndex;
                currentProfile.SourceConnectionName = comboBoxConnectionSource.SelectedItem.ToString();
                currentProfile.setSourceConneciton();
                if (comboBoxOperation.SelectedItem.ToString() != "Export Data")
                {
                    currentProfile.TargetConnectionName = comboBoxConnectionTarget.SelectedItem.ToString();
                    currentProfile.setTargetConneciton();
                }

                //Backup Export Records numbers if existing
                List<SelectedNtoNRelationship> backupSelectedEntites = currentProfile.SelectedNtoNRelationships;

                currentProfile.SelectedNtoNRelationships = new List<SelectedNtoNRelationship>();

                NtoNAssociationsTransportProfile oldProfile = man.GetProfile(currentProfile.ProfileName);

                dataGridView1.EndEdit();
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)row.Cells[0];
                    if (check.Value != null && (bool)check.Value)
                    {
                        NtoNRelationship nnr = es.NtoNRelationships.Find(r => r.RelationshipSchemaName == (string)row.Cells[1].Value);
                        SelectedNtoNRelationship ee = new SelectedNtoNRelationship();
                        ee.RelationshipSchemaName = nnr.RelationshipSchemaName;
                        ee.IntersectEntityName = nnr.IntersectEntityName;
                        ee.Entity1IntersectAttribute = nnr.Entity1IntersectAttribute;
                        ee.Entity1LogicalName = nnr.Entity1LogicalName;
                        ee.Entity2IntersectAttribute = nnr.Entity2IntersectAttribute;
                        ee.Entity2LogicalName = nnr.Entity2LogicalName;
                        ee.ExportedRecords = 0;
                        currentProfile.SelectedNtoNRelationships.Add(ee);
                    }
                }

                currentProfile.Operation = comboBoxOperation.SelectedIndex;
                man.UpdateProfile(currentProfile);
            }

            runProfileToolStripMenuItem.Enabled = true;
            toolStripStatusLabel.Text = "Profile " + currentProfile.ProfileName + " saved.";
            LogManager.WriteLog("Profile " + currentProfile.ProfileName + " saved.");
            return result;
        }
 private void newToolStripMenuItem_Click(object sender, EventArgs e)
 {
     currentProfile = null;
     textBoxTransportationProfileName.Text = "";
     //comboBoxImportMode.SelectedIndex = 0;
     comboBoxConnectionSource.SelectedItem = null;
     comboBoxConnectionTarget.SelectedItem = null;
     comboBoxTransportationProfiles.SelectedItem = null;
     comboBoxOperation.SelectedIndex = 2;
     //comboBoxImportMode.SelectedIndex = 1;
 }
 private void deleteProfileToolStripMenuItem_Click(object sender, EventArgs e)
 {
     string currentTransportationProfileName = currentProfile.ProfileName;
     DialogResult dResTest;
     dResTest = MessageBox.Show("Are you sure you want to delete this Profile ?", "Confirm Profile Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
     if (dResTest == DialogResult.No)
     {
         return;
     }
     else
     {
         comboBoxTransportationProfiles.Items.Remove(currentProfile.ProfileName);
         comboBoxTransportationProfiles.SelectedItem = null;
         man.DeleteProfile(currentProfile);
         currentProfile = null;
         textBoxTransportationProfileName.Text = "";
         labelStructureLastLoadedDate.Text = "never";
         textBoxTransportationProfileName.Enabled = true;
         comboBoxConnectionSource.SelectedItem = null;
         comboBoxConnectionTarget.SelectedItem = null;
         comboBoxOperation.SelectedIndex = 2;
         //comboBoxImportMode.SelectedIndex = 1;
         toolStripStatusLabel.Text = "Profile " + currentTransportationProfileName + " deleted";
     }
 }
 private void comboBoxTransportationProfiles_SelectedIndexChanged(object sender, EventArgs e)
 {
     comboBoxConnectionSource.SelectedItem = null;
     comboBoxConnectionTarget.SelectedItem = null;
     if (comboBoxTransportationProfiles.SelectedItem != null)
     {
         currentProfile = man.Profiles[comboBoxTransportationProfiles.SelectedIndex];
         textBoxTransportationProfileName.Text = currentProfile.ProfileName;
         //comboBoxImportMode.SelectedIndex = currentProfile.ImportMode;
         comboBoxConnectionSource.SelectedItem = currentProfile.SourceConnectionName;
         comboBoxConnectionTarget.SelectedItem = currentProfile.TargetConnectionName;
         TemporarySelectedEntityListForIgnoredAttributes = currentProfile.SelectedNtoNRelationships;
         deleteProfileToolStripMenuItem.Enabled = true;
         textBoxTransportationProfileName.Enabled = false;
         comboBoxOperation.SelectedIndex = currentProfile.Operation;
         runProfileToolStripMenuItem.Enabled = true;
     }
     else
     {
         currentProfile = null;
         textBoxTransportationProfileName.Text = "";
         comboBoxOperation.SelectedIndex = 2;
         //comboBoxImportMode.SelectedIndex = 1;
         deleteProfileToolStripMenuItem.Enabled = false;
         textBoxTransportationProfileName.Enabled = true;
         labelStructureLastLoadedDate.Text = "never";
         runProfileToolStripMenuItem.Enabled = false;
     }
 }