/// <summary>
 /// Sets the target conneciton.
 /// </summary>
 /// <remarks>
 /// The TargetConnectionName must be previously set.
 /// </remarks>
 public void setTargetConneciton()
 {
     if (!string.IsNullOrEmpty(TargetConnectionName))
     {
         TargetConnection = cm.getConnection(TargetConnectionName);
     }
 }
 /// <summary>
 /// Sets the source conneciton.
 /// </summary>
 /// <remarks>
 /// The SourceConnectionName must be previously set.
 /// </remarks>
 public void setSourceConneciton()
 {
     if (!string.IsNullOrEmpty(SourceConnectionName))
     {
         SourceConnection = cm.getConnection(SourceConnectionName);
     }
 }
Пример #3
0
        private void buttonLoadReports_Click(object sender, EventArgs e)
        {
            if (comboBoxConnectionSource.SelectedItem == null)
            {
                MessageBox.Show("You must select a connection before loading Reports!");
                return;
            }

            toolStripStatusLabel1.Text = "Loading reports. Please wait...";
            Application.DoEvents();

            reportsList = new List <MSCRMReport>();
            dataGridView1.DataSource = reportsList;

            try
            {
                MSCRMConnection connection = cm.MSCRMConnections[comboBoxConnectionSource.SelectedIndex];
                _serviceProxy = cm.connect(connection);

                QueryExpression queryReports = new QueryExpression
                {
                    EntityName = "report",
                    ColumnSet  = new ColumnSet(true),
                    Criteria   = new FilterExpression(),
                };

                EntityCollection reports = _serviceProxy.RetrieveMultiple(queryReports);

                foreach (Entity report in reports.Entities)
                {
                    string      description = report.Attributes.Contains("description") ? (string)report["description"] : "";
                    MSCRMReport MSCRMReport = new MSCRMReport
                    {
                        Id          = report.Id,
                        Name        = (string)report["name"],
                        Description = description
                    };
                    reportsList.Add(MSCRMReport);
                }
                man.WriteReports(comboBoxConnectionSource.SelectedItem.ToString(), reportsList);
                dataGridView1.DataSource   = reportsList.ToList();
                toolStripStatusLabel1.Text = "Reports loaded.";
            }
            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);
                }
            }
        }
        /// <summary>
        /// Gets the source conneciton.
        /// </summary>
        /// <returns>
        /// The Source MSCRMConnection.
        /// </returns>
        /// <remarks>
        /// The SourceConnectionName must be previously set.
        /// </remarks>
        public MSCRMConnection getSourceConneciton()
        {
            if (!string.IsNullOrEmpty(SourceConnectionName))
            {
                SourceConnection = cm.getConnection(SourceConnectionName);
            }

            return(SourceConnection);
        }
        /// <summary>
        /// Gets the target conneciton.
        /// </summary>
        /// <returns>
        /// The Target MSCRMConnection.
        /// </returns>
        /// <remarks>
        /// The TargetConnectionName must be previously set.
        /// </remarks>
        public MSCRMConnection getTargetConneciton()
        {
            if (!string.IsNullOrEmpty(TargetConnectionName))
            {
                TargetConnection = cm.getConnection(TargetConnectionName);
            }

            return(TargetConnection);
        }
Пример #6
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 = false
                };

                // 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);
        }
Пример #7
0
        private void mapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.EndEdit();
                Guid SourceBUId = Guid.Empty;
                Guid TargetBUId = Guid.Empty;
                //Get Source Default Transaction Currency
                string          fetchBU          = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' count='1'>
                                      <entity name='businessunit'>
                                        <attribute name='businessunitid' />
                                        <attribute name='createdon' />
                                        <order attribute='createdon' descending='false' />
                                      </entity>
                                    </fetch> ";
                MSCRMConnection connectionSource = rdt.currentProfile.getSourceConneciton();
                _serviceProxySource = cm.connect(connectionSource);

                EntityCollection resultSource = _serviceProxySource.RetrieveMultiple(new FetchExpression(fetchBU));
                foreach (var s in resultSource.Entities)
                {
                    SourceBUId = (Guid)s.Attributes["businessunitid"];
                }

                //Get Target Default Transaction Currency
                MSCRMConnection connectionTarget = rdt.currentProfile.getTargetConneciton();
                _serviceProxyTarget = cm.connect(connectionTarget);

                EntityCollection resultTarget = _serviceProxyTarget.RetrieveMultiple(new FetchExpression(fetchBU));
                foreach (var t in resultTarget.Entities)
                {
                    TargetBUId = (Guid)t.Attributes["businessunitid"];
                }

                //Add the mapping
                RecordMapping rr = new RecordMapping();
                rr.EntityName     = "businessunit";
                rr.SourceRecordId = SourceBUId;
                rr.TargetRecordId = TargetBUId;
                rm.Add(rr);
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = rm;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Mapping error: " + ex.Message);
            }
        }
Пример #8
0
        /// <summary>
        /// Runs the Workflow Execution profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        public void RunProfile(MSCRMWorkflowExecutionProfile profile)
        {
            LogManager.WriteLog("Running Workflow Execution Profile: " + profile.ProfileName);

            try
            {
                MSCRMConnection connection = profile.getSourceConneciton();
                _serviceProxy = cm.connect(connection);

                EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(profile.FetchXMLQuery));

                foreach (Entity record in result.Entities)
                {
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
                    {
                        WorkflowId = profile.WorkflowId,
                        EntityId   = record.Id
                    };

                    // Execute the workflow.
                    ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_serviceProxy.Execute(request);
                }
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                throw;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                }
                throw;
            }
            LogManager.WriteLog("All workflows were launched.");
        }
        /// <summary>
        /// Downloads the solutions.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <returns>List of solutions.</returns>
        public List <MSCRMSolution> DownloadSolutions(MSCRMConnection connection)
        {
            List <MSCRMSolution> solutionsLst = new List <MSCRMSolution>();

            _serviceProxy = cm.connect(connection);

            QueryExpression querySampleSolution = new QueryExpression
            {
                EntityName = "solution",
                ColumnSet  = new ColumnSet(true),
                Criteria   = new FilterExpression(),
            };

            querySampleSolution.Criteria.AddCondition("ismanaged", ConditionOperator.Equal, false);
            querySampleSolution.Criteria.AddCondition("isvisible", ConditionOperator.Equal, true);
            EntityCollection solutions = _serviceProxy.RetrieveMultiple(querySampleSolution);

            foreach (Entity solution in solutions.Entities)
            {
                EntityReference publisher      = (EntityReference)solution["publisherid"];
                string          description    = solution.Attributes.Contains("description") ? (string)solution["description"] : "";
                MSCRMSolution   MESCRMSolution = new MSCRMSolution
                {
                    UniqueName  = (string)solution["uniquename"],
                    DisplayName = (string)solution["friendlyname"],
                    Version     = (string)solution["version"],
                    Publisher   = publisher.Name,
                    Description = description
                };
                solutionsLst.Add(MESCRMSolution);
            }

            WriteSolutions(connection.ConnectionName, solutionsLst);

            return(solutionsLst);
        }
Пример #10
0
        /// <summary>
        /// Exports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="DataExportReportFileName">Name of the data export report file.</param>
        private void Export(MSCRMDataExportProfile profile, string DataExportReportFileName)
        {
            try
            {
                DataExportReport report = new DataExportReport(DataExportReportFileName);
                //Get Data Export Report
                if (File.Exists(DataExportReportFileName))
                {
                    report = ReadReport(DataExportReportFileName);
                }

                //Set Data export folder
                string dataExportFolder = Folder + "\\" + profile.ProfileName + "\\Data";
                if (!Directory.Exists(dataExportFolder))
                {
                    Directory.CreateDirectory(dataExportFolder);
                }

                MSCRMConnection connection = profile.getSourceConneciton();
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                profile.TotalExportedRecords = 0;
                //Mesure export time
                DateTime exportStartDT = DateTime.Now;

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

                //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 recordsCount = 0;
                // Specify the current paging cookie. For retrieving the first page, pagingCookie should be null.
                string pagingCookie = null;
                string entityName   = "";

                DateTime now           = DateTime.Now;
                string   fileName      = Folder + "\\" + profile.ProfileName + "\\Data\\ExportedData";
                string   fileExtension = profile.ExportFormat.ToLower();
                if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                {
                    fileExtension = "xml";
                }

                fileName += now.Year + "-" + now.Month + "-" + now.Day + "-" + now.Hour + "-" + now.Minute + "-" + now.Second + "." + fileExtension;
                this.ExportedDataFileName = fileName;

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

                    StringReader  stringReader = new StringReader(profile.FetchXMLQuery);
                    XmlTextReader reader       = new XmlTextReader(stringReader);
                    // Load document
                    XmlDocument doc = new XmlDocument();
                    doc.Load(reader);
                    XmlNodeList xnl = doc.ChildNodes[0].ChildNodes[0].ChildNodes;

                    List <string> columns          = new List <string>();
                    List <string> DisplayedColumns = new List <string>();
                    foreach (XmlNode sm in xnl)
                    {
                        if (sm.Name == "attribute")
                        {
                            columns.Add(sm.Attributes[0].Value);
                            if (profile.ExportFormat.ToLower() == "csv")
                            {
                                DisplayedColumns.Add(profile.DataSeparator + sm.Attributes[0].Value + profile.DataSeparator);
                            }
                            else if (profile.ExportFormat.ToLower() == "xml")
                            {
                                DisplayedColumns.Add(sm.Attributes[0].Value);
                            }
                            else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                            {
                                DisplayedColumns.Add(sm.Attributes[0].Value);
                            }
                        }
                        else if (sm.Name == "link-entity")
                        {
                            //Linked entity
                            string      linkedEntityAlias    = sm.Attributes.GetNamedItem("alias").Value;
                            string      linkedAttributeyName = sm.Attributes.GetNamedItem("to").Value;
                            XmlNodeList xnlLinkedEntity      = sm.ChildNodes;
                            foreach (XmlNode linkedAttribute in xnlLinkedEntity)
                            {
                                //Check if this is not a filter
                                if (linkedAttribute.Name == "filter")
                                {
                                    continue;
                                }

                                columns.Add(linkedEntityAlias + "." + linkedAttribute.Attributes[0].Value);
                                if (profile.ExportFormat.ToLower() == "csv")
                                {
                                    DisplayedColumns.Add(profile.DataSeparator + linkedAttributeyName + "_" + linkedAttribute.Attributes[0].Value + profile.DataSeparator);
                                }
                                else if (profile.ExportFormat.ToLower() == "xml")
                                {
                                    DisplayedColumns.Add(linkedAttributeyName + "_" + linkedAttribute.Attributes[0].Value);
                                }
                                else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                                {
                                    DisplayedColumns.Add(linkedAttributeyName + "_" + linkedAttribute.Attributes[0].Value);
                                }
                            }
                        }
                    }

                    // Execute the fetch query and get the xml result.
                    RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
                    {
                        Query = new FetchExpression(xml)
                    };

                    EntityCollection returnCollection = ((RetrieveMultipleResponse)_serviceProxy.Execute(fetchRequest)).EntityCollection;
                    recordsCount += returnCollection.Entities.Count;
                    if (recordsCount > 0)
                    {
                        if (profile.ExportFormat.ToLower() == "csv")
                        {
                            WriteCSV(returnCollection, fileName, columns, DisplayedColumns, profile);
                        }
                        else if (profile.ExportFormat.ToLower() == "xml")
                        {
                            WriteXML(returnCollection, fileName, columns, DisplayedColumns, profile);
                        }
                        else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                        {
                            WriteXMLSpreadsheet2003(returnCollection, fileName, columns, DisplayedColumns, profile);
                        }
                    }
                    // 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;
                    }
                }

                Encoding encoding = GetEncoding(profile.Encoding);

                if (profile.ExportFormat.ToLower() == "xml")
                {
                    using (var writer = new StreamWriter(fileName, true, encoding))
                    {
                        writer.WriteLine("</Records>");
                        writer.Flush();
                    }
                }
                else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                {
                    using (var writer = new StreamWriter(fileName, true, encoding))
                    {
                        writer.WriteLine("</Table></Worksheet></Workbook>\n");
                        writer.Flush();
                    }
                }

                LogManager.WriteLog("Exported " + recordsCount + " " + entityName + " records.");

                report.TotalExportedRecords = recordsCount;
                ExportedRecordsNumber       = recordsCount;
                //Delete file if  no record found
                if (recordsCount < 1)
                {
                    File.Delete(fileName);
                }

                WriteReport(report, DataExportReportFileName);

                TimeSpan exportTimeSpan = DateTime.Now - exportStartDT;
                LogManager.WriteLog("Export finished for " + profile.ProfileName + ". Exported " + recordsCount + " records in " + exportTimeSpan.ToString().Substring(0, 10));
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                throw;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                }
                throw;
            }
        }
Пример #11
0
        /// <summary>
        /// Handles the Click event of the buttonLoadSolutionsImportJobs control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void buttonLoadSolutionsImportJobs_Click(object sender, EventArgs e)
        {
            try
            {
                List <MSCRMSolutionImportJob> Lst = new List <MSCRMSolutionImportJob>();
                dataGridView1.DataSource = Lst;

                if (comboBoxConnectionSource.SelectedItem == null)
                {
                    MessageBox.Show("You must select a connection before loading the Solution Import Jobs!");
                    return;
                }

                toolStripStatusLabel1.Text = "Loading Solution Import Jobs. Please wait...";
                Application.DoEvents();

                MSCRMConnection connection = cm.MSCRMConnections[comboBoxConnectionSource.SelectedIndex];
                _serviceProxy = cm.connect(connection);

                //Get Source Default Transaction Currency
                string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                      <entity name='importjob'>
                                        <attribute name='completedon' />
                                        <attribute name='createdby' />
                                        <attribute name='data' />
                                        <attribute name='importjobid' />
                                        <attribute name='modifiedon' />
                                        <attribute name='progress' />
                                        <attribute name='solutionname' />
                                        <attribute name='startedon' />
                                        <order attribute='createdon' descending='true' />
                                      </entity>
                                    </fetch> ";


                EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(fetchXml));

                if (result.Entities.Count < 1)
                {
                    MessageBox.Show("There are no Solution Import Jobs!");
                    return;
                }
                List <MSCRMSolutionImportJob> ImportJobsList = new List <MSCRMSolutionImportJob>();
                foreach (Entity ImportJob in result.Entities)
                {
                    MSCRMSolutionImportJob job = new MSCRMSolutionImportJob();
                    if (ImportJob.Contains("completedon"))
                    {
                        job.completedon = (DateTime)ImportJob["completedon"];
                    }
                    if (ImportJob.Contains("createdby"))
                    {
                        job.createdby = ((EntityReference)ImportJob["createdby"]).Name;
                    }
                    if (ImportJob.Contains("data"))
                    {
                        job.data = (String)ImportJob["data"];
                    }
                    if (ImportJob.Contains("importjobid"))
                    {
                        job.importjobid = (Guid)ImportJob["importjobid"];
                    }
                    if (ImportJob.Contains("modifiedon"))
                    {
                        job.modifiedon = (DateTime)ImportJob["modifiedon"];
                    }
                    if (ImportJob.Contains("progress"))
                    {
                        job.progress = Math.Round((Double)ImportJob["progress"], 2);
                    }
                    if (ImportJob.Contains("solutionname"))
                    {
                        job.solutionname = (String)ImportJob["solutionname"];
                    }
                    if (ImportJob.Contains("startedon"))
                    {
                        job.startedon = (DateTime)ImportJob["startedon"];
                    }

                    if (job.importjobid != null && job.importjobid != Guid.Empty)
                    {
                        ImportJobsList.Add(job);
                    }
                }

                SortableBindingList <MSCRMSolutionImportJob> sorted = new SortableBindingList <MSCRMSolutionImportJob>(ImportJobsList);
                dataGridView1.DataSource = sorted;

                toolStripStatusLabel1.Text = "Loaded " + result.Entities.Count + " Import Jobs.";
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                MessageBox.Show("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                toolStripStatusLabel1.Text = "Error.";
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                    toolStripStatusLabel1.Text = "Error.";
                }
                else
                {
                    MessageBox.Show("Error:" + ex.Message);
                    toolStripStatusLabel1.Text = "Error.";
                }
            }
        }
        /// <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(TransportationProfile profile, string transportReportFileName)
        {
            int totalTreatedRecords    = 0;
            int totalImportFailures    = 0;
            int totalImportSuccess     = 0;
            int ReconnectionRetryCount = 5;

            try
            {
                TransportReport report = new TransportReport(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;

                //Order import according to profile's import order
                IOrderedEnumerable <SelectedEntity> orderedSelectedEntities = profile.SelectedEntities.OrderBy(e => e.TransportOrder);

                foreach (SelectedEntity ee in orderedSelectedEntities)
                {
                    //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.EntityName;
                    string[] filePaths        = Directory.GetFiles(entityFolderPath, "*.xml");

                    LogManager.WriteLog("Importing " + ee.EntityName + " 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 e in fromDisk.Entities)
                                {
                                    //Records mapping for the Lookup attributes
                                    Entity entity = MapRecords(profile, e);

                                    string executingOperation = "";
                                    try
                                    {
                                        if (profile.ImportMode == 0)
                                        {
                                            executingOperation = "Create";
                                            service.Create(entity);
                                        }
                                        else if (profile.ImportMode == 1)
                                        {
                                            try
                                            {
                                                executingOperation = "Update";
                                                service.Update(entity);
                                            }
                                            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
                                            {
                                                executingOperation = "Create";
                                                service.Create(entity);
                                            }
                                        }
                                        else if (profile.ImportMode == 2)
                                        {
                                            executingOperation = "Update";
                                            service.Update(entity);
                                        }
                                        importedRecordsForEntity++;
                                        totalImportSuccess++;
                                    }
                                    catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                                    {
                                        totalImportFailures++;
                                        importFailuresForEntity++;
                                        ImportFailure failure = new ImportFailure
                                        {
                                            CreatedOn  = DateTime.Now.ToString(),
                                            EntityName = ee.EntityName,
                                            Operation  = executingOperation,
                                            Reason     = ex.Detail.Message,
                                            Url        = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + ee.EntityName + "&id=" + entity.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++;
                                            ImportFailure failure = new ImportFailure
                                            {
                                                CreatedOn  = DateTime.Now.ToString(),
                                                EntityName = ee.EntityName,
                                                Operation  = executingOperation,
                                                Reason     = ex.InnerException.Message,
                                                Url        = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + ee.EntityName + "&id=" + entity.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.EntityName + " 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>
        /// Exports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="transportReportFileName">Name of the transport report file.</param>
        private void Export(TransportationProfile profile, string transportReportFileName)
        {
            try
            {
                TransportReport report = new TransportReport(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();
                EnvStructure    es         = ReadEnvStructure(profile.SourceConnectionName);
                _serviceProxy = cm.connect(connection);
                IOrganizationService       service         = (IOrganizationService)_serviceProxy;
                List <TransportReportLine> TransportReport = new List <TransportReportLine>();
                profile.TotalExportedRecords = 0;
                //Mesure export time
                DateTime exportStartDT = DateTime.Now;

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

                int recordCount = 0;
                if (es != null)
                {
                    //Order export according to profile's transport order
                    IOrderedEnumerable <SelectedEntity> orderedSelectedEntities = profile.SelectedEntities.OrderBy(se => se.TransportOrder);

                    foreach (SelectedEntity ee in orderedSelectedEntities)
                    {
                        LogManager.WriteLog("Exporting data for entity " + ee.EntityName);
                        DateTime entityExportStartDT = DateTime.Now;
                        string   fetchXml            = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                        fetchXml += "<entity name='" + ee.EntityName + "'>";
                        //Get Entity structure
                        EnvEntity strE = new EnvEntity();
                        foreach (EnvEntity envE in es.Entities)
                        {
                            if (envE.EntityName == ee.EntityName)
                            {
                                strE = envE;
                                break;
                            }
                        }

                        //Create fetchXML Query
                        foreach (string ea in strE.Attributes)
                        {
                            if (ee.IgnoredAttributes == null)
                            {
                                fetchXml += "<attribute name='" + ea + "' />";
                            }
                            else if (!ee.IgnoredAttributes.Contains(ea))
                            {
                                fetchXml += "<attribute name='" + ea + "' />";
                            }
                        }

                        //Add Query filter
                        fetchXml += ee.Filter;

                        fetchXml += "</entity></fetch>";
                        int recordCountPerEntity = ExportEntity(profile, fetchXml);
                        recordCount += recordCountPerEntity;

                        DateTime            entityExportEndDT = DateTime.Now;
                        TimeSpan            ts = entityExportEndDT - entityExportStartDT;
                        TransportReportLine transportReportLine = new TransportReportLine();
                        transportReportLine.Entity           = ee.EntityName;
                        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>
        /// 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",
                    "channelaccessprofile"
                };

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

                foreach (EntityMetadata currentEntity in EMD)
                {
                    if (currentEntity.LogicalName == "externalpartyitem")
                    {
                        AdditionalEntities.Add(currentEntity.LogicalName);
                    }
                    if (IgnoredEntities.IndexOf(currentEntity.LogicalName) < 0 &&
                        currentEntity.IsIntersect.Value == false &&
                        (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.
                            if ((currentAttribute.AttributeOf == null) &&
                                IgnoredAttributes.IndexOf(currentAttribute.LogicalName) < 0 &&
                                currentAttribute.IsValidForRead != null &&
                                currentAttribute.IsValidForRead.Value &&
                                currentAttribute.IsValidForCreate != null &&
                                currentAttribute.IsValidForCreate.Value)
                            {
                                ee.Attributes.Add(currentAttribute.LogicalName);
                            }
                        }
                        //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;
            }
        }
Пример #15
0
        /// <summary>
        /// Handles the Click event of the getRecordsNumberToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void getRecordsNumberToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (comboBoxConnectionSource.SelectedItem == null)
            {
                MessageBox.Show("You must first select a source before counting the records!");
                return;
            }

            if (allEntities.Count == 0)
            {
                MessageBox.Show("You must load the entities from the source before counting the records!");
                return;
            }

            if (selectedEntities.Count == 0)
            {
                MessageBox.Show("You must check at least 1 Entity for records counting!");
                return;
            }

            openInExcelToolStripMenuItem.Visible = false;
            toolStripStatusLabel1.Text           = "Retrieving records number. Please wait...";
            Application.DoEvents();

            try
            {
                DateTime now = DateTime.Now;
                string   tempExportedFilePath = String.Concat(Folder + "\\" + comboBoxConnectionSource.SelectedItem + "_" + now.Year + "-" + now.Month + "-" + now.Day + "-" + now.Hour + "-" + now.Minute + "-" + now.Second + ".xml");

                MemoryStream ms = new MemoryStream();

                MSCRMConnection connection = cm.MSCRMConnections[comboBoxConnectionSource.SelectedIndex];

                using (StreamWriter sw = new StreamWriter(tempExportedFilePath))
                    using (_serviceProxy = cm.connect(connection))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

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

                        // <?mso-application progid="Excel.Sheet"?>
                        metadataWriter.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

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

                        foreach (RecordLine selectedEntity in selectedEntities)
                        {
                            int entityRecordsNumber = 0;

                            string query_count = "<fetch distinct='false' mapping='logical' aggregate='true'>";
                            query_count += "<entity name='" + selectedEntity.Entity + "'>";
                            query_count += "<attribute name='" + selectedEntity.AttribuiteIdName + "' alias='records_count' aggregate='count'/>";
                            query_count += selectedEntity.Filter;
                            query_count += "</entity>";
                            query_count += "</fetch>";

                            EntityCollection query_count_result = _serviceProxy.RetrieveMultiple(new FetchExpression(query_count));

                            foreach (var c in query_count_result.Entities)
                            {
                                entityRecordsNumber = (Int32)((AliasedValue)c["records_count"]).Value;
                            }

                            // Start Entity Node
                            metadataWriter.WriteStartElement("Entity");
                            metadataWriter.WriteElementString("Entity", selectedEntity.Entity);
                            metadataWriter.WriteElementString("Records", entityRecordsNumber.ToString());

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

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

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

                //Propose the file for saving
                XmlDocument doc = new XmlDocument();
                doc.Load(tempExportedFilePath);
                SaveFileDialog saveXMLDialog = new SaveFileDialog();
                saveXMLDialog.Filter     = "XML Files | *.xml";
                saveXMLDialog.DefaultExt = "xml";
                saveXMLDialog.FileName   = comboBoxConnectionSource.SelectedItem.ToString() + "_Records_Number";
                DialogResult savRes = saveXMLDialog.ShowDialog();
                if (savRes == DialogResult.OK)
                {
                    doc.Save(saveXMLDialog.FileName);
                }

                exportedFilePath = saveXMLDialog.FileName;

                //Delete temporary file
                File.Delete(tempExportedFilePath);
                //Display Open in Excel Button
                openInExcelToolStripMenuItem.Visible = true;
                toolStripStatusLabel1.Text           = "Records number generated.";
            }
            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);
                }
            }
        }
        /// <summary>
        /// Imports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        private void Import(MSCRMSolutionsTransportProfile profile)
        {
            //Check if there is a solutions to import
            if (Directory.Exists(profile.SolutionExportFolder))
            {
                IOrderedEnumerable <string> subDirectories = Directory.GetDirectories(profile.SolutionExportFolder).OrderByDescending(x => x);
                if (subDirectories.Count <string>() == 0)
                {
                    LogManager.WriteLog("There are no solutions for import.");
                    return;
                }

                //Check which solutions to import: Newest, Oldest, specific exprot date solutions
                string solutionsToImportFolder = "";
                if (profile.SolutionsToImport == "Newest")
                {
                    solutionsToImportFolder = subDirectories.ElementAt(0);
                }
                else if (profile.SolutionsToImport == "Oldest")
                {
                    solutionsToImportFolder = subDirectories.ElementAt(subDirectories.Count <string>() - 1);
                }
                else
                {
                    solutionsToImportFolder = subDirectories.First(s => s.EndsWith(profile.SolutionsToImport));
                }

                if (solutionsToImportFolder == "")
                {
                    LogManager.WriteLog("The specified solutions to import were not found.");
                    return;
                }

                //get all solutions archives
                string[] solutionsArchivesNames = Directory.GetFiles(solutionsToImportFolder, "*.zip");
                if (solutionsArchivesNames.Count <string>() == 0)
                {
                    LogManager.WriteLog("There are no solutions for import.");
                    return;
                }

                string[] pathList      = solutionsToImportFolder.Split(new Char [] { '\\' });
                string   DirectoryName = pathList[pathList.Count <string>() - 1];
                LogManager.WriteLog("Importing solutions from " + DirectoryName);

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

                foreach (string solutionArchiveName in solutionsArchivesNames)
                {
                    bool selectedsolutionfound = false;
                    foreach (string solutionname in profile.SelectedSolutionsNames)
                    {
                        if (Path.GetFileName(solutionArchiveName).StartsWith(solutionname))
                        {
                            selectedsolutionfound = true;
                        }
                    }

                    if (!selectedsolutionfound)
                    {
                        continue;
                    }

                    //Import Solution
                    LogManager.WriteLog("Importing solution archive " + Path.GetFileName(solutionArchiveName) + " into " + connection.ConnectionName);

                    byte[] fileBytes = File.ReadAllBytes(solutionArchiveName);

                    Guid ImportJobId = Guid.NewGuid();

                    ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest()
                    {
                        CustomizationFile = fileBytes,
                        OverwriteUnmanagedCustomizations = profile.OverwriteUnmanagedCustomizations,
                        PublishWorkflows = profile.PublishWorkflows,
                        ImportJobId      = ImportJobId
                    };

                    _serviceProxy.Execute(impSolReqWithMonitoring);


                    Entity ImportJob = _serviceProxy.Retrieve("importjob", impSolReqWithMonitoring.ImportJobId, new ColumnSet(true));
                    //File.WriteAllText(solutionsToImportFolder + "\\importlog_ORIGINAL_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + ".xml", (string)ImportJob["data"]);

                    RetrieveFormattedImportJobResultsRequest importLogRequest = new RetrieveFormattedImportJobResultsRequest()
                    {
                        ImportJobId = ImportJobId
                    };
                    RetrieveFormattedImportJobResultsResponse importLogResponse = (RetrieveFormattedImportJobResultsResponse)_serviceProxy.Execute(importLogRequest);

                    DateTime now     = DateTime.Now;
                    string   timeNow = String.Format("{0:yyyyMMddHHmmss}", now);

                    string exportedSolutionFileName = solutionsToImportFolder + "\\importlog_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + "_" + timeNow + ".xml";

                    //Fix bad Status and Message export
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml((string)ImportJob["data"]);
                    String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value;

                    File.WriteAllText(exportedSolutionFileName, importLogResponse.FormattedResults);

                    LogManager.WriteLog("Solution " + Path.GetFileName(solutionArchiveName) + " was imported with success in " + connection.ConnectionName);
                }

                //Check if customizations are to be published
                if (profile.PublishAllCustomizationsTarget)
                {
                    LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ...");
                    PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(publishRequest);
                }

                LogManager.WriteLog("Solutions Import finished for Profile: " + profile.ProfileName);
            }
            else
            {
                LogManager.WriteLog("There are no solutions for import.");
                return;
            }
        }
        /// <summary>
        /// Downloads the solutions.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <returns>List of solutions.</returns>
        public List<MSCRMSolution> DownloadSolutions(MSCRMConnection connection)
        {
            List<MSCRMSolution> solutionsLst = new List<MSCRMSolution>();
            _serviceProxy = cm.connect(connection);

            QueryExpression querySampleSolution = new QueryExpression
            {
                EntityName = "solution",
                ColumnSet = new ColumnSet(true),
                Criteria = new FilterExpression(),
            };
            querySampleSolution.Criteria.AddCondition("ismanaged", ConditionOperator.Equal, false);
            querySampleSolution.Criteria.AddCondition("isvisible", ConditionOperator.Equal, true);
            EntityCollection solutions = _serviceProxy.RetrieveMultiple(querySampleSolution);

            foreach (Entity solution in solutions.Entities)
            {
                EntityReference publisher = (EntityReference)solution["publisherid"];
                string description = solution.Attributes.Contains("description") ? (string)solution["description"] : "";
                MSCRMSolution MESCRMSolution = new MSCRMSolution
                {
                    UniqueName = (string)solution["uniquename"],
                    DisplayName = (string)solution["friendlyname"],
                    Version = (string)solution["version"],
                    Publisher = publisher.Name,
                    Description = description
                };
                solutionsLst.Add(MESCRMSolution);
            }

            WriteSolutions(connection.ConnectionName, solutionsLst);

            return solutionsLst;
        }
Пример #18
0
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            connection = cm.MSCRMConnections[comboBoxSource.SelectedIndex];
            LogManager.WriteLog("Loading Server Settings.");
            toolStripStatusLabel1.Text = "";
            try
            {
                string deploymentURI = connection.ServerAddress.Replace(connection.OrganizationName + "/", "") + "XRMDeployment/2011/Deployment.svc";
                serviceClient = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(new Uri(deploymentURI));
                serviceClient.ClientCredentials.Windows.ClientCredential.UserName = connection.UserName;
                serviceClient.ClientCredentials.Windows.ClientCredential.Password = connection.Password;

                // Retrieve all deployed instances of Microsoft Dynamics CRM.
                var organizations = serviceClient.RetrieveAll(DeploymentEntityType.Organization);

                Microsoft.Xrm.Sdk.Deployment.EntityInstanceId currentOrganization = null;
                foreach (var organization in organizations)
                {
                    if (organization.Name.ToLower() == connection.OrganizationName.ToLower())
                        currentOrganization = organization;
                }

                RetrieveAdvancedSettingsRequest request = new RetrieveAdvancedSettingsRequest()
                {
                    ConfigurationEntityName = "Deployment",
                    ColumnSet = new ColumnSet()
                };

                ConfigurationEntity ce = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(request)).Entity;

                foreach (var setting in ce.Attributes)
                {
                    if (setting.Key == "AggregateQueryRecordLimit")
                        numericUpDownAggregateQueryRecordLimit.Text = setting.Value.ToString();
                    else if (setting.Key == "AutomaticallyInstallDatabaseUpdates")
                        checkBoxAutomaticallyInstallDatabaseUpdates.Checked = (bool)setting.Value;
                    else if (setting.Key == "AutomaticallyReprovisionLanguagePacks")
                        checkBoxAutomaticallyReprovisionLanguagePacks.Checked = (bool)setting.Value;
                }

                // Retrieve details of first organization from previous call.
                Microsoft.Xrm.Sdk.Deployment.Organization deployment =
                    (Microsoft.Xrm.Sdk.Deployment.Organization)serviceClient.Retrieve(
                        DeploymentEntityType.Organization,
                        currentOrganization);

                // Print out retrieved details about your organization.
                string organizationProperties = "";
                organizationProperties += "Friendly Name: " + deployment.FriendlyName + "\r\n";
                organizationProperties += "Unique Name: " + deployment.UniqueName + "\r\n";
                organizationProperties += "Organization Version: " + deployment.Version + "\r\n";
                organizationProperties += "SQL Server Name: " + deployment.SqlServerName + "\r\n";
                organizationProperties += "SRS URL: " + deployment.SrsUrl + "\r\n";
                organizationProperties += "Base Currency Code: " + deployment.BaseCurrencyCode + "\r\n";
                organizationProperties += "Base Currency Name: " + deployment.BaseCurrencyName + "\r\n";
                organizationProperties += "Base Currency Precision: " + deployment.BaseCurrencyPrecision + "\r\n";
                organizationProperties += "Base Currency Symbol: " + deployment.BaseCurrencySymbol + "\r\n";
                organizationProperties += "Base Language Code: " + deployment.BaseLanguageCode + "\r\n";
                organizationProperties += "Database Name: " + deployment.DatabaseName + "\r\n";
                organizationProperties += "Sql Collation: " + deployment.SqlCollation + "\r\n";
                organizationProperties += "Sqm Is Enabled: " + deployment.SqmIsEnabled + "\r\n";
                organizationProperties += "State: " + deployment.State + "\r\n";

                textBoxOrganizationProperties.Text = organizationProperties;

                // Retrieve license and user information for your organization.
                TrackLicenseRequest licenseRequest = new TrackLicenseRequest();
                TrackLicenseResponse licenseResponse = (TrackLicenseResponse)serviceClient.Execute(licenseRequest);

                // Print out the number of servers and the user list.
                string licenseanduserinformation = "Number of servers: ";
                licenseanduserinformation += licenseResponse.NumberOfServers.HasValue ? licenseResponse.NumberOfServers.Value.ToString() : "null";
                licenseanduserinformation += "\r\n";
                licenseanduserinformation += "Users:\r\n";
                foreach (String user in licenseResponse.UsersList)
                {
                    licenseanduserinformation += user + "\r\n";
                }
                textBoxLicenceanduserinformation.Text = licenseanduserinformation;

                // Retrieve server settings for your organization.
                RetrieveAdvancedSettingsRequest requestServerSettings =
                    new RetrieveAdvancedSettingsRequest
                    {
                        ConfigurationEntityName = "ServerSettings",
                        ColumnSet = new ColumnSet(false)
                    };
                ConfigurationEntity configuration = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(requestServerSettings)).Entity;

                // Print out all advanced settings where IsWritable==true.
                foreach (var setting in configuration.Attributes)
                {
                    if (setting.Key != "Id")
                    {
                        if (setting.Key == "DisableUserInfoClaim")
                            checkBoxDisableUserInfoClaim.Checked = (bool)setting.Value;
                        else if (setting.Key == "MaxExpandCount")
                            numericUpDownMaxExpandCount.Text = setting.Value.ToString();
                        else if (setting.Key == "MaxResultsPerCollection")
                            numericUpDownMaxResultsPerCollection.Text = setting.Value.ToString();
                        else if (setting.Key == "NlbEnabled")
                            checkBoxNlbEnabled.Checked = (bool)setting.Value;
                        else if (setting.Key == "PostponeAppFabricRequestsInMinutes")
                            numericUpDownPostponeAppFabricRequestsInMinutes.Text = setting.Value.ToString();
                        else if (setting.Key == "PostViaExternalRouter")
                            checkBoxPostViaExternalRouter.Checked = (bool)setting.Value;
                        else if (setting.Key == "SslHeader")
                            textBoxSslHeader.Text = setting.Value.ToString();
                    }
                }

                toolStripStatusLabel1.Text = connection.OrganizationName + " deployment properties were successfully loaded.";
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                //string url = connection.ServerAddress + "main.aspx?pagetype=entityrecord&etn=eaf_contrat_client&id=" + entity.Id.ToString();
                LogManager.WriteLog("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                MessageBox.Show("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message);
                }
            }
        }
Пример #19
0
        private void buttonLoadWorkflows_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBoxConnectionSource.SelectedItem == null)
                {
                    MessageBox.Show("You must select a connection before loading workflows!");
                    return;
                }

                toolStripStatusLabel1.Text = "Loading workflows. Please wait...";
                Application.DoEvents();

                string fetchXMLQuery = @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                    <entity name='workflow'><attribute name='workflowid' /><attribute name='name' />
                    <order attribute='name' descending='false' /><filter type='and'>
                    <condition attribute='type' operator='eq' value='1' />
                    <condition attribute='category' operator='eq' value='0' />
                    <condition attribute='statecode' operator='eq' value='1' />
                    <condition attribute='ondemand' operator='eq' value='1' />
                    </filter></entity></fetch>";

                MSCRMConnection connection = cm.MSCRMConnections[comboBoxConnectionSource.SelectedIndex];
                man._serviceProxy = cm.connect(connection);

                EntityCollection result = man._serviceProxy.RetrieveMultiple(new FetchExpression(fetchXMLQuery));

                List <MSCRMWorkflow> workflows = new List <MSCRMWorkflow>();
                foreach (var workflow in result.Entities)
                {
                    //this.comboBoxWorkflows.Items.AddRange(new object[] { (string)workflow["name"] });
                    workflows.Add(new MSCRMWorkflow {
                        Id = (Guid)workflow["workflowid"], Name = (string)workflow["name"]
                    });
                }
                man.WriteWorkflows(comboBoxConnectionSource.SelectedItem.ToString(), workflows);

                //Read workflows
                this.comboBoxWorkflows.Items.Clear();
                List <MSCRMWorkflow> readedWorkflows = man.ReadWorkflows(comboBoxConnectionSource.SelectedItem.ToString());
                foreach (MSCRMWorkflow workflow in readedWorkflows)
                {
                    this.comboBoxWorkflows.Items.AddRange(new object[] { workflow.Name });
                }
                this.Workflows = readedWorkflows;

                toolStripStatusLabel1.Text = "Workflows loaded.";
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                    toolStripStatusLabel1.Text = "Error.";
                }
                else
                {
                    MessageBox.Show("Error:" + ex.Message);
                    toolStripStatusLabel1.Text = "Error.";
                }
            }
        }
Пример #20
0
 /// <summary>
 /// Sets the target conneciton.
 /// </summary>
 /// <remarks>
 /// The TargetConnectionName must be previously set.
 /// </remarks>
 public void setTargetConneciton()
 {
     if (!string.IsNullOrEmpty(TargetConnectionName))
         TargetConnection = cm.getConnection(TargetConnectionName);
 }
Пример #21
0
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            connection = cm.MSCRMConnections[comboBoxSource.SelectedIndex];
            LogManager.WriteLog("Loading Server Settings.");
            toolStripStatusLabel1.Text = "";
            try
            {
                string deploymentURI = connection.ServerAddress.Replace(connection.OrganizationName + "/", "") + "XRMDeployment/2011/Deployment.svc";
                serviceClient = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(new Uri(deploymentURI));
                serviceClient.ClientCredentials.Windows.ClientCredential.UserName = connection.UserName;
                serviceClient.ClientCredentials.Windows.ClientCredential.Password = connection.Password;

                // Retrieve all deployed instances of Microsoft Dynamics CRM.
                var organizations = serviceClient.RetrieveAll(DeploymentEntityType.Organization);

                Microsoft.Xrm.Sdk.Deployment.EntityInstanceId currentOrganization = null;
                foreach (var organization in organizations)
                {
                    if (organization.Name.ToLower() == connection.OrganizationName.ToLower())
                    {
                        currentOrganization = organization;
                    }
                }

                RetrieveAdvancedSettingsRequest request = new RetrieveAdvancedSettingsRequest()
                {
                    ConfigurationEntityName = "Deployment",
                    ColumnSet = new ColumnSet()
                };

                ConfigurationEntity ce = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(request)).Entity;

                foreach (var setting in ce.Attributes)
                {
                    if (setting.Key == "AggregateQueryRecordLimit")
                    {
                        numericUpDownAggregateQueryRecordLimit.Text = setting.Value.ToString();
                    }
                    else if (setting.Key == "AutomaticallyInstallDatabaseUpdates")
                    {
                        checkBoxAutomaticallyInstallDatabaseUpdates.Checked = (bool)setting.Value;
                    }
                    else if (setting.Key == "AutomaticallyReprovisionLanguagePacks")
                    {
                        checkBoxAutomaticallyReprovisionLanguagePacks.Checked = (bool)setting.Value;
                    }
                }

                // Retrieve details of first organization from previous call.
                Microsoft.Xrm.Sdk.Deployment.Organization deployment =
                    (Microsoft.Xrm.Sdk.Deployment.Organization)serviceClient.Retrieve(
                        DeploymentEntityType.Organization,
                        currentOrganization);

                // Print out retrieved details about your organization.
                string organizationProperties = "";
                organizationProperties += "Friendly Name: " + deployment.FriendlyName + "\r\n";
                organizationProperties += "Unique Name: " + deployment.UniqueName + "\r\n";
                organizationProperties += "Organization Version: " + deployment.Version + "\r\n";
                organizationProperties += "SQL Server Name: " + deployment.SqlServerName + "\r\n";
                organizationProperties += "SRS URL: " + deployment.SrsUrl + "\r\n";
                organizationProperties += "Base Currency Code: " + deployment.BaseCurrencyCode + "\r\n";
                organizationProperties += "Base Currency Name: " + deployment.BaseCurrencyName + "\r\n";
                organizationProperties += "Base Currency Precision: " + deployment.BaseCurrencyPrecision + "\r\n";
                organizationProperties += "Base Currency Symbol: " + deployment.BaseCurrencySymbol + "\r\n";
                organizationProperties += "Base Language Code: " + deployment.BaseLanguageCode + "\r\n";
                organizationProperties += "Database Name: " + deployment.DatabaseName + "\r\n";
                organizationProperties += "Sql Collation: " + deployment.SqlCollation + "\r\n";
                organizationProperties += "Sqm Is Enabled: " + deployment.SqmIsEnabled + "\r\n";
                organizationProperties += "State: " + deployment.State + "\r\n";

                textBoxOrganizationProperties.Text = organizationProperties;

                // Retrieve license and user information for your organization.
                TrackLicenseRequest  licenseRequest  = new TrackLicenseRequest();
                TrackLicenseResponse licenseResponse = (TrackLicenseResponse)serviceClient.Execute(licenseRequest);

                // Print out the number of servers and the user list.
                string licenseanduserinformation = "Number of servers: ";
                licenseanduserinformation += licenseResponse.NumberOfServers.HasValue ? licenseResponse.NumberOfServers.Value.ToString() : "null";
                licenseanduserinformation += "\r\n";
                licenseanduserinformation += "Users:\r\n";
                foreach (String user in licenseResponse.UsersList)
                {
                    licenseanduserinformation += user + "\r\n";
                }
                textBoxLicenceanduserinformation.Text = licenseanduserinformation;

                // Retrieve server settings for your organization.
                RetrieveAdvancedSettingsRequest requestServerSettings =
                    new RetrieveAdvancedSettingsRequest
                {
                    ConfigurationEntityName = "ServerSettings",
                    ColumnSet = new ColumnSet(false)
                };
                ConfigurationEntity configuration = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(requestServerSettings)).Entity;

                // Print out all advanced settings where IsWritable==true.
                foreach (var setting in configuration.Attributes)
                {
                    if (setting.Key != "Id")
                    {
                        if (setting.Key == "DisableUserInfoClaim")
                        {
                            checkBoxDisableUserInfoClaim.Checked = (bool)setting.Value;
                        }
                        else if (setting.Key == "MaxExpandCount")
                        {
                            numericUpDownMaxExpandCount.Text = setting.Value.ToString();
                        }
                        else if (setting.Key == "MaxResultsPerCollection")
                        {
                            numericUpDownMaxResultsPerCollection.Text = setting.Value.ToString();
                        }
                        else if (setting.Key == "NlbEnabled")
                        {
                            checkBoxNlbEnabled.Checked = (bool)setting.Value;
                        }
                        else if (setting.Key == "PostponeAppFabricRequestsInMinutes")
                        {
                            numericUpDownPostponeAppFabricRequestsInMinutes.Text = setting.Value.ToString();
                        }
                        else if (setting.Key == "PostViaExternalRouter")
                        {
                            checkBoxPostViaExternalRouter.Checked = (bool)setting.Value;
                        }
                        else if (setting.Key == "SslHeader")
                        {
                            textBoxSslHeader.Text = setting.Value.ToString();
                        }
                    }
                }

                toolStripStatusLabel1.Text = connection.OrganizationName + " deployment properties were successfully loaded.";
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                //string url = connection.ServerAddress + "main.aspx?pagetype=entityrecord&etn=eaf_contrat_client&id=" + entity.Id.ToString();
                LogManager.WriteLog("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                MessageBox.Show("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message);
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Gets the target conneciton.
        /// </summary>
        /// <returns>
        /// The Target MSCRMConnection.
        /// </returns>
        /// <remarks>
        /// The TargetConnectionName must be previously set.
        /// </remarks>
        public MSCRMConnection getTargetConneciton()
        {
            if (!string.IsNullOrEmpty(TargetConnectionName))
                TargetConnection = cm.getConnection(TargetConnectionName);

            return TargetConnection;
        }
Пример #23
0
        /// <summary>
        /// Handles the Click event of the getRecordsNumberToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void getRecordsNumberToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (comboBoxConnectionSource.SelectedItem == null)
            {
                MessageBox.Show("You must first select a source before counting the records!");
                return;
            }

            if (allEntities.Count == 0)
            {
                MessageBox.Show("You must load the entities from the source before counting the records!");
                return;
            }

            if (selectedEntities.Count == 0)
            {
                MessageBox.Show("You must check at least 1 Entity for records counting!");
                return;
            }

            openInExcelToolStripMenuItem.Visible = false;
            toolStripStatusLabel1.Text           = "Retrieving records number. Please wait...";
            Application.DoEvents();

            try
            {
                DateTime now = DateTime.Now;
                string   tempExportedFilePath = String.Concat(Folder + "\\" + comboBoxConnectionSource.SelectedItem + "_" + now.Year + "-" + now.Month + "-" + now.Day + "-" + now.Hour + "-" + now.Minute + "-" + now.Second + ".xml");

                MemoryStream ms = new MemoryStream();

                MSCRMConnection connection = cm.MSCRMConnections[comboBoxConnectionSource.SelectedIndex];

                using (StreamWriter sw = new StreamWriter(tempExportedFilePath))
                    using (_serviceProxy = cm.connect(connection))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

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

                        // <?mso-application progid="Excel.Sheet"?>
                        metadataWriter.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

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

                        foreach (RecordLine selectedEntity in selectedEntities)
                        {
                            int    entityRecordsNumber = 0;
                            int    fetchCount          = 5000;
                            int    pageNumber          = 1;
                            string pagingCookie        = null;

                            string query_count = "<fetch>";
                            query_count += "<entity name='" + selectedEntity.Entity + "'>";
                            query_count += "<attribute name='" + selectedEntity.AttribuiteIdName + "'/>";
                            query_count += selectedEntity.Filter;
                            query_count += "</entity>";
                            query_count += "</fetch>";

                            while (true)
                            {
                                string xml = CreateXml(query_count, pagingCookie, pageNumber, fetchCount);
                                RetrieveMultipleRequest request = new RetrieveMultipleRequest();
                                request.Query = new FetchExpression(xml);
                                EntityCollection query_count_result = ((RetrieveMultipleResponse)_serviceProxy.Execute(request)).EntityCollection;

                                entityRecordsNumber = entityRecordsNumber + query_count_result.Entities.Count;

                                // Check for morerecords, if it returns 1.
                                if (query_count_result.MoreRecords)
                                {
                                    // Increment the page number to retrieve the next page.
                                    pageNumber++;

                                    // Set the paging cookie to the paging cookie returned from current results.
                                    pagingCookie = query_count_result.PagingCookie;
                                }
                                else
                                {
                                    // If no more records in the result nodes, exit the loop.
                                    break;
                                }
                            }

                            // Start Entity Node
                            metadataWriter.WriteStartElement("Entity");
                            metadataWriter.WriteElementString("Entity", selectedEntity.Entity);
                            metadataWriter.WriteElementString("Records", entityRecordsNumber.ToString());

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

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

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

                //Propose the file for saving
                XmlDocument doc = new XmlDocument();
                doc.Load(tempExportedFilePath);
                SaveFileDialog saveXMLDialog = new SaveFileDialog();
                saveXMLDialog.Filter     = "XML Files | *.xml";
                saveXMLDialog.DefaultExt = "xml";
                saveXMLDialog.FileName   = comboBoxConnectionSource.SelectedItem.ToString() + "_Records_Number";
                DialogResult savRes = saveXMLDialog.ShowDialog();
                if (savRes == DialogResult.OK)
                {
                    doc.Save(saveXMLDialog.FileName);
                }

                exportedFilePath = saveXMLDialog.FileName;

                //Delete temporary file
                File.Delete(tempExportedFilePath);
                //Display Open in Excel Button
                openInExcelToolStripMenuItem.Visible = true;
                toolStripStatusLabel1.Text           = "Records number generated.";
            }
            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);
                }
            }
        }
Пример #24
0
 /// <summary>
 /// Sets the source conneciton.
 /// </summary>
 /// <remarks>
 /// The SourceConnectionName must be previously set.
 /// </remarks>
 public void setSourceConneciton()
 {
     if (!string.IsNullOrEmpty(SourceConnectionName))
         SourceConnection = cm.getConnection(SourceConnectionName);
 }
        /// <summary>
        /// Exports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        private void Export(MSCRMSolutionsTransportProfile profile)
        {
            try
            {
                //Set Data export folder
                if (!Directory.Exists(profile.SolutionExportFolder))
                {
                    Directory.CreateDirectory(profile.SolutionExportFolder);
                }

                MSCRMConnection connection = profile.getSourceConneciton();
                _serviceProxy = cm.connect(connection);

                //Download fresh list of solutions for versions update
                List <MSCRMSolution> solutions = DownloadSolutions(connection);

                DateTime now        = DateTime.Now;
                string   folderName = String.Format("{0:yyyyMMddHHmmss}", now);

                if (!Directory.Exists(profile.SolutionExportFolder + "\\" + folderName))
                {
                    Directory.CreateDirectory(profile.SolutionExportFolder + "\\" + folderName);
                }

                foreach (string SolutionName in profile.SelectedSolutionsNames)
                {
                    //Check if customizations are to be published
                    if (profile.PublishAllCustomizationsSource)
                    {
                        LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ...");
                        PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                        _serviceProxy.Execute(publishRequest);
                    }
                    LogManager.WriteLog("Exporting Solution " + SolutionName + " from " + connection.ConnectionName);

                    ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
                    exportSolutionRequest.Managed      = profile.ExportAsManaged;
                    exportSolutionRequest.SolutionName = SolutionName;
                    exportSolutionRequest.ExportAutoNumberingSettings          = profile.ExportAutoNumberingSettings;
                    exportSolutionRequest.ExportCalendarSettings               = profile.ExportCalendarSettings;
                    exportSolutionRequest.ExportCustomizationSettings          = profile.ExportCustomizationSettings;
                    exportSolutionRequest.ExportEmailTrackingSettings          = profile.ExportEmailTrackingSettings;
                    exportSolutionRequest.ExportGeneralSettings                = profile.ExportGeneralSettings;
                    exportSolutionRequest.ExportIsvConfig                      = profile.ExportIsvConfig;
                    exportSolutionRequest.ExportMarketingSettings              = profile.ExportMarketingSettings;
                    exportSolutionRequest.ExportOutlookSynchronizationSettings = profile.ExportOutlookSynchronizationSettings;
                    exportSolutionRequest.ExportRelationshipRoles              = profile.ExportRelationshipRoles;

                    string managed = "";
                    if (profile.ExportAsManaged)
                    {
                        managed = "managed";
                    }
                    MSCRMSolution          selectedSolution        = solutions.Find(s => s.UniqueName == SolutionName);
                    string                 selectedSolutionVersion = selectedSolution.Version.Replace(".", "_");
                    ExportSolutionResponse exportSolutionResponse  = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest);
                    byte[]                 exportXml = exportSolutionResponse.ExportSolutionFile;
                    string                 filename  = SolutionName + "_" + selectedSolutionVersion + "_" + managed + ".zip";
                    File.WriteAllBytes(profile.SolutionExportFolder + "\\" + folderName + "\\" + filename, exportXml);
                    LogManager.WriteLog("Export finished for Solution: " + SolutionName + ". Exported file: " + filename);
                }
                LogManager.WriteLog("Export finished for Profile: " + profile.ProfileName);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                throw;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                }
                throw;
            }
        }
Пример #26
0
        /// <summary>
        /// Gets the source conneciton.
        /// </summary>
        /// <returns>
        /// The Source MSCRMConnection.
        /// </returns>
        /// <remarks>
        /// The SourceConnectionName must be previously set.
        /// </remarks>
        public MSCRMConnection getSourceConneciton()
        {
            if (!string.IsNullOrEmpty(SourceConnectionName))
                SourceConnection = cm.getConnection(SourceConnectionName);

            return SourceConnection;
        }
Пример #27
0
        private int GetImportProgress(Guid ImportJobId, MSCRMConnection targetConnection)
        {
            int progress = 0;
            //Get Source Default Transaction Currency
            string fetchXml = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                      <entity name='importjob'>
                                        <attribute name='progress' />
                                        <order attribute='createdon' descending='true' />
                                        <filter type='and'>
                                            <condition attribute='importjobid' operator='eq' value='{0}' />
                                        </filter>
                                      </entity>
                                    </fetch> ", ImportJobId);

            using (OrganizationServiceProxy _serviceProxyImport = cm.connect(targetConnection))
            {
                EntityCollection result = _serviceProxyImport.RetrieveMultiple(new FetchExpression(fetchXml));

                if (result.Entities.Count < 1)
                    return 0;

                List<MSCRMSolutionImportJob> ImportJobsList = new List<MSCRMSolutionImportJob>();
                Entity ImportJob = result.Entities[0];
                if (ImportJob.Contains("progress"))
                    progress = Convert.ToInt32((Double)ImportJob["progress"]);
            }
            return progress;
        }