public ForEachComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

            // set up the context
            XPathNodeIterator context_nodes = configuration.Select("context");
            foreach (XPathNavigator context_node in context_nodes)
            {
                string prefix = context_node.GetAttribute("prefix", String.Empty);
                string name = context_node.GetAttribute("name", String.Empty);
                context.AddNamespace(prefix, name);
            }

			// load the expression format
			XPathNavigator variable_node = configuration.SelectSingleNode("variable");
			if (variable_node == null) throw new ConfigurationErrorsException("When instantiating a ForEach component, you must specify a variable using the <variable> element.");
			string xpath_format = variable_node.GetAttribute("expression", String.Empty);
			if ((xpath_format == null) || (xpath_format.Length == 0)) throw new ConfigurationErrorsException("When instantiating a ForEach component, you must specify a variable expression using the expression attribute");
			xpath = XPathExpression.Compile(xpath_format);

			// load the subcomponents
			WriteMessage(MessageLevel.Info, "Loading subcomponents.");
			XPathNavigator components_node = configuration.SelectSingleNode("components");
			if (components_node == null) throw new ConfigurationErrorsException("When instantiating a ForEach component, you must specify subcomponents using the <components> element.");
			
			components = BuildAssembler.LoadComponents(components_node);

			WriteMessage(MessageLevel.Info, String.Format("Loaded {0} subcomponents.", components.Count));

		}
		public SaveComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			// load the target path format
			XPathNavigator save_node = configuration.SelectSingleNode("save");
			if (save_node == null) throw new ConfigurationErrorsException("When instantiating a save component, you must specify a the target file using the <save> element.");

			string base_value = save_node.GetAttribute("base", String.Empty);
			if (!String.IsNullOrEmpty(base_value)) {
				basePath = Path.GetFullPath(Environment.ExpandEnvironmentVariables(base_value));
			}

			string path_value = save_node.GetAttribute("path", String.Empty);
			if (String.IsNullOrEmpty(path_value)) WriteMessage(MessageLevel.Error, "Each save element must have a path attribute specifying an XPath that evaluates to the location to save the file.");
			path_expression = XPathExpression.Compile(path_value);

            string select_value = save_node.GetAttribute("select", String.Empty);
            if (!String.IsNullOrEmpty(select_value))
                select_expression = XPathExpression.Compile(select_value);

            settings.Encoding = Encoding.UTF8;

			string indent_value = save_node.GetAttribute("indent", String.Empty);
			if (!String.IsNullOrEmpty(indent_value)) settings.Indent = Convert.ToBoolean(indent_value);

			string omit_value = save_node.GetAttribute("omit-xml-declaration", String.Empty);
			if (!String.IsNullOrEmpty(omit_value)) settings.OmitXmlDeclaration = Convert.ToBoolean(omit_value);

            linkPath = save_node.GetAttribute("link", String.Empty);
            if (String.IsNullOrEmpty(linkPath)) linkPath = "../html";

			// encoding

			settings.CloseOutput = true;

		}
Exemple #3
0
        public ReferenceCodeComponent(BuildAssembler assembler,
                                      XPathNavigator configuration) : base(assembler, configuration, false)
        {
            _codeRefStorage = SnippetStorage.Database; //Default to database storage...

            if (this.Mode == CodeHighlightMode.IndirectIris)
            {
                _codeRefSeparator = "\n...\n\n";
            }
            else
            {
                _codeRefSeparator = "\n...\n";
            }

            try
            {
                this.ParseSources(configuration, false);

                _codeRefSelector = XPathExpression.Compile("//codeReference");
                _codeSelector    = XPathExpression.Compile("//code");

                CodeController.Create("reference", this.Mode);
            }
            catch (Exception ex)
            {
                base.WriteMessage(MessageLevel.Error, ex);
            }
        }
Exemple #4
0
        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            // Get the condition
            XPathNavigator conditionElement = configuration.SelectSingleNode("switch");

            if (conditionElement == null)
            {
                throw new ConfigurationErrorsException("You must specify a condition using the <switch> statement with a 'value' attribute.");
            }

            string conditionValue = conditionElement.GetAttribute("value", String.Empty);

            if (String.IsNullOrEmpty(conditionValue))
            {
                throw new ConfigurationErrorsException("The switch statement must have a 'value' attribute, which is an xpath expression.");
            }

            condition = XPathExpression.Compile(conditionValue);

            // Load the component stacks for each case
            XPathNodeIterator caseElements = configuration.Select("case");

            foreach (XPathNavigator caseElement in caseElements)
            {
                string caseValue = caseElement.GetAttribute("value", String.Empty);

                this.WriteMessage(MessageLevel.Info, "Loading components for " + caseValue + " case");

                cases.Add(caseValue, BuildAssembler.LoadComponents(caseElement));
            }

            // Set a default group ID
            this.GroupId = null;
        }
        public ConceptualCodeComponent(BuildAssembler assembler,
                                       XPathNavigator configuration) : base(assembler, configuration, true)
        {
            _codeRefStorage   = SnippetStorage.Database; //Default to database storage...
            _codeRefSeparator = "\n...\n\n";

            try
            {
                this.ParseSources(configuration, true);

                _codeRefContext = new CustomContext();
                _codeRefContext.AddNamespace("ddue",
                                             "http://ddue.schemas.microsoft.com/authoring/2003/5");
                _codeRefSelector = XPathExpression.Compile("//ddue:codeReference");
                _codeRefSelector.SetContext(_codeRefContext);

                _codeContext = new CustomContext();
                _codeContext.AddNamespace("ddue",
                                          "http://ddue.schemas.microsoft.com/authoring/2003/5");
                _codeSelector = XPathExpression.Compile("//ddue:code");
                _codeSelector.SetContext(_codeContext);

                CodeController.Create("conceptual", this.Mode);
            }
            catch (Exception ex)
            {
                base.WriteMessage(MessageLevel.Error, ex);
            }
        }
		public IntellisenseComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			XPathNavigator output_node = configuration.SelectSingleNode("output");
			if (output_node != null) {
                
				string directory_value = output_node.GetAttribute("directory", String.Empty);
				if (!String.IsNullOrEmpty(directory_value)) {
					directory = Environment.ExpandEnvironmentVariables(directory_value);
					if (!Directory.Exists(directory)) WriteMessage(MessageLevel.Error, String.Format("The output directory '{0}' does not exist.", directory));
				}
			}

            // a way to get additional information into the intellisense file
            XPathNodeIterator input_nodes = configuration.Select("input");
            foreach (XPathNavigator input_node in input_nodes) {
                string file_value = input_node.GetAttribute("file", String.Empty);
                if (!String.IsNullOrEmpty(file_value)) {
                    string file = Environment.ExpandEnvironmentVariables(file_value);
                    ReadInputFile(file);
                }
            }

			context.AddNamespace("ddue", "http://ddue.schemas.microsoft.com/authoring/2003/5");

			summaryExpression.SetContext(context);
            memberSummaryExpression.SetContext(context);
			returnsExpression.SetContext(context);
			parametersExpression.SetContext(context);
			parameterNameExpression.SetContext(context);
            templatesExpression.SetContext(context);
            templateNameExpression.SetContext(context);
            exceptionExpression.SetContext(context);
            exceptionCrefExpression.SetContext(context);
        }
Exemple #7
0
        public PauseComponent(BuildAssembler assembler,
                              XPathNavigator configuration)
            : base(assembler, configuration)
        {
            _initDeplay  = _runDelay = _runDelayCount = 0;
            _runDelayMax = 1;

            try
            {
                XPathNavigator itemNode = configuration.SelectSingleNode("initPeriod");
                if (itemNode != null && !String.IsNullOrEmpty(itemNode.Value))
                {
                    _initDeplay = Convert.ToInt32(itemNode.Value);
                }
                itemNode = configuration.SelectSingleNode("runPeriod");
                if (itemNode != null && !String.IsNullOrEmpty(itemNode.Value))
                {
                    _runDelay = Convert.ToInt32(itemNode.Value);
                    string runMax = itemNode.GetAttribute("repeat", String.Empty);
                    if (!String.IsNullOrEmpty(runMax))
                    {
                        _runDelayMax = Convert.ToInt32(runMax);
                    }
                }

                if (_initDeplay > 0)
                {
                    Thread.Sleep(_initDeplay);
                }
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
        public ReferencePostTransComponent(BuildAssembler assembler,
                                           XPathNavigator configuration)
            : base(assembler, configuration)
        {
            try
            {
                _rootId = String.Empty;

                CodeController codeController = CodeController.GetInstance("reference");
                if (codeController != null)
                {
                    _codeApply    = true;
                    _codeSelector = XPathExpression.Compile(
                        "//pre/span[@name='SandAssist' and @class='tgtSentence']");
                    _mathSelector = XPathExpression.Compile(
                        "//img/span[@name='SandMath' and @class='tgtSentence']");
                }

                _mediaSelector = XPathExpression.Compile(
                    "//img/span[@name='SandMedia' and @class='tgtSentence']");

                this.ParseRootNamespace(configuration);
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
Exemple #9
0
 public ConceptualMediaComponent(BuildAssembler assembler,
                                 XPathNavigator configuration)
     : base(assembler, configuration)
 {
     _headSelector      = XPathExpression.Compile("//head");
     _artLinkExpression = XPathExpression.Compile("//artLink");
 }
        protected CopyComponentEx(XPathNavigator configuration, Dictionary <string, object> data)
            : base(configuration, data)
        {
            IndexedDocumentController cached = null;

            foreach (KeyValuePair <string, object> item in data)
            {
                cached = item.Value as IndexedDocumentController;
                if (cached != null)
                {
                    break;
                }
            }

            if (cached != null)
            {
                BuildComponent copyComponent = cached.Component;
                if (copyComponent != null)
                {
                    BuildAssembler assembler = copyComponent.BuildAssembler;

                    if (assembler != null)
                    {
                        _messageWriter = assembler.MessageWriter;
                    }
                }
            }

            _thisType = this.GetType();
        }
Exemple #11
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            // get the condition
            XPathNavigator condition_element = configuration.SelectSingleNode("switch");

            if (condition_element == null)
            {
                throw new ConfigurationErrorsException("You must specify a condition using the <switch> statement with a 'value' attribute.");
            }

            string condition_value = condition_element.GetAttribute("value", String.Empty);

            if (String.IsNullOrEmpty(condition_value))
            {
                throw new ConfigurationErrorsException("The switch statement must have a 'value' attribute, which is an xpath expression.");
            }

            condition = XPathExpression.Compile(condition_value);

            // load the component stacks for each case
            XPathNodeIterator case_elements = configuration.Select("case");

            foreach (XPathNavigator case_element in case_elements)
            {
                string case_value = case_element.GetAttribute("value", String.Empty);

                cases.Add(case_value, BuildAssembler.LoadComponents(case_element));
            }
        }
Exemple #12
0
        protected PreTransComponent(BuildAssembler assembler,
                                    XPathNavigator configuration) : base(assembler, configuration)
        {
            BuildLocalizedContents localizedContents =
                BuildLocalizedContents.Instance;

            if (localizedContents != null && !localizedContents.IsInitialized)
            {
                XPathNavigator navigator = configuration.SelectSingleNode(
                    "BuildLocalizedContents");
                if (navigator != null)
                {
                    string contentFile = navigator.GetAttribute("file",
                                                                String.Empty);
                    if (!String.IsNullOrEmpty(contentFile))
                    {
                        contentFile = Environment.ExpandEnvironmentVariables(contentFile);
                        contentFile = Path.GetFullPath(contentFile);

                        if (File.Exists(contentFile))
                        {
                            localizedContents.Initialize(contentFile, assembler.MessageWriter);
                        }
                    }
                }
            }
        }
Exemple #13
0
        protected IndexedDocumentSource(BuildComponent component)
        {
            BuildComponentExceptions.NotNull(component, "component");

            _component = component;
            _thisType  = this.GetType();
            _assembler = component.BuildAssembler;
        }
        /// <summary>
        /// Creates a new instance of the <see cref="MHSComponent"/> class.
        /// </summary>
        /// <param name="assembler">The active <see cref="BuildAssembler"/>.</param>
        /// <param name="configuration">The current <see cref="XPathNavigator"/> of the configuration.</param>
        public MshcComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            _locale           = String.Empty;
            _selfBranded      = MHSDefault.SelfBranded;
            _topicVersion     = MHSDefault.TopicVersion;
            _tocParent        = MHSDefault.TocParent;
            _tocParentVersion = MHSDefault.TocParentVersion;
            _toc = new Dictionary <string, TocInfo>(
                StringComparer.OrdinalIgnoreCase);

            string tocFile = MHSDefault.TocFile;

            XPathNavigator data = configuration.SelectSingleNode(
                ConfigurationTag.Data);

            if (data != null)
            {
                string value = data.GetAttribute(ConfigurationAttr.Locale, String.Empty);
                if (!String.IsNullOrEmpty(value))
                {
                    _locale = value;
                }

                value = data.GetAttribute(ConfigurationAttr.SelfBranded, String.Empty);
                if (!String.IsNullOrEmpty(value))
                {
                    _selfBranded = bool.Parse(value);
                }

                value = data.GetAttribute(ConfigurationAttr.TopicVersion, String.Empty);
                if (!String.IsNullOrEmpty(value))
                {
                    _topicVersion = value;
                }

                value = data.GetAttribute(ConfigurationAttr.TocParent, String.Empty);
                if (!String.IsNullOrEmpty(value))
                {
                    _tocParent = value;
                }

                value = data.GetAttribute(ConfigurationAttr.TocParentVersion, String.Empty);
                if (!String.IsNullOrEmpty(value))
                {
                    _tocParentVersion = value;
                }

                value = data.GetAttribute(ConfigurationAttr.TocFile, String.Empty);
                if (!String.IsNullOrEmpty(value))
                {
                    tocFile = value;
                }
            }

            LoadToc(Path.GetFullPath(
                        Environment.ExpandEnvironmentVariables(tocFile)));
        }
		public CloneComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {
			
			XPathNodeIterator branch_nodes = configuration.Select("branch");
			foreach (XPathNavigator branch_node in branch_nodes) {
				BuildComponent[] branch = BuildAssembler.LoadComponents(branch_node);
				branches.Add(branch);
			}

		}
		public ValidateComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			XPathNodeIterator schema_nodes = configuration.Select("schema");
			foreach (XPathNavigator schema_node in schema_nodes) {
				string file = schema_node.GetAttribute("file", String.Empty);
				schemas.Add(null, file);
			}
					
		}
        // Instantiation logic

		public ResolveConceptualLinksComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

            string showBrokenLinkTextValue = configuration.GetAttribute("showBrokenLinkText", String.Empty);
            if (!String.IsNullOrEmpty(showBrokenLinkTextValue)) showBrokenLinkText = Convert.ToBoolean(showBrokenLinkTextValue);

			XPathNodeIterator targetsNodes = configuration.Select("targets");
			foreach (XPathNavigator targetsNode in targetsNodes) {

                // the base directory containing target; required
                string baseValue = targetsNode.GetAttribute("base", String.Empty);
                if (String.IsNullOrEmpty(baseValue)) WriteMessage(MessageLevel.Error, "Every targets element must have a base attribute that specifies the path to a directory of target metadata files.");
                baseValue = Environment.ExpandEnvironmentVariables(baseValue);
                if (!Directory.Exists(baseValue)) WriteMessage(MessageLevel.Error, String.Format("The specified target metadata directory '{0}' does not exist.", baseValue));

                // an xpath expression to construct a file name
                // (not currently used; pattern is hard-coded to $target.cmp.xml
                string filesValue = targetsNode.GetAttribute("files", String.Empty);

                // an xpath expression to construct a url
                string urlValue = targetsNode.GetAttribute("url", String.Empty);
                XPathExpression urlExpression;
                if (String.IsNullOrEmpty(urlValue)) {
                    urlExpression = XPathExpression.Compile("concat(/metadata/topic/@id,'.htm')");
                } else {
                    urlExpression = CompileXPathExpression(urlValue);
                }
                
                // an xpath expression to construct link text
                string textValue = targetsNode.GetAttribute("text", String.Empty);
                XPathExpression textExpression;
                if (String.IsNullOrEmpty(textValue)) {
                    textExpression = XPathExpression.Compile("string(/metadata/topic/title)");
                } else {
                    textExpression = CompileXPathExpression(textValue);
                }

                // the type of link to create to targets found in the directory; required
                string typeValue = targetsNode.GetAttribute("type", String.Empty);
                if (String.IsNullOrEmpty(typeValue)) WriteMessage(MessageLevel.Error, "Every targets element must have a type attribute that specifies what kind of link to create to targets found in that directory.");
                
                // convert the link type to an enumeration member
                LinkType type = LinkType.None;
                try {
                    type = (LinkType) Enum.Parse(typeof(LinkType), typeValue, true);
                } catch (ArgumentException) {
                    WriteMessage(MessageLevel.Error, String.Format("'{0}' is not a valid link type.", typeValue));
                }

                // we have all the required information; create a TargetDirectory and add it to our collection
                TargetDirectory targetDirectory = new TargetDirectory(baseValue, urlExpression, textExpression, type);
                targetDirectories.Add(targetDirectory);

            }

            WriteMessage(MessageLevel.Info, String.Format("Collected {0} targets directories.", targetDirectories.Count));	

		}
        public HxfGeneratorComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

            // get configuration data
            inputValue = configuration.GetAttribute("input", String.Empty);
            if (!String.IsNullOrEmpty(inputValue)) inputValue = Environment.ExpandEnvironmentVariables(inputValue);
            outputValue = configuration.GetAttribute("output", String.Empty);
            if (!String.IsNullOrEmpty(outputValue)) outputValue = Environment.ExpandEnvironmentVariables(outputValue);
           
            // subscribe to component events
            assembler.ComponentEvent += new EventHandler(FileCreatedHandler);
        }
		public SyntaxComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			XPathNavigator syntax_node = configuration.SelectSingleNode("syntax");
			string syntax_input_xpath = syntax_node.GetAttribute("input", String.Empty);
			if (String.IsNullOrEmpty(syntax_input_xpath)) throw new ConfigurationErrorsException("You must specify an XPath for input in the syntax element.");
			syntax_input = XPathExpression.Compile(syntax_input_xpath);
			string syntax_output_xpath = syntax_node.GetAttribute("output", String.Empty);
			if (String.IsNullOrEmpty(syntax_output_xpath)) throw new ConfigurationErrorsException("You must specify an XPath for output in the syntax element.");
			syntax_output = XPathExpression.Compile(syntax_output_xpath);

			writerType = typeof(ManagedSyntaxWriter);
			//if (writerType == null) Console.WriteLine("null writer");

			XPathNodeIterator generator_nodes = configuration.Select("generators/generator");
			foreach (XPathNavigator generator_node in generator_nodes) {

                // get the data to load the generator
				string assembly_path = generator_node.GetAttribute("assembly", String.Empty);
                if (String.IsNullOrEmpty(assembly_path)) WriteMessage(MessageLevel.Error, "Each generator element must have an assembly attribute.");
                string type_name = generator_node.GetAttribute("type", String.Empty);
                if (String.IsNullOrEmpty(type_name)) WriteMessage(MessageLevel.Error, "Each generator element must have a type attribute.");

                // expand environment variables in the path
				assembly_path = Environment.ExpandEnvironmentVariables(assembly_path);

				//Console.WriteLine("loading {0} from {1}", type_name, assembly_path);
                try {
                    Assembly assembly = Assembly.LoadFrom(assembly_path);
                    SyntaxGenerator generator = (SyntaxGenerator)assembly.CreateInstance(type_name, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[1] { generator_node.Clone() }, null, null);

                    if (generator == null) {
                        WriteMessage(MessageLevel.Error, String.Format("The type '{0}' does not exist in the assembly '{1}'.", type_name, assembly_path));
                    } else {
                        generators.Add(generator);
                    }

                } catch (IOException e) {
                    WriteMessage(MessageLevel.Error, String.Format("A file access error occured while attempting to load the build component '{0}'. The error message is: {1}", assembly_path, e.Message));
                } catch (BadImageFormatException e) {
                    WriteMessage(MessageLevel.Error, String.Format("A syntax generator assembly '{0}' is invalid. The error message is: {1}.", assembly_path, e.Message));
                } catch (TypeLoadException e) {
                    WriteMessage(MessageLevel.Error, String.Format("The type '{0}' does not exist in the assembly '{1}'. The error message is: {2}", type_name, assembly_path, e.Message));
                } catch (MissingMethodException e) {
                    WriteMessage(MessageLevel.Error, String.Format("The type '{0}' in the assembly '{1}' does not have an appropriate constructor. The error message is: {2}", type_name, assembly_path, e.Message));
                } catch (TargetInvocationException e) {
                    WriteMessage(MessageLevel.Error, String.Format("An error occured while attempting to instantiate the type '{0}' in the assembly '{1}'. The error message is: {2}", type_name, assembly_path, e.InnerException.Message));
                } catch (InvalidCastException) {
                    WriteMessage(MessageLevel.Error, String.Format("The type '{0}' in the assembly '{1}' is not a SyntaxGenerator.", type_name, assembly_path));
                }
			}

			WriteMessage(MessageLevel.Info, String.Format("Loaded {0} syntax generators.", generators.Count));		

		}
Exemple #20
0
        public void Create_JavadocResolver_Test()
        {
            XPathDocument configFile = new XPathDocument("test-config.xml");
            var           navigator  = configFile.CreateNavigator();
            var           rootNode   = navigator.SelectSingleNode("/component");
            var           assembler  = new BuildAssembler();

            var component = new ResolveJavadocLinksComponent(assembler, rootNode);

            Assert.That(component.ExternalResover, Is.TypeOf <JavadocResolver>());
        }
Exemple #21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">This is thrown if an error is detected in the
        /// configuration.</exception>
        public LatexBuildComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            var nav = configuration.SelectSingleNode("fontSize");

            if (nav != null)
            {
                _fontSize = nav.GetAttribute("value", String.Empty);
            }
            _paths = GetWorkingDirectories(configuration);
        }
Exemple #22
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        public MultiFormatOutputComponent(BuildAssembler assembler, XPathNavigator configuration) :
            base(assembler, configuration)
        {
            Assembly          asm          = Assembly.GetExecutingAssembly();
            FileVersionInfo   fvi          = FileVersionInfo.GetVersionInfo(asm.Location);
            List <string>     buildFormats = new List <string>();
            XPathNavigator    nav;
            XPathNodeIterator outputSets;
            string            format;

            base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
                                                               "\r\n    [{0}, version {1}]\r\n    Multi-Format Output Component. {2}\r\n    http://SHFB.CodePlex.com",
                                                               fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));

            formatComponents = new Dictionary <string, IEnumerable <BuildComponent> >();

            // Get the requested formats
            nav    = configuration.SelectSingleNode("build");
            format = nav.GetAttribute("formats", String.Empty);

            if (String.IsNullOrEmpty(format))
            {
                throw new ConfigurationErrorsException("You must specify a string value for the <build> " +
                                                       "'formats' attribute.");
            }

            foreach (string f in format.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                buildFormats.Add(f.Trim());
            }

            // Get the component configurations for each of the requested formats
            outputSets = configuration.Select("helpOutput");

            foreach (XPathNavigator set in outputSets)
            {
                format = set.GetAttribute("format", String.Empty);

                if (String.IsNullOrEmpty(format))
                {
                    throw new ConfigurationErrorsException("You must specify a string value for the <output> " +
                                                           "'format' attribute.");
                }

                // Only include formats that were requested
                if (buildFormats.Contains(format))
                {
                    base.WriteMessage(MessageLevel.Info, "Loading components for " + format + " format");
                    formatComponents.Add(format, base.BuildAssembler.LoadComponents(set));
                }
            }
        }
        public ResolveLinksComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            var fileName = configuration.SelectSingleNode("topicIndex/@location").Value;

            string[] lines = File.ReadAllLines(fileName);
            foreach (var line in lines)
            {
                string[] index = line.Split(',');
                if (topicIndex.ContainsKey(index[0])) throw new Exception("Found more than one Cobol program with PROGRAM-ID " + index[0] + ".");
                topicIndex.Add(index[0], index[1]);
            }
        }
        public ConceptualPostTransComponent(BuildAssembler assembler,
                                            XPathNavigator configuration)
            : base(assembler, configuration)
        {
            try
            {
                MathController mathFormatters = MathController.GetInstance("conceptual");
                if (mathFormatters != null)
                {
                    _mathApply          = true;
                    _mathNumber         = mathFormatters.ShowNumber;
                    _mathNumFormat      = mathFormatters.NumberFormat;
                    _mathNumIncludePage = mathFormatters.NumberIncludesPage;

                    _mathSelector = XPathExpression.Compile(
                        "//artLink[starts-with(@target, 'Equation|')]");

                    if (String.IsNullOrEmpty(_mathNumFormat))
                    {
                        if (_mathNumIncludePage)
                        {
                            _mathNumFormat = "({0}.{1})";
                        }
                        else
                        {
                            _mathNumFormat = "({0})";
                        }
                    }
                }

                CodeController codeController = CodeController.GetInstance("conceptual");
                if (codeController != null)
                {
                    _codeApply = true;

                    // This works for Vs2005...
                    _codeSelector = XPathExpression.Compile(
                        "//pre/span[@name='SandAssist' and @class='tgtSentence']");

                    _spanSelector = XPathExpression.Compile(
                        "span[@name='SandAssist' and @class='tgtSentence']");
                }

                _tokensSelector = XPathExpression.Compile(
                    "//span[@name='SandTokens' and @class='tgtSentence']");
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
		public SharedContentComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			// get context
			context = GetContext(configuration);

			// get the tags to be resolved
			XPathNodeIterator resolve_nodes = configuration.Select("replace");
			foreach (XPathNavigator resolve_node in resolve_nodes) {
				string path = resolve_node.GetAttribute("elements", String.Empty);
				if (String.IsNullOrEmpty(path)) path = "//(include|includeAttribute)";
				// if (String.IsNullOrEmpty(path)) WriteMessage(MessageLevel.Error, "Each resolve element must contain a path attribute specifying an XPath expression for shared content elements.");
				try {
					XPathExpression path_expresion = XPathExpression.Compile(path, context);
				} catch (XPathException) {
					WriteMessage(MessageLevel.Error, String.Format("The elements expression '{0}' is not a valid XPath.", path));
				}

				string item = resolve_node.GetAttribute("item", String.Empty);
				if (String.IsNullOrEmpty(item)) item = "string(@item)";
				try {
					XPathExpression item_expression = XPathExpression.Compile(item, context);
				} catch (XPathException) {
					WriteMessage(MessageLevel.Error, String.Format("The item expression '{0}' is not a valid XPath.", item));
				}

				string parameters = resolve_node.GetAttribute("parameters", String.Empty);
				if (String.IsNullOrEmpty(parameters)) parameters = "parameter";

				string attribute = resolve_node.GetAttribute("attribute", String.Empty);
				if (String.IsNullOrEmpty(attribute)) attribute = "string(@name)";

				elements.Add( new SharedContentElement(path, item, parameters, attribute, context) );
			}

			// Console.WriteLine("{0} elements explicitly defined", elements.Count);

			if (elements.Count == 0) elements.Add( new SharedContentElement(@"//include | //includeAttribute", "string(@item)", "parameter", "string(@name)", context) );

			// get the source and target formats
			XPathNodeIterator content_nodes = configuration.Select("content");
			foreach (XPathNavigator content_node in content_nodes)
            {
                // get the files				
                string sharedContentFiles = content_node.GetAttribute("file", String.Empty);
                if (String.IsNullOrEmpty(sharedContentFiles))
                    WriteMessage(MessageLevel.Error, "The content/@file attribute must specify a path.");
                ParseDocuments(sharedContentFiles);
            }
            WriteMessage(MessageLevel.Info, String.Format("Loaded {0} shared content items.", content.Count));
		}
 public PlatformsComponent(BuildAssembler assembler, XPathNavigator configuration)
     : base(assembler, configuration)
 {
     // get the filter files
     XPathNodeIterator filterNodes = configuration.Select("filter");
     foreach (XPathNavigator filterNode in filterNodes)
     {
         string filterFiles = filterNode.GetAttribute("files", String.Empty);
         if ((filterFiles == null) || (filterFiles.Length == 0))
             throw new ConfigurationErrorsException("The filter/@files attribute must specify a path.");
         ParseDocuments(filterFiles);
     }
     //WriteMessage(MessageLevel.Info, String.Format("Indexed {0} elements.", index.Count));
 }
		public CopyFromFileComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			if (configuration == null) throw new ArgumentNullException("configuration");

			string data_name = null;

			// get information about the data file
			XPathNodeIterator data_nodes = configuration.Select("data");
			foreach (XPathNavigator data_node in data_nodes) {
				string data_file = data_node.GetAttribute("file", String.Empty);
				if (String.IsNullOrEmpty(data_file)) WriteMessage(MessageLevel.Error, "Data elements must have a file attribute specifying a file from which to load data.");
				data_file = Environment.ExpandEnvironmentVariables(data_file);

				data_name = data_node.GetAttribute("name", String.Empty);
				if (String.IsNullOrEmpty(data_name)) data_name = Guid.NewGuid().ToString();

				// load a schema, if one is specified
				string schema_file = data_node.GetAttribute("schema", String.Empty);
				XmlReaderSettings settings = new XmlReaderSettings();
				if (!String.IsNullOrEmpty(schema_file)) {
					settings.Schemas.Add(null, schema_file);
				}

				// load the document
				WriteMessage(MessageLevel.Info, String.Format("Loading data file '{0}'.", data_file) );
				using (XmlReader reader = XmlReader.Create(data_file, settings)) {
					XPathDocument data_document = new XPathDocument(reader);
					Data.Add(data_name, data_document);
				}
			}
			

			// get the source and target expressions for each copy command
			XPathNodeIterator copy_nodes = configuration.Select("copy");
			foreach (XPathNavigator copy_node in copy_nodes) {
				string source_name = copy_node.GetAttribute("name", String.Empty);
				if (String.IsNullOrEmpty(source_name)) source_name = data_name;

				XPathDocument source_document = (XPathDocument) Data[source_name];

				string source_xpath = copy_node.GetAttribute("source", String.Empty);
				if (String.IsNullOrEmpty(source_xpath)) throw new ConfigurationErrorsException("When instantiating a CopyFromFile component, you must specify a source xpath format using the source attribute.");
				string target_xpath = copy_node.GetAttribute("target", String.Empty);
				if (String.IsNullOrEmpty(target_xpath)) throw new ConfigurationErrorsException("When instantiating a CopyFromFile component, you must specify a target xpath format using the target attribute.");
				copy_commands.Add( new CopyFromFileCommand(source_document, source_xpath, target_xpath) );
			}

		}
		public TransformComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			// load the transforms
			XPathNodeIterator transform_nodes = configuration.Select("transform");
			foreach (XPathNavigator transform_node in transform_nodes) {

				// load the transform
				string file = transform_node.GetAttribute("file", String.Empty);
				if (String.IsNullOrEmpty(file)) WriteMessage(MessageLevel.Error, "Each transform element must specify a file attribute.");
				file = Environment.ExpandEnvironmentVariables(file);

				Transform transform = null;
				try {
					transform = new Transform(file);
				} catch (IOException e) {
					WriteMessage(MessageLevel.Error, String.Format("The transform file '{0}' could not be loaded. The error message is: {1}", file, BuildComponentUtilities.GetExceptionMessage(e)));
				} catch (XmlException e) {
					WriteMessage(MessageLevel.Error, String.Format("The transform file '{0}' is not a valid XML file. The error message is: {1}", file, BuildComponentUtilities.GetExceptionMessage(e)));
				} catch (XsltException e) {
					WriteMessage(MessageLevel.Error, String.Format("The XSL transform '{0}' contains an error. The error message is: {1}", file, BuildComponentUtilities.GetExceptionMessage(e))); 
				}


				transforms.Add(transform);


				// load any arguments
				XPathNodeIterator argument_nodes = transform_node.Select("argument");
				foreach (XPathNavigator argument_node in argument_nodes) {
					string key = argument_node.GetAttribute("key", String.Empty);
					if ((key == null) || (key.Length == 0)) WriteMessage(MessageLevel.Error, "When creating a transform argument, you must specify a key using the key attribute");

                    // set "expand-value" attribute to true to expand environment variables embedded in "value".
                    string expand_attr = argument_node.GetAttribute("expand-value", String.Empty);
                    bool expand_value = String.IsNullOrEmpty(expand_attr) ? false : Convert.ToBoolean(expand_attr);

					string value = argument_node.GetAttribute("value", String.Empty);
					if ((value != null) && (value.Length > 0)) {
                        transform.Arguments.AddParam(key, String.Empty, expand_value ? Environment.ExpandEnvironmentVariables(value) : value);
                    }
                    else {
						transform.Arguments.AddParam(key, String.Empty, argument_node.Clone());
					}
				}			

			}

		}
Exemple #29
0
        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            // Get the context namespaces
            XPathNodeIterator contextNodes = configuration.Select("context");

            foreach (XPathNavigator contextNode in contextNodes)
            {
                contextNamespaces[contextNode.GetAttribute("prefix", String.Empty)] =
                    contextNode.GetAttribute("name", String.Empty);
            }

            // Get the condition
            XPathNavigator ifNode = configuration.SelectSingleNode("if");

            if (ifNode == null)
            {
                throw new ConfigurationErrorsException("You must specify a condition using the <if> element.");
            }

            string conditionXPath = ifNode.GetAttribute("condition", String.Empty);

            if (String.IsNullOrEmpty(conditionXPath))
            {
                throw new ConfigurationErrorsException("You must define a condition attribute on the <if> element");
            }

            condition = XPathExpression.Compile(conditionXPath);

            // Construct the true branch
            XPathNavigator thenNode = configuration.SelectSingleNode("then");

            if (thenNode != null)
            {
                trueBranch = BuildAssembler.LoadComponents(thenNode);
            }

            // Construct the false branch
            XPathNavigator elseNode = configuration.SelectSingleNode("else");

            if (elseNode != null)
            {
                falseBranch = BuildAssembler.LoadComponents(elseNode);
            }

            // Set a default group ID
            this.GroupId = null;
        }
Exemple #30
0
        public ReferenceLinkComponent(BuildAssembler assembler,
                                      XPathNavigator configuration)
            : base(assembler, configuration)
        {
            _hasMsdnStorage = false;
            _hasTopicLinks  = false;

            _linkTarget = "_blank";
            _hrefFormat = "{0}.htm";

            _baseLinkType = ConceptualLinkType.Null;

            _buildController = BuildComponentController.Controller;

            this.ParseReferenceConfiguration(configuration);
            this.ParseConceptualConfiguration(configuration);
        }
        //=====================================================================
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        public MultiFormatOutputComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
            List<string> buildFormats = new List<string>();
            XPathNavigator nav;
            XPathNodeIterator outputSets;
            string format;

            base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
                "\r\n    [{0}, version {1}]\r\n    Multi-Format Output Component. {2}\r\n    http://SHFB.CodePlex.com",
                fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));

            formatComponents = new Dictionary<string, IEnumerable<BuildComponent>>();

            // Get the requested formats
            nav = configuration.SelectSingleNode("build");
            format = nav.GetAttribute("formats", String.Empty);

            if(String.IsNullOrEmpty(format))
                throw new ConfigurationErrorsException("You must specify a string value for the <build> " +
                    "'formats' attribute.");

            foreach(string f in format.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                buildFormats.Add(f.Trim());

            // Get the component configurations for each of the requested formats
            outputSets = configuration.Select("helpOutput");

            foreach(XPathNavigator set in outputSets)
            {
                format = set.GetAttribute("format", String.Empty);

                if(String.IsNullOrEmpty(format))
                    throw new ConfigurationErrorsException("You must specify a string value for the <output> " +
                        "'format' attribute.");

                // Only include formats that were requested
                if(buildFormats.Contains(format))
                {
                    base.WriteMessage(MessageLevel.Info, "Loading components for " + format + " format");
                    formatComponents.Add(format, base.BuildAssembler.LoadComponents(set));
                }
            }
        }
Exemple #32
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            // set up the context
            XPathNodeIterator context_nodes = configuration.Select("context");

            foreach (XPathNavigator context_node in context_nodes)
            {
                string prefix = context_node.GetAttribute("prefix", String.Empty);
                string name   = context_node.GetAttribute("name", String.Empty);
                context.AddNamespace(prefix, name);
            }

            // load the expression format
            XPathNavigator variable_node = configuration.SelectSingleNode("variable");

            if (variable_node == null)
            {
                throw new ConfigurationErrorsException("When instantiating a ForEach component, you must " +
                                                       "specify a variable using the <variable> element.");
            }

            string xpath_format = variable_node.GetAttribute("expression", String.Empty);

            if ((xpath_format == null) || (xpath_format.Length == 0))
            {
                throw new ConfigurationErrorsException("When instantiating a ForEach component, you must " +
                                                       "specify a variable expression using the expression attribute");
            }

            xpath = XPathExpression.Compile(xpath_format);

            // load the subcomponents
            WriteMessage(MessageLevel.Info, "Loading subcomponents.");
            XPathNavigator components_node = configuration.SelectSingleNode("components");

            if (components_node == null)
            {
                throw new ConfigurationErrorsException("When instantiating a ForEach component, you must " +
                                                       "specify subcomponents using the <components> element.");
            }

            components = BuildAssembler.LoadComponents(components_node);

            WriteMessage(MessageLevel.Info, "Loaded {0} subcomponents.", components.Count());
        }
Exemple #33
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        /// <remarks>See the <see cref="MSHelpAttrComponent"/> class topic
        /// for an example of the configuration</remarks>
        /// <exception cref="ConfigurationErrorsException">This is thrown if
        /// an error is detected in the configuration.</exception>
        public MSHelpAttrComponent(BuildAssembler assembler,
                                   XPathNavigator configuration) : base(assembler, configuration)
        {
            XPathNodeIterator attrs;
            string            name, value;

            Assembly        asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            attributes = new List <KeyValuePair <string, string> >();

            base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
                                                               "\r\n    [{0}, version {1}]\r\n    MS Help 2 Attribute Component. {2}\r\n    http://SHFB.CodePlex.com",
                                                               fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));

            // At least one attribute element is required to do anything
            attrs = configuration.Select("attributes/attribute");

            if (attrs.Count == 0)
            {
                base.WriteMessage(MessageLevel.Info, "No additional help attributes found, this component " +
                                  "will not do anything.");
            }
            else
            {
                // A name is required.  Value is optional.
                foreach (XPathNavigator nav in attrs)
                {
                    name  = nav.GetAttribute("name", String.Empty);
                    value = nav.GetAttribute("value", String.Empty);

                    if (String.IsNullOrEmpty(name))
                    {
                        throw new ConfigurationErrorsException(
                                  "A 'name' attribute is required on the <attribute> " +
                                  "element");
                    }

                    attributes.Add(new KeyValuePair <string, string>(name, value));
                }

                base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
                                                                   "Loaded {0} attributes", attributes.Count));
            }
        }
Exemple #34
0
        public ReferenceMediaComponent(BuildAssembler assembler,
                                       XPathNavigator configuration)
            : base(assembler, configuration)
        {
            _artLinkExpression = XPathExpression.Compile("//mediaLink | //mediaLinkInline");

            XPathNavigator optionsNode = configuration.SelectSingleNode("options");

            if (optionsNode != null)
            {
                string tempText = optionsNode.GetAttribute("useInclude", String.Empty);
                if (!String.IsNullOrEmpty(tempText))
                {
                    _useInclude = tempText.Equals("true",
                                                  StringComparison.OrdinalIgnoreCase);
                }
            }
        }
Exemple #35
0
        public ReferenceMathComponent(BuildAssembler assembler,
                                      XPathNavigator configuration) : base(assembler, configuration, false)
        {
            try
            {
                if (_latexFormatter != null)
                {
                    _xpathSelector = XPathExpression.Compile(
                        "//math[starts-with(@address, 'Math')]");

                    MathController.Create("reference", _numberShow,
                                          _numberIncludesPage, _numberByPage, _numberFormat);
                }
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
Exemple #36
0
        public IndexedDocumentController(CopyFromIndexComponent component,
                                         XPathNavigator configuration, CustomContext context,
                                         IDictionary <string, object> globalData)
        {
            BuildComponentExceptions.NotNull(component, "component");

            _component = component;
            _thisType  = this.GetType();
            _assembler = component.BuildAssembler;

            _documentSources = new Dictionary <string, IndexedDocumentSources>(
                StringComparer.OrdinalIgnoreCase);

            // set up the indices
            XPathNodeIterator indexNodes = configuration.Select("index");

            foreach (XPathNavigator indexNode in indexNodes)
            {
                // get the name of the index
                string name = indexNode.GetAttribute("name", String.Empty);
                if (String.IsNullOrEmpty(name))
                {
                    throw new BuildComponentException("Each index must have a unique name.");
                }

                if (String.Equals(name, "reflection",
                                  StringComparison.OrdinalIgnoreCase))
                {
                    this.ProcessReflectionIndex(indexNode, context, globalData);
                }
                else if (String.Equals(name, "comments",
                                       StringComparison.OrdinalIgnoreCase))
                {
                    this.ProcessCommentsIndex(indexNode, context, globalData);
                }
                else
                {
                    this.ProcessIndex(indexNode, context, globalData);
                }
            }
        }
        /// <summary>
        /// Initializes new instance of the <see cref="CloneComponent"/> class with
        /// the specified parameters.
        /// </summary>
        /// <param name="assembler"></param>
        /// <param name="configuration"></param>
        public CloneComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            try
            {
                _listBranches = new List <IList <BuildComponent> >();

                // Select and process all the branches...
                XPathNodeIterator branchNodes = configuration.Select("branch");
                if (branchNodes != null && branchNodes.Count != 0)
                {
                    foreach (XPathNavigator branchNode in branchNodes)
                    {
                        IList <BuildComponent> components = assembler.LoadComponents(branchNode);
                        if (components != null && components.Count != 0)
                        {
                            _listBranches.Add(components);
                        }
                    }
                }

                // Select and process the "default" node, only one is expected...
                XPathNavigator defaultNode = configuration.SelectSingleNode("default");
                if (defaultNode != null)
                {
                    _defaultBranch = assembler.LoadComponents(defaultNode);
                }

                // For the special case where neither "branch" nor "default" is
                // specified, we treat anything there as default...
                if ((branchNodes == null || branchNodes.Count == 0) &&
                    defaultNode == null)
                {
                    _defaultBranch = assembler.LoadComponents(configuration);
                }
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
		public ResolveArtLinksComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			XPathNodeIterator targets_nodes = configuration.Select("targets");
			foreach (XPathNavigator targets_node in targets_nodes) {

				string input = targets_node.GetAttribute("input", String.Empty);
				if (String.IsNullOrEmpty(input)) WriteMessage(MessageLevel.Error, "Each targets element must have an input attribute specifying a directory containing art files.");
				input = Environment.ExpandEnvironmentVariables(input);
				if (!Directory.Exists(input)) WriteMessage(MessageLevel.Error, String.Format("The art input directory '{0}' does not exist.", input));

                string baseOutputPath = targets_node.GetAttribute("baseOutput", String.Empty);
                if (!String.IsNullOrEmpty(baseOutputPath)) {
                    baseOutputPath = Path.GetFullPath(Environment.ExpandEnvironmentVariables(baseOutputPath));
                }

                string outputPath_value = targets_node.GetAttribute("outputPath", string.Empty);
                if (string.IsNullOrEmpty(outputPath_value)) WriteMessage(MessageLevel.Error, "Each targets element must have an output attribute specifying a directory in which to place referenced art files.");
                XPathExpression output_XPath = XPathExpression.Compile(outputPath_value);
                                                
                string linkValue = targets_node.GetAttribute("link", String.Empty);
                if (String.IsNullOrEmpty(linkValue)) linkValue = "../art";
                //linkValue = Environment.ExpandEnvironmentVariables(linkValue);

				string map = targets_node.GetAttribute("map", String.Empty);
				if (String.IsNullOrEmpty(map)) WriteMessage(MessageLevel.Error, "Each targets element must have a map attribute specifying a file that maps art ids to files in the input directory.");
				map = Environment.ExpandEnvironmentVariables(map);
				if (!File.Exists(map)) WriteMessage(MessageLevel.Error, String.Format("The art map file '{0}' does not exist.", map));

                string format = targets_node.GetAttribute("format", String.Empty);
                XPathExpression format_xpath = String.IsNullOrEmpty(format) ? null : XPathExpression.Compile(format);

                string relative_to = targets_node.GetAttribute("relative-to", String.Empty);
                XPathExpression relative_to_xpath = String.IsNullOrEmpty(relative_to) ? null : XPathExpression.Compile(relative_to);

				AddTargets(map, input, baseOutputPath, output_XPath, linkValue, format_xpath, relative_to_xpath);

			}

			WriteMessage(MessageLevel.Info, String.Format("Indexed {0} art targets.", targets.Count));

		}
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        /// <remarks>See the <see cref="MSHelpAttrComponent"/> class topic
        /// for an example of the configuration</remarks>
        /// <exception cref="ConfigurationErrorsException">This is thrown if
        /// an error is detected in the configuration.</exception>
        public MSHelpAttrComponent(BuildAssembler assembler,
          XPathNavigator configuration)
            : base(assembler, configuration)
        {
            XPathNodeIterator attrs;
            string name, value;

            Assembly asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
            attributes = new List<KeyValuePair<string, string>>();

            base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
                "\r\n    [{0}, version {1}]\r\n    MS Help 2 Attribute Component. {2}\r\n    http://SHFB.CodePlex.com",
                fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));

            // At least one attribute element is required to do anything
            attrs = configuration.Select("attributes/attribute");

            if(attrs.Count == 0)
                base.WriteMessage(MessageLevel.Info, "No additional help attributes found, this component " +
                    "will not do anything.");
            else
            {
                // A name is required.  Value is optional.
                foreach(XPathNavigator nav in attrs)
                {
                    name = nav.GetAttribute("name", String.Empty);
                    value = nav.GetAttribute("value", String.Empty);

                    if(String.IsNullOrEmpty(name))
                        throw new ConfigurationErrorsException(
                            "A 'name' attribute is required on the <attribute> " +
                            "element");

                    attributes.Add(new KeyValuePair<string, string>(name, value));
                }

                base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
                    "Loaded {0} attributes", attributes.Count));
            }
        }
		public SwitchComponent(BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			// get the condition
			XPathNavigator condition_element = configuration.SelectSingleNode("switch");
			if (condition_element == null) {
				throw new ConfigurationErrorsException("You must specifiy a condition using the <switch> statement with a 'value' attribute.");
			}
			string condition_value = condition_element.GetAttribute("value", String.Empty);
			if (String.IsNullOrEmpty(condition_value)) {
				throw new ConfigurationErrorsException("The switch statement must have a 'value' attribute, which is an xpath expression.");
			}
			condition = XPathExpression.Compile(condition_value);

			// load the component stacks for each case
			XPathNodeIterator case_elements = configuration.Select("case");
			foreach (XPathNavigator case_element in case_elements) {
				string case_value = case_element.GetAttribute("value", String.Empty);
				BuildComponent[] components = BuildAssembler.LoadComponents(case_element);
				cases.Add(case_value, components);
			}
		}
        public void Initialize(BuildComponent component)
        {
            if (_isInitialized)
            {
                return;
            }
            if (component == null)
            {
                throw new ArgumentNullException();
            }

            BuildAssembler assembler = component.BuildAssembler;

            if (assembler == null)
            {
                throw new ArgumentException();
            }

            _messageWriter = assembler.MessageWriter;
            _isInitialized = (_messageWriter != null);
        }
        public CopyFromFilesComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {
            XPathNodeIterator copy_nodes = configuration.Select("copy");
            foreach (XPathNavigator copy_node in copy_nodes) {

                string root_value = copy_node.GetAttribute("base", String.Empty);
                if (String.IsNullOrEmpty(root_value)) root_value = Environment.CurrentDirectory;
                root_value = Environment.ExpandEnvironmentVariables(root_value);
                if (!Directory.Exists(root_value)) WriteMessage(MessageLevel.Error, String.Format("The base directory '{0}' does not exist.", root_value));

                string file_value = copy_node.GetAttribute("file", String.Empty);
                if (String.IsNullOrEmpty(file_value)) WriteMessage(MessageLevel.Error, "Each copy element must have a file attribute specifying the file to copy from.");

                string source_value = copy_node.GetAttribute("source", String.Empty);
                string target_value = copy_node.GetAttribute("target", String.Empty);

                CopyFromFilesCommand copy_command = new CopyFromFilesCommand(root_value, file_value, source_value, target_value);
                copy_commands.Add(copy_command);
            }

            WriteMessage(MessageLevel.Info, String.Format("Loaded {0} copy commands.", copy_commands.Count));
        }
		public IfThenComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {
			
			// get the condition
			XPathNavigator if_node = configuration.SelectSingleNode("if");
			if (if_node == null) throw new ConfigurationErrorsException("You must specify a condition using the <if> element.");
			string condition_xpath = if_node.GetAttribute("condition", String.Empty);
			if (String.IsNullOrEmpty(condition_xpath)) throw new ConfigurationErrorsException();
			condition = XPathExpression.Compile(condition_xpath);

			// construct the true branch
			XPathNavigator then_node = configuration.SelectSingleNode("then");
			if (then_node != null) true_branch = BuildAssembler.LoadComponents(then_node);

			// construct the false branch
			XPathNavigator else_node = configuration.SelectSingleNode("else");
			if (else_node != null) false_branch = BuildAssembler.LoadComponents(else_node);

            // keep a pointer to the context for future use
            context = assembler.Context;

		}
		// instantiation logic

		public ExampleComponent(BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

            XPathNodeIterator contentNodes = configuration.Select("examples");
			foreach (XPathNavigator contentNode in contentNodes) {
				string file = contentNode.GetAttribute("file", String.Empty);
                file = Environment.ExpandEnvironmentVariables(file);
                if (String.IsNullOrEmpty(file)) WriteMessage(MessageLevel.Error, String.Format("Each examples element must contain a file attribute."));
				LoadContent(file);
			}

			WriteMessage(MessageLevel.Info, String.Format("Loaded {0} code snippets", snippets.Count));

			XPathNodeIterator colorsNodes = configuration.Select("colors");
			foreach (XPathNavigator colorsNode in colorsNodes) {
				string language = colorsNode.GetAttribute("language", String.Empty);
				List<ColorizationRule> rules = new List<ColorizationRule>();

				XPathNodeIterator colorNodes = colorsNode.Select("color");
				foreach (XPathNavigator colorNode in colorNodes) {
					string pattern = colorNode.GetAttribute("pattern", String.Empty);
					string region = colorNode.GetAttribute("region", String.Empty);
					string name = colorNode.GetAttribute("class", String.Empty);
					if (String.IsNullOrEmpty(region)) {
						rules.Add( new ColorizationRule(pattern, name) );						
					} else {
						rules.Add( new ColorizationRule(pattern, region, name) );
					}
				}

				colorization[language] = rules;
				WriteMessage(MessageLevel.Info, String.Format("Loaded {0} colorization rules for the language '{1}'.", rules.Count, language));
			}

			context.AddNamespace("ddue", "http://ddue.schemas.microsoft.com/authoring/2003/5");

			selector = XPathExpression.Compile("//ddue:codeReference");
			selector.SetContext(context);
		}
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            // Get the condition
            XPathNavigator if_node = configuration.SelectSingleNode("if");

            if (if_node == null)
            {
                throw new ConfigurationErrorsException("You must specify a condition using the <if> element.");
            }

            string condition_xpath = if_node.GetAttribute("condition", String.Empty);

            if (String.IsNullOrEmpty(condition_xpath))
            {
                throw new ConfigurationErrorsException("You must define a condition attribute on the <if> element");
            }

            condition = XPathExpression.Compile(condition_xpath);

            // Construct the true branch
            XPathNavigator then_node = configuration.SelectSingleNode("then");

            if (then_node != null)
            {
                true_branch = BuildAssembler.LoadComponents(then_node);
            }

            // Construct the false branch
            XPathNavigator else_node = configuration.SelectSingleNode("else");

            if (else_node != null)
            {
                false_branch = BuildAssembler.LoadComponents(else_node);
            }

            // Keep a pointer to the context for future use
            context = this.BuildAssembler.Context;
        }
Exemple #46
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        /// <exception cref="ConfigurationErrorsException">This is thrown if
        /// an error is detected in the configuration.</exception>
        public CachedCopyFromIndexComponent(BuildAssembler assembler,
                                            XPathNavigator configuration) : base(assembler, configuration)
        {
            Assembly        asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            base.WriteMessage(MessageLevel.Info, String.Format(
                                  CultureInfo.InvariantCulture,
                                  "\r\n    [{0}, version {1}]\r\n    Cached Copy From Index " +
                                  " Component.  {2}\r\n    http://SHFB.CodePlex.com",
                                  fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));

            // For each index, search for cached entries to load
            foreach (XPathNavigator index in configuration.Select("index"))
            {
                cacheId = index.GetAttribute("name", String.Empty);

                foreach (XPathNavigator cache in index.Select("cache"))
                {
                    this.LoadCache(index, cacheId, cache);
                }
            }
        }
        public ConceptualMathComponent(BuildAssembler assembler,
                                       XPathNavigator configuration) : base(assembler, configuration, true)
        {
            try
            {
                if (_latexFormatter != null)
                {
                    _xsltContext = new CustomContext();
                    _xsltContext.AddNamespace("ddue",
                                              "http://ddue.schemas.microsoft.com/authoring/2003/5");

                    _xpathSelector = XPathExpression.Compile(
                        "//ddue:math[starts-with(@address, 'Math')]");
                    _xpathSelector.SetContext(_xsltContext);

                    MathController.Create("conceptual", _numberShow,
                                          _numberIncludesPage, _numberByPage, _numberFormat);
                }
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
		public WdxResolveConceptualLinksComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {
            //System.Diagnostics.Debugger.Break();

            string av; // temporary attribute values

            // base-url is an xpath expression that is used to lookup the url that relative links need to be
            // relative to. The lookup is done against the current document. This attribute is needed only if 
            // one of the targets uses relative links that are not in the current directory. If not specified,
            // the target uses the url from the meta data unchanged.
            av = configuration.GetAttribute("base-url", String.Empty);
            if (!String.IsNullOrEmpty(av))
                baseUrl = CompileXPathExpression(av);

            // invalid-link-format specifies a string format to be used for invalid (target is not a valid GUID)
            // links. The string formatter is called with parameter {0} set to the target attribute of the link,
            // and parameter {1} set to the tag content from the source document. A reasonable default is used
            // if the value is not specified.
            av = configuration.GetAttribute("invalid-link-format", String.Empty);
            if (!String.IsNullOrEmpty(av))
                invalidLinkFormat = av;

            // broken-link-format specifies a string format to be used for broken links (target GUID lookup
            // failed in all targets). The string formatter is called with parameter {0} set to the target attribute
            // of the link, and parameter {1} set to the tag content from the source document. A reasonable
            // default is used if the value is not specified.
            av = configuration.GetAttribute("broken-link-format", String.Empty);
            if (!String.IsNullOrEmpty(av))
                brokenLinkFormat = av;

            // <targets> specifies a lookup solution for each possible set of link targets. Each target must
            // specify either a lookup file or error condition (invalid-link, broken-link).
            XPathNodeIterator targetsNodes = configuration.Select("targets");
			foreach (XPathNavigator targetsNode in targetsNodes) {

                // lookup-file specifies the meta data file used for looking up URLs and titles. The value will
                // go through environment variable expansion during setup and then through string formatting after
                // computing the url, with parameter {0} set to the link target GUID. This attribute is required.
                string lookupFile = targetsNode.GetAttribute("lookup-file", String.Empty);
                if (string.IsNullOrEmpty(lookupFile))
                    WriteMessage(MessageLevel.Error, "Each target must have a lookup-file attribute.");
                else
                    lookupFile = Environment.ExpandEnvironmentVariables(lookupFile);
                
                // check-file-exists if specified ensures that the link target file exists; if it doesn't exist we
                // take the broken link action.
                string checkFileExists = targetsNode.GetAttribute("check-file-exists", String.Empty);
                if (!String.IsNullOrEmpty(checkFileExists))
                    checkFileExists = Environment.ExpandEnvironmentVariables(checkFileExists);

                // url is an xpath expression that is used to lookup the link url in the meta data file. The default
                // value can be used to lookup the url in .cmp.xml files.
                av = targetsNode.GetAttribute("url", String.Empty);
                XPathExpression url = String.IsNullOrEmpty(av) ? 
                    XPathExpression.Compile("concat(/metadata/topic/@id,'.htm')") :
                    XPathExpression.Compile(av);

                // text is an xpath expression that is used to lookup the link text in the meta data file. The default
                // value can be used to lookup the link text in .cmp.xml files.
                av = targetsNode.GetAttribute("text", string.Empty);
                XPathExpression text = String.IsNullOrEmpty(av) ?
                    XPathExpression.Compile("string(/metadata/topic/title)") :
                    XPathExpression.Compile(av);

                // relative-url determines whether the links from this target set are relative to the current page
                // and need to be adjusted to the base directory.
                av = targetsNode.GetAttribute("relative-url", String.Empty);
                bool relativeUrl = String.IsNullOrEmpty(av) ? false : Convert.ToBoolean(av);;

                // format is a format string that is used to generate the link. Parameter {0} is the url;
                // parameter {1} is the text. The default creates a standard HTML link.
                string format = targetsNode.GetAttribute("format", String.Empty);
                if (String.IsNullOrEmpty(format))
                    format = defaultFormat;
                
                // target looks OK
                targetSets.Add(new TargetSet(lookupFile, checkFileExists, url, text, relativeUrl, format));
            }

            WriteMessage(MessageLevel.Info, String.Format("Collected {0} targets directories.", targetSets.Count));	
		}
        /// <summary>
        /// Creates a new instance of the <see cref="MHSComponent"/> class.
        /// </summary>
        /// <param name="assembler">The active <see cref="BuildAssembler"/>.</param>
        /// <param name="configuration">The current <see cref="XPathNavigator"/> of the configuration.</param>
        public MSHCComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            string tocFile = MHSDefault.TocFile;
            XPathNavigator data = configuration.SelectSingleNode(ConfigurationTag.Data);
            if (data != null)
            {
                string value = data.GetAttribute(ConfigurationAttr.Locale, string.Empty);
                if (!string.IsNullOrEmpty(value))
                    _locale = value;

                value = data.GetAttribute(ConfigurationAttr.SelfBranded, string.Empty);
                if (!string.IsNullOrEmpty(value))
                    _selfBranded = bool.Parse(value);

                value = data.GetAttribute(ConfigurationAttr.TopicVersion, string.Empty);
                if (!string.IsNullOrEmpty(value))
                    _topicVersion = value;

                value = data.GetAttribute(ConfigurationAttr.TocParent, string.Empty);
                if (!string.IsNullOrEmpty(value))
                    _tocParent = value;

                value = data.GetAttribute(ConfigurationAttr.TocParentVersion, string.Empty);
                if (!string.IsNullOrEmpty(value))
                    _tocParentVersion = value;

                value = data.GetAttribute(ConfigurationAttr.TocFile, string.Empty);
                if (!string.IsNullOrEmpty(value))
                    tocFile = value;
            }
            LoadToc(Path.GetFullPath(Environment.ExpandEnvironmentVariables(tocFile)));
        }
        //=====================================================================
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        /// <remarks>See the <see cref="ShowMissingComponent"/> class topic
        /// for an example of the configuration</remarks>
        /// <exception cref="ConfigurationErrorsException">This is thrown if
        /// an error is detected in the configuration.</exception>
        public ShowMissingComponent(BuildAssembler assembler,
          XPathNavigator configuration)
            : base(assembler, configuration)
        {
            XPathDocument content;
            XPathNavigator nav, contentNav;
            string value = null;

            Assembly asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            base.WriteMessage(MessageLevel.Info, String.Format(
                CultureInfo.InvariantCulture,
                "\r\n    [{0}, version {1}]\r\n    Show Missing " +
                "Documentation Component. {2}\r\n    http://SHFB.CodePlex.com",
                fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));

            // All elements are optional.  If omitted, all properties are
            // true except for showMissingRemarks and showMissingValues;
            autoDocConstructors = autoDocDispose = showMissingParams =
                showMissingTypeParams = showMissingReturns = showMissingSummaries =
                showMissingNamespaces = true;

            nav = configuration.SelectSingleNode("AutoDocumentConstructors");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out autoDocConstructors))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <AutoDocumentConstructors> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("AutoDocumentDisposeMethods");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out autoDocDispose))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <AutoDocumentDisposeMethods> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingParams");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingParams))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingParams> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingTypeParams");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingTypeParams))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingTypeParams> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingRemarks");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingRemarks))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingRemarks> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingReturns");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingReturns))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingReturns> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingSummaries");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingSummaries))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingSummaries> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingValues");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingValues))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingValues> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingNamespaces");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingNamespaces))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingNamespaces> " +
                        "'value' attribute.");
            }

            nav = configuration.SelectSingleNode("ShowMissingIncludeTargets");
            if(nav != null)
            {
                value = nav.GetAttribute("value", String.Empty);

                if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
                  out showMissingIncludeTargets))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a Boolean value for the <ShowMissingIncludeTargets> " +
                        "'value' attribute.");
            }

            autoDocCtorMsg = "Initializes a new instance of the <see " +
                "cref=\"T:{0}\"/> class";
            autoDocStaticCtorMsg = "Initializes the static fields of the " +
                "<see cref=\"T:{0}\"/> class";

            autoDocDisposeMsg = "Releases all resources used by the <see " +
                "cref=\"T:{0}\"/>";
            autoDocDisposeBoolMsg = "Releases the unmanaged resources used by " +
                "the <see cref=\"T:{0}\"/> and optionally releases the " +
                "managed resources";
            autoDocDisposeParamMsg = "True to release both managed and " +
                "unmanaged resources; false to release only unmanaged resources";

            missingTagMsg = "<p style=\"color: #dc143c; font-size: 8.5pt; " +
                        "font-weight: bold;\">[Missing &lt;{0}&gt; " +
                        "documentation for {1}]</p>";
            missingParamTagMsg = "<p style=\"color: #dc143c; font-size: 8.5pt; " +
                    "font-weight: bold;\">[Missing &lt;{0} name=\"{1}\"/&gt; " +
                    "documentation for \"{2}\"]</p>";
            missingIncludeTargetMsg = "<p style=\"color: #dc143c; font-size: 8.5pt; " +
                    "font-weight: bold;\">[Missing &lt;include&gt; target " +
                    "documentation in '{0}'.  File: '{1}' Path: '{2}']</p>";

            nav = configuration.SelectSingleNode("contentFile");
            if(nav != null)
            {
                value = nav.GetAttribute("filename", String.Empty);

                if(String.IsNullOrEmpty(value) || !File.Exists(value))
                    throw new ConfigurationErrorsException("You must specify " +
                        "a filename value for the <contentFile> 'filename' " +
                        "attribute and it must exist.");

                content = new XPathDocument(value);
                contentNav = content.CreateNavigator();

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbAutoDocConstructor']");
                if(nav != null)
                    autoDocCtorMsg = nav.Value;

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbAutoDocStaticConstructor']");
                if(nav != null)
                    autoDocStaticCtorMsg = nav.Value;

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbAutoDocDispose']");
                if(nav != null)
                    autoDocDisposeMsg = nav.Value;

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbAutoDocDisposeBool']");
                if(nav != null)
                    autoDocDisposeBoolMsg = nav.Value;

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbAutoDocDisposeParam']");
                if(nav != null)
                    autoDocDisposeParamMsg = nav.Value;

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbMissingTag']");
                if(nav != null)
                    missingTagMsg = nav.Value;

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbMissingParamTag']");
                if(nav != null)
                    missingParamTagMsg = nav.Value;

                nav = contentNav.SelectSingleNode(
                    "content/item[@id='shfbMissingIncludeTarget']");
                if(nav != null)
                    missingIncludeTargetMsg = nav.Value;
            }

            isEnabled = (autoDocConstructors || autoDocDispose ||
                showMissingParams || showMissingTypeParams ||
                showMissingRemarks || showMissingReturns ||
                showMissingSummaries || showMissingValues ||
                showMissingNamespaces || showMissingIncludeTargets);

            if(!isEnabled)
                base.WriteMessage(MessageLevel.Info, "  All Show Missing " +
                    "options are disabled.  The component will do nothing.");
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        /// <remarks>See the <see cref="VersionInfoComponent"/> class topic
        /// for an example of the configuration</remarks>
        /// <exception cref="ConfigurationErrorsException">This is thrown if
        /// an error is detected in the configuration.</exception>
        public VersionInfoComponent(BuildAssembler assembler,
          XPathNavigator configuration)
            : base(assembler, configuration)
        {
            XPathDocument assemblies;
            XPathNavigator nav, fileVersion;

            string reflectionFilename, line, asmVersion;
            StringBuilder sb = new StringBuilder(1024);

            Assembly asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            base.WriteMessage(MessageLevel.Info, String.Format(
                CultureInfo.InvariantCulture,
                "\r\n    [{0}, version {1}]\r\n    Version Information " +
                "Component. {2}\r\n    http://SHFB.CodePlex.com",
                fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));

            // The reflectionFile element is required.  The file must exist if
            // specified.  This is a hack to get version information into
            // each topic.  Note that it requires a modification to the
            // reference_content.xml file for each style.
            nav = configuration.SelectSingleNode("reflectionFile");
            if(nav == null)
                throw new ConfigurationErrorsException(
                    "The <reflectionFile> element is required for the " +
                    "VersionInfoComponent");

            reflectionFilename = nav.GetAttribute("filename", String.Empty);

            if(String.IsNullOrEmpty(reflectionFilename))
                throw new ConfigurationErrorsException("A filename is " +
                    "required in the <reflectionFile> element");

            if(!File.Exists(reflectionFilename))
                throw new ConfigurationErrorsException(
                    "The reflection file '" + reflectionFilename +
                    "' must exist");

            assemblyVersions = new Dictionary<string, string>();

            // Load the part of the reflection info file that contains the
            // assembly definitions.  The file itself can be huge so we
            // will use a stream reader to extract the assembly info and
            // load that into the XPath document.
            using(StreamReader sr = new StreamReader(reflectionFilename))
            {
                do
                {
                    line = sr.ReadLine();
                    sb.Append(line);

                } while(!line.Contains("/assemblies") &&
                  !line.Contains("<apis>"));
            }

            // Some projects like those for AjaxDoc don't have assemblies
            if(line.Contains("<apis>"))
                sb.Append("</apis>");

            sb.Append("</reflection>");

            using(StringReader sr = new StringReader(sb.ToString()))
            {
                assemblies = new XPathDocument(sr);
                nav = assemblies.CreateNavigator();

                foreach(XPathNavigator asmNode in nav.Select(
                  "reflection/assemblies/assembly"))
                {
                    asmVersion = asmNode.SelectSingleNode(
                        "assemblydata/@version").Value;

                    // If the file version attribute is present, show it too
                    fileVersion = asmNode.SelectSingleNode(
                        "attributes/attribute[type/@api='T:System.Reflection." +
                        "AssemblyFileVersionAttribute']/argument/value");

                    if(fileVersion != null)
                        asmVersion = String.Format(CultureInfo.InvariantCulture,
                            "{0} ({1})", asmVersion, fileVersion.InnerXml);

                    assemblyVersions.Add(asmNode.GetAttribute("name",
                        String.Empty), asmVersion);
                }
            }
        }
		public IntellisenseComponent2 (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {

			XPathNavigator output_node = configuration.SelectSingleNode("output");
			if (output_node != null) {
                
				string directory_value = output_node.GetAttribute("directory", String.Empty);
				if (!String.IsNullOrEmpty(directory_value)) {
					directory = Environment.ExpandEnvironmentVariables(directory_value);
					if (!Directory.Exists(directory)) WriteMessage(MessageLevel.Error, String.Format("The output directory '{0}' does not exist.", directory));
				}
			}

            XPathNavigator expression_node = configuration.SelectSingleNode("expressions");
            if (expression_node != null) {

                string root = expression_node.GetAttribute("root", string.Empty);
                try {
                    rootExpression = XPathExpression.Compile(root);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", root));
                }

                string assembly = expression_node.GetAttribute("assembly", string.Empty);
                try {
                    assemblyExpression = XPathExpression.Compile(assembly);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", assembly));
                }

                string summary = expression_node.GetAttribute("summary", string.Empty);
                try {
                    summaryExpression = XPathExpression.Compile(summary);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", summary));
                }

                string parameters = expression_node.GetAttribute("parameters", string.Empty);
                try {
                    parametersExpression = XPathExpression.Compile(parameters);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", parameters));
                }

                string parameterContent = expression_node.GetAttribute("parameterContent", string.Empty);
                try {
                    parameterContentExpression = XPathExpression.Compile(parameterContent);
                } catch (XPathException ) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", parameterContent));
                }

                string templates = expression_node.GetAttribute("templates", string.Empty);
                try {
                    templatesExpression = XPathExpression.Compile(templates);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", templates));
                }

                string templateContent = expression_node.GetAttribute("templateContent", string.Empty);
                try {
                    templateContentExpression = XPathExpression.Compile(templateContent);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", templateContent));
                }

                string returns = expression_node.GetAttribute("returns", string.Empty);
                try {
                    returnsExpression = XPathExpression.Compile(returns);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", returns));
                }

                string exception = expression_node.GetAttribute("exception", string.Empty);
                try {
                    exceptionExpression = XPathExpression.Compile(exception);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", exception));
                }

                string exceptionCref = expression_node.GetAttribute("exceptionCref", string.Empty);
                try {
                    exceptionCrefExpression = XPathExpression.Compile(exceptionCref);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", exceptionCref));
                }

                string enumeration = expression_node.GetAttribute("enumeration", string.Empty);
                try {
                    enumerationExpression = XPathExpression.Compile(enumeration);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", enumeration));
                }

                string enumerationApi = expression_node.GetAttribute("enumerationApi", string.Empty);
                try {
                    enumerationApiExpression = XPathExpression.Compile(enumerationApi);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", enumerationApi));
                }

                string memberSummary = expression_node.GetAttribute("memberSummary", string.Empty);
                try {
                    memberSummaryExpression = XPathExpression.Compile(memberSummary);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", memberSummary));
                }

            }

            // a way to get additional information into the intellisense file
            XPathNodeIterator input_nodes = configuration.Select("input");
            foreach (XPathNavigator input_node in input_nodes) {
                string file_value = input_node.GetAttribute("file", String.Empty);
                if (!String.IsNullOrEmpty(file_value)) {
                    string file = Environment.ExpandEnvironmentVariables(file_value);
                    ReadInputFile(file);
                }
            }
        }
		public DisplayComponent (BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) {
			XPathNavigator xpath_format_node = configuration.SelectSingleNode("xpath");
			if (xpath_format_node != null) xpath_format = xpath_format_node.Value;
		}
        public CopyFromIndexComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration) {

            // set up the context
            XPathNodeIterator context_nodes = configuration.Select("context");
            foreach (XPathNavigator context_node in context_nodes) {
                string prefix = context_node.GetAttribute("prefix", String.Empty);
                string name = context_node.GetAttribute("name", String.Empty);
                context.AddNamespace(prefix, name);
            }

            // set up the indices
            XPathNodeIterator index_nodes = configuration.Select("index");
            foreach (XPathNavigator index_node in index_nodes) {

                // get the name of the index
                string name = index_node.GetAttribute("name", String.Empty);
                if (String.IsNullOrEmpty(name)) throw new ConfigurationErrorsException("Each index must have a unique name.");

                // get the xpath for value nodes
                string value_xpath = index_node.GetAttribute("value", String.Empty);
                if (String.IsNullOrEmpty(value_xpath)) WriteMessage(MessageLevel.Error, "Each index element must have a value attribute containing an XPath that describes index entries.");

                // get the xpath for keys (relative to value nodes)
                string key_xpath = index_node.GetAttribute("key", String.Empty);
                if (String.IsNullOrEmpty(key_xpath)) WriteMessage(MessageLevel.Error, "Each index element must have a key attribute containing an XPath (relative to the value XPath) that evaluates to the entry key.");

                // get the cache size
                int cache = 10;
                string cache_value = index_node.GetAttribute("cache", String.Empty);
                if (!String.IsNullOrEmpty(cache_value)) cache = Convert.ToInt32(cache_value);

                // create the index
                IndexedDocumentCache index = new IndexedDocumentCache(this, key_xpath, value_xpath, context, cache);

                // search the data directories for entries
                XPathNodeIterator data_nodes = index_node.Select("data");
                foreach (XPathNavigator data_node in data_nodes) {

                    string base_value = data_node.GetAttribute("base", String.Empty);
                    if (!String.IsNullOrEmpty(base_value)) base_value = Environment.ExpandEnvironmentVariables(base_value);

                    bool recurse = false;
                    string recurse_value = data_node.GetAttribute("recurse", String.Empty);
                    if (!String.IsNullOrEmpty(recurse_value)) recurse = (bool)Convert.ToBoolean(recurse_value);

                    // get the files				
                    string files = data_node.GetAttribute("files", String.Empty);
                    if (String.IsNullOrEmpty(files)) WriteMessage(MessageLevel.Error, "Each data element must have a files attribute specifying which files to index.");
                    // if ((files == null) || (files.Length == 0)) throw new ConfigurationErrorsException("When instantiating a CopyFromDirectory component, you must specify a directory path using the files attribute.");
                    files = Environment.ExpandEnvironmentVariables(files);

                    WriteMessage(MessageLevel.Info, String.Format("Searching for files that match '{0}'.", files));
                    index.AddDocuments(base_value, files, recurse);

                }
                WriteMessage(MessageLevel.Info, String.Format("Indexed {0} elements in {1} files.", index.Count, index.DocumentCount));

                Data.Add(name, index);

            }

            // get the copy commands
            XPathNodeIterator copy_nodes = configuration.Select("copy");
            foreach (XPathNavigator copy_node in copy_nodes) {

                string source_name = copy_node.GetAttribute("name", String.Empty);
                if (String.IsNullOrEmpty(source_name)) throw new ConfigurationErrorsException("Each copy command must specify an index to copy from.");

                string key_xpath = copy_node.GetAttribute("key", String.Empty);

                string source_xpath = copy_node.GetAttribute("source", String.Empty);
                if (String.IsNullOrEmpty(source_xpath)) throw new ConfigurationErrorsException("When instantiating a CopyFromDirectory component, you must specify a source xpath format using the source attribute.");

                string target_xpath = copy_node.GetAttribute("target", String.Empty);
                if (String.IsNullOrEmpty(target_xpath)) throw new ConfigurationErrorsException("When instantiating a CopyFromDirectory component, you must specify a target xpath format using the target attribute.");

                string attribute_value = copy_node.GetAttribute("attribute", String.Empty);

                string ignoreCase_value = copy_node.GetAttribute("ignoreCase", String.Empty);

                string missingEntryValue = copy_node.GetAttribute("missing-entry", String.Empty);
                string missingSourceValue = copy_node.GetAttribute("missing-source", String.Empty);
                string missingTargetValue = copy_node.GetAttribute("missing-target", String.Empty);

                IndexedDocumentCache index = (IndexedDocumentCache)Data[source_name];

                CopyCommand copyCommand = new CopyCommand(index, key_xpath, source_xpath, target_xpath, attribute_value, ignoreCase_value);
                if (!String.IsNullOrEmpty(missingEntryValue)) {
                    try {
                        copyCommand.MissingEntry = (MessageLevel)Enum.Parse(typeof(MessageLevel), missingEntryValue, true);
                    } catch (ArgumentException) {
                        WriteMessage(MessageLevel.Error, String.Format("'{0}' is not a message level.", missingEntryValue));
                    }
                }
                if (!String.IsNullOrEmpty(missingSourceValue)) {
                    try {
                        copyCommand.MissingSource = (MessageLevel)Enum.Parse(typeof(MessageLevel), missingSourceValue, true);
                    } catch (ArgumentException) {
                        WriteMessage(MessageLevel.Error, String.Format("'{0}' is not a message level.", missingSourceValue));
                    }
                }
                if (!String.IsNullOrEmpty(missingTargetValue)) {
                    try {
                        copyCommand.MissingTarget = (MessageLevel)Enum.Parse(typeof(MessageLevel), missingTargetValue, true);
                    } catch (ArgumentException) {
                        WriteMessage(MessageLevel.Error, String.Format("'{0}' is not a message level.", missingTargetValue));
                    }
                }

                copy_commands.Add(copyCommand);

            }

            XPathNodeIterator component_nodes = configuration.Select("components/component");
            foreach (XPathNavigator component_node in component_nodes) {

                // get the data to load the component
                string assembly_path = component_node.GetAttribute("assembly", String.Empty);
                if (String.IsNullOrEmpty(assembly_path)) WriteMessage(MessageLevel.Error, "Each component element must have an assembly attribute.");
                string type_name = component_node.GetAttribute("type", String.Empty);
                if (String.IsNullOrEmpty(type_name)) WriteMessage(MessageLevel.Error, "Each component element must have a type attribute.");

                // expand environment variables in the path
                assembly_path = Environment.ExpandEnvironmentVariables(assembly_path);

                //Console.WriteLine("loading {0} from {1}", type_name, assembly_path);
                try 
                {
                    Assembly assembly = Assembly.LoadFrom(assembly_path);
                    CopyComponent component = (CopyComponent)assembly.CreateInstance(type_name, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[2] { component_node.Clone(), Data }, null, null);

                    if (component == null)
                    {
                        WriteMessage(MessageLevel.Error, String.Format("The type '{0}' does not exist in the assembly '{1}'.", type_name, assembly_path));
                    }
                    else
                    {
                        components.Add(component);
                    }

                }
                catch (IOException e)
                {
                    WriteMessage(MessageLevel.Error, String.Format("A file access error occured while attempting to load the build component '{0}'. The error message is: {1}", assembly_path, e.Message));
                }
                catch (BadImageFormatException e)
                {
                    WriteMessage(MessageLevel.Error, String.Format("A syntax generator assembly '{0}' is invalid. The error message is: {1}.", assembly_path, e.Message));
                }
                catch (TypeLoadException e)
                {
                    WriteMessage(MessageLevel.Error, String.Format("The type '{0}' does not exist in the assembly '{1}'. The error message is: {2}", type_name, assembly_path, e.Message));
                }
                catch (MissingMethodException e)
                {
                    WriteMessage(MessageLevel.Error, String.Format("The type '{0}' in the assembly '{1}' does not have an appropriate constructor. The error message is: {2}", type_name, assembly_path, e.Message));
                }
                catch (TargetInvocationException e)
                {
                    WriteMessage(MessageLevel.Error, String.Format("An error occured while attempting to instantiate the type '{0}' in the assembly '{1}'. The error message is: {2}", type_name, assembly_path, e.InnerException.Message));
                }
                catch (InvalidCastException)
                {
                    WriteMessage(MessageLevel.Error, String.Format("The type '{0}' in the assembly '{1}' is not a SyntaxGenerator.", type_name, assembly_path));
                }
            }

            WriteMessage(MessageLevel.Info, String.Format("Loaded {0} copy components.", components.Count));

        }
        //=====================================================================
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        public ResolveConceptualLinksComponent(BuildAssembler assembler,
          XPathNavigator configuration)
            : base(assembler, configuration)
        {
            TargetDirectory targetDirectory;
            XPathExpression urlExp, textExp, linkTextExp;
            LinkType linkType = LinkType.None;
            string attribute, basePath;

            targetDirectories = new TargetDirectoryCollection();
            cache = new Dictionary<string, TargetInfo>(cacheSize);

            attribute = configuration.GetAttribute("showBrokenLinkText", String.Empty);

            if(!String.IsNullOrEmpty(attribute))
                showBrokenLinkText = Convert.ToBoolean(attribute, CultureInfo.InvariantCulture);

            foreach(XPathNavigator navigator in configuration.Select("targets"))
            {
                basePath = navigator.GetAttribute("base", String.Empty);

                if(String.IsNullOrEmpty(basePath))
                    base.WriteMessage(MessageLevel.Error, "Every targets " +
                        "element must have a base attribute that specifies " +
                        "the path to a directory of target metadata files.");

                basePath = Environment.ExpandEnvironmentVariables(basePath);
                if(!Directory.Exists(basePath))
                    base.WriteMessage(MessageLevel.Error, String.Format(
                        CultureInfo.InvariantCulture, "The specified target " +
                        "metadata directory '{0}' does not exist.", basePath));

                attribute = navigator.GetAttribute("url", String.Empty);

                if(String.IsNullOrEmpty(attribute))
                    urlExp = XPathExpression.Compile("concat(/metadata/topic/@id,'.htm')");
                else
                    urlExp = this.CompileXPathExpression(attribute);

                attribute = navigator.GetAttribute("text", String.Empty);

                if(String.IsNullOrEmpty(attribute))
                    textExp = XPathExpression.Compile("string(/metadata/topic/title)");
                else
                    textExp = this.CompileXPathExpression(attribute);

                // EFW - Added support for linkText option
                attribute = navigator.GetAttribute("linkText", String.Empty);

                if(String.IsNullOrEmpty(attribute))
                    linkTextExp = XPathExpression.Compile("string(/metadata/topic/linkText)");
                else
                    linkTextExp = this.CompileXPathExpression(attribute);

                attribute = navigator.GetAttribute("type", String.Empty);

                if(String.IsNullOrEmpty(attribute))
                    base.WriteMessage(MessageLevel.Error, "Every targets " +
                        "element must have a type attribute that specifies " +
                        "what kind of link to create to targets found in " +
                        "that directory.");

                try
                {
                    linkType = (LinkType)Enum.Parse(typeof(LinkType), attribute, true);
                }
                catch(ArgumentException)
                {
                    base.WriteMessage(MessageLevel.Error, String.Format(CultureInfo.InvariantCulture,
                        "'{0}' is not a valid link type.", attribute));
                }

                targetDirectory = new TargetDirectory(basePath, urlExp, textExp, linkTextExp, linkType);
                targetDirectories.Add(targetDirectory);
            }

            base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
                "Collected {0} targets directories.", targetDirectories.Count));
        }
Exemple #56
0
        //=====================================================================

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        public IntelliSenseComponent(BuildAssembler assembler,
                                     XPathNavigator configuration) : base(assembler, configuration)
        {
            XPathNavigator nav;
            string         attrValue;

            Assembly        asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            base.WriteMessage(MessageLevel.Info, String.Format(
                                  CultureInfo.InvariantCulture,
                                  "\r\n    [{0}, version {1}]\r\n    IntelliSense Component. " +
                                  "{2}\r\n    http://SHFB.CodePlex.com", fvi.ProductName,
                                  fvi.ProductVersion, fvi.LegalCopyright));

            outputFolder       = String.Empty;
            namespacesFilename = "Namespaces";
            this.writers       = new Dictionary <string, XmlWriter>();

            assemblyExpression = XPathExpression.Compile(
                "/document/reference/containers/library/@assembly");
            subgroupExpression = XPathExpression.Compile(
                "string(/document/reference/apidata/@subgroup)");
            elementsExpression = XPathExpression.Compile(
                "/document/reference/elements/element");

            summaryExpression   = XPathExpression.Compile("summary");
            paramExpression     = XPathExpression.Compile("param");
            typeparamExpression = XPathExpression.Compile("typeparam");
            returnsExpression   = XPathExpression.Compile("returns");
            exceptionExpression = XPathExpression.Compile("exception");

            nav = configuration.SelectSingleNode("output");

            if (nav != null)
            {
                attrValue = nav.GetAttribute("includeNamespaces",
                                             String.Empty);

                if (!String.IsNullOrEmpty(attrValue) && !Boolean.TryParse(
                        attrValue, out includeNamespaces))
                {
                    throw new ConfigurationErrorsException("You must " +
                                                           "specify a Boolean value for the <output> " +
                                                           "'includeNamespaces' attribute.");
                }

                attrValue = nav.GetAttribute("folder", String.Empty);

                if (!String.IsNullOrEmpty(attrValue))
                {
                    outputFolder = Environment.ExpandEnvironmentVariables(
                        attrValue);

                    if (!Directory.Exists(outputFolder))
                    {
                        Directory.CreateDirectory(outputFolder);
                    }
                }

                attrValue = nav.GetAttribute("namespacesFile", String.Empty);

                if (!String.IsNullOrEmpty(attrValue))
                {
                    namespacesFilename = attrValue;
                }
            }
        }
        protected MediaComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            _artIdExpression   = XPathExpression.Compile("string(@id)");
            _artFileExpression = XPathExpression.Compile("string(image/@file)");
            _artTextExpression = XPathExpression.Compile("string(image/altText)");

            _artTargets = new Dictionary <string, MediaTarget>(
                StringComparer.OrdinalIgnoreCase);

            XPathNodeIterator targetsNodes = configuration.Select("targets");

            foreach (XPathNavigator targetsNode in targetsNodes)
            {
                string input = targetsNode.GetAttribute("input", String.Empty);
                if (String.IsNullOrEmpty(input))
                {
                    this.WriteMessage(MessageLevel.Error,
                                      "Each targets element must have an input attribute specifying a directory containing art files.");
                }

                input = Environment.ExpandEnvironmentVariables(input);

                if (!Directory.Exists(input))
                {
                    this.WriteMessage(MessageLevel.Error, String.Format(
                                          "The art input directory '{0}' does not exist.", input));
                }

                string baseOutputPath = targetsNode.GetAttribute(
                    "baseOutput", String.Empty);
                if (!String.IsNullOrEmpty(baseOutputPath))
                {
                    baseOutputPath = Path.GetFullPath(
                        Environment.ExpandEnvironmentVariables(baseOutputPath));
                }

                string outputPathValue = targetsNode.GetAttribute(
                    "outputPath", String.Empty);
                if (string.IsNullOrEmpty(outputPathValue))
                {
                    this.WriteMessage(MessageLevel.Error,
                                      "Each targets element must have an output attribute specifying a directory in which to place referenced art files.");
                }
                XPathExpression outputXPath = XPathExpression.Compile(
                    outputPathValue);

                string linkValue = targetsNode.GetAttribute("link", String.Empty);
                if (String.IsNullOrEmpty(linkValue))
                {
                    linkValue = "../art";
                }
                //linkValue = Environment.ExpandEnvironmentVariables(linkValue);

                string map = targetsNode.GetAttribute("map", String.Empty);
                if (String.IsNullOrEmpty(map))
                {
                    this.WriteMessage(MessageLevel.Error,
                                      "Each targets element must have a map attribute specifying a file that maps art ids to files in the input directory.");
                }
                map = Environment.ExpandEnvironmentVariables(map);
                if (!File.Exists(map))
                {
                    WriteMessage(MessageLevel.Error, String.Format(
                                     "The art map file '{0}' does not exist.", map));
                }

                string          format      = targetsNode.GetAttribute("format", String.Empty);
                XPathExpression formatXPath = String.IsNullOrEmpty(format) ?
                                              null : XPathExpression.Compile(format);

                string relativeTo = targetsNode.GetAttribute(
                    "relative-to", String.Empty);
                XPathExpression relativeToXPath = String.IsNullOrEmpty(
                    relativeTo) ? null : XPathExpression.Compile(relativeTo);

                this.AddTargets(map, input, baseOutputPath, outputXPath, linkValue,
                                formatXPath, relativeToXPath);
            }

            this.WriteMessage(MessageLevel.Info, String.Format(
                                  "Indexed {0} art targets.", _artTargets.Count));
        }
Exemple #58
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        /// <exception cref="ConfigurationErrorsException">This is thrown if
        /// an error is detected in the configuration.</exception>
        public PostTransformComponent(BuildAssembler assembler,
                                      XPathNavigator configuration) : base(assembler, configuration)
        {
            XPathNavigator nav;
            string         attr;

            Assembly        asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            base.WriteMessage(MessageLevel.Info, String.Format(
                                  CultureInfo.InvariantCulture,
                                  "\r\n    [{0}, version {1}]\r\n    Post-Transform Component. " +
                                  "{2}\r\n    http://www.codeplex.com/SHFB", fvi.ProductName,
                                  fvi.ProductVersion, fvi.LegalCopyright));

            // The <colorizer> element is required and defines the colorizer
            // file locations.
            nav = configuration.SelectSingleNode("colorizer");
            if (nav == null)
            {
                throw new ConfigurationErrorsException("You must specify " +
                                                       "a <colorizer> element to define the code colorizer " +
                                                       "files.");
            }

            // All of the attributes are required
            stylesheet = nav.GetAttribute("stylesheet", String.Empty);
            scriptFile = nav.GetAttribute("scriptFile", String.Empty);
            copyImage  = nav.GetAttribute("copyImage", String.Empty);

            if (String.IsNullOrEmpty(stylesheet))
            {
                throw new ConfigurationErrorsException("You must specify a " +
                                                       "'stylesheet' attribute on the <colorizer> element");
            }

            if (String.IsNullOrEmpty(scriptFile))
            {
                throw new ConfigurationErrorsException("You must specify a " +
                                                       "'scriptFile' attribute on the <colorizer> element");
            }

            if (String.IsNullOrEmpty(copyImage))
            {
                throw new ConfigurationErrorsException("You must specify a " +
                                                       "'copyImage' attribute on the <colorizer> element");
            }

            // This specifies the output and the XPath expression used
            // to get the filename.  If the base class found them, we will.
            nav = configuration.SelectSingleNode("outputPath");
            if (nav != null)
            {
                outputPath = nav.GetAttribute("value", String.Empty);
            }

            if (String.IsNullOrEmpty(outputPath))
            {
                throw new ConfigurationErrorsException("You must specify a " +
                                                       "'value' attribute on the <outputPath> element");
            }

            // All present.  Make sure they exist.
            stylesheet = Path.GetFullPath(stylesheet);
            scriptFile = Path.GetFullPath(scriptFile);
            copyImage  = Path.GetFullPath(copyImage);

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

            if (!File.Exists(stylesheet))
            {
                throw new ConfigurationErrorsException("Could not find " +
                                                       "stylesheet file: " + stylesheet);
            }

            if (!File.Exists(stylesheet))
            {
                throw new ConfigurationErrorsException("Could not find " +
                                                       "script file: " + scriptFile);
            }

            if (!File.Exists(copyImage))
            {
                throw new ConfigurationErrorsException("Could not find " +
                                                       "image file: " + copyImage);
            }

            if (!Directory.Exists(outputPath))
            {
                throw new ConfigurationErrorsException("The output path '" +
                                                       outputPath + "' must exist");
            }

            // The logo element is optional.  The file must exist if
            // specified.
            nav = configuration.SelectSingleNode("logoFile");
            if (nav != null)
            {
                logoFilename = nav.GetAttribute("filename", String.Empty);

                if (!String.IsNullOrEmpty(logoFilename))
                {
                    if (!File.Exists(logoFilename))
                    {
                        throw new ConfigurationErrorsException("The logo " +
                                                               "file '" + logoFilename + "' must exist");
                    }

                    logoAltText = nav.GetAttribute("altText", String.Empty);

                    attr = nav.GetAttribute("height", String.Empty);
                    if (!String.IsNullOrEmpty(attr))
                    {
                        if (!Int32.TryParse(attr, out logoHeight))
                        {
                            throw new ConfigurationErrorsException("The logo " +
                                                                   "height must be an integer value");
                        }
                    }

                    attr = nav.GetAttribute("width", String.Empty);
                    if (!String.IsNullOrEmpty(attr))
                    {
                        if (!Int32.TryParse(attr, out logoWidth))
                        {
                            throw new ConfigurationErrorsException("The logo " +
                                                                   "width must be an integer value");
                        }
                    }

                    // Ignore them if negative
                    if (logoHeight < 0)
                    {
                        logoHeight = 0;
                    }

                    if (logoWidth < 0)
                    {
                        logoWidth = 0;
                    }

                    // Placement and alignment are optional
                    attr = nav.GetAttribute("placement", String.Empty);
                    if (!String.IsNullOrEmpty(attr))
                    {
                        placement = (LogoPlacement)Enum.Parse(
                            typeof(LogoPlacement), attr, true);
                    }
                    else
                    {
                        placement = LogoPlacement.Left;
                    }

                    attr = nav.GetAttribute("alignment", String.Empty);
                    if (!String.IsNullOrEmpty(attr))
                    {
                        alignment = attr;
                    }
                    else
                    {
                        alignment = "left";
                    }
                }
            }
        }
        /// <summary>
        /// Constructor for SnippetComponent class.
        /// </summary>
        /// <param name="assembler">An instance of Build Assembler</param>
        /// <param name="configuration">configuration to be parsed for information related to snippets</param>
        public SnippetComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            Debug.Assert(assembler != null);
            Debug.Assert(configuration != null);

            // Get the parsnip examples location.
            XPathNodeIterator examplesNode = configuration.Select("examples/example");

            if (examplesNode.Count == 0)
                WriteMessage(MessageLevel.Error, "Each snippet component element must have a child element named 'examples' containing an element named 'example' with an attribute named 'directory', whose value is a path to the directory containing examples.");

            foreach (XPathNavigator exampleNode in examplesNode)
            {
                string rootDirectory = exampleNode.GetAttribute("directory", string.Empty);

                if (string.IsNullOrEmpty(rootDirectory))
                    WriteMessage(MessageLevel.Error, "Each examples element must have a directory attribute specifying a directory containing parsnip samples.");

                rootDirectory = Environment.ExpandEnvironmentVariables(rootDirectory);
                if (!Directory.Exists(rootDirectory))
                    WriteMessage(MessageLevel.Error, String.Format("The examples/@directory attribute specified a directory that doesn't exist: '{0}'", rootDirectory));

                // create a dictionary that maps the example names to the example path under the root directory
                this.loadExamples(rootDirectory);
            }

            // Get the approved log files location.
            XPathNodeIterator approvedSnippetsNode = configuration.Select("approvalLogs/approvalLog");

            if (approvedSnippetsNode.Count == 0)
                WriteMessage(MessageLevel.Warn, "The config did not have an 'approvalLogs' node to specify a snippet approval logs.");
            
            foreach (XPathNavigator node in approvedSnippetsNode)
            {
                string approvalLogFile = node.GetAttribute("file", string.Empty);

                if (string.IsNullOrEmpty(approvalLogFile))
                    WriteMessage(MessageLevel.Error, "The approvalLog node must have a 'file' attribute specifying the path to a snippet approval log.");

                approvalLogFile = Environment.ExpandEnvironmentVariables(approvalLogFile);
                if (!File.Exists(approvalLogFile))
                    WriteMessage(MessageLevel.Error, String.Format("The approvalLog/@file attribute specified a file that doesn't exist: '{0}'", approvalLogFile));

                // load the approval log into the approvedSnippetIndex dictionary
                this.parseApprovalLogFiles(approvalLogFile);
            }

            // Get the names of the unit directories in the sample tree to exclude from parsing
            //     <excludedUnits><unitFolder name="CPP_OLD" /></excludedUnits>
            XPathNodeIterator excludedUnitNodes = configuration.Select("excludedUnits/unitFolder");
            foreach (XPathNavigator unitFolder in excludedUnitNodes)
            {
                string folderName = unitFolder.GetAttribute("name", string.Empty);

                if (string.IsNullOrEmpty(folderName))
                    WriteMessage(MessageLevel.Error, "Each excludedUnits/unitFolder node must have a 'name' attribute specifying the name of a folder name to exclude.");

                folderName = Environment.ExpandEnvironmentVariables(folderName);

                // add the folderName to the list of names to be excluded
                this.excludedUnits.Add(folderName.ToLower(),null);
            }

            // Get the languages defined.
            XPathNodeIterator languageNodes = configuration.Select("languages/language");
            foreach (XPathNavigator languageNode in languageNodes)
            {
                // read the @languageId, @unit, and @extension attributes
                string languageId = languageNode.GetAttribute("languageId", string.Empty);
                if (string.IsNullOrEmpty(languageId))
                    WriteMessage(MessageLevel.Error, "Each language node must specify an @languageId attribute.");

                string unit = languageNode.GetAttribute("unit", string.Empty);

                // if both @languageId and @unit are specified, add this language to the language map
                if (!string.IsNullOrEmpty(unit))
                    languageMap.Add(unit.ToLower(), languageId);

                // add languageId to the languageList for purpose of ordering snippets in the output
                if (!languageList.Contains(languageId))
                    languageList.Add(languageId.ToLower());

                string extension = languageNode.GetAttribute("extension", string.Empty);
                if (!string.IsNullOrEmpty(extension))
                {
                    if (!extension.Contains("."))
                    {
                        extension = "." + extension;
                        WriteMessage(MessageLevel.Warn, String.Format("The @extension value must begin with a period. Adding a period to the extension value '{0}' of the {1} language.", extension, languageId));
                    }
                    else
                    {
                        int indexOfPeriod = extension.IndexOf('.');
                        if (indexOfPeriod != 0)
                        {
                            extension = extension.Substring(indexOfPeriod);
                            WriteMessage(MessageLevel.Warn, String.Format("The @extension value must begin with a period. Using the substring beginning with the first period of the specified extension value '{0}' of the {1} language.", extension, languageId));
                        }
                    }
                }

                // read the color nodes, if any, and add them to the list of colorization rules
                List<ColorizationRule> rules = new List<ColorizationRule>();

                XPathNodeIterator colorNodes = languageNode.Select("color");
                foreach (XPathNavigator colorNode in colorNodes)
                {
                    string pattern = colorNode.GetAttribute("pattern", String.Empty);
                    string region = colorNode.GetAttribute("region", String.Empty);
                    string name = colorNode.GetAttribute("class", String.Empty);
                    if (String.IsNullOrEmpty(region))
                    {
                        rules.Add(new ColorizationRule(pattern, name));
                    }
                    else
                    {
                        rules.Add(new ColorizationRule(pattern, region, name));
                    }
                }

                this.languages.Add(new Language(languageId, extension, rules));
                WriteMessage(MessageLevel.Info, String.Format("Loaded {0} colorization rules for the language '{1}', extension '{2}.", rules.Count, languageId, extension));
            }

            this.context.AddNamespace("ddue", "http://ddue.schemas.microsoft.com/authoring/2003/5");
            this.selector = XPathExpression.Compile("//ddue:codeReference");
            this.selector.SetContext(this.context);

            // create the snippet cache
            snippetCache = new SnippetCache(100, approvedSnippetIndex, languageMap, languages, excludedUnits);
        }
        public LiveExampleComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration) {

            XPathNavigator parsnip_node = configuration.SelectSingleNode("parsnip");
            string approvedFile = null;
            if (parsnip_node != null) {
                approvedFile = parsnip_node.GetAttribute("approved-file", String.Empty);

                string omitBadExamplesValue = parsnip_node.GetAttribute("omit-bad-examples", String.Empty);
                if (!string.IsNullOrEmpty(omitBadExamplesValue))
                    omitBadExamples = Boolean.Parse(omitBadExamplesValue);

                //string runBadExamplesValue = parsnip_node.GetAttribute("run-bad-examples", String.Empty);
                //if (!string.IsNullOrEmpty(runBadExamplesValue))
                //    runBadExamples = Boolean.Parse(runBadExamplesValue);
            }

            if (string.IsNullOrEmpty(approvedFile))
                WriteMessage(MessageLevel.Warn, "No approved samples file specified; all available samples will be included.");
            else
                LoadApprovedFile(approvedFile);

            context = new CustomContext();
            context.AddNamespace("ddue", "http://ddue.schemas.microsoft.com/authoring/2003/5");

            selector = XPathExpression.Compile("//ddue:codeReference");
            selector.SetContext(context);
        }