Esempio n. 1
0
        public void Init()
        {
            projectManager = Substitute.For <IProjectManager>();
            projectConfigurationManager = new ProjectConfigurationManager();
            dialogFactory       = Substitute.For <IDialogFactory>();
            authManager         = new AuthManagerStub();
            codeProviderFactory = Substitute.For <ICodeProviderFactory>();
            globalConfiguration = Substitute.For <IGlobalConfiguration>();;
            CreateMethodCmd.Initialize(projectManager, authManager, dialogFactory, projectConfigurationManager, codeProviderFactory, globalConfiguration);
            createMethodCmd = CreateMethodCmd.Instance;
            iVsUIShell      = Substitute.For <IVsUIShell>();
            var currentPath = AppDomain.CurrentDomain.BaseDirectory;

            projectManager.ProjectConfigPath.Returns(Path.Combine(currentPath, "TestData\\projectConfig.xml"));
            projectManager.MethodConfigPath.Returns(Path.Combine(currentPath, "TestData\\method-config.xml"));
            template = new TemplateInfo {
                TemplateName = string.Empty
            };
            eventSpecificDataType = new EventSpecificDataType {
                EventSpecificData = EventSpecificData.None
            };
            templateLoader       = new TemplateLoader(dialogFactory);
            packageManager       = new PackageManager(authManager);
            codeProvider         = Substitute.For <ICodeProvider>();
            projectConfiguration = projectConfigurationManager.Load(projectManager.ProjectConfigPath);
            templateLoader.Load(projectManager.MethodConfigPath);
            codeProviderFactory.GetCodeProvider(null, null).ReturnsForAnyArgs(codeProvider);
        }
 public void Init()
 {
     projectManager = Substitute.For<IProjectManager>();
     projectConfigurationManager = Substitute.For<ProjectConfigurationManager>();
     dialogFactory = Substitute.For<IDialogFactory>();
     RefreshConfigCmd.Initialize(projectManager, dialogFactory, projectConfigurationManager);
     refreshConfigCmd = RefreshConfigCmd.Instance;
     iVsUIShell = Substitute.For<IVsUIShell>();
 }
 public void Init()
 {
     projectManager = Substitute.For <IProjectManager>();
     projectConfigurationManager = new ProjectConfigurationManager();
     dialogFactory = Substitute.For <IDialogFactory>();
     authManager   = Substitute.For <IAuthenticationManager>();
     ConnectionInfoCmd.Initialize(projectManager, authManager, dialogFactory, projectConfigurationManager);
     сonnectionInfoCmd = ConnectionInfoCmd.Instance;
     iVsUIShell        = Substitute.For <IVsUIShell>();
 }
Esempio n. 4
0
        void OnExecute()
        {
            // Initialize a logging factory and get a logger for ourselves
            ApplicationLogging.Initialize();
            Log = ApplicationLogging.Factory.CreateLogger("ReaperKing.Builder");

            // Initialize a configuration manager
            Config = new ProjectConfigurationManager();
            Config.AddType <BuildConfiguration>();

            // Clean up arguments
            AssemblyPath = PathUtils.EnsureRooted(AssemblyPath);
            Log.LogInformation("Reaper King building tool");

            // Load the project assembly and find the Site class.
            Assembly siteAssembly;
            Type     siteType;

            Log.LogInformation("Static configuration assembly is now being loaded");
            AllowAssembliesFromUserPath();
            (siteAssembly, siteType) = GetSiteBuildRecipeType();
            Config.ScanType(siteType);

            // Set the ImmutableRuntimeConfiguration early.
            RuntimeConfig = new()
            {
                ContentRoot    = new FileInfo(ProjectFilename).Directory?.FullName,
                AssemblyRoot   = AssemblyPath,
                DeploymentPath = PathUtils.EnsureRooted("public"),
            };
            Config.Override <ImmutableRuntimeConfiguration>(RuntimeConfig);

            // Create an instance of the build recipe class.
            Log.LogInformation("Static Site Configuration object is being created");
            var instance = Activator.CreateInstance(siteType,
                                                    Config,
                                                    ApplicationLogging.Factory);

            if (!(instance is Site site))
            {
                Log.LogCritical("Static Configuration instance is not valid.");
                return;
            }
            SiteObject = site;

            // Load the project configuration from a file
            Log.LogInformation("Project configuration is now being loaded");
            LoadProjectConfig();

            // Add the assembly to RazorLight's metadata references
            AddTypeMetadataToRazor(siteAssembly);

            ProceedBakeSite();
            Log.LogInformation("Site has been successfully built.");
        }
Esempio n. 5
0
File: Site.cs Progetto: alex4401/rk
        public RkBuildRecipe(ProjectConfigurationManager project,
                             ILoggerFactory loggerFactory)
            : base(typeof(RkBuildRecipe), project, loggerFactory)
        {
            AddModule(new RkFandomImageVirtualFsModule(this));
            AddModule(new RkSitemapExclusionModule(this));
            AddModule(new RkUglifyModule(this));
            AddModule(new RkDocumentCollectionModule(this));
            AddModule(new RkImageOptimizationModule(this));

            ProjectConfig.AddType <AnhydrateConfiguration>();
        }
Esempio n. 6
0
File: Site.cs Progetto: alex4401/rk
        protected Site(Type selfType,
                       ProjectConfigurationManager project,
                       ILoggerFactory loggerFactory)
        {
            (ProjectConfig, LogFactory) = (project, loggerFactory);
            Log = LogFactory.CreateLogger(selfType.FullName);

            ImmutableConfig = project.Get <ImmutableRuntimeConfiguration>();
            WebConfig       = project.Get <WebConfiguration>();

            _razorProject = new RazorScopedFilesystemProject(Path.Join(ContentRoot, "templates"));
            RazorEngine   = new RazorLightEngineBuilder()
                            .UseProject(_razorProject)
                            .UseMemoryCachingProvider()
                            .Build();
        }
        public void Init()
        {
            projectManager = Substitute.For <IProjectManager>();
            projectConfigurationManager = Substitute.For <ProjectConfigurationManager>();
            dialogFactory       = Substitute.For <IDialogFactory>();
            authManager         = new AuthManagerStub();
            codeProviderFactory = Substitute.For <ICodeProviderFactory>();
            codeProvider        = Substitute.For <ICodeProvider>();
            codeProviderFactory.GetCodeProvider(null).ReturnsForAnyArgs(codeProvider);
            iVsUIShell = Substitute.For <IVsUIShell>();
            var currentPath = AppDomain.CurrentDomain.BaseDirectory;

            projectManager.ProjectConfigPath.Returns(Path.Combine(currentPath, "TestData\\projectConfig.xml"));
            projectConfigurationManager.Load(projectManager.ProjectConfigPath);
            projectManager.MethodName.Returns("TestMethod");
            projectManager.MethodPath.Returns(Path.Combine(currentPath, "TestData\\TestMethod.txt"));
            messageManager = Substitute.For <MessageManager>();
            DebugMethodCmd.Initialize(projectManager, authManager, dialogFactory, projectConfigurationManager, codeProviderFactory, messageManager);
            debugMethodCmd = DebugMethodCmd.Instance;

            var project    = Substitute.For <Project>();
            var properties = Substitute.For <EnvDTE.Properties>();
            var property   = Substitute.For <Property>();
            var propertiesForActiveConfigurations = Substitute.For <EnvDTE.Properties>();
            var propertyForActiveConfiguration    = Substitute.For <Property>();
            var configurationManager = Substitute.For <ConfigurationManager>();
            var activeConfigurator   = Substitute.For <Configuration>();

            projectManager.SelectedProject.Returns(project);
            project.FileName.Returns(currentPath);
            project.Properties.Returns(properties);
            properties.Item(Arg.Any <string>()).Returns(property);
            property.Value = "";

            project.ConfigurationManager.Returns(configurationManager);
            configurationManager.ActiveConfiguration.Returns(activeConfigurator);
            activeConfigurator.Properties.Returns(propertiesForActiveConfigurations);
            propertiesForActiveConfigurations.Item(Arg.Any <string>()).Returns(propertyForActiveConfiguration);
            propertyForActiveConfiguration.Value = "";
            projectManager.When(x => x.AttachToProcess(Arg.Any <System.Diagnostics.Process>())).Do(x => { });
            var codeModel = Substitute.For <CodeModel>();

            project.CodeModel.Returns(codeModel);
            codeModel.Language.Returns("");
        }
Esempio n. 8
0
        public void Init()
        {
            projectManager = Substitute.For <IProjectManager>();
            projectConfigurationManager = Substitute.For <ProjectConfigurationManager>();
            dialogFactory       = Substitute.For <IDialogFactory>();
            codeProviderFactory = Substitute.For <ICodeProviderFactory>();
            CreatePartialElementCmd.Initialize(projectManager, dialogFactory, projectConfigurationManager, codeProviderFactory);
            createPartialElementCmd = CreatePartialElementCmd.Instance;
            iVsUIShell = Substitute.For <IVsUIShell>();
            var currentPath = AppDomain.CurrentDomain.BaseDirectory;

            projectManager.ProjectConfigPath.Returns(Path.Combine(currentPath, "TestData\\projectConfig.xml"));
            projectManager.MethodName.Returns("TestMethod");
            projectConfiguration = projectConfigurationManager.Load(projectManager.ProjectConfigPath);
            projectConfiguration.UseVSFormatting = false;
            codeProvider = Substitute.For <ICodeProvider>();
            codeProviderFactory.GetCodeProvider(null, null).ReturnsForAnyArgs(codeProvider);
        }
Esempio n. 9
0
        public void Init()
        {
            projectManager = Substitute.For <IProjectManager>();
            projectConfigurationManager = Substitute.For <ProjectConfigurationManager>();
            dialogFactory       = Substitute.For <IDialogFactory>();
            authManager         = Substitute.For <IAuthenticationManager>();
            codeProviderFactory = Substitute.For <ICodeProviderFactory>();
            codeProvider        = Substitute.For <ICodeProvider>();
            codeProviderFactory.GetCodeProvider(null, null).ReturnsForAnyArgs(codeProvider);
            OpenFromPackageCmd.Initialize(projectManager, authManager, dialogFactory, projectConfigurationManager, codeProviderFactory);
            openFromPackageCmd = OpenFromPackageCmd.Instance;
            iVsUIShell         = Substitute.For <IVsUIShell>();
            var currentPath = AppDomain.CurrentDomain.BaseDirectory;

            projectManager.ProjectConfigPath.Returns(Path.Combine(currentPath, "TestData\\projectConfig.xml"));
            projectConfiguration = projectConfigurationManager.Load(projectManager.ProjectConfigPath);
            templateLoader       = new TemplateLoader();
            projectManager.MethodConfigPath.Returns(Path.Combine(currentPath, "TestData\\method-config.xml"));
            templateLoader.Load(projectManager.MethodConfigPath);
        }
Esempio n. 10
0
 public void Init()
 {
     projectManager = Substitute.For <IProjectManager>();
     projectConfigurationManager = Substitute.For <ProjectConfigurationManager>();
     dialogFactory       = Substitute.For <IDialogFactory>();
     authManager         = Substitute.For <IAuthenticationManager>();
     codeProviderFactory = Substitute.For <ICodeProviderFactory>();
     codeProvider        = Substitute.For <ICodeProvider>();
     codeProviderFactory.GetCodeProvider(null).ReturnsForAnyArgs(codeProvider);
     messageManager = Substitute.For <MessageManager>();
     SaveToPackageCmd.Initialize(projectManager, authManager, dialogFactory, projectConfigurationManager, codeProviderFactory, messageManager);
     saveToPackageCmd = SaveToPackageCmd.Instance;
     iVsUIShell       = Substitute.For <IVsUIShell>();
     currentPath      = AppDomain.CurrentDomain.BaseDirectory;
     projectManager.ProjectConfigPath.Returns(Path.Combine(currentPath, "TestData\\projectConfig.xml"));
     projectConfigurationManager.Load(projectManager.ProjectConfigPath);
     projectConfigurationManager.CurrentProjectConfiguraiton.MethodConfigPath = Path.Combine(currentPath, "TestData\\method-config.xml");
     templateLoader = new TemplateLoader();
     templateLoader.Load(projectConfigurationManager.CurrentProjectConfiguraiton.MethodConfigPath);
     projectManager.MethodPath.Returns(Path.Combine(currentPath, "TestData\\TestMethod.txt"));
     packageManager = Substitute.For <PackageManager>(authManager, messageManager);
     File.Delete(Path.Combine(currentPath, "imports.mf"));
 }
        /// <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);
                    }
                }
            });
        }
Esempio n. 12
0
 public void Init()
 {
     projectConfigurationManager = new ProjectConfigurationManager();
 }
Esempio n. 13
0
File: Site.cs Progetto: alex4401/rk
 public Site(ProjectConfigurationManager project,
             ILoggerFactory loggerFactory)
     : this(typeof(Site), project, loggerFactory)
 {
 }
Esempio n. 14
0
 public void Init()
 {
     messageManager = new VisualStudioMessageManager();
     projectConfigurationManager = new ProjectConfigurationManager(messageManager);
 }
Esempio n. 15
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);
            }
        }