public static List <CrmSolution> CreateCrmSolutionView(EntityCollection solutions)
        {
            List <CrmSolution> crmSolutions = new List <CrmSolution>();

            foreach (Entity entity in solutions.Entities)
            {
                CrmSolution solution = new CrmSolution
                {
                    SolutionId = entity.Id,
                    Name       = entity.GetAttributeValue <string>("friendlyname"),
                    Prefix     = entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix").Value.ToString(),
                    UniqueName = entity.GetAttributeValue <string>("uniquename")
                };

                crmSolutions.Add(solution);
            }

            crmSolutions = SortSolutions(crmSolutions);

            return(crmSolutions);
        }
Example #2
0
        public static ObservableCollection <CrmSolution> CreateCrmSolutionView(EntityCollection solutions)
        {
            var crmSolutions = new ObservableCollection <CrmSolution>();

            foreach (var entity in solutions.Entities)
            {
                var solution = new CrmSolution
                {
                    SolutionId  = entity.Id,
                    Name        = entity.GetAttributeValue <string>("friendlyname"),
                    UniqueName  = entity.GetAttributeValue <string>("uniquename"),
                    NameVersion = $"{entity.GetAttributeValue<string>("friendlyname")} {entity.GetAttributeValue<string>("version")}"
                };

                crmSolutions.Add(solution);
            }

            crmSolutions = SortSolutions(crmSolutions);

            return(crmSolutions);
        }
Example #3
0
        private string GetSolutionFromCrm(string connString, CrmSolution selectedSolution, bool managed)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(connString);

                using (_orgService = new OrganizationService(connection))
                {
                    ExportSolutionRequest request = new ExportSolutionRequest
                    {
                        Managed      = managed,
                        SolutionName = selectedSolution.UniqueName
                    };

                    ExportSolutionResponse response = (ExportSolutionResponse)_orgService.Execute(request);

                    var    tempFolder = Path.GetTempPath();
                    string fileName   = Path.GetFileName(selectedSolution.UniqueName + "_" +
                                                         FormatVersionString(selectedSolution.Version) + ((managed) ? "_managed" : String.Empty) + ".zip");
                    var tempFile = Path.Combine(tempFolder, fileName);
                    if (File.Exists(tempFile))
                    {
                        File.Delete(tempFile);
                    }
                    File.WriteAllBytes(tempFile, response.ExportSolutionFile);

                    return(tempFile);
                }
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return(null);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return(null);
            }
        }
Example #4
0
        private async void Create_Click(object sender, RoutedEventArgs e)
        {
            if (Solutions.SelectedItem == null || Files.SelectedItem == null ||
                string.IsNullOrEmpty(Name.Text) || Type.SelectedItem == null)
            {
                return;
            }

            string relativePath = ((ComboBoxItem)Files.SelectedItem).Content.ToString();
            string filePath     = Path.GetDirectoryName(_project.FullName) + relativePath.Replace("/", "\\");

            if (!File.Exists(filePath))
            {
                _logger.WriteToOutputWindow("Missing File: " + filePath, Logger.MessageType.Error);
                MessageBox.Show("File does not exist");
                return;
            }

            CrmSolution solution    = (CrmSolution)Solutions.SelectedItem;
            int         type        = Convert.ToInt32(((ComboBoxItem)Type.SelectedItem).Tag.ToString());
            string      prefix      = Prefix.Text;
            string      name        = Name.Text;
            string      displayName = DisplayName.Text;

            LockOverlay.Visibility = Visibility.Visible;

            bool result = await System.Threading.Tasks.Task.Run(() => CreateWebResource(solution.SolutionId, solution.UniqueName, type, prefix, name, displayName, filePath, relativePath));

            LockOverlay.Visibility = Visibility.Hidden;

            if (!result)
            {
                MessageBox.Show("Error Creating Web Resource. See the Output Window for additional details.");
                return;
            }

            DialogResult = true;
            Close();
        }
Example #5
0
        private string GetSolutionFromCrm(string connString, CrmSolution selectedSolution, bool managed)
        {
            try
            {
                var client = new CrmServiceClient(connString);
                // Hardcode connection timeout to one-hour to support large solutions.
                client.OrganizationServiceProxy.Timeout = new TimeSpan(1, 0, 0);

                ExportSolutionRequest request = new ExportSolutionRequest
                {
                    Managed      = managed,
                    SolutionName = selectedSolution.UniqueName
                };

                ExportSolutionResponse response = (ExportSolutionResponse)client.OrganizationServiceProxy.Execute(request);

                var    tempFolder = Path.GetTempPath();
                string fileName   = Path.GetFileName(selectedSolution.UniqueName + "_" +
                                                     FormatVersionString(selectedSolution.Version) + ((managed) ? "_managed" : String.Empty) + ".zip");
                var tempFile = Path.Combine(tempFolder, fileName);
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                File.WriteAllBytes(tempFile, response.ExportSolutionFile);

                return(tempFile);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return(null);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return(null);
            }
        }
Example #6
0
        public static ObservableCollection <CrmSolution> CreateCrmSolutionView(EntityCollection solutions)
        {
            ObservableCollection <CrmSolution> crmSolutions = new ObservableCollection <CrmSolution>();

            foreach (Entity entity in solutions.Entities)
            {
                CrmSolution solution = new CrmSolution
                {
                    SolutionId  = entity.Id,
                    Name        = entity.GetAttributeValue <string>("friendlyname"),
                    UniqueName  = entity.GetAttributeValue <string>("uniquename"),
                    Version     = Version.Parse(entity.GetAttributeValue <string>("version")),
                    Prefix      = entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix").Value.ToString(),
                    NameVersion = $"{entity.GetAttributeValue<string>("friendlyname")} {entity.GetAttributeValue<string>("version")}"
                };

                crmSolutions.Add(solution);
            }

            crmSolutions = SortSolutions(crmSolutions);

            return(crmSolutions);
        }
        private async Task <bool> GetSolutions(string connString)
        {
            _dte.StatusBar.Text = "Connecting to CRM and getting solutions...";
            _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync);
            LockMessage.Content    = "Working...";
            LockOverlay.Visibility = Visibility.Visible;

            EntityCollection results = await Task.Run(() => GetSolutionsFromCrm(connString));

            if (results == null)
            {
                _dte.StatusBar.Clear();
                _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
                LockOverlay.Visibility = Visibility.Hidden;
                MessageBox.Show("Error Retrieving Solutions. See the Output Window for additional details.");
                return(false);
            }

            _logger.WriteToOutputWindow("Retrieved Solutions From CRM", Logger.MessageType.Info);

            ObservableCollection <CrmSolution> solutions = new ObservableCollection <CrmSolution>();

            CrmSolution emptyItem = new CrmSolution
            {
                SolutionId = Guid.Empty,
                Name       = String.Empty
            };

            solutions.Add(emptyItem);

            foreach (Entity entity in results.Entities)
            {
                CrmSolution solution = new CrmSolution
                {
                    SolutionId = entity.Id,
                    Name       = entity.GetAttributeValue <string>("friendlyname"),
                    Prefix     = entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix").Value.ToString(),
                    UniqueName = entity.GetAttributeValue <string>("uniquename"),
                    Version    = Version.Parse(entity.GetAttributeValue <string>("version"))
                };

                solutions.Add(solution);
            }

            //Empty on top
            var i =
                solutions.IndexOf(
                    solutions.FirstOrDefault(s => s.SolutionId == new Guid("00000000-0000-0000-0000-000000000000")));

            var item = solutions[i];

            solutions.RemoveAt(i);
            solutions.Insert(0, item);

            //Default second
            i =
                solutions.IndexOf(
                    solutions.FirstOrDefault(s => s.SolutionId == new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238")));
            item = solutions[i];
            solutions.RemoveAt(i);
            solutions.Insert(1, item);

            solutions = HandleMappings(solutions);
            SolutionToPackage.ItemsSource = solutions;
            if (solutions.Count(s => !string.IsNullOrEmpty(s.BoundProject)) > 0)
            {
                SolutionToPackage.SelectedItem = solutions.First(s => !string.IsNullOrEmpty(s.BoundProject));
                var selectedProject = ConnPane.SelectedProject;
                if (selectedProject != null)
                {
                    SolutionToPackage.IsEnabled = !File.Exists(Path.GetDirectoryName(selectedProject.FullName) + "\\Other\\Solution.xml");
                }
            }
            else
            {
                SolutionToPackage.IsEnabled = true;
            }

            CrmSolution crmSolution = solutions.FirstOrDefault(s => !string.IsNullOrEmpty(s.BoundProject));

            DownloadManaged.IsChecked = crmSolution != null && solutions.First(s => !string.IsNullOrEmpty(s.BoundProject)).DownloadManagedSolution;

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
            LockOverlay.Visibility = Visibility.Hidden;

            return(true);
        }
Example #8
0
        private bool GetSolutions()
        {
            try
            {
                List <CrmSolution> solutions = new List <CrmSolution>();

                CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString);
                using (_orgService = new OrganizationService(connection))
                {
                    QueryExpression query = new QueryExpression
                    {
                        EntityName = "solution",
                        ColumnSet  = new ColumnSet("friendlyname", "solutionid", "uniquename"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "ismanaged",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { false }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "isvisible",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { true  }
                                }
                            }
                        },
                        Orders =
                        {
                            new OrderExpression
                            {
                                AttributeName = "friendlyname",
                                OrderType     = OrderType.Ascending
                            }
                        }
                    };

                    EntityCollection results = _orgService.RetrieveMultiple(query);


                    foreach (Entity entity in results.Entities)
                    {
                        CrmSolution solution = new CrmSolution
                        {
                            SolutionId = entity.Id,
                            Name       = entity.GetAttributeValue <string>("friendlyname"),
                            UniqueName = entity.GetAttributeValue <string>("uniquename")
                        };

                        solutions.Add(solution);
                    }
                }

                //Default on top
                var i    = solutions.FindIndex(s => s.SolutionId == new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"));
                var item = solutions[i];
                solutions.RemoveAt(i);
                solutions.Insert(0, item);

                Solutions.ItemsSource = solutions;

                return(true);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solutions From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solutions From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return(false);
            }
        }
Example #9
0
        public static async Task <string> GetSolutionFromCrm(CrmServiceClient client, CrmSolution selectedSolution, bool managed)
        {
            try
            {
                // Hardcode connection timeout to one-hour to support large solutions.
                //TODO: Find a better way to handle this
                if (client.OrganizationServiceProxy != null)
                {
                    client.OrganizationServiceProxy.Timeout = new TimeSpan(1, 0, 0);
                }
                if (client.OrganizationWebProxyClient != null)
                {
                    client.OrganizationWebProxyClient.InnerChannel.OperationTimeout = new TimeSpan(1, 0, 0);
                }

                var request = new ExportSolutionRequest
                {
                    Managed      = managed,
                    SolutionName = selectedSolution.UniqueName
                };
                var response = await Task.Run(() => (ExportSolutionResponse)client.Execute(request));

                ExLogger.LogToFile(Logger, Resource.Message_RetrievedSolution, LogLevel.Info);
                OutputLogger.WriteToOutputWindow(Resource.Message_RetrievedSolution, MessageType.Info);

                var fileName = FileHandler.FormatSolutionVersionString(selectedSolution.UniqueName, selectedSolution.Version, managed);
                var tempFile = FileHandler.WriteTempFile(fileName, response.ExportSolutionFile);

                return(tempFile);
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorRetrievingSolution, ex);

                return(null);
            }
        }
        private void CreatePackage(CrmSolution selectedSolution, Version version, string savePath, Project project, bool?downloadManaged)
        {
            try
            {
                //https://msdn.microsoft.com/en-us/library/jj602987.aspx#arguments

                CommandWindow cw = _dte2.ToolWindows.CommandWindow;

                var    props  = _dte.Properties["CRM Developer Extensions", "Solution Packager"];
                string spPath = (string)props.Item("SolutionPackagerPath").Value;

                if (string.IsNullOrEmpty(spPath))
                {
                    MessageBox.Show("Set SDK bin folder unmanagedPath under Tools -> Options -> CRM Developer Extensions");
                    return;
                }

                if (!spPath.EndsWith("\\"))
                {
                    spPath += "\\";
                }

                string toolPath = @"""" + spPath + "SolutionPackager.exe" + @"""";

                if (!File.Exists(spPath + "SolutionPackager.exe"))
                {
                    MessageBox.Show("SolutionPackager.exe not found at: " + spPath);
                    return;
                }

                string filename = selectedSolution.UniqueName + "_" +
                                  FormatVersionString(version) + ".zip";

                string command = toolPath + " /action: Pack";
                command += " /zipfile:" + "\"" + savePath + "\\" + filename + "\"";
                command += " /folder: " + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\"";

                if (downloadManaged == true)
                {
                    command += " /packagetype:Both";
                }

                // Use a mapping file if one exists in the root folder of the project and be named mapping.xml
                if (File.Exists(Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml"))
                {
                    command += " /map:" + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml\"";
                }

                cw.SendInput("shell " + command, true);

                AddNewSolutionToProject(savePath, project, filename);
                if (downloadManaged == true)
                {
                    AddNewSolutionToProject(savePath, project, filename.Replace(".zip", "_managed.zip"));
                }
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error launching Solution Packager: " + Environment.NewLine + Environment.NewLine + ex.Message, Logger.MessageType.Error);
            }
        }
Example #11
0
        private async Task <bool> ExtractPackage(string path, CrmSolution selectedSolution, Project project, bool?downloadManaged)
        {
            //https://msdn.microsoft.com/en-us/library/jj602987.aspx#arguments
            try
            {
                CommandWindow cw = _dte2.ToolWindows.CommandWindow;

                var    props  = _dte.Properties["CRM Developer Extensions", "Solution Packager"];
                string spPath = (string)props.Item("SolutionPackagerPath").Value;

                if (string.IsNullOrEmpty(spPath))
                {
                    MessageBox.Show("Set SDK bin folder path under Tools -> Options -> CRM Developer Extensions");
                    return(false);
                }

                if (!spPath.EndsWith("\\"))
                {
                    spPath += "\\";
                }

                string toolPath = @"""" + spPath + "SolutionPackager.exe" + @"""";

                if (!File.Exists(spPath + "SolutionPackager.exe"))
                {
                    MessageBox.Show("SolutionPackager.exe not found at: " + spPath);
                    return(false);
                }

                string tempDirectory = Path.GetDirectoryName(path);
                if (Directory.Exists(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(path)))
                {
                    Directory.Delete(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(path), true);
                }
                DirectoryInfo extractedFolder =
                    Directory.CreateDirectory(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(path));

                string command = toolPath + " /action: Extract";
                command += " /zipfile:" + "\"" + path + "\"";
                command += " /folder: " + "\"" + extractedFolder.FullName + "\"";
                command += " /clobber";

                cw.SendInput("shell " + command, true);

                //Need this
                System.Threading.Thread.Sleep(1000);

                bool solutionFileDelete    = RemoveDeletedItems(extractedFolder.FullName, ConnPane.SelectedProject.ProjectItems);
                bool solutionFileAddChange = ProcessDownloadedSolution(extractedFolder, Path.GetDirectoryName(ConnPane.SelectedProject.FullName),
                                                                       ConnPane.SelectedProject.ProjectItems);

                Directory.Delete(extractedFolder.FullName, true);

                //Solution change or file not present
                bool solutionChange = solutionFileDelete || solutionFileAddChange;
                StoreSolutionFile(path, project, solutionChange);

                //Download Managed
                if (downloadManaged != true)
                {
                    return(false);
                }

                path = await Task.Run(() => GetSolutionFromCrm(ConnPane.SelectedConnection.ConnectionString, selectedSolution, true));

                if (string.IsNullOrEmpty(path))
                {
                    _dte.StatusBar.Clear();
                    LockOverlay.Visibility = Visibility.Hidden;
                    MessageBox.Show("Error Retrieving Solution. See the Output Window for additional details.");
                    return(false);
                }

                return(solutionChange);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error launching Solution Packager: " + Environment.NewLine + Environment.NewLine + ex.Message, Logger.MessageType.Error);
                return(false);
            }
        }
        private async Task <bool> ExtractPackage(string unmanagedPath, string managedPath, CrmSolution selectedSolution, Project project, bool?downloadManaged)
        {
            //https://msdn.microsoft.com/en-us/library/jj602987.aspx#arguments
            try
            {
                CommandWindow cw = _dte2.ToolWindows.CommandWindow;

                var    props  = _dte.Properties["CRM Developer Extensions", "Solution Packager"];
                string spPath = (string)props.Item("SolutionPackagerPath").Value;

                if (string.IsNullOrEmpty(spPath))
                {
                    MessageBox.Show("Set SDK bin folder unmanagedPath under Tools -> Options -> CRM Developer Extensions");
                    return(false);
                }

                if (!spPath.EndsWith("\\"))
                {
                    spPath += "\\";
                }

                string toolPath = @"""" + spPath + "SolutionPackager.exe" + @"""";

                if (!File.Exists(spPath + "SolutionPackager.exe"))
                {
                    MessageBox.Show("SolutionPackager.exe not found at: " + spPath);
                    return(false);
                }

                string tempDirectory = Path.GetDirectoryName(unmanagedPath);
                if (Directory.Exists(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(unmanagedPath)))
                {
                    Directory.Delete(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(unmanagedPath), true);
                }
                DirectoryInfo extractedFolder =
                    Directory.CreateDirectory(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(unmanagedPath));

                string command = toolPath + " /action: Extract";
                command += " /zipfile:" + "\"" + unmanagedPath + "\"";
                command += " /folder: " + "\"" + extractedFolder.FullName + "\"";
                command += " /clobber";

                // Add a mapping file which should be in the root folder of the project and be named mapping.xml
                if (File.Exists(Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml"))
                {
                    command += " /map:" + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml\"";
                }

                // Write Solution Package output to a log file named SolutionPackager.log in the root folder of the project
                command += " /log:" + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\SolutionPackager.log\"";

                // Unpack managed solution as well.
                if (downloadManaged == true)
                {
                    command += " /packagetype:Both";
                }

                cw.SendInput("shell " + command, true);

                //Need this. Extend to allow bigger solutions to unpack
                System.Threading.Thread.Sleep(10000);

                bool solutionFileDelete    = RemoveDeletedItems(extractedFolder.FullName, ConnPane.SelectedProject.ProjectItems);
                bool solutionFileAddChange = ProcessDownloadedSolution(extractedFolder, Path.GetDirectoryName(ConnPane.SelectedProject.FullName),
                                                                       ConnPane.SelectedProject.ProjectItems);

                Directory.Delete(extractedFolder.FullName, true);

                //Solution change or file not present
                bool solutionChange = solutionFileDelete || solutionFileAddChange;
                StoreSolutionFile(unmanagedPath, project, solutionChange);
                if (downloadManaged == true && !string.IsNullOrEmpty(managedPath))
                {
                    StoreSolutionFile(managedPath, project, solutionChange);
                }

                return(solutionChange);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error launching Solution Packager: " + Environment.NewLine + Environment.NewLine + ex.Message, Logger.MessageType.Error);
                return(false);
            }
        }
        private async void Package_OnClick(object sender, RoutedEventArgs e)
        {
            CrmSolution selectedSolution = (CrmSolution)SolutionToPackage.SelectedItem;

            if (selectedSolution == null || selectedSolution.SolutionId == Guid.Empty)
            {
                return;
            }

            string solutionXmlPath = Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\Other\\Solution.xml";

            if (!File.Exists(solutionXmlPath))
            {
                MessageBox.Show("Solution.xml does not exist at: " +
                                Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\Other");
                return;
            }

            XmlDocument doc = new XmlDocument();

            doc.Load(solutionXmlPath);

            XmlNodeList versionNodes = doc.GetElementsByTagName("Version");

            if (versionNodes.Count != 1)
            {
                MessageBox.Show("Invalid Solutions.xml: could not locate Versions node");
                return;
            }

            Version version;
            bool    validVersion = Version.TryParse(versionNodes[0].InnerText, out version);

            if (!validVersion)
            {
                MessageBox.Show("Invalid Solutions.xml: invalid version");
                return;
            }

            var selectedProject = ConnPane.SelectedProject;

            if (selectedProject == null)
            {
                return;
            }

            bool?downloadManaged = DownloadManaged.IsChecked;

            string savePath;
            var    props             = _dte.Properties["CRM Developer Extensions", "Solution Packager"];
            bool   saveSolutionFiles = (bool)props.Item("SaveSolutionFiles").Value;

            if (saveSolutionFiles)
            {
                savePath = Path.GetDirectoryName(selectedProject.FullName) + "\\_Solutions";
            }
            else
            {
                FolderBrowserDialog folderDialog = new FolderBrowserDialog();
                DialogResult        result       = folderDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    savePath = folderDialog.SelectedPath;
                }
                else
                {
                    return;
                }
            }

            string overwriteMessage = null;

            if (File.Exists(savePath + "\\" + selectedSolution.UniqueName + "_" +
                            FormatVersionString(version) + ".zip"))
            {
                overwriteMessage = "Overwrite unmanaged solution version: " + version + "?";
            }

            if (downloadManaged == true)
            {
                if (File.Exists(savePath + "\\" + selectedSolution.UniqueName + "_" +
                                FormatVersionString(version) + "_managed.zip"))
                {
                    overwriteMessage += Environment.NewLine + "and/or" + Environment.NewLine + "Overwrite managed solution version: " + version + "?";
                }
            }

            if (!string.IsNullOrEmpty(overwriteMessage))
            {
                MessageBoxResult result = MessageBox.Show(overwriteMessage, "Overwrite?", MessageBoxButton.YesNo);
                if (result != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            await Task.Run(() => CreatePackage(selectedSolution, version, savePath, selectedProject, downloadManaged));
        }
        private async void Unpackage_OnClick(object sender, RoutedEventArgs e)
        {
            SolutionToPackage.IsEnabled = false;

            _dte.StatusBar.Text = "Connecting to CRM and getting unmanaged solution...";
            _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync);
            LockMessage.Content    = "Working...";
            LockOverlay.Visibility = Visibility.Visible;

            if (SolutionToPackage.SelectedItem == null)
            {
                return;
            }

            CrmSolution selectedSolution = (CrmSolution)SolutionToPackage.SelectedItem;
            bool?       downloadManaged  = DownloadManaged.IsChecked;

            // Export the unmanaged solution archive from CRM
            _logger.WriteToOutputWindow("Started Download of Unmanaged Solution From CRM", Logger.MessageType.Info);
            string unmanagedPath = await Task.Run(() => GetSolutionFromCrm(ConnPane.SelectedConnection.ConnectionString, selectedSolution, false));

            if (string.IsNullOrEmpty(unmanagedPath))
            {
                _dte.StatusBar.Clear();
                LockOverlay.Visibility = Visibility.Hidden;
                MessageBox.Show("Error Retrieving Unmanaged Solution. See the Output Window for additional details.");
                return;
            }

            _logger.WriteToOutputWindow("Retrieved Unmanaged Solution From CRM", Logger.MessageType.Info);
            _dte.StatusBar.Text = "Extracting solution...";

            Project project = ConnPane.SelectedProject;

            // If the managed flag was set, export the managed solution archive from CRM
            string managedPath = null;

            if (downloadManaged == true)
            {
                _dte.StatusBar.Text = "Connecting to CRM and getting managed solution...";
                _logger.WriteToOutputWindow("Started Download of Managed Solution From CRM", Logger.MessageType.Info);
                managedPath =
                    await
                    Task.Run(
                        () =>
                        GetSolutionFromCrm(ConnPane.SelectedConnection.ConnectionString, selectedSolution, true));

                if (string.IsNullOrEmpty(managedPath))
                {
                    _dte.StatusBar.Clear();
                    LockOverlay.Visibility = Visibility.Hidden;
                    MessageBox.Show("Error Retrieving Managed Solution. See the Output Window for additional details.");
                    return;
                }

                _logger.WriteToOutputWindow("Retrieved Managed Solution From CRM", Logger.MessageType.Info);
            }

            // Upack the solution(s) using the Solution Packager
            bool solutionChange = await Task.Run(() => ExtractPackage(unmanagedPath, managedPath, selectedSolution, project, downloadManaged));

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
            LockOverlay.Visibility = Visibility.Hidden;

            Package.IsEnabled = true;
        }
Example #15
0
        public static async Task <string> GetSolutionFromCrm(CrmServiceClient client, CrmSolution selectedSolution, bool managed)
        {
            try
            {
                // Hardcode connection timeout to one-hour to support large solutions.
                if (client.OrganizationServiceProxy != null)
                {
                    client.OrganizationServiceProxy.Timeout = new TimeSpan(1, 0, 0);
                }
                if (client.OrganizationWebProxyClient != null)
                {
                    client.OrganizationWebProxyClient.InnerChannel.OperationTimeout = new TimeSpan(1, 0, 0);
                }

                ExportSolutionRequest request = new ExportSolutionRequest
                {
                    Managed      = managed,
                    SolutionName = selectedSolution.UniqueName
                };
                ExportSolutionResponse response = await Task.Run(() => (ExportSolutionResponse)client.Execute(request));

                string fileName = FileHandler.FormatSolutionVersionString(selectedSolution.UniqueName, selectedSolution.Version, managed);
                string tempFile = FileHandler.WriteTempFile(fileName, response.ExportSolutionFile);

                return(tempFile);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                OutputLogger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error);
                return(null);
            }
            catch (Exception ex)
            {
                OutputLogger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error);
                return(null);
            }
        }
        private void AddOrUpdateMapping(CrmSolution solution)
        {
            try
            {
                var path = Path.GetDirectoryName(ConnPane.SelectedProject.FullName);
                if (!SharedConfigFile.ConfigFileExists(ConnPane.SelectedProject))
                {
                    _logger.WriteToOutputWindow("Error Updating Mappings In Config File: Missing CRMDeveloperExtensions.config File", Logger.MessageType.Error);
                    return;
                }

                XmlDocument doc = new XmlDocument();
                doc.Load(path + "\\CRMDeveloperExtensions.config");

                //Update or delete existing mapping
                XmlNodeList solutionNodes = doc.GetElementsByTagName("Solution");
                if (solutionNodes.Count > 0)
                {
                    foreach (XmlNode node in solutionNodes)
                    {
                        bool    changed = false;
                        XmlNode orgId   = node["OrgId"];
                        if (orgId != null && orgId.InnerText.ToUpper() != ConnPane.SelectedConnection.OrgId.ToUpper())
                        {
                            continue;
                        }

                        XmlNode projectNameNode = node["ProjectName"];
                        if (projectNameNode != null && projectNameNode.InnerText.ToUpper() != solution.BoundProject.ToUpper())
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(solution.BoundProject) || solution.SolutionId == Guid.Empty)
                        {
                            //Delete
                            var parentNode = node.ParentNode;
                            if (parentNode != null)
                            {
                                parentNode.RemoveChild(node);
                                changed = true;
                            }
                        }
                        else
                        {
                            //Update
                            XmlNode solutionIdNode = node["SolutionId"];
                            if (solutionIdNode != null)
                            {
                                string oldSolutionId = solutionIdNode.InnerText;
                                if (oldSolutionId != solution.SolutionId.ToString())
                                {
                                    solutionIdNode.InnerText = solution.SolutionId.ToString();
                                    changed = true;
                                }
                            }
                            XmlNode downloadManagedNode = node["DownloadManaged"];
                            if (downloadManagedNode != null)
                            {
                                string oldDownloadManaged   = downloadManagedNode.InnerText;
                                string downloadManagedValue = (solution.DownloadManagedSolution) ? "true" : "false";
                                if (oldDownloadManaged != downloadManagedValue)
                                {
                                    downloadManagedNode.InnerText = downloadManagedValue;
                                    changed = true;
                                }
                            }
                        }

                        if (!changed)
                        {
                            return;
                        }

                        if (SharedConfigFile.IsConfigReadOnly(path + "\\CRMDeveloperExtensions.config"))
                        {
                            FileInfo file = new FileInfo(path + "\\CRMDeveloperExtensions.config")
                            {
                                IsReadOnly = false
                            };
                        }

                        doc.Save(path + "\\CRMDeveloperExtensions.config");
                        return;
                    }
                }

                //Create new mapping
                XmlNodeList projects = doc.GetElementsByTagName("Solutions");
                if (projects.Count <= 0)
                {
                    return;
                }

                XmlNode solutionNode = doc.CreateElement("Solution");
                XmlNode org          = doc.CreateElement("OrgId");
                org.InnerText = ConnPane.SelectedConnection.OrgId;
                solutionNode.AppendChild(org);
                XmlNode projectNameNode2 = doc.CreateElement("ProjectName");
                projectNameNode2.InnerText = solution.BoundProject;
                solutionNode.AppendChild(projectNameNode2);
                XmlNode solutionId = doc.CreateElement("SolutionId");
                solutionId.InnerText = solution.SolutionId.ToString();
                solutionNode.AppendChild(solutionId);
                XmlNode downloadManaged = doc.CreateElement("DownloadManaged");
                downloadManaged.InnerText = (DownloadManaged.IsChecked == true) ? "true" : "false";
                solutionNode.AppendChild(downloadManaged);
                projects[0].AppendChild(solutionNode);

                if (SharedConfigFile.IsConfigReadOnly(path + "\\CRMDeveloperExtensions.config"))
                {
                    FileInfo file = new FileInfo(path + "\\CRMDeveloperExtensions.config")
                    {
                        IsReadOnly = false
                    };
                }

                doc.Save(path + "\\CRMDeveloperExtensions.config");
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Updating Mappings In Config File: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
            }
        }
Example #17
0
        private bool GetSolutions(Guid selectedSolutionId)
        {
            try
            {
                List <CrmSolution> solutions = new List <CrmSolution>();

                var             client = new CrmServiceClient(_connection.ConnectionString);
                QueryExpression query  = new QueryExpression
                {
                    EntityName = "solution",
                    ColumnSet  = new ColumnSet("friendlyname", "solutionid", "uniquename"),
                    Criteria   = new FilterExpression
                    {
                        Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "ismanaged",
                                Operator      = ConditionOperator.Equal,
                                Values        = { false }
                            },
                            new ConditionExpression
                            {
                                AttributeName = "isvisible",
                                Operator      = ConditionOperator.Equal,
                                Values        = { true  }
                            }
                        }
                    },
                    LinkEntities =
                    {
                        new LinkEntity
                        {
                            LinkFromEntityName    = "solution",
                            LinkFromAttributeName = "publisherid",
                            LinkToEntityName      = "publisher",
                            LinkToAttributeName   = "publisherid",
                            Columns     = new ColumnSet("customizationprefix"),
                            EntityAlias = "publisher"
                        }
                    },
                    Orders =
                    {
                        new OrderExpression
                        {
                            AttributeName = "friendlyname",
                            OrderType     = OrderType.Ascending
                        }
                    }
                };

                EntityCollection results = client.OrganizationServiceProxy.RetrieveMultiple(query);


                foreach (Entity entity in results.Entities)
                {
                    CrmSolution solution = new CrmSolution
                    {
                        SolutionId = entity.Id,
                        Name       = entity.GetAttributeValue <string>("friendlyname"),
                        Prefix     = entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix").Value.ToString(),
                        UniqueName = entity.GetAttributeValue <string>("uniquename")
                    };

                    solutions.Add(solution);
                }

                //Default on top
                var i    = solutions.FindIndex(s => s.SolutionId == new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"));
                var item = solutions[i];
                solutions.RemoveAt(i);
                solutions.Insert(0, item);

                if (selectedSolutionId != Guid.Empty)
                {
                    var sel = solutions.FindIndex(s => s.SolutionId == selectedSolutionId);
                    if (sel != -1)
                    {
                        Solutions.SelectedIndex = sel;
                    }
                }

                Solutions.ItemsSource = solutions;

                return(true);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solutions From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Retrieving Solutions From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return(false);
            }
        }
        private async void Create_OnClick(object sender, RoutedEventArgs e)
        {
            if (!ValidateForm())
            {
                return;
            }

            string filePath = GetFilePath();

            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }

            string relativePath = ((ComboBoxItem)Files.SelectedItem).Content.ToString();
            string name         = Name.Text.Trim();
            string prefix       = Prefix.Text;
            int    type         = Convert.ToInt32(((ComboBoxItem)Type.SelectedItem).Tag.ToString());
            string displayName  = DisplayName.Text.Trim();
            string description  = Description.Text.Trim();

            ShowMessage("Creating...");

            Entity webResource =
                Crm.WebResource.CreateNewWebResourceEntity(type, prefix, name, displayName, description, filePath);

            Guid webResourceId = await Task.Run(() => Crm.WebResource.CreateWebResourceInCrm(_client, webResource));

            if (webResourceId == Guid.Empty)
            {
                HideMessage();
                DialogResult = false;
                Close();
            }

            CrmSolution solution = (CrmSolution)Solutions.SelectedItem;

            if (solution.SolutionId != ExtensionConstants.DefaultSolutionId)
            {
                bool addedToSolution = await Task.Run(() => Crm.Solution.AddWebResourceToSolution(_client, solution.UniqueName, webResourceId));

                if (!addedToSolution)
                {
                    HideMessage();
                    DialogResult = false;
                    Close();
                    return;
                }
            }

            NewId   = webResourceId;
            NewType = type;
            NewName = prefix + name;
            if (!string.IsNullOrEmpty(displayName))
            {
                NewDisplayName = displayName;
            }
            NewBoundFile  = relativePath;
            NewSolutionId = solution.SolutionId;

            HideMessage();
            DialogResult = true;
            Close();
        }