예제 #1
0
        public static void SetIncludesForNewProject(VCProject vcProject,
                                                    CompilerSpecificationCommandResult compilerSpecsCommandResult,
                                                    ProjectInformationCommandResult projectInformation)
        {
            (IEnumerable <CompilerMacroResult> macros, IEnumerable <string> includes) =
                ProjectIncludesManager.FindMacrosAndIncludesForMinTarget(compilerSpecsCommandResult,
                                                                         projectInformation);

            if (macros == null)
            {
                macros = Enumerable.Empty <CompilerMacroResult>();
            }
            if (includes == null)
            {
                includes = Enumerable.Empty <string>();
            }

            foreach (VCConfiguration2 config in vcProject.Configurations)
            {
                IVCRulePropertyStorage plcnextCommonPropertiesRule = config.Rules.Item(Constants.PLCnextRuleName);
                if (plcnextCommonPropertiesRule == null)
                {
                    MessageBox.Show("PLCnextCommonProperties rule was not found in configuration rules collection.");
                }

                string joinedMacros = macros.Any() ? string.Join(";",
                                                                 macros.Select(m => m.Name + (string.IsNullOrEmpty(m.Value.Trim()) ? null : "=" + m.Value)))
                        : string.Empty;
                string joinedIncludes = includes.Any() ? string.Join(";", includes) : string.Empty;

                plcnextCommonPropertiesRule.SetPropertyValue(Constants.PLCnextMacrosKey, joinedMacros);
                plcnextCommonPropertiesRule.SetPropertyValue(Constants.PLCnextIncludesKey, joinedIncludes);
            }
        }
예제 #2
0
        private void FetchProjectComponents()
        {
            ProjectInformationCommandResult projectInformation = _plcncliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                                      typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_no_include_detection,
                                                                                                      Resources.Option_get_project_information_project, $"\"{_projectDirectory}\"") as ProjectInformationCommandResult;

            if (projectInformation != null)
            {
                Components = projectInformation.Entities.Where(e => e.Type.Equals("component"))
                             .Select(e => $"{e.Namespace}::{e.Name}");
                SelectedNamespace = projectInformation.Namespace;
            }
        }
예제 #3
0
        FindMacrosAndIncludesForMinTarget(CompilerSpecificationCommandResult compilerSpecsCommandResult,
                                          ProjectInformationCommandResult projectInformation)
        {
            IEnumerable <CompilerMacroResult> macros = Enumerable.Empty <CompilerMacroResult>();
            IEnumerable <string> includes            = Enumerable.Empty <string>();

            TargetResult minCompilerTarget = FindMinTargetForMacros(compilerSpecsCommandResult);

            if (minCompilerTarget != null)
            {
                macros = GetMacrosForTarget(minCompilerTarget, compilerSpecsCommandResult);
            }

            TargetResult minIncludeTarget = FindMinTargetForIncludes(projectInformation);

            includes = GetIncludesForTarget(minIncludeTarget, projectInformation);


            return(macros, includes);
        }
        public ProjectTargetValueEditorModel(IServiceProvider serviceProvider, string projectDirectory)
        {
            this.serviceProvider = serviceProvider;
            IPlcncliCommunication cliCommunication = serviceProvider.GetService(typeof(SPlcncliCommunication)) as IPlcncliCommunication;

            if (cliCommunication != null)
            {
                TargetsCommandResult targetsCommandResult =
                    cliCommunication.ExecuteCommand(Resources.Command_get_targets, null, typeof(TargetsCommandResult))
                    as TargetsCommandResult;
                InstalledTargets = targetsCommandResult.Targets;

                ProjectInformationCommandResult projectInfo = cliCommunication.ExecuteCommand(
                    Resources.Command_get_project_information, null, typeof(ProjectInformationCommandResult),
                    Resources.Option_get_project_information_no_include_detection,
                    Resources.Option_get_project_information_project, $"\"{projectDirectory}\"") as
                                                              ProjectInformationCommandResult;
                ProjectTargets = projectInfo.Targets;
                //TODO extract these commands somewhere after the viewModel.Showmodal call (and possibly asyncron), otherwise the ui seems to be too unresponsive
            }
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Import(object sender, EventArgs e)
        {
            DTE2 dte = Package.GetGlobalService(typeof(DTE)) as DTE2;

            try
            {
                bool closed = SolutionSaveService.SaveAndCloseSolution(dte.Solution);
                if (!closed)
                {
                    return;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show($"Project import could not be started:\n{exception.Message}", "Import failed");
                return;
            }

            ThreadHelper.JoinableTaskFactory.Run(
                "Importing project",
                async(progress) =>
            {
                if (_plcncliCommunication == null)
                {
                    MessageBox.Show("Could not import project because no plcncli communication found.");
                }
                string projectFilePath = string.Empty;
                if (OpenImportWizard())
                {
                    string projectDirectory = Path.GetDirectoryName(projectFilePath);

                    progress.Report(new ThreadedWaitDialogProgressData("Fetching project information."));
                    ProjectInformationCommandResult projectInformation = await GetProjectInformation();
                    if (projectInformation == null)
                    {
                        return;
                    }
                    string projectName = projectInformation.Name;
                    string projectType = projectInformation.Type;
                    IEnumerable <TargetResult> projectTargets = projectInformation.Targets;

                    await CreateVSProject(projectType, projectDirectory, projectName, projectTargets);

                    MessageBox.Show("If the imported project has source folders different from the standard 'src', they have to be set manually in the project properties.",
                                    "Successfully imported project", MessageBoxButton.OK, MessageBoxImage.Information);
                }

                bool OpenImportWizard()
                {
                    ImportDialogModel model         = new ImportDialogModel();
                    ImportDialogViewModel viewModel = new ImportDialogViewModel(model);
                    ImportDialogView view           = new ImportDialogView(viewModel);

                    view.ShowModal();
                    if (view.DialogResult == true)
                    {
                        projectFilePath = model.ProjectFilePath;
                        return(true);
                    }
                    return(false);
                }

                async Task <ProjectInformationCommandResult> GetProjectInformation()
                {
                    ProjectInformationCommandResult result = null;
                    await Task.Run(() =>
                    {
                        try
                        {
                            result = _plcncliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                          typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                          $"\"{projectFilePath}\"") as ProjectInformationCommandResult;
                        }
                        catch (PlcncliException ex)
                        {
                            result = _plcncliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                            throw ex;
                        }
                    });
                    return(result);
                }

                async Task CreateVSProject(string projectType, string projectDirectory, string projectName, IEnumerable <TargetResult> projectTargets)
                {
                    progress.Report(new ThreadedWaitDialogProgressData("Creating project files."));
                    bool projectFileCreated = await CreateVSProjectFile();
                    if (!projectFileCreated)
                    {
                        return;
                    }

                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    dte.Solution.Create(projectDirectory, projectName);
                    dte.Solution.AddFromFile($"{Path.Combine(projectDirectory, projectName)}.vcxproj");

                    Project project = null;
                    foreach (Project proj in dte.Solution.Projects)
                    {
                        if (proj.Name.Equals(projectName))
                        {
                            project = proj;
                            break;
                        }
                    }
                    if (project == null)
                    {
                        MessageBox.Show("Something went wrong during creation of new project. Project was not found in solution.");
                        return;
                    }

                    progress.Report(new ThreadedWaitDialogProgressData("Creating project configurations."));
                    ProjectConfigurationManager.CreateConfigurationsForAllProjectTargets
                        (projectTargets.Select(t => t.GetNameFormattedForCommandLine()), project);

                    //**********delete intermediate**********
                    string intermediateFolder = Path.Combine(projectDirectory, "intermediate");
                    if (Directory.Exists(intermediateFolder))
                    {
                        Directory.Delete(intermediateFolder, true);
                    }

                    //**********add project items to project**********

                    IEnumerable <string> directories = Directory.GetDirectories(projectDirectory).Where(d => !d.EndsWith("bin"));

                    IEnumerable <string> projectFiles =
                        Directory.GetFiles(projectDirectory, "*.*pp", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(projectDirectory, "*.txt", SearchOption.TopDirectoryOnly))
                        .Where(f => !f.EndsWith("UndefClang.hpp"))
                        .Concat(directories.SelectMany(d => Directory.GetFiles(d, "*.*pp", SearchOption.AllDirectories)
                                                       .Concat(Directory.GetFiles(d, "*.txt", SearchOption.AllDirectories)))
                                .Where(f => !f.EndsWith("UndefClang.hpp"))
                                );

                    foreach (string file in projectFiles)
                    {
                        project.ProjectItems.AddFromFile(file);
                    }

                    progress.Report(new ThreadedWaitDialogProgressData("Generating intermediate code."));
                    GenerateCode();

                    progress.Report(new ThreadedWaitDialogProgressData("Setting includes and macros."));
                    SetIncludesAndMacros();

                    project.Save();

                    async Task <bool> CreateVSProjectFile()
                    {
                        string filePath = Path.Combine(projectDirectory, $"{projectName}.vcxproj");
                        if (File.Exists(filePath))
                        {
                            MessageBox.Show($"Project creation failed because the file {filePath} already exists.");
                            return(false);
                        }

                        string additionalPropertiesKey = "additionalproperties";
                        string projectTypeKey          = "projecttype";
                        string targetsFileNameKey      = "targetsfilename";

                        Dictionary <string, string> replacementDictionary = new Dictionary <string, string>
                        {
                            { additionalPropertiesKey, string.Empty },
                            { projectTypeKey, projectType }
                        };
                        if (projectType == Resources.ProjectType_PLM)
                        {
                            replacementDictionary[additionalPropertiesKey] = "<PLCnCLIGenerateDT>true</PLCnCLIGenerateDT>";
                        }

                        if (projectType == Resources.ProjectType_ConsumableLibrary)
                        {
                            replacementDictionary.Add(targetsFileNameKey, "PLCnCLIBuild.targets");
                        }
                        else
                        {
                            replacementDictionary.Add(targetsFileNameKey, "PLCnCLI.targets");
                        }

                        string fileContent          = await GetProjectFileTemplate();
                        Match replaceParameterMatch = ReplaceParameterRegex.Match(fileContent);

                        while (replaceParameterMatch.Success)
                        {
                            string parameter = replaceParameterMatch.Groups["parameter"].Value;
                            if (!replacementDictionary.ContainsKey(parameter))
                            {
                                MessageBox.Show($"The parameter {parameter} could not be replaced in the project file.");
                                replaceParameterMatch = replaceParameterMatch.NextMatch();
                                continue;
                            }
                            fileContent = fileContent.Replace(replaceParameterMatch.Value, replacementDictionary[parameter]);

                            replaceParameterMatch = replaceParameterMatch.NextMatch();
                        }


                        try
                        {
                            File.WriteAllText(filePath, fileContent);
                            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PlcNextVSExtension.PlcNextProject.Import.ProjectTemplate.UndefClang.hpp"))
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    string content = await reader.ReadToEndAsync();
                                    File.WriteAllText(Path.Combine(projectDirectory, "UndefClang.hpp"), content);
                                }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + ex.StackTrace ?? string.Empty, $"Exception during writing of {filePath}");
                            return(false);
                        }

                        return(true);

                        async Task <string> GetProjectFileTemplate()
                        {
                            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PlcNextVSExtension.PlcNextProject.Import.ProjectTemplate.PLCnextImportTemplate.vcxproj"))
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    return(await reader.ReadToEndAsync());
                                }
                        }
                    }

                    void GenerateCode()
                    {
                        _plcncliCommunication.ExecuteCommand(Resources.Command_generate_code, null, null, Resources.Option_generate_code_project, $"\"{projectDirectory}\"");
                    }

                    void SetIncludesAndMacros()
                    {
                        ProjectInformationCommandResult projectInformation = _plcncliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                                                  typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project, $"\"{projectDirectory}\"") as ProjectInformationCommandResult;

                        CompilerSpecificationCommandResult compilerSpecsCommandResult =
                            _plcncliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                 typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project, $"\"{projectDirectory}\"") as
                            CompilerSpecificationCommandResult;

                        VCProject vcProject = project.Object as VCProject;
                        ProjectIncludesManager.SetIncludesForNewProject(vcProject, compilerSpecsCommandResult, projectInformation);
                    }
                }
            });
        }
예제 #6
0
        public void ProjectFinishedGenerating(Project project)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                GeneratePLCnCLIProject();
            }
            catch (Exception e)
            {
                try
                {
                    project.DTE.Solution.Remove(project);
                    DeleteProjectDirectory();
                    DeleteSolutionFolderIfEmpty(project.DTE);
                }
                catch (Exception)
                {}

                throw e;
            }

            void GeneratePLCnCLIProject()
            {
                _project = project;
                VCProject p = _project.Object as VCProject;

                //**********create new plcncli project**********
                //**********get project type**********
                VCConfiguration        configuration = p.ActiveConfiguration;
                IVCRulePropertyStorage plcnextRule   = configuration.Rules.Item(Constants.PLCnextRuleName);

                if (plcnextRule == null)
                {
                    throw new NullReferenceException("PLCnextCommonProperties rule was not found in configuration rules collection.");
                }
                string projectType = plcnextRule.GetUnevaluatedPropertyValue("ProjectType_");

                string        newProjectCommand   = Resources.Command_new_plmproject;
                List <string> newProjectArguments = new List <string>
                {
                    Resources.Option_new_project_output, $"\"{_projectDirectory}\"",
                    Resources.Option_new_project_projectNamespace, _projectNamespace
                };

                if (!projectType.Equals(Resources.ProjectType_ConsumableLibrary))
                {
                    newProjectArguments.Add(Resources.Option_new_project_componentName);
                    newProjectArguments.Add(_componentName);

                    if (projectType.Equals(Resources.ProjectType_PLM))
                    {
                        newProjectArguments.Add(Resources.Option_new_project_programName);
                        newProjectArguments.Add(_programName);
                    }
                }

                if (projectType.Equals(Resources.ProjectType_ACF))
                {
                    newProjectCommand = Resources.Command_new_acfproject;
                }
                else if (projectType.Equals(Resources.ProjectType_ConsumableLibrary))
                {
                    newProjectCommand = Resources.Command_new_consumablelibrary;
                }

                _plcncliCommunication.ExecuteCommand(newProjectCommand, null, null, newProjectArguments.ToArray());


                //**********create configurations**********
                ProjectConfigurationManager.CreateConfigurationsForAllProjectTargets
                    (_projectTargets.Select(t => t.GetNameFormattedForCommandLine()), project);

                foreach (TargetResult target in _projectTargets)
                {
                    //**********set project target**********
                    _plcncliCommunication.ExecuteCommand(Resources.Command_set_target, null, null,
                                                         Resources.Option_set_target_add, Resources.Option_set_target_name, target.Name,
                                                         Resources.Option_set_target_version, target.Version, Resources.Option_set_target_project,
                                                         $"\"{_projectDirectory}\"");
                }


                //add project items to project
                IEnumerable <string> projectFiles =
                    Directory.GetFiles(_projectDirectory, "*.*pp", SearchOption.AllDirectories)
                    .Concat(Directory.GetFiles(_projectDirectory, "*.txt", SearchOption.AllDirectories))
                    .Where(f => !f.EndsWith("UndefClang.hpp"));

                foreach (string file in projectFiles)
                {
                    project.ProjectItems.AddFromFile(file);
                }

                //**********generate code**********
                _plcncliCommunication.ExecuteCommand(Resources.Command_generate_code, null, null, Resources.Option_generate_code_project, $"\"{_projectDirectory}\"");

                ProjectInformationCommandResult projectInformation = _plcncliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                                          typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project, $"\"{_projectDirectory}\"") as ProjectInformationCommandResult;

                CompilerSpecificationCommandResult compilerSpecsCommandResult =
                    _plcncliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                         typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project, $"\"{_projectDirectory}\"") as
                    CompilerSpecificationCommandResult;

                ProjectIncludesManager.SetIncludesForNewProject(p, compilerSpecsCommandResult, projectInformation);
            }
        }
예제 #7
0
        public static void UpdateIncludesAndMacrosForExistingProject(VCProject vcProject,
                                                                     IEnumerable <CompilerMacroResult> oldMacros,
                                                                     CompilerSpecificationCommandResult newCompilerSpecs,
                                                                     IEnumerable <string> oldIncludes,
                                                                     ProjectInformationCommandResult newProjectInformation)
        {
            var(newMacros, newIncludes) =
                ProjectIncludesManager.FindMacrosAndIncludesForMinTarget(newCompilerSpecs,
                                                                         newProjectInformation);
            if (newMacros == null)
            {
                newMacros = Enumerable.Empty <CompilerMacroResult>();
            }
            if (newIncludes == null)
            {
                newIncludes = Enumerable.Empty <string>();
            }

            IVCRulePropertyStorage plcnextCommonPropertiesRule = vcProject.ActiveConfiguration.Rules.Item(Constants.PLCnextRuleName);


            foreach (VCConfiguration2 config in vcProject.Configurations)
            {
                plcnextCommonPropertiesRule = config.Rules.Item(Constants.PLCnextRuleName);

                CheckIncludesVariableIsInProjectIncludes(config);
                CheckMacrosVariableIsInProjectMacros(config);

                DeleteObsoleteIncludes();
                DeleteObsoleteMacros();

                void DeleteObsoleteIncludes()
                {
                    string savedIncludes = plcnextCommonPropertiesRule.GetUnevaluatedPropertyValue(Constants.PLCnextIncludesKey);

                    if (!string.IsNullOrEmpty(savedIncludes) || oldIncludes == null || !oldIncludes.Any())
                    {
                        return;
                    }

                    IVCRulePropertyStorage rule            = config.Rules.Item(Constants.VCppIncludesRuleName);
                    IEnumerable <string>   currentIncludes = rule.GetUnevaluatedPropertyValue(Constants.VCppIncludesKey)
                                                             .Split(';')
                                                             .Where(i => !oldIncludes.Contains(i));

                    rule.SetPropertyValue(Constants.VCppIncludesKey, currentIncludes.Any() ?
                                          string.Join(";", currentIncludes) : string.Empty);
                }

                void DeleteObsoleteMacros()
                {
                    string savedMacros = plcnextCommonPropertiesRule.GetUnevaluatedPropertyValue(Constants.PLCnextMacrosKey);

                    if (!string.IsNullOrEmpty(savedMacros) || oldMacros == null || !oldMacros.Any())
                    {
                        return;
                    }

                    IVCRulePropertyStorage            clRule        = config.Rules.Item(Constants.CLRuleName);
                    IEnumerable <CompilerMacroResult> currentMacros =
                        clRule.GetUnevaluatedPropertyValue(Constants.VCPreprocessorsKey)
                        .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(m => m.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
                        .Select(m => new CompilerMacroResult {
                        Name = m[0], Value = m.Length == 2 ? m[1].Trim() : null
                    });

                    currentMacros = currentMacros.Where(m => !oldMacros.Any(y => y.Name.Equals(m.Name) &&
                                                                            (y.Value != null ?
                                                                             (m.Value == null ?
                                                                              string.IsNullOrEmpty(y.Value.Trim()) :
                                                                              y.Value.Trim().Equals(m.Value.Trim())) :
                                                                             string.IsNullOrEmpty(m.Value?.Trim()))));
                    IEnumerable <string> macros = currentMacros.Select(m => m.Name + (string.IsNullOrEmpty(m.Value?.Trim()) ? string.Empty : ("=" + m.Value)));

                    clRule.SetPropertyValue(Constants.VCPreprocessorsKey, macros.Any() ? string.Join(";", macros) : string.Empty);
                }
            }

            plcnextCommonPropertiesRule.SetPropertyValue(Constants.PLCnextIncludesKey, newIncludes.Any() ?
                                                         string.Join(";", newIncludes) :
                                                         string.Empty);

            plcnextCommonPropertiesRule.SetPropertyValue(Constants.PLCnextMacrosKey, newMacros.Any() ?
                                                         string.Join(";", newMacros.Select(m => m.Name + (string.IsNullOrEmpty(m.Value?.Trim()) ? string.Empty : ("=" + m.Value))))
                : string.Empty);


            void CheckIncludesVariableIsInProjectIncludes(VCConfiguration2 config)
            {
                IVCRulePropertyStorage rule = config.Rules.Item(Constants.VCppIncludesRuleName);
                string currentIncludes      = rule.GetUnevaluatedPropertyValue(Constants.VCppIncludesKey);

                if (!currentIncludes.Split(';').Where(i => i.Trim().Equals($"$({Constants.PLCnextIncludesKey})", StringComparison.OrdinalIgnoreCase)).Any())
                {
                    string includes = string.IsNullOrEmpty(currentIncludes) ? $"$({Constants.PLCnextIncludesKey})"
                                                        : string.Join(";", currentIncludes, $"$({Constants.PLCnextIncludesKey})");
                    rule.SetPropertyValue(Constants.VCppIncludesKey, includes);
                }
            }

            void CheckMacrosVariableIsInProjectMacros(VCConfiguration2 config)
            {
                IVCRulePropertyStorage clRule = config.Rules.Item(Constants.CLRuleName);
                string currentMacros          =
                    clRule.GetUnevaluatedPropertyValue(Constants.VCPreprocessorsKey);

                if (!currentMacros.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                    .Where(m => m.Trim()
                           .Equals($"$({Constants.PLCnextMacrosKey})", StringComparison.OrdinalIgnoreCase))
                    .Any())
                {
                    string macros = string.IsNullOrEmpty(currentMacros) ? $"$({Constants.PLCnextMacrosKey})"
                                                       : string.Join(";", currentMacros, $"$({Constants.PLCnextMacrosKey})");
                    clRule.SetPropertyValue(Constants.VCPreprocessorsKey, macros);
                }
            }
        }
예제 #8
0
 private static IEnumerable <string> GetIncludesForTarget(TargetResult target, ProjectInformationCommandResult projectInformation)
 {
     return(projectInformation?.IncludePaths
            .Where(x => x.Targets == null ||
                   !x.Targets.Any() ||
                   (target != null && x.Targets.Any(t => t.Name.Equals(target.Name) &&
                                                    t.LongVersion.Equals(target.LongVersion))
                   )
                   )
            .Select(p => p.PathValue));
 }
예제 #9
0
 public static TargetResult FindMinTargetForIncludes(ProjectInformationCommandResult projectInformation)
 {
     return(projectInformation?.Targets
            .Where(t => t.Available == true)
            .MinTarget());
 }
예제 #10
0
        private void UpdateIncludesOnBeforeSave(VCProject p, string projectDirectory)
        {
            var(includesSaved, macrosSaved) = ProjectIncludesManager.CheckSavedIncludesAndMacros(p);
            IEnumerable <string> includesBefore            = null;
            IEnumerable <CompilerMacroResult> macrosBefore = null;

            try
            {
                ThreadHelper.JoinableTaskFactory.Run("Updating includes and macros", async(progress) =>
                {
                    await Task.Run(() => GetIncludesAndMacros());

                    void GetIncludesAndMacros()
                    {
                        if (!includesSaved)
                        {
                            progress.Report(new ThreadedWaitDialogProgressData("Fetching project information"));
                            ProjectInformationCommandResult projectInformationBefore = null;
                            try
                            {
                                projectInformationBefore = cliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                           typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                                           $"\"{projectDirectory}\"") as ProjectInformationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                projectInformationBefore = cliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                            }
                            includesBefore = projectInformationBefore?.IncludePaths.Select(x => x.PathValue);
                            if (includesBefore == null)
                            {
                                includesBefore = Enumerable.Empty <string>();
                            }
                        }

                        if (!macrosSaved)
                        {
                            progress.Report(new ThreadedWaitDialogProgressData("Fetching compiler information"));

                            CompilerSpecificationCommandResult compilerSpecsBefore = null;
                            try
                            {
                                compilerSpecsBefore = cliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                                      typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project,
                                                                                      $"\"{projectDirectory}\"") as CompilerSpecificationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                compilerSpecsBefore = cliCommunication.ConvertToTypedCommandResult <CompilerSpecificationCommandResult>(ex.InfoMessages);
                            }
                            macrosBefore = compilerSpecsBefore?.Specifications.FirstOrDefault()
                                           ?.CompilerMacros.Where(m => !m.Name.StartsWith("__has_include(")) ?? Enumerable.Empty <CompilerMacroResult>();
                        }
                    }
                });

                this.vcProject        = p;
                this.projectDirectory = p.ProjectDirectory;
                this.wrapper          = new IncludesAndMacrosWrapper(includesBefore, macrosBefore);
            }
            catch (Exception e)
            {
                Reset();
                try
                {
                    ThreadHelper.ThrowIfNotOnUIThread();
                    IVsActivityLog log = Package.GetGlobalService(typeof(SVsActivityLog)) as IVsActivityLog;
                    log.LogEntry((uint)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR, this.ToString(),
                                 "An error occurred while updating the includes: " + e.Message + e.StackTrace);
                }
                catch (Exception) { /*try to log error in activity log*/ }
            }
        }
예제 #11
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void SetTargets(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IServiceProvider serviceProvider = package;
            Project          project         = GetProject();

            if (project == null)
            {
                return;
            }
            string projectDirectory = Path.GetDirectoryName(project.FullName);

            //show dialog
            ProjectTargetValueEditorModel     model     = new ProjectTargetValueEditorModel(serviceProvider, projectDirectory);
            ProjectTargetValueEditorViewModel viewModel = new ProjectTargetValueEditorViewModel(model);
            ProjectTargetValueEditorView      view      = new ProjectTargetValueEditorView(viewModel);

            view.ShowModal();

            if (view.DialogResult == true)
            {
                if (!(serviceProvider.GetService(typeof(SPlcncliCommunication)) is IPlcncliCommunication cliCommunication))
                {
                    MessageBox.Show("Could not set project targets because no plcncli communication found.");
                    return;
                }

                VCProject p = project.Object as VCProject;
                bool      needProjectInformation  = false;
                bool      needCompilerInformation = false;

                var(includesSaved, macrosSaved) = ProjectIncludesManager.CheckSavedIncludesAndMacros(p);
                needProjectInformation          = !includesSaved;
                needCompilerInformation         = !macrosSaved;

                IEnumerable <string> includesBefore                        = null;
                IEnumerable <CompilerMacroResult>  macrosBefore            = Enumerable.Empty <CompilerMacroResult>();
                CompilerSpecificationCommandResult compilerSpecsAfter      = null;
                ProjectInformationCommandResult    projectInformationAfter = null;


                IVsTaskStatusCenterService taskCenter = Package.GetGlobalService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
                ITaskHandler taskHandler = taskCenter.PreRegister(
                    new TaskHandlerOptions()
                {
                    Title = $"Setting project targets"
                },
                    new TaskProgressData());
                Task task = Task.Run(async() =>
                {
                    try
                    {
                        if (needProjectInformation)
                        {
                            ProjectInformationCommandResult projectInformationBefore = null;
                            try
                            {
                                projectInformationBefore = cliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                           typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                                           $"\"{projectDirectory}\"") as ProjectInformationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                try
                                {
                                    projectInformationBefore = cliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                                }
                                catch (PlcncliException) {}
                            }

                            includesBefore = projectInformationBefore?.IncludePaths.Select(x => x.PathValue);
                            if (includesBefore == null)
                            {
                                includesBefore = Enumerable.Empty <string>();
                            }
                        }

                        if (needCompilerInformation)
                        {
                            CompilerSpecificationCommandResult compilerSpecsBefore = null;
                            try
                            {
                                compilerSpecsBefore = cliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                                      typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project,
                                                                                      $"\"{projectDirectory}\"") as CompilerSpecificationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                compilerSpecsBefore = cliCommunication.ConvertToTypedCommandResult <CompilerSpecificationCommandResult>(ex.InfoMessages);
                            }
                            macrosBefore = compilerSpecsBefore?.Specifications.FirstOrDefault()
                                           ?.CompilerMacros.Where(m => !m.Name.StartsWith("__has_include(")) ?? Enumerable.Empty <CompilerMacroResult>();
                        }

                        SetTargets();

                        try
                        {
                            projectInformationAfter = cliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                      typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                                      $"\"{projectDirectory}\"") as ProjectInformationCommandResult;
                        }
                        catch (PlcncliException ex)
                        {
                            projectInformationAfter = cliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                        }
                        try
                        {
                            compilerSpecsAfter = cliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                                 typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project,
                                                                                 $"\"{projectDirectory}\"") as CompilerSpecificationCommandResult;
                        }
                        catch (PlcncliException ex)
                        {
                            compilerSpecsAfter = cliCommunication.ConvertToTypedCommandResult <CompilerSpecificationCommandResult>(ex.InfoMessages);
                        }

                        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                        ProjectConfigurationManager.CreateConfigurationsForAllProjectTargets
                            (projectInformationAfter?.Targets.Select(t => t.GetNameFormattedForCommandLine()), project);


                        ProjectIncludesManager.UpdateIncludesAndMacrosForExistingProject(p, macrosBefore,
                                                                                         compilerSpecsAfter, includesBefore, projectInformationAfter);

                        p.Save();

                        ProjectIncludesManager.AddTargetsFileToOldProjects(p);

                        void SetTargets()
                        {
                            foreach (TargetResult target in model.TargetsToAdd)
                            {
                                cliCommunication.ExecuteCommand(Resources.Command_set_target, null, null,
                                                                Resources.Option_set_target_add, Resources.Option_set_target_project,
                                                                $"\"{projectDirectory}\"",
                                                                Resources.Option_set_target_name, target.Name, Resources.Option_set_target_version,
                                                                $"\"{target.LongVersion}\"");
                            }

                            foreach (TargetResult target in model.TargetsToRemove)
                            {
                                cliCommunication.ExecuteCommand(Resources.Command_set_target, null, null,
                                                                Resources.Option_set_target_remove, Resources.Option_set_target_project,
                                                                $"\"{projectDirectory}\"",
                                                                Resources.Option_set_target_name, target.Name, Resources.Option_set_target_version,
                                                                $"\"{target.LongVersion}\"");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + ex.StackTrace ?? string.Empty, "Exception during setting of targets");
                        throw ex;
                    }
                });
                taskHandler.RegisterTask(task);
            }
        }
예제 #12
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind,
                               object[] customParams)
        {
            string itemName = replacementsDictionary["$safeitemname$"];

            ThreadHelper.ThrowIfNotOnUIThread();

            if (automationObject is DTE dte)
            {
                object activeProjects      = dte.ActiveSolutionProjects;
                Array  activeProjectsArray = (Array)activeProjects;
                if (activeProjectsArray.Length > 0)
                {
                    Project project = (Project)activeProjectsArray.GetValue(0);
                    if (project != null)
                    {
                        IEnumerable <string> validProjectTypes = Enumerable.Empty <string>();
                        string itemType = string.Empty;
                        GetWizardDataFromTemplate();

                        string projectDirectory = Path.GetDirectoryName(project.FullName);
                        ProjectInformationCommandResult projectInformation = _plcncliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                                                  typeof(ProjectInformationCommandResult),
                                                                                                                  Resources.Option_get_project_information_no_include_detection,
                                                                                                                  Resources.Option_get_project_information_project, $"\"{projectDirectory}\"") as ProjectInformationCommandResult;
                        string projecttype = projectInformation.Type;

                        if (projecttype == null || !validProjectTypes.Contains(projecttype))
                        {
                            MessageBox.Show(
                                $"This template is not available for the selected project. The template is available for the project types" +
                                $"{validProjectTypes.Aggregate(string.Empty, (s1, s2) => s1 + $"\n'{s2}'")}\nbut the selected project is of type\n'{projecttype}'.",
                                "Template not available for project type",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                            throw new WizardBackoutException();
                        }

                        NewItemModel      model     = new NewItemModel(_plcncliCommunication, projectDirectory, itemType);
                        NewItemViewModel  viewModel = new NewItemViewModel(model);
                        NewItemDialogView view      = new NewItemDialogView(viewModel);

                        bool?result = view.ShowModal();
                        if (result != null && result == true)
                        {
                            try
                            {
                                if (itemType.Equals(Resources.ItemType_program))
                                {
                                    _plcncliCommunication.ExecuteCommand(Resources.Command_new_program, null, null,
                                                                         Resources.Option_new_program_project, $"\"{projectDirectory}\"",
                                                                         Resources.Option_new_program_name, itemName,
                                                                         Resources.Option_new_program_component, model.SelectedComponent,
                                                                         Resources.Option_new_program_namespace, model.SelectedNamespace);
                                }
                                else if (itemType.Equals(Resources.ItemType_component))
                                {
                                    string command = Resources.Command_new_component;
                                    if (projecttype.Equals(Resources.ProjectType_ACF))
                                    {
                                        command = Resources.Command_new_acfcomponent;
                                    }
                                    _plcncliCommunication.ExecuteCommand(command, null, null,
                                                                         Resources.Option_new_component_project, $"\"{projectDirectory}\"",
                                                                         Resources.Option_new_component_name, itemName,
                                                                         Resources.Option_new_component_namespace, model.SelectedNamespace);
                                }

                                string[] itemFiles = Directory.GetFiles(Path.Combine(projectDirectory, "src"), $"{itemName}.*pp");
                                foreach (string itemFile in itemFiles)
                                {
                                    project.ProjectItems.AddFromFile(itemFile);
                                }

                                _plcncliCommunication.ExecuteCommand(Resources.Command_generate_code, null, null,
                                                                     Resources.Option_generate_code_project, $"\"{projectDirectory}\"");
                            }catch (PlcncliException e)
                            {
                                MessageBox.Show(e.Message, "Error occured", MessageBoxButton.OK, MessageBoxImage.Error);
                                throw new WizardBackoutException();
                            }
                        }


                        void GetWizardDataFromTemplate()
                        {
                            string wizardData = replacementsDictionary["$wizarddata$"];

                            XDocument  document = XDocument.Parse(wizardData);
                            XNamespace nspace   = document.Root.GetDefaultNamespace();

                            validProjectTypes = document.Element(nspace + "Data").Element(nspace + "ValidProjectTypes")
                                                .Descendants(nspace + "Type").Select(e => e.Value);

                            itemType =
                                document.Element(nspace + "Data").Element(nspace + "ItemType").Value;
                        }
                    }
                }
            }
        }