Esempio n. 1
0
        public static void ArgumentAlreadySet(string argumentName, bool isSet, ILogger logger = null)
        {
            if (isSet)
            {
                var errorMessage     = string.Format("{0} is already set.", argumentName);
                var builderException = new BuilderException(errorMessage);

                if (logger != null && logger.IsErrorEnabled())
                {
                    logger.LogError(errorMessage, builderException);
                }

                throw builderException;
            }
        }
        /// <summary>
        /// Load and initialize the plug-ins used by this project
        /// </summary>
        /// <exception cref="BuilderException">This is thrown if a requested plug-in is not found</exception>
        private void LoadPlugIns()
        {
            Lazy <IPlugIn, IPlugInMetadata> plugIn;
            IPlugIn       instance;
            XmlDocument   config;
            StringBuilder sb = new StringBuilder(256);

            this.ReportProgress("Loading and initializing plug-ins...");
            loadedPlugIns = new Dictionary <string, IPlugIn>();

            var availablePlugs = componentContainer.GetExports <IPlugIn, IPlugInMetadata>();
            var projectPlugIns = new Dictionary <string, string>();

            // Get the project plug-ins first
            foreach (var kv in project.PlugInConfigurations)
            {
                if (!kv.Value.Enabled)
                {
                    this.ReportProgress("{0} plug-in is disabled and will not be loaded", kv.Key);
                }
                else
                {
                    projectPlugIns.Add(kv.Key, kv.Value.Configuration);
                }
            }

            // Add presentation style plug-in dependencies that are not in the project already
            foreach (var dp in presentationStyle.PlugInDependencies)
            {
                if (!projectPlugIns.ContainsKey(dp.Id))
                {
                    projectPlugIns.Add(dp.Id, dp.Configuration);
                }
            }

            // Note that a list of failures is accumulated as we may need to run the Completion Notification
            // plug-in to report the failures when done.
            foreach (var kv in projectPlugIns)
            {
                plugIn = null;

                try
                {
                    plugIn = availablePlugs.FirstOrDefault(p => p.Metadata.Id == kv.Key);

                    if (plugIn == null)
                    {
                        sb.AppendFormat("Error: Unable to locate plug-in '{0}' in any of the component or " +
                                        "project folders and it cannot be used.\r\n", kv.Key);
                        continue;
                    }

                    // For partial builds, only plug-ins that run in partial builds are loaded
                    if (this.PartialBuildType == PartialBuildType.None || plugIn.Metadata.RunsInPartialBuild)
                    {
                        // Plug-ins are singletons and will be disposed of by the composition container when it
                        // is disposed of.
                        instance = plugIn.Value;

                        config = new XmlDocument();
                        config.LoadXml(kv.Value);

                        instance.Initialize(this, config.CreateNavigator());

                        loadedPlugIns.Add(kv.Key, instance);
                    }
                }
                catch (Exception ex)
                {
                    BuilderException bex = ex as BuilderException;

                    if (bex != null)
                    {
                        sb.AppendFormat("{0}: {1}\r\n", bex.ErrorCode, bex.Message);
                    }
                    else
                    {
                        sb.AppendFormat("{0}: Unexpected error: {1}\r\n",
                                        (plugIn != null) ? plugIn.Metadata.Id : kv.Key, ex.ToString());
                    }
                }
            }

            if (sb.Length != 0)
            {
                sb.Insert(0, "Plug-in loading errors:\r\n");
                throw new BuilderException("BE0028", sb.ToString());
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Load and initialize the plug-ins used by this project
        /// </summary>
        /// <exception cref="BuilderException">This is thrown if a requested
        /// plug-in is not found or has a version that is not supported by
        /// this version of the help file builder.</exception>
        private void LoadPlugIns()
        {
            PlugInConfiguration plugInConfig;
            IPlugIn             plugIn;
            XmlDocument         config;
            StringBuilder       sb = new StringBuilder(256);

            this.ReportProgress("Loading and initializing plug-ins...");
            loadedPlugIns = new Dictionary <string, IPlugIn>();

            // Note that a list of failures is accumulate as we may need to
            // run the Completion Notification plug-in to report the failures
            // when done.
            foreach (string key in project.PlugInConfigurations.Keys)
            {
                plugInConfig = project.PlugInConfigurations[key];

                if (!plugInConfig.Enabled)
                {
                    this.ReportProgress("{0} plug-in is disabled and will " +
                                        "not be loaded", key);
                    continue;
                }

                plugIn = null;

                try
                {
                    if (!PlugInManager.IsSupported(key))
                    {
                        sb.AppendFormat("Error: Unable to locate plug-in '{0}' " +
                                        "or it is of a version that is not supported by " +
                                        "this version of the help file builder\r\n", key);
                        continue;
                    }

                    plugIn = PlugInManager.PlugIns[key].NewInstance();

                    // For partial builds, only plug-ins that run in partial
                    // builds are loaded.
                    if (!this.IsPartialBuild || plugIn.RunsInPartialBuild)
                    {
                        config = new XmlDocument();
                        config.LoadXml(plugInConfig.Configuration);
                        plugIn.Initialize(this, config.CreateNavigator());
                        loadedPlugIns.Add(key, plugIn);
                    }
                    else
                    {
                        plugIn.Dispose();
                    }
                }
                catch (ReflectionTypeLoadException rex)
                {
                    sb.AppendFormat("Unable to load plug-in assembly for {0}:\r\n",
                                    key);

                    if (rex.Types.Length != 0)
                    {
                        sb.AppendFormat("  Assembly: {0}\r\n",
                                        rex.Types[0].Module.FullyQualifiedName);
                    }

                    foreach (Exception ex in rex.LoaderExceptions)
                    {
                        sb.AppendFormat("  {0}\r\n", ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    BuilderException bex = ex as BuilderException;

                    if (bex != null)
                    {
                        sb.AppendFormat("{0}: {1}\r\n", bex.ErrorCode,
                                        bex.Message);
                    }
                    else
                    {
                        sb.AppendFormat("{0}: Unexpected error: {1}\r\n",
                                        (plugIn != null) ? plugIn.Name : key, ex.ToString());
                    }
                }
            }

            if (sb.Length != 0)
            {
                sb.Insert(0, "Plug-in loading errors:\r\n");
                throw new BuilderException("BE0028", sb.ToString());
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Convert the project
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void btnConvert_Click(object sender, EventArgs e)
        {
            ConvertToMSBuildFormat converter = null;
            string project, folder;
            bool   isValid = true;

            epErrors.Clear();
            epErrors.SetIconPadding(txtProjectFile, btnSelectProject.Width + 5);
            epErrors.SetIconPadding(txtNewProjectFolder, btnSelectNewFolder.Width + 5);

            project = txtProjectFile.Text.Trim();

            if (txtNewProjectFolder.Enabled)
            {
                folder = txtNewProjectFolder.Text.Trim();
            }
            else
            {
                folder = Path.GetDirectoryName(txtNewProjectFolder.Text);
            }

            if (project.Length == 0)
            {
                epErrors.SetError(txtProjectFile, "A project file must be specified");
                isValid = false;
            }
            else
            if (!File.Exists(project))
            {
                epErrors.SetError(txtProjectFile, "The specified project file does not exist");
                isValid = false;
            }

            if (folder.Length == 0)
            {
                epErrors.SetError(txtNewProjectFolder, "An output folder for the converted project must " +
                                  "be specified");
                isValid = false;
            }

            if (isValid)
            {
                project = Path.GetFullPath(project);
                folder  = Path.GetFullPath(folder);

                if (FolderPath.TerminatePath(Path.GetDirectoryName(project)) == FolderPath.TerminatePath(folder))
                {
                    epErrors.SetError(txtNewProjectFolder, "The output folder cannot match the folder of the " +
                                      "original project");
                    isValid = false;
                }
            }

            if (!isValid)
            {
                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                switch (cboProjectFormat.SelectedIndex)
                {
                case 1:
                    if (currentProject == null)
                    {
                        converter = new ConvertFromNDoc(txtProjectFile.Text, txtNewProjectFolder.Text);
                    }
                    else
                    {
                        converter = new ConvertFromNDoc(txtProjectFile.Text, currentProject);
                    }
                    break;

                case 2:
                    if (currentProject == null)
                    {
                        converter = new ConvertFromDocProject(txtProjectFile.Text, txtNewProjectFolder.Text);
                    }
                    else
                    {
                        converter = new ConvertFromDocProject(txtProjectFile.Text, currentProject);
                    }
                    break;

                case 3:
                    if (currentProject == null)
                    {
                        converter = new ConvertFromSandcastleGui(txtProjectFile.Text, txtNewProjectFolder.Text);
                    }
                    else
                    {
                        converter = new ConvertFromSandcastleGui(txtProjectFile.Text, currentProject);
                    }
                    break;

                case 4:
                    if (currentProject == null)
                    {
                        converter = new ConvertFromMSExampleGui(txtProjectFile.Text, txtNewProjectFolder.Text);
                    }
                    else
                    {
                        converter = new ConvertFromMSExampleGui(txtProjectFile.Text, currentProject);
                    }
                    break;

                default:
                    if (currentProject == null)
                    {
                        converter = new ConvertFromShfbFile(txtProjectFile.Text, txtNewProjectFolder.Text);
                    }
                    else
                    {
                        converter = new ConvertFromShfbFile(txtProjectFile.Text, currentProject);
                    }
                    break;
                }

                newProjectFilename = converter.ConvertProject();

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);

                BuilderException bex = ex as BuilderException;

                if (bex != null)
                {
                    MessageBox.Show("Unable to convert project.  Reason: Error " + bex.ErrorCode + ":" +
                                    bex.Message, Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    MessageBox.Show("Unable to convert project.  Reason: " + ex.Message, Constants.AppName,
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;

                if (converter != null)
                {
                    converter.Dispose();
                }
            }
        }
Esempio n. 5
0
        public void Execute(Project p)
        {
            // generate temporary filename
            string tempFileName;

            try
            {
                var protoFilename = Path.GetTempFileName();

                // build more unique filename (include timestamp)
                tempFileName = string.Format("{0}{1}{2}", DateTime.Now.ToFileTime(), Path.GetFileName(protoFilename), ".cmd");

                // prep filename with actual path
                tempFileName = Path.Combine(Path.GetDirectoryName(protoFilename), tempFileName);

                // move file to new .cmd
                File.Move(protoFilename, tempFileName);
            }
            catch (Exception e)
            {
                log.Error("Failed to generate temporary command script", e);
                throw BuilderException.CreateFailedToStartException(p, e);
            }

            TextWriter writer = null;

            if (p == null)
            {
                throw new BuilderException("No project provided", null);
            }

            try
            {
                if (ManagedBuilderSettings.IsDebug && ManagedBuilderSettings.DebugGenerateSingleFile)
                {
                    writer = DebugCommandFile;
                    Monitor.Enter(DebugCommandFile);
                }
                else
                {
                    var fs = new FileStream(tempFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
                    writer = new StreamWriter(fs);
                }

                if (!ManagedBuilderSettings.CommandLineConfig.FrameworkCommands.ContainsKey(p.Framework))
                {
                    throw new BuilderException("Unsupported framework", p);
                }

                log.DebugFormat("{0}:Building command line script in [{1}]", p.Name, tempFileName);

                // setup property manager for this compilation instance
                var propMan = new PropertyManager();

                var projectPath = p.Path;
                if (!Path.IsPathRooted(projectPath))
                {
                    projectPath = Path.Combine(PropertyManager.Common["build.directory"], projectPath);
                }

                log.DebugFormat("Project file: {0}", projectPath);
                log.DebugFormat("Project platform: {0}", p.PlatformName);
                log.DebugFormat("Project config: {0}", p.ConfigurationName);
                log.DebugFormat("Project build options: {0}", p.BuildOpt);
                log.DebugFormat("Project location: {0}", Path.GetDirectoryName(projectPath));

                propMan.Add("project.file", projectPath);
                propMan.Add("project.buildopts", p.BuildOpt);
                propMan.Add("project.sccpath", p.SccPath);
                propMan.Add("project.platform", p.PlatformName);
                propMan.Add("project.configuration", p.ConfigurationName);
                propMan.AddDirectoryProperty("project.dir", Path.GetDirectoryName(projectPath));

                var cmdlet = ManagedBuilderSettings.CommandLineConfig.FrameworkCommands[p.Framework];

                var cmdletOut = string.Format("call {0} {1}",
                                              propMan.Evaluate(cmdlet.Commandlet), propMan.Evaluate(cmdlet.Arguments));
                writer.WriteLine(cmdletOut);
                log.DebugFormat("{0}: {1}", p.Name, cmdletOut);

                // setup binplace
                if (ManagedBuilderSettings.CommandLineConfig.BinPlaceEnabled)
                {
                    // location where binplace is stored
                    var binPlaceLocation = propMan.Evaluate(
                        ManagedBuilderSettings.CommandLineConfig.BinPlaceLocation);
                    var binPlaceFile = propMan.Evaluate(
                        ManagedBuilderSettings.CommandLineConfig.BinPlaceFilename);
                    var binPlaceRoot = propMan.Evaluate(
                        ManagedBuilderSettings.CommandLineConfig.BinPlaceRoot);

                    foreach (var output in p.Outputs)
                    {
                        var actualDestPath = "";
                        if (!String.IsNullOrEmpty(output.DestPath))
                        {
                            actualDestPath = string.Format(
                                "-b {0} ",
                                output.DestPath);
                        }

                        foreach (var path in output.PathList)
                        {
                            if (string.IsNullOrEmpty(path))
                            {
                                log.Warn("Found an empty path in project outputs");
                                continue;
                            }

                            var binPlaceOut = string.Format(
                                "{4} {0} -r {1} -p {2} {3}",
                                actualDestPath,
                                binPlaceRoot,
                                // todo app.config needs to be set so that these values are evaluated
                                Path.Combine(PropertyManager.Common["build.directory"], binPlaceFile),
                                Path.Combine(PropertyManager.Common["build.directory"], path),
                                binPlaceLocation
                                );

                            // write output to batch script
                            writer.WriteLine(binPlaceOut);
                            log.DebugFormat("{0}: {1}", p.Name, binPlaceOut);
                        }
                    }
                }

                if (ManagedBuilderSettings.IsDebug && ManagedBuilderSettings.DebugGenerateSingleFile)
                {
                    Monitor.Exit(DebugCommandFile);
                    DebugCommandFile.Flush();
                }
                else
                {
                    writer.Close();
                }

                log.DebugFormat("{0}: Executing command line script [{1}]", p.Name, tempFileName);
                var startInfo = new ProcessStartInfo();
                startInfo.Arguments =
                    string.Format("/c \"{0}\"", tempFileName);
                startInfo.FileName = "cmd.exe";
                //startInfo.RedirectStandardOutput = true;
                startInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                startInfo.CreateNoWindow  = true;
                startInfo.UseShellExecute = false;

                // todo: make it changeable via config
                startInfo.WorkingDirectory = PropertyManager.Common["build.directory"];

                try
                {
                    var process = Process.Start(startInfo);
                    if (process == null)
                    {
                        throw BuilderException.CreateFailedToStartException(p);
                    }

                    using (process)
                    {
                        process.WaitForExit();

                        if (process.ExitCode != 0)
                        {
                            throw BuilderException.CreateBuildFailedDueToExitCodeException(p, process.ExitCode);
                        }
                    }
                }
                catch (BuilderException be)
                {
                    throw;
                }
                catch (Exception e)
                {
                    throw BuilderException.CreateFailedToStartException(p, e);
                }
            }
            finally
            {
                if (!ManagedBuilderSettings.IsDebug)
                {
                    File.Delete(tempFileName);
                }
            }
        }