private static void CreateFile(Guid importJobIDGuid, String pathFile, String format)
        {
            RetrieveFormattedImportJobResultsRequest formatedImportJobRequest = new RetrieveFormattedImportJobResultsRequest
            {
                ImportJobId = importJobIDGuid
            };

            RetrieveFormattedImportJobResultsResponse formatedImportJobResponse = (RetrieveFormattedImportJobResultsResponse)_client.Execute(formatedImportJobRequest);
            int    i    = 0;
            string path = pathFile.Substring(0, pathFile.Length - 4) + format;

            if (!File.Exists(path))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.Write(formatedImportJobResponse.FormattedResults);
                }
            }
            else
            {
                while (File.Exists(path))
                {
                    i++;
                    String fileName = pathFile.Substring(0, pathFile.Length - 4) + "(" + i.ToString() + ")";
                    path = fileName + format;
                }
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.Write(formatedImportJobResponse.FormattedResults);
                }
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            base.WriteVerbose(string.Format("Downloading Solution Import Log for: {0}", ImportJobId));

            CrmConnection connection = CrmConnection.Parse(connectionString);

            using (OrganizationService service = new OrganizationService(connection))
            {
                ImportJob importJob = service.Retrieve(ImportJob.EntityLogicalName, importJobId, new ColumnSet(true)).ToEntity <ImportJob>();

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

                if (!string.IsNullOrEmpty(outputFile))
                {
                    File.WriteAllText(outputFile, importLogResponse.FormattedResults);
                }

                WriteObject(importJob);
            }

            base.WriteVerbose(string.Format("Solution Import Log Downloaded Successfully"));
        }
Exemple #3
0
        /// <summary>
        /// Handles the CellClick event of the dataGridView1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DataGridViewCellEventArgs"/> instance containing the event data.</param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex == -1 && e.ColumnIndex == 8)
                {
                    return;
                }

                if (e.ColumnIndex == this.dataGridView1.Rows[0].Cells.Count - 1)
                {
                    //MessageBox.Show((e.RowIndex + 1) + "  Row  " + (e.ColumnIndex + 1) + "  Column button clicked " + this.dataGridView1.Rows[e.RowIndex].Cells[0].Value);
                    RetrieveFormattedImportJobResultsRequest importLogRequest = new RetrieveFormattedImportJobResultsRequest()
                    {
                        ImportJobId = new Guid(this.dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())
                    };
                    RetrieveFormattedImportJobResultsResponse importLogResponse = (RetrieveFormattedImportJobResultsResponse)_serviceProxy.Execute(importLogRequest);

                    if (!Directory.Exists(Folder))
                    {
                        Directory.CreateDirectory(Folder);
                    }
                    string SolutionName = this.dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

                    string FileName = Folder + "\\importlog_" + Path.GetFileNameWithoutExtension(SolutionName) + ".xml";

                    File.WriteAllText(FileName, importLogResponse.FormattedResults);

                    //Check if the file exist
                    if (!File.Exists(FileName))
                    {
                        MessageBox.Show("File not found!");
                        return;
                    }

                    // These are the Win32 error code for file not found or access denied.
                    const int ERROR_FILE_NOT_FOUND = 2;
                    const int ERROR_ACCESS_DENIED  = 5;
                    try
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo();
                        startInfo.FileName  = "EXCEL.EXE";
                        startInfo.Arguments = FileName;
                        Process.Start(startInfo);
                    }
                    catch (Win32Exception ex)
                    {
                        if (ex.NativeErrorCode == ERROR_FILE_NOT_FOUND)
                        {
                            ProcessStartInfo startInfo = new ProcessStartInfo();
                            startInfo.FileName  = "NOTEPAD.EXE";
                            startInfo.Arguments = FileName;
                            Process.Start(startInfo);
                        }
                        else if (ex.NativeErrorCode == ERROR_ACCESS_DENIED)
                        {
                            MessageBox.Show(ex.Message + ". You do not have permission to access this file.");
                        }
                    }
                }
            }
            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>
        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;
            }
        }