Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="input">{http://microsoft.com/schemas/VisualStudio/TeamTest/2010}TestMethod</param>
        /// <returns></returns>
        public XPathNavigator GetTestTargets(XPathNavigator?input)
        {
            XNamespace ns = this.GetXmlNamespace() + ":out";

            try
            {
                /*
                 * <TestMethod codeBase="C:\Repos\mwwhited\BinaryDataDecoders\src\BinaryDataDecoders.ExpressionCalculator.Tests\bin\Debug\netcoreapp3.1\BinaryDataDecoders.ExpressionCalculator.Tests.dll"
                 *  adapterTypeName="executor://mstestadapter/v2"
                 *  className="BinaryDataDecoders.ExpressionCalculator.Tests.Parser.Int64ExpressionParserTests"
                 *  name="GetDistinctVariablesTests" />
                 */

                var codeBase  = input?.GetAttribute("codeBase", "");
                var className = input?.GetAttribute("className", "");
                var name      = input?.GetAttribute("name", "");

                if (!File.Exists(codeBase))
                {
                    return(new XElement(ns + "targets", new XComment($"File: \"{codeBase}\" not found")).ToXPathNavigable().CreateNavigator());
                }

                var assembly   = string.IsNullOrWhiteSpace(codeBase) ? null : Assembly.LoadFrom(codeBase);
                var testClass  = string.IsNullOrWhiteSpace(className) ? null : assembly?.GetType(className);
                var testMethod = string.IsNullOrWhiteSpace(name) ? null : testClass?.GetMethod(name);
                var attributes = testMethod?.GetCustomAttributes <TestTargetAttribute>() ?? Enumerable.Empty <TestTargetAttribute>();

                var xml = new XElement(ns + "targets",
                                       from a in attributes
                                       select new XElement(ns + "target",
                                                           new XAttribute("name", a.Class.Name),
                                                           new XAttribute("namespace", a.Class.Namespace),
                                                           new XAttribute("assembly", a.Class.Assembly.FullName),
                                                           (string.IsNullOrWhiteSpace(a.Member) ? null : new XAttribute("member", a.Member))
                                                           )
                                       );

                var xPathNavigable = xml.ToXPathNavigable();
                var xPathNavigator = xPathNavigable.CreateNavigator();
                return(xPathNavigator);
            }
            catch (Exception ex)
            {
                return(new XElement(ns + "targets", new XComment(ex.Message)).ToXPathNavigable().CreateNavigator());
            }
        }
Beispiel #2
0
        Coverage CoverageFromSummaryNode(XPathNavigator summaryNode)
        {
            var hasSequencePoints        = double.TryParse(summaryNode?.GetAttribute("numSequencePoints", ""), out var sequencePoints);
            var hasVisitedSequencePoints = double.TryParse(summaryNode?.GetAttribute("visitedSequencePoints", ""), out var visitedSequencePoints);

            var hasBranchPoints        = double.TryParse(summaryNode?.GetAttribute("numBranchPoints", ""), out var branchPoints);
            var hasVisitedBranchPoints = double.TryParse(summaryNode?.GetAttribute("visitedBranchPoints", ""), out var visitedBranchPoints);

            if (summaryNode == null || !hasSequencePoints || !hasVisitedSequencePoints || !hasBranchPoints || !hasVisitedBranchPoints)
            {
                return(Coverage.NaN);
            }

            var lineCoverage   = (visitedSequencePoints / sequencePoints) * 100;
            var branchCoverage = (visitedBranchPoints / branchPoints) * 100;

            return(new Coverage(lineCoverage, branchCoverage));
        }
Beispiel #3
0
    public MediaValues(XPathNavigator xpath)
    {
        if (xpath == null) throw new ArgumentNullException("xpath");
        Name = xpath.GetAttribute("nodeName", "");
        Values = new Dictionary<string, string>();
        var result = xpath.SelectChildren(XPathNodeType.Element);
        while (result.MoveNext())
        {
            if (result.Current != null && !result.Current.HasAttributes)
            {
                Values.Add(result.Current.Name, result.Current.Value);
            }
        }

        if (Values.Keys.Contains("error"))
        {
            NiceUrl = "";
        }
        else
        {
            NiceUrl = Values["umbracoFile"];
        }
    }
Beispiel #4
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            XPathNavigator syntaxNode       = configuration.SelectSingleNode("syntax");
            string         syntaxInputXPath = syntaxNode.GetAttribute("input", String.Empty);

            if (String.IsNullOrEmpty(syntaxInputXPath))
            {
                throw new ConfigurationErrorsException("You must specify an XPath for input in the syntax element");
            }

            syntaxInput = XPathExpression.Compile(syntaxInputXPath);

            string syntaxOutputXPath = syntaxNode.GetAttribute("output", String.Empty);

            if (String.IsNullOrEmpty(syntaxOutputXPath))
            {
                throw new ConfigurationErrorsException("You must specify an XPath for output in the syntax element");
            }

            syntaxOutput = XPathExpression.Compile(syntaxOutputXPath);

            string attrValue = syntaxNode.GetAttribute("renderReferenceLinks", String.Empty);

            if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out renderReferenceLinks))
            {
                renderReferenceLinks = false;
            }

            XPathNodeIterator generatorNodes = configuration.Select("generators/generator");

            // Configuration changes are stored separately since the actual generators may be added to the
            // configuration file at build time.  Substitution of the edited configuration is easier to do here.
            var generatorConfigs = configuration.SelectSingleNode("configurations");

            // If we have configuration nodes, note the order of the syntax generators.  These will be used to
            // order the snippets.
            if (generatorConfigs != null)
            {
                int order = 1;

                foreach (XPathNavigator id in generatorConfigs.Select("generator/@id"))
                {
                    languageOrder.Add(id.Value, order++);
                }
            }

            foreach (XPathNavigator generatorNode in generatorNodes)
            {
                // Get the ID of the syntax generator
                string id = generatorNode.GetAttribute("id", String.Empty);

                if (String.IsNullOrWhiteSpace(id))
                {
                    this.WriteMessage(MessageLevel.Error, "Each generator element must have an id attribute");
                }

                var generatorFactory = generatorFactories.FirstOrDefault(g => g.Metadata.Id == id);

                if (generatorFactory == null)
                {
                    this.WriteMessage(MessageLevel.Error, "A syntax generator with the ID '{0}' could not be found", id);
                }

                // Track the languages for grouping
                generatorLanguages.Add(generatorFactory.Metadata.Id);
                languageSet.Add(generatorFactory.Metadata);

                foreach (string alternateId in (generatorFactory.Metadata.AlternateIds ?? String.Empty).Split(
                             new[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    generatorLanguages.Add(alternateId);
                }

                try
                {
                    var generator  = generatorFactory.Value.Create();
                    var configNode = generatorNode.Clone();

                    if (generatorConfigs != null)
                    {
                        var alternateConfig = generatorConfigs.SelectSingleNode("generator[@id='" + id + "']");

                        if (alternateConfig != null && alternateConfig.HasChildren)
                        {
                            // Since there may be custom attributes on the generator node, we'll make a copy and
                            // substitute the child elements that make up the configuration.
                            var alternate = XElement.Parse(alternateConfig.OuterXml);
                            var genNode   = XElement.Parse(configNode.OuterXml);

                            genNode.RemoveNodes();
                            genNode.Add(alternate.Elements());

                            configNode = genNode.CreateNavigator();
                        }
                    }

                    generator.Initialize(configNode);
                    generators.Add(generator);
                }
                catch (Exception ex)
                {
                    this.WriteMessage(MessageLevel.Error, "An error occurred while attempting to instantiate " +
                                      "the '{0}' syntax generator. The error message is: {1}{2}", id, ex.Message,
                                      ex.InnerException != null ? "\r\n" + ex.InnerException.Message : String.Empty);
                }
            }

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

            // If this is not found or set, we'll assume the presentation style does not support grouping
            var containerElement = configuration.SelectSingleNode("containerElement");

            if (containerElement != null)
            {
                // If grouping is disabled, skip the remainder of the set up.  This will happen if the user adds
                // a custom configuration to a project for a presentation style that doesn't support it.
                bool groupingEnabled;

                containerElementName = containerElement.GetAttribute("name", String.Empty);
                attrValue            = containerElement.GetAttribute("groupingEnabled", String.Empty);

                if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out groupingEnabled))
                {
                    groupingEnabled = false;
                }

                if (!groupingEnabled || String.IsNullOrWhiteSpace(containerElementName))
                {
                    return;
                }

                // Get the "no example tab" options
                attrValue = containerElement.GetAttribute("addNoExampleTabs", String.Empty);

                if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out addNoExampleTabs))
                {
                    addNoExampleTabs = true;
                }

                attrValue = containerElement.GetAttribute("includeOnSingleSnippets", String.Empty);

                if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out includeOnSingleSnippets))
                {
                    includeOnSingleSnippets = false;
                }

                // Create the XPath queries used for code snippet grouping and sorting
                var context = new CustomContext();

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

                referenceRoot = XPathExpression.Compile("document/comments|document/syntax");
                referenceCode = XPathExpression.Compile("//code|//div[@codeLanguage]");

                conceptualRoot = XPathExpression.Compile("document/topic");
                conceptualCode = XPathExpression.Compile("//ddue:code|//ddue:snippet");
                conceptualCode.SetContext(context);

                // Hook up the event handler to group and sort code snippets just prior to XSL transformation
                this.BuildAssembler.ComponentEvent += TransformComponent_TopicTransforming;
            }
        }
Beispiel #5
0
        //=====================================================================

        /// <summary>
        /// This is used to create the index cache database
        /// </summary>
        /// <param name="configuration">The configuration to use</param>
        private PersistentDictionary <string, string> CreateCache(XPathNavigator configuration)
        {
            PersistentDictionary <string, string> cache = null;
            HashSet <string> namespaceFileFilter = new HashSet <string>();
            string           groupId, cachePathAttrName, cachePath, baseDirectory, wildcardPath, recurseValue, dupWarning,
                             fullPath, directoryPart, filePart;
            bool recurse, reportDuplicateIds, isProjectData = false;
            int  localCacheSize, filesToLoad;

            var parent = configuration.Clone();

            parent.MoveToParent();

            groupId = configuration.GetAttribute("groupId", String.Empty);

            // If caching project data, they will all go into a common index
            if (groupId.StartsWith("Project_", StringComparison.OrdinalIgnoreCase))
            {
                cachePathAttrName = "projectCachePath";
                isProjectData     = true;
            }
            else
            {
                cachePathAttrName = "frameworkCachePath";
            }

            cache = esentCaches.FirstOrDefault(c => c.Database.Contains(groupId));

            if (cache != null)
            {
                cachePath = cache.Database;
            }
            else
            {
                cachePath = parent.GetAttribute(cachePathAttrName, String.Empty);

                if (String.IsNullOrWhiteSpace(cachePath))
                {
                    return(null);
                }

                cachePath = Path.Combine(cachePath, groupId);

                string cacheSize = parent.GetAttribute("localCacheSize", String.Empty);

                if (String.IsNullOrWhiteSpace(cacheSize) || !Int32.TryParse(cacheSize, out localCacheSize))
                {
                    localCacheSize = 2500;
                }

                // Column compression is left on here as it does benefit the string data
                cache = new PersistentDictionary <string, string>(cachePath)
                {
                    LocalCacheSize = localCacheSize
                };
            }

            baseDirectory = configuration.GetAttribute("base", String.Empty);

            if (!String.IsNullOrWhiteSpace(baseDirectory))
            {
                baseDirectory = Environment.ExpandEnvironmentVariables(baseDirectory);
            }

            wildcardPath = configuration.GetAttribute("files", String.Empty);

            if (String.IsNullOrWhiteSpace(wildcardPath))
            {
                base.Component.WriteMessage(MessageLevel.Error, "Each data element must have a files attribute " +
                                            "specifying which files to index.");
            }

            wildcardPath = Environment.ExpandEnvironmentVariables(wildcardPath);

            recurseValue = configuration.GetAttribute("recurse", String.Empty);

            if (String.IsNullOrWhiteSpace(recurseValue) || !Boolean.TryParse(recurseValue, out recurse))
            {
                recurse = false;
            }

            // Support suppression of duplicate ID warnings.  This can happen a lot when common classes appear in
            // multiple assemblies.
            dupWarning = configuration.GetAttribute("duplicateWarning", String.Empty);

            if (String.IsNullOrWhiteSpace(dupWarning) || !Boolean.TryParse(dupWarning, out reportDuplicateIds))
            {
                reportDuplicateIds = true;
            }

            if (String.IsNullOrEmpty(baseDirectory))
            {
                fullPath = wildcardPath;
            }
            else
            {
                // Verify that the directory exists
                if (!Directory.Exists(baseDirectory))
                {
                    throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The targets " +
                                                              "directory '{0}' does not exist.  The configuration is most likely out of date.  " +
                                                              "Please delete this component from the project, add it back, and reconfigure it.",
                                                              baseDirectory), "configuration");
                }

                fullPath = Path.Combine(baseDirectory, wildcardPath);
            }

            fullPath = Environment.ExpandEnvironmentVariables(fullPath);

            directoryPart = Path.GetDirectoryName(fullPath);

            if (String.IsNullOrEmpty(directoryPart))
            {
                directoryPart = Environment.CurrentDirectory;
            }

            filePart = Path.GetFileName(fullPath);

            // Filtering reduces the number of files to load, especially for the core reflection data files
            namespaceFileFilter.Clear();

            foreach (XPathNavigator filter in configuration.Select("namespace/@file"))
            {
                namespaceFileFilter.Add(filter.Value);
            }

            // Loading new targets can take a while so issue a diagnostic message as an alert
            filesToLoad = 0;

            if (namespaceFileFilter.Count != 0)
            {
                // Reflection data can be filtered by namespace so some or all of it may already be there
                foreach (string file in Directory.EnumerateFiles(directoryPart, filePart, recurse ?
                                                                 SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
                {
                    if ((namespaceFileFilter.Count == 0 || namespaceFileFilter.Contains(Path.GetFileName(file))) &&
                        !cache.ContainsKey("N:" + Path.GetFileNameWithoutExtension(file)))
                    {
                        filesToLoad++;
                    }
                }
            }
            else
            {
                // Comments files can't be filtered by namespace so we'll assume that if the collection is not
                // empty, it has already been loaded unless it's a project comments file list.  In that case,
                // we will merge them if necessary.
                if (isProjectData || cache.Count == 0)
                {
                    filesToLoad = Directory.EnumerateFiles(directoryPart, filePart, recurse ?
                                                           SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Count();
                }
            }

            if (filesToLoad != 0)
            {
                // The time estimate is a ballpark figure and depends on the system
                base.Component.WriteMessage(MessageLevel.Diagnostic, "{0} file(s) need to be added to the " +
                                            "ESENT index cache database.  Indexing them will take about {1:N0} minute(s), please be " +
                                            "patient.  Cache location: {2}", filesToLoad, Math.Ceiling(filesToLoad / 60.0), cachePath);

                // Limit the degree of parallelism or it overwhelms the ESENT version store
                Parallel.ForEach(Directory.EnumerateFiles(directoryPart, filePart,
                                                          recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly),
                                 new ParallelOptions {
                    MaxDegreeOfParallelism = 3
                },
                                 file =>
                {
                    // Skip the file if not in a defined filter
                    if (namespaceFileFilter.Count != 0 && !namespaceFileFilter.Contains(Path.GetFileName(file)))
                    {
                        return;
                    }

                    // Get the keys from the file and add them to the index
                    foreach (var kv in base.GetValues(file))
                    {
                        // Only report the warning if wanted
                        if (cache.ContainsKey(kv.Key) && reportDuplicateIds)
                        {
                            this.Component.WriteMessage(MessageLevel.Warn, "An entry for the key '{0}' " +
                                                        "already exists and will be replaced by the one from '{1}'", kv.Key, file);
                        }

                        cache[kv.Key] = kv.Value.InnerXml;
                    }
                });
            }

            return(cache);
        }
Beispiel #6
0
        protected virtual void ProcessArguments(ControllerConfiguration config, ActionArgs args)
        {
            if (args.Values == null)
            {
                return;
            }
            FieldValueDictionary values = new FieldValueDictionary(args);

            _pk = null;
            // detect negative primary keys
            XPathNavigator pkNav = config.SelectSingleNode("/c:dataController/c:fields/c:field[@isPrimaryKey=\'true\']");

            if (pkNav != null)
            {
                FieldValue fv = null;
                if (values.TryGetValue(pkNav.GetAttribute("name", String.Empty), out fv))
                {
                    int value = 0;
                    if ((fv.NewValue != null) && int.TryParse(Convert.ToString(fv.NewValue), out value))
                    {
                        if (value < 0)
                        {
                            if (args.CommandName == "Insert")
                            {
                                // request a new row from business rules
                                PageRequest newRowRequest = new PageRequest();
                                newRowRequest.Controller       = args.Controller;
                                newRowRequest.View             = args.View;
                                newRowRequest.Inserting        = true;
                                newRowRequest.RequiresMetaData = true;
                                newRowRequest.MetadataFilter   = new string[] {
                                    "fields"
                                };
                                ViewPage page = ControllerFactory.CreateDataController().GetPage(newRowRequest.Controller, newRowRequest.View, newRowRequest);
                                if (page.NewRow != null)
                                {
                                    for (int i = 0; (i < page.NewRow.Length); i++)
                                    {
                                        object newValue = page.NewRow[i];
                                        if (newValue != null)
                                        {
                                            DataField field = page.Fields[i];
                                            if (field.IsPrimaryKey)
                                            {
                                                // resolve the value of the primary key
                                                ResolvePrimaryKey(args.Controller, fv.Name, value, newValue);
                                                value       = 0;
                                                fv.NewValue = newValue;
                                            }
                                            else
                                            {
                                                // inject a missing default value in the arguments
                                                FieldValue newFieldValue = null;
                                                if (values.TryGetValue(field.Name, out newFieldValue))
                                                {
                                                    if (!(newFieldValue.Modified))
                                                    {
                                                        newFieldValue.NewValue = newValue;
                                                        newFieldValue.Modified = true;
                                                    }
                                                }
                                                else
                                                {
                                                    List <FieldValue> newValues = new List <FieldValue>(args.Values);
                                                    newFieldValue = new FieldValue(field.Name, newValue);
                                                    newValues.Add(newFieldValue);
                                                    args.Values        = newValues.ToArray();
                                                    values[field.Name] = newFieldValue;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            // resolve the primary key after the command execution
                            if (value < 0)
                            {
                                _pk         = new FieldValue(fv.Name, value);
                                fv.NewValue = null;
                                fv.Modified = false;
                            }
                        }
                    }
                }
            }
            // resolve negative foreign keys
            if (_resolvedKeys.Count > 0)
            {
                XPathNodeIterator fkIterator = config.Select("/c:dataController/c:fields/c:field[c:items/@dataController]");
                while (fkIterator.MoveNext())
                {
                    FieldValue fv = null;
                    if (values.TryGetValue(fkIterator.Current.GetAttribute("name", String.Empty), out fv))
                    {
                        XPathNavigator itemsDataControllerNav = fkIterator.Current.SelectSingleNode("c:items/@dataController", config.Resolver);
                        object         resolvedKey            = null;
                        if (_resolvedKeys.TryGetValue(String.Format("{0}${1}", itemsDataControllerNav.Value, fv.NewValue), out resolvedKey))
                        {
                            fv.NewValue = resolvedKey;
                        }
                    }
                }
            }
        }
Beispiel #7
0
        // References

        private void WriteTypeReference(XPathNavigator reference, SyntaxWriter writer)
        {
            switch (reference.LocalName)
            {
            case "arrayOf":
                int rank = Convert.ToInt32(reference.GetAttribute("rank", String.Empty),
                                           CultureInfo.InvariantCulture);

                XPathNavigator element = reference.SelectSingleNode(typeExpression);
                WriteTypeReference(element, writer);
                writer.WriteString("[");

                for (int i = 1; i < rank; i++)
                {
                    writer.WriteString(",");
                }

                writer.WriteString("]");
                break;

            case "pointerTo":
                XPathNavigator pointee = reference.SelectSingleNode(typeExpression);
                WriteTypeReference(pointee, writer);
                writer.WriteString("*");
                break;

            case "referenceTo":
                XPathNavigator referee = reference.SelectSingleNode(typeExpression);
                WriteTypeReference(referee, writer);
                break;

            case "type":
                string id = reference.GetAttribute("api", String.Empty);

                XPathNavigator outerTypeReference = reference.SelectSingleNode(typeOuterTypeExpression);
                if (outerTypeReference != null)
                {
                    WriteTypeReference(outerTypeReference, writer);
                    writer.WriteString(".");
                }

                WriteNormalTypeReference(id, writer);
                XPathNodeIterator typeModifiers = reference.Select(typeModifiersExpression);
                while (typeModifiers.MoveNext())
                {
                    WriteTypeReference(typeModifiers.Current, writer);
                }
                break;

            case "template":
                string name = reference.GetAttribute("name", String.Empty);
                writer.WriteString(name);
                XPathNodeIterator modifiers = reference.Select(typeModifiersExpression);
                while (modifiers.MoveNext())
                {
                    WriteTypeReference(modifiers.Current, writer);
                }
                break;

            case "specialization":
                writer.WriteString("<");
                XPathNodeIterator arguments = reference.Select(specializationArgumentsExpression);
                while (arguments.MoveNext())
                {
                    if (arguments.CurrentPosition > 1)
                    {
                        writer.WriteString(", ");
                    }
                    WriteTypeReference(arguments.Current, writer);
                }
                writer.WriteString(">");
                break;
            }
        }
Beispiel #8
0
        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            XPathNavigator keywordsNode = configuration.SelectSingleNode("keywords");

            if (keywordsNode == null)
            {
                return;
            }

            string filespec = keywordsNode.GetAttribute("files", String.Empty);

            filespec = Environment.ExpandEnvironmentVariables(filespec);
            string keywordXPath = keywordsNode.GetAttribute("keyword", String.Empty);
            string topicXPath   = keywordsNode.GetAttribute("topic", String.Empty);

            if (String.IsNullOrEmpty(keywordXPath) || String.IsNullOrEmpty(topicXPath) || String.IsNullOrEmpty(filespec))
            {
                return;
            }

            xpathFromConfig = keywordXPath;

            string[] keywordFiles = null;
            if (File.Exists(filespec))
            {
                // we're loading a single file
                AddBKeywords(filespec, topicXPath, keywordXPath);
            }
            else
            {
                // must be loading a set of files
                if (Directory.Exists(filespec))
                {
                    // if they specified a directory, transform all the files in the directory
                    keywordFiles = Directory.GetFiles(filespec);
                }
                else
                {
                    // it's not a file or a directory, maybe it's a path with wildcards
                    string directoryPath = Path.GetDirectoryName(filespec);
                    string filePath      = Path.GetFileName(filespec);
                    keywordFiles = Directory.GetFiles(directoryPath, filePath);
                }
                foreach (string file in keywordFiles)
                {
                    // load targets from each file
                    AddBKeywords(file, topicXPath, keywordXPath);
                }
            }

            // set up the context
            // put in a default entry for ddue
            nsManager.AddNamespace("ddue", "http://ddue.schemas.microsoft.com/authoring/2003/6");
            // look for context nodes, which could override the default
            XPathNodeIterator contextNodes = configuration.Select("context");

            foreach (XPathNavigator contextNode in contextNodes)
            {
                string prefix = contextNode.GetAttribute("prefix", String.Empty);
                string uri    = contextNode.GetAttribute("name", String.Empty);
                nsManager.AddNamespace(prefix, uri);
            }


            // set up the index of source files
            XPathNodeIterator sourceNodes = configuration.Select("source");

            foreach (XPathNavigator sourceNode in sourceNodes)
            {
                string valueXPath = sourceNode.GetAttribute("value", String.Empty);
                string keyXPath   = sourceNode.GetAttribute("key", String.Empty);
                if (String.IsNullOrEmpty(valueXPath) || String.IsNullOrEmpty(keyXPath))
                {
                    WriteMessage(MessageLevel.Error, "@key and @value must be set in the 'source' node.");
                    return;
                }

                keyQuery   = XPathExpression.Compile(keyXPath);
                valueQuery = XPathExpression.Compile(valueXPath);

                // search the data directories for entries
                XPathNodeIterator dataNodes = sourceNode.Select("data");
                foreach (XPathNavigator dataNode in dataNodes)
                {
                    string dataFiles = dataNode.GetAttribute("files", String.Empty);
                    dataFiles = Environment.ExpandEnvironmentVariables(dataFiles);
                    if ((dataFiles == null) || (dataFiles.Length == 0))
                    {
                        throw new ConfigurationErrorsException("When instantiating a CopyFromDirectory component, you must specify a directory path using the files attribute.");
                    }
                    WriteMessage(MessageLevel.Info, "Searching for files that match '{0}'.", dataFiles);
                    int fileCount = ParseDocuments(dataFiles);
                    WriteMessage(MessageLevel.Info, "Found {0} files.", fileCount);
                }
                WriteMessage(MessageLevel.Info, "Indexed {0} elements.", index.Count);
            }

            // get the copy commands
            XPathNodeIterator copyNodes = configuration.Select("copy");

            foreach (XPathNavigator copyNode in copyNodes)
            {
                string sourceXPath = copyNode.GetAttribute("source", String.Empty);
                string targetXPath = copyNode.GetAttribute("target", String.Empty);
                if (String.IsNullOrEmpty(sourceXPath) || String.IsNullOrEmpty(targetXPath))
                {
                    WriteMessage(MessageLevel.Error, "@source and @target must be set in the 'copy' node.");
                    return;
                }

                copySets.Add(new CopySet(sourceXPath, targetXPath, nsManager));
            }
        }
 public Action(XPathNavigator action, IXmlNamespaceResolver resolver)
 {
     this._id                      = action.GetAttribute("id", String.Empty);
     this._commandName             = action.GetAttribute("commandName", String.Empty);
     this._commandArgument         = action.GetAttribute("commandArgument", String.Empty);
     this._headerText              = action.GetAttribute("headerText", String.Empty);
     this._description             = action.GetAttribute("description", String.Empty);
     this._cssClass                = action.GetAttribute("cssClass", String.Empty);
     this._confirmation            = action.GetAttribute("confirmation", String.Empty);
     this._notify                  = action.GetAttribute("notify", String.Empty);
     this._whenLastCommandName     = action.GetAttribute("whenLastCommandName", String.Empty);
     this._whenLastCommandArgument = action.GetAttribute("whenLastCommandArgument", String.Empty);
     this._causesValidation        = !((action.GetAttribute("causesValidation", String.Empty) == "false"));
     this._whenKeySelected         = (action.GetAttribute("whenKeySelected", String.Empty) == "true");
     this._whenTag                 = action.GetAttribute("whenTag", String.Empty);
     this._whenHRef                = action.GetAttribute("whenHRef", String.Empty);
     this._whenView                = action.GetAttribute("whenView", String.Empty);
     this._whenClientScript        = action.GetAttribute("whenClientScript", String.Empty);
     this._key                     = action.GetAttribute("key", String.Empty);
 }
Beispiel #10
0
        private void ObjectElementUsageForClassStruct(XPathNavigator reflection, SyntaxWriter writer)
        {
            string typeName    = (string)reflection.Evaluate(apiNameExpression);
            bool   isGeneric   = (bool)reflection.Evaluate(apiIsGenericExpression);
            string xamlBlockId = System.Enum.GetName(typeof(XamlHeadingID), XamlHeadingID.xamlObjectElementUsageHeading);

            string contentPropertyId = (string)reflection.Evaluate(contentPropertyIdExpression);

            if (String.IsNullOrEmpty(contentPropertyId))
            {
                contentPropertyId = (string)reflection.Evaluate(ancestorContentPropertyIdExpression);
            }

            // start the syntax block
            writer.WriteStartSubBlock(xamlBlockId);

            writer.WriteString("<");

            if (isGeneric)
            {
                writer.WriteIdentifier(typeName);

                // for generic types show the type arguments
                XPathNodeIterator templates = (XPathNodeIterator)reflection.Evaluate(apiTemplatesExpression);

                if (templates.Count > 0)
                {
                    writer.WriteString(" x:TypeArguments=\"");

                    while (templates.MoveNext())
                    {
                        XPathNavigator template = templates.Current;
                        string         name     = template.GetAttribute("name", String.Empty);
                        writer.WriteString(name);

                        if (templates.CurrentPosition < templates.Count)
                        {
                            writer.WriteString(",");
                        }
                    }

                    writer.WriteString("\"");
                }
            }
            else
            {
                // for non-generic types just show the name
                writer.WriteIdentifier(typeName);
            }

            if (String.IsNullOrEmpty(contentPropertyId))
            {
                writer.WriteString(" .../>");
            }
            else
            {
                // close the start tag
                writer.WriteString(">");

                // the inner xml of the Object Element syntax for a type with a content property
                // is a link to the content property
                writer.WriteLine();
                writer.WriteString("  ");
                writer.WriteReferenceLink(contentPropertyId);
                writer.WriteLine();

                // write the end tag
                writer.WriteString("</");
                writer.WriteIdentifier(typeName);
                writer.WriteString(">");
            }

            // end the sub block
            writer.WriteEndSubBlock();
        }
    private static HashSet <string> ParsePluginsXML(string platform, List <string> in_pluginFiles)
    {
        HashSet <string> newDlls = new HashSet <string>();

        foreach (string pluginFile in in_pluginFiles)
        {
            if (!File.Exists(pluginFile))
            {
                continue;
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(pluginFile);
                XPathNavigator Navigator = doc.CreateNavigator();

                XPathNavigator pluginInfoNode = Navigator.SelectSingleNode("//PluginInfo");
                string         boolMotion     = pluginInfoNode.GetAttribute("Motion", "");

                XPathNodeIterator it = Navigator.Select("//Plugin");

                if (boolMotion == "true")
                {
                    newDlls.Add("AkMotion");
                }

                foreach (XPathNavigator node in it)
                {
                    uint pid = UInt32.Parse(node.GetAttribute("ID", ""));
                    if (pid == 0)
                    {
                        continue;
                    }

                    string dll = string.Empty;

                    if (platform == "Switch")
                    {
                        if ((PluginID)pid == PluginID.WwiseMeter)
                        {
                            dll = "AkMeter";
                        }
                    }
                    else if (builtInPluginIDs.Contains((PluginID)pid))
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(dll))
                    {
                        dll = node.GetAttribute("DLL", "");
                    }

                    newDlls.Add(dll);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("Wwise: " + pluginFile + " could not be parsed. " + ex.Message);
            }
        }

        return(newDlls);
    }
Beispiel #12
0
        private static string[] WriteTableNames(string xmlId, string def)
        {
            Trace.WriteLine("auto referenceAddress;");

            string ecuid      = null;
            string memmodel   = null;
            int    tableCount = 0;
            string datatype   = null;
            bool   ecu16bit   = false;
            int    dtaddr     = 0;
            string cpu        = "32";

            string rombase = GetRomBase(xmlId, def);

            string[] roms = new string[2] {
                rombase, xmlId
            };

            using (Stream stream = File.OpenRead(def))
            {
                XPathDocument  doc = new XPathDocument(stream);
                XPathNavigator nav = doc.CreateNavigator();
                foreach (string id in roms)
                {
                    tableCount = 0;
                    names.Clear();
                    if (id.Contains("BASE"))
                    {
                        continue;
                    }
                    else if (id.Equals(rombase))
                    {
                        Trace.WriteLine("Warning(\"Marking tables using addresses from inherited base ROM: " +
                                        id.ToUpper() + "\");");
                    }
                    string            path = "/roms/rom/romid[xmlid='" + id + "']";
                    XPathNodeIterator iter = nav.Select(path);
                    iter.MoveNext();
                    nav = iter.Current;
                    nav.MoveToChild(XPathNodeType.Element);

                    while (nav.MoveToNext())
                    {
                        if (nav.Name == "ecuid")
                        {
                            ecuid = nav.InnerXml;
                        }
                        if (nav.Name == "memmodel")
                        {
                            memmodel = nav.InnerXml;
                            break;
                        }
                    }

                    if (string.IsNullOrEmpty(ecuid))
                    {
                        Trace.TraceWarning("Could not find definition for " + id);
                        return(null);
                    }
                    if (memmodel.Contains("68HC"))
                    {
                        ecu16bit = true;
                        cpu      = "16";
                    }

                    nav.MoveToParent();
                    while (nav.MoveToNext())
                    {
                        if (nav.Name == "table")
                        {
                            string name           = nav.GetAttribute("name", "");
                            string storageAddress = nav.GetAttribute("storageaddress", "");

                            name = ConvertName(name);
                            UpdateTableList(name, storageAddress);
                            if (ecu16bit)
                            {
                                datatype = ConvertName("Table_" + name);
                                dtaddr   = Convert.ToInt32(storageAddress, 16);
                                dtaddr   = dtaddr - 1;
                            }

                            List <string> axes = new List <string>();
                            if (nav.HasChildren)
                            {
                                nav.MoveToChild(XPathNodeType.Element);

                                do
                                {
                                    string axis = nav.GetAttribute("type", "");
                                    axes.Add(axis);
                                    string axisAddress = nav.GetAttribute("storageaddress", "");

                                    axis = ConvertName(name + "_" + axis);
                                    UpdateTableList(axis, axisAddress);
                                } while (nav.MoveToNext());

                                if (axes.Count == 2 &&
                                    (axes[0].ToUpper() == "X AXIS" && axes[1].ToUpper() == "Y AXIS") &&
                                    !ecu16bit)
                                {
                                    string tableName = ConvertName("Table_" + name);
                                    UpdateTableList(tableName, "2axis");
                                }
                                else if (axes.Count == 1 &&
                                         axes[0].ToUpper() == "Y AXIS" &&
                                         !ecu16bit)
                                {
                                    string tableName = ConvertName("Table_" + name);
                                    UpdateTableList(tableName, "1axis");
                                }
                                else if (axes.Count > 0 && ecu16bit && axes[0].ToUpper().Contains("AXIS"))
                                {
                                    string dataTypeAddr = "0x" + dtaddr.ToString("X");
                                    UpdateTableList(datatype, dataTypeAddr);
                                }
                                nav.MoveToParent();
                            }
                            tableCount++;
                        }
                    }
                    if (tableCount < 1)
                    {
                        Trace.WriteLine("// No tables found specifically for ROM " + id + ", used inherited ROM");
                    }
                }
                WriteIdcTableNames();
            }
            string[] results = new string[2] {
                ecuid, cpu
            };
            return(results);
        }
Beispiel #13
0
        /// <summary>
        /// Loads this <see cref="BlogMLAttachment"/> using the supplied <see cref="XPathNavigator"/>.
        /// </summary>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <returns><b>true</b> if the <see cref="BlogMLAttachment"/> was initialized using the supplied <paramref name="source"/>, otherwise <b>false</b>.</returns>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="BlogMLAttachment"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        public bool Load(XPathNavigator source)
        {
            bool wasLoaded = false;

            Guard.ArgumentNotNull(source, "source");
            if (source.HasAttributes)
            {
                string embeddedAttribute    = source.GetAttribute("embedded", String.Empty);
                string mimeTypeAttribute    = source.GetAttribute("mime-type", String.Empty);
                string sizeAttribute        = source.GetAttribute("size", String.Empty);
                string externalUriAttribute = source.GetAttribute("external-uri", String.Empty);
                string urlAttribute         = source.GetAttribute("url", String.Empty);

                if (!String.IsNullOrEmpty(embeddedAttribute))
                {
                    bool isEmbedded;
                    if (Boolean.TryParse(embeddedAttribute, out isEmbedded))
                    {
                        this.IsEmbedded = isEmbedded;
                        wasLoaded       = true;
                    }
                }

                if (!String.IsNullOrEmpty(mimeTypeAttribute))
                {
                    this.MimeType = mimeTypeAttribute;
                    wasLoaded     = true;
                }

                if (!String.IsNullOrEmpty(sizeAttribute))
                {
                    long size;
                    if (Int64.TryParse(sizeAttribute, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out size))
                    {
                        this.Size = size;
                        wasLoaded = true;
                    }
                }

                if (!String.IsNullOrEmpty(externalUriAttribute))
                {
                    Uri externalUri;
                    if (Uri.TryCreate(externalUriAttribute, UriKind.RelativeOrAbsolute, out externalUri))
                    {
                        this.ExternalUri = externalUri;
                        wasLoaded        = true;
                    }
                }

                if (!String.IsNullOrEmpty(urlAttribute))
                {
                    Uri url;
                    if (Uri.TryCreate(urlAttribute, UriKind.RelativeOrAbsolute, out url))
                    {
                        this.Url  = url;
                        wasLoaded = true;
                    }
                }
            }

            if (!String.IsNullOrEmpty(source.Value))
            {
                this.Content = source.Value;
                wasLoaded    = true;
            }

            return(wasLoaded);
        }
Beispiel #14
0
        public static int Main(string[] args)
        {
            // write banner
            ConsoleApplication.WriteBanner();

            // specify options
            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, MRefBuilder.config is used", "configFilePath"));
            options.Add(new ListOption("dep", "Speficy assemblies to load for dependencies.", "dependencyAssembly"));
            // options.Add( new BooleanOption("namespaces", "Control whether information on namespaces in provided.") );
            options.Add(new BooleanOption("internal", "Specify whether to document internal as well as externally exposed APIs."));

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("MRefBuilder [options] assemblies");
                options.WriteOptionSummary(Console.Out);
                return(0);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count < 1)
            {
                Console.WriteLine("Specify at least one assembly to reflect.");
                return(1);
            }

            // load the configuration file
            XPathDocument config;
            string        configDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string        configFile      = Path.Combine(configDirectory, "MRefBuilder.config");

            if (results.Options["config"].IsPresent)
            {
                configFile      = (string)results.Options["config"].Value;
                configDirectory = Path.GetDirectoryName(configFile);
            }
            try {
                config = new XPathDocument(configFile);
            } catch (IOException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to read the configuration file '{0}'. The error message is: {1}", configFile, e.Message));
                return(1);
            } catch (UnauthorizedAccessException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to read the configuration file '{0}'. The error message is: {1}", configFile, e.Message));
                return(1);
            } catch (XmlException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The configuration file '{0}' is not well-formed. The error message is: {1}", configFile, e.Message));
                return(1);
            }

            // adjust the target platform
            XPathNodeIterator platformNodes = config.CreateNavigator().Select("/configuration/dduetools/platform");

            if (platformNodes.MoveNext())
            {
                XPathNavigator platformNode = platformNodes.Current;
                string         version      = platformNode.GetAttribute("version", String.Empty);
                string         path         = platformNode.GetAttribute("path", String.Empty);
                path = Environment.ExpandEnvironmentVariables(path);
                if (!Directory.Exists(path))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The specifed target platform directory '{0}' does not exist.", path));
                    return(1);
                }
                if (version == "2.0")
                {
                    TargetPlatform.SetToV2(path);
                }
                else if (version == "1.1")
                {
                    TargetPlatform.SetToV1_1(path);
                }
                else if (version == "1.0")
                {
                    TargetPlatform.SetToV1(path);
                }
                else
                {
                    Console.WriteLine("Unknown target platform version '{0}'.", version);
                    return(1);
                }
            }

            // create a namer
            ApiNamer       namer     = new OrcasNamer();
            XPathNavigator namerNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/namer");

            if (namerNode != null)
            {
                string assemblyPath = namerNode.GetAttribute("assembly", String.Empty);
                string typeName     = namerNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    namer = (ApiNamer)assembly.CreateInstance(typeName);

                    if (namer == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    }
                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (BadImageFormatException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The component assembly '{0}' is not a valid managed assembly.", assemblyPath));
                    return(1);
                } catch (TypeLoadException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (MissingMethodException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (TargetInvocationException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the component assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                    return(1);
                } catch (InvalidCastException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the component assembly '{1}' is not a component type.", typeName, assemblyPath));
                    return(1);
                }
            }

            // create a resolver
            AssemblyResolver resolver     = new AssemblyResolver();
            XPathNavigator   resolverNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/resolver");

            if (resolverNode != null)
            {
                string assemblyPath = resolverNode.GetAttribute("assembly", String.Empty);
                string typeName     = resolverNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    resolver = (AssemblyResolver)assembly.CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[1] {
                        resolverNode
                    }, null, null);

                    if (resolver == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    }
                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (BadImageFormatException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The component assembly '{0}' is not a valid managed assembly.", assemblyPath));
                    return(1);
                } catch (TypeLoadException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (MissingMethodException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (TargetInvocationException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the component assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                    return(1);
                } catch (InvalidCastException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the component assembly '{1}' is not a component type.", typeName, assemblyPath));
                    return(1);
                }
            }
            resolver.UnresolvedAssemblyReference += new EventHandler <AssemblyReferenceEventArgs>(UnresolvedAssemblyReferenceHandler);

            // get a textwriter for output
            TextWriter output = Console.Out;

            if (results.Options["out"].IsPresent)
            {
                string file = (string)results.Options["out"].Value;
                try {
                    output = new StreamWriter(file, false, Encoding.UTF8);
                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create an output file. The error message is: {0}", e.Message));
                    return(1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create an output file. The error message is: {0}", e.Message));
                    return(1);
                }
            }


            // dependency directory
            string[] dependencies = new string[0];
            if (results.Options["dep"].IsPresent)
            {
                dependencies = (string[])results.Options["dep"].Value;
            }


            try {
                // create a builder
                ManagedReflectionWriter builder = new ManagedReflectionWriter(output, namer);

                // specify the resolver for the builder
                builder.Resolver = resolver;

                // builder.ApiFilter = new ExternalDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));

                // specify the filter for the builder

                if (results.Options["internal"].IsPresent && (bool)results.Options["internal"].Value)
                {
                    builder.ApiFilter = new AllDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));
                }
                else
                {
                    builder.ApiFilter = new ExternalDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));
                }

                // register add-ins to the builder

                XPathNodeIterator addinNodes = config.CreateNavigator().Select("/configuration/dduetools/addins/addin");
                foreach (XPathNavigator addinNode in addinNodes)
                {
                    string assemblyPath = addinNode.GetAttribute("assembly", String.Empty);
                    string typeName     = addinNode.GetAttribute("type", String.Empty);

                    assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                    if (!Path.IsPathRooted(assemblyPath))
                    {
                        assemblyPath = Path.Combine(configDirectory, assemblyPath);
                    }

                    try {
                        Assembly         assembly = Assembly.LoadFrom(assemblyPath);
                        MRefBuilderAddIn addin    = (MRefBuilderAddIn)assembly.CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[2] {
                            builder, addinNode
                        }, null, null);

                        if (namer == null)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the addin assembly '{1}'.", typeName, assemblyPath));
                            return(1);
                        }
                    } catch (IOException e) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the addin assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                        return(1);
                    } catch (BadImageFormatException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The addin assembly '{0}' is not a valid managed assembly.", assemblyPath));
                        return(1);
                    } catch (TypeLoadException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the addin assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    } catch (MissingMethodException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type '{0}' in the addin assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    } catch (TargetInvocationException e) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the addin assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                        return(1);
                    } catch (InvalidCastException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the addin assembly '{1}' is not an MRefBuilderAddIn type.", typeName, assemblyPath));
                        return(1);
                    }
                }

                try {
                    // add a handler for unresolved assembly references
                    //builder.UnresolvedModuleHandler = new System.Compiler.Module.AssemblyReferenceResolver(AssemblyNotFound);

                    // load dependent bits
                    foreach (string dependency in dependencies)
                    {
                        try {
                            builder.LoadAccessoryAssemblies(dependency);
                        } catch (IOException e) {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while loading dependency assemblies. The error message is: {0}", e.Message));
                            return(1);
                        }
                    }

                    // parse the bits
                    foreach (string dllPath in results.UnusedArguments)
                    {
                        try {
                            builder.LoadAssemblies(dllPath);
                        } catch (IOException e) {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while loading assemblies for reflection. The error message is: {0}", e.Message));
                            return(1);
                        }
                    }

                    ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Loaded {0} assemblies for reflection and {1} dependency assemblies.", builder.Assemblies.Length, builder.AccessoryAssemblies.Length));

                    // register callbacks

                    //builder.RegisterStartTagCallback("apis", new MRefBuilderCallback(startTestCallback));

                    //MRefBuilderAddIn addin = new XamlAttachedMembersAddIn(builder, null);

                    builder.VisitApis();

                    ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Wrote information on {0} namespaces, {1} types, and {2} members", builder.Namespaces.Length, builder.Types.Length, builder.Members.Length));
                } finally {
                    builder.Dispose();
                }
            } finally {
                // output.Close();
            }

            return(0);
        }
Beispiel #15
0
        //=====================================================================

        /// <summary>
        /// Create a binding redirect settings instance from an XPath navigator
        /// containing the settings.
        /// </summary>
        /// <param name="pathProvider">The base path provider object</param>
        /// <param name="navigator">The XPath navigator from which to
        /// obtain the settings.</param>
        /// <returns>A <see cref="BindingRedirectSettings"/> object containing
        /// the settings from the XPath navigator.</returns>
        /// <remarks>It should contain an element called <c>dependentAssembly</c>
        /// with a configFile attribute or a nested <c>assemblyIdentity</c> and
        /// <c>bindingRedirect</c> element that define the settings.</remarks>
        public static BindingRedirectSettings FromXPathNavigator(
            IBasePathProvider pathProvider, XPathNavigator navigator)
        {
            BindingRedirectSettings brs = new BindingRedirectSettings(pathProvider);
            XPathNavigator          nav;
            string value;

            string[] versions;
            Version  tempVersion;

            if (navigator != null)
            {
                value = navigator.GetAttribute("importFrom", String.Empty).Trim();

                if (value.Length != 0)
                {
                    brs.ConfigurationFile = new FilePath(value, pathProvider);
                }
                else
                {
                    nav = navigator.SelectSingleNode("assemblyIdentity");

                    if (nav != null)
                    {
                        brs.AssemblyName = nav.GetAttribute("name",
                                                            String.Empty).Trim();
                        brs.PublicKeyToken = nav.GetAttribute("publicKeyToken",
                                                              String.Empty).Trim();
                        brs.Culture = nav.GetAttribute("culture",
                                                       String.Empty).Trim();
                    }

                    nav = navigator.SelectSingleNode("bindingRedirect");

                    if (nav != null)
                    {
                        value = nav.GetAttribute("newVersion", String.Empty).Trim();

                        if (value.Length != 0)
                        {
                            brs.NewVersion = new Version(value);
                        }

                        value    = nav.GetAttribute("oldVersion", String.Empty).Trim();
                        versions = value.Split('-');

                        if (versions.Length == 2)
                        {
                            if (versions[0].Trim().Length != 0)
                            {
                                brs.OldVersion = new Version(versions[0]);
                            }

                            if (versions[1].Trim().Length != 0)
                            {
                                brs.OldVersionTo = new Version(versions[1]);
                            }

                            if (brs.OldVersion > brs.oldVersionTo)
                            {
                                tempVersion      = brs.OldVersion;
                                brs.OldVersion   = brs.oldVersionTo;
                                brs.oldVersionTo = tempVersion;
                            }
                        }
                        else
                        {
                            brs.OldVersion = new Version(versions[0]);
                        }
                    }
                }
            }

            return(brs);
        }
Beispiel #16
0
 public override void LoadAdditionals(XPathNavigator reader)
 {
     Size = (MemoryVariableSize)Enum.Parse(typeof(MemoryVariableSize), reader.GetAttribute("Size", reader.NamespaceURI));
 }
Beispiel #17
0
        //============================================================
        //	PUBLIC METHODS
        //============================================================
        #region Fill(AtomCategoryDocument resource)
        /// <summary>
        /// Modifies the <see cref="AtomCategoryDocument"/> to match the data source.
        /// </summary>
        /// <param name="resource">The <see cref="AtomCategoryDocument"/> to be filled.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="resource"/> is a null reference (Nothing in Visual Basic).</exception>
        public void Fill(AtomCategoryDocument resource)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(resource, "resource");

            //------------------------------------------------------------
            //	Create namespace resolver
            //------------------------------------------------------------
            XmlNamespaceManager manager = AtomUtility.CreateNamespaceManager(this.Navigator.NameTable);

            //------------------------------------------------------------
            //	Attempt to fill syndication resource
            //------------------------------------------------------------
            XPathNavigator documentNavigator = this.Navigator.SelectSingleNode("app:categories", manager);

            if (documentNavigator != null)
            {
                AtomUtility.FillCommonObjectAttributes(resource, documentNavigator);

                if (documentNavigator.HasChildren)
                {
                    if (documentNavigator.HasAttributes)
                    {
                        string fixedAttribute  = documentNavigator.GetAttribute("fixed", String.Empty);
                        string schemeAttribute = documentNavigator.GetAttribute("scheme", String.Empty);
                        string hrefAttribute   = documentNavigator.GetAttribute("href", String.Empty);

                        if (!String.IsNullOrEmpty(fixedAttribute))
                        {
                            if (String.Compare(fixedAttribute, "yes", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                resource.IsFixed = true;
                            }
                            else if (String.Compare(fixedAttribute, "no", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                resource.IsFixed = false;
                            }
                        }

                        if (!String.IsNullOrEmpty(schemeAttribute))
                        {
                            Uri scheme;
                            if (Uri.TryCreate(schemeAttribute, UriKind.RelativeOrAbsolute, out scheme))
                            {
                                resource.Scheme = scheme;
                            }
                        }

                        if (!String.IsNullOrEmpty(hrefAttribute))
                        {
                            Uri href;
                            if (Uri.TryCreate(hrefAttribute, UriKind.RelativeOrAbsolute, out href))
                            {
                                resource.Uri = href;
                            }
                        }
                    }

                    if (documentNavigator.HasChildren)
                    {
                        XPathNodeIterator categoryIterator = documentNavigator.Select("atom:category", manager);

                        if (categoryIterator != null && categoryIterator.Count > 0)
                        {
                            while (categoryIterator.MoveNext())
                            {
                                AtomCategory category = new AtomCategory();
                                if (category.Load(categoryIterator.Current, this.Settings))
                                {
                                    resource.AddCategory(category);
                                }
                            }
                        }
                    }
                }

                SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(documentNavigator, this.Settings);
                adapter.Fill(resource, manager);
            }
        }
        //============================================================
        //	PUBLIC METHODS
        //============================================================
        #region Fill(BlogMLDocument resource)
        /// <summary>
        /// Modifies the <see cref="BlogMLDocument"/> to match the data source.
        /// </summary>
        /// <param name="resource">The <see cref="BlogMLDocument"/> to be filled.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="resource"/> is a null reference (Nothing in Visual Basic).</exception>
        public void Fill(BlogMLDocument resource)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(resource, "resource");

            //------------------------------------------------------------
            //	Create namespace resolver
            //------------------------------------------------------------
            XmlNamespaceManager manager = BlogMLUtility.CreateNamespaceManager(this.Navigator.NameTable);

            //------------------------------------------------------------
            //	Attempt to fill syndication resource
            //------------------------------------------------------------
            XPathNavigator blogNavigator = this.Navigator.SelectSingleNode("blog:blog", manager);

            if (blogNavigator != null)
            {
                if (blogNavigator.HasAttributes)
                {
                    string dateCreatedAttribute = blogNavigator.GetAttribute("date-created", String.Empty);
                    string rootUrlAttribute     = blogNavigator.GetAttribute("root-url", String.Empty);

                    if (!String.IsNullOrEmpty(dateCreatedAttribute))
                    {
                        DateTime createdOn;
                        if (SyndicationDateTimeUtility.TryParseRfc3339DateTime(dateCreatedAttribute, out createdOn))
                        {
                            resource.GeneratedOn = createdOn;
                        }
                    }

                    if (!String.IsNullOrEmpty(rootUrlAttribute))
                    {
                        Uri rootUrl;
                        if (Uri.TryCreate(rootUrlAttribute, UriKind.RelativeOrAbsolute, out rootUrl))
                        {
                            resource.RootUrl = rootUrl;
                        }
                    }
                }

                if (blogNavigator.HasChildren)
                {
                    XPathNavigator titleNavigator    = blogNavigator.SelectSingleNode("blog:title", manager);
                    XPathNavigator subtitleNavigator = blogNavigator.SelectSingleNode("blog:sub-title", manager);

                    if (titleNavigator != null)
                    {
                        BlogMLTextConstruct title = new BlogMLTextConstruct();
                        if (title.Load(titleNavigator))
                        {
                            resource.Title = title;
                        }
                    }

                    if (subtitleNavigator != null)
                    {
                        BlogMLTextConstruct subtitle = new BlogMLTextConstruct();
                        if (subtitle.Load(subtitleNavigator))
                        {
                            resource.Subtitle = subtitle;
                        }
                    }

                    BlogML20SyndicationResourceAdapter.FillDocumentCollections(resource, blogNavigator, manager, this.Settings);
                }

                SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(blogNavigator, this.Settings);
                adapter.Fill(resource, manager);
            }
        }
Beispiel #19
0
        private static void WriteStandardParameters(string target, string ecuid, uint ssmBase, string cpu, string loggerdef)
        {
            Trace.WriteLine("auto addr;");

            if (target == "ecu" | target == "ECU")
            {
                target = "2";
            }
            if (target == "tcu" | target == "TCU")
            {
                target = "1";
            }

            string ptrName  = "PtrSsmGet_";
            string funcName = "SsmGet_";

            if (cpu.Equals("16"))
            {
                ptrName  = "PtrSsm_";
                funcName = "Ssm_";
                Trace.WriteLine("auto opAddr, seg;");
                Trace.WriteLine("if (SegByName(\"DATA\") != BADADDR) seg = 1;");
                Trace.WriteLine("");
            }

            using (Stream stream = File.OpenRead(loggerdef))
            {
                XPathDocument     doc  = new XPathDocument(stream);
                XPathNavigator    nav  = doc.CreateNavigator();
                string            path = "/logger/protocols/protocol[@id='SSM']/parameters/parameter";
                XPathNodeIterator iter = nav.Select(path);
                string            id   = "";
                while (iter.MoveNext())
                {
                    XPathNavigator navigator = iter.Current;
                    if (navigator.GetAttribute("target", "") == target)
                    {
                        continue;
                    }
                    string name = navigator.GetAttribute("name", "");
                    id = navigator.GetAttribute("id", "");
                    if (cpu.Equals("16") && id.Equals("P89"))
                    {
                        continue;
                    }
                    name = name + "_" + id.Trim();
                    string pointerName  = ConvertName(ptrName + name);
                    string functionName = ConvertName(funcName + name);

                    if (!navigator.MoveToChild("address", ""))
                    {
                        continue;
                    }

                    string addressString = iter.Current.InnerXml;
                    addressString = addressString.Substring(2);

                    uint address = uint.Parse(addressString, System.Globalization.NumberStyles.HexNumber);
                    if (cpu.Equals("16") && address > 0x18F)    // addresses over this will overrun DTC structure
                    {
                        continue;
                    }
                    address       = address * 4;
                    address       = address + ssmBase;
                    addressString = "0x" + address.ToString("X8");

                    Trace.WriteLine(string.Format("MakeUnknown({0}, 4, DOUNK_SIMPLE);", addressString));
                    Trace.WriteLine(string.Format("MakeDword({0});", addressString));
                    MakeName(addressString, pointerName);

                    string getAddress = string.Format("addr = Dword({0});", addressString);
                    Trace.WriteLine(getAddress);
                    MakeName("addr", functionName);

                    if (cpu.Equals("16"))
                    {
                        string length = "1";
                        length = navigator.GetAttribute("length", "");
                        FormatData("addr", length);
                        string        fGetter = ConvertName("SsmGet_" + name);
                        StringBuilder builder = new StringBuilder();
                        builder.AppendLine("opAddr = FindImmediate(0, 0x21, (addr - 0x20000));");
                        builder.AppendLine("addr = GetFunctionAttr(opAddr, FUNCATTR_START);");
                        builder.AppendLine("if (addr != BADADDR)");
                        builder.AppendLine("{");
                        builder.AppendLine("    if (seg)");
                        builder.AppendLine("    {");
                        builder.AppendLine("        OpAlt(opAddr, 0, \"\");");
                        builder.AppendLine("        OpOff(MK_FP(\"ROM\", opAddr), 0, 0x20000);");
                        builder.AppendLine("    }");
                        builder.AppendLine("    add_dref(opAddr, Dword(" + addressString + "), dr_I);");
                        string command = string.Format("    MakeNameEx(addr, \"{0}\", SN_CHECK);", fGetter);
                        builder.AppendLine(command);
                        builder.AppendLine("}");
                        builder.AppendLine("else");
                        builder.AppendLine("{");
                        builder.AppendLine("    Message(\"No reference to " + name + "\\n\");");
                        builder.AppendLine("}");
                        Trace.Write(builder.ToString());
                    }
                    Trace.WriteLine("");
                }
                // now let's print the switch references
                // Name format: Switches_b7_b6_b5_b4_b3_b2_b1_b0
                IDictionary <string, Array> switchList = new Dictionary <string, Array>();
                path = "/logger/protocols/protocol[@id='SSM']/switches/switch";
                iter = nav.Select(path);
                string bit = "";
                while (iter.MoveNext())
                {
                    XPathNavigator navigator = iter.Current;
                    if (navigator.GetAttribute("target", "") == target)
                    {
                        continue;
                    }
                    id = navigator.GetAttribute("id", "");
                    id = id.Replace("S", "");
                    string addr = navigator.GetAttribute("byte", "");
                    addr = addr.Substring(2);
                    bit  = navigator.GetAttribute("bit", "");
                    Array values;
                    if (!switchList.TryGetValue(addr, out values))
                    {
                        string[] temp = new string[8] {
                            "x", "x", "x", "x", "x", "x", "x", "x"
                        };
                        switchList.Add(addr, temp);
                    }
                    if (switchList.TryGetValue(addr, out values))
                    {
                        uint i = uint.Parse(bit, System.Globalization.NumberStyles.HexNumber);
                        values.SetValue(id.Trim(), i);
                        Array.Copy(values, switchList[addr], values.Length);
                    }
                }
                PrintSwitches(switchList, ssmBase, cpu);
            }
        }
Beispiel #20
0
 /// <summary>
 /// See <see cref="XPathNavigator.GetAttribute"/>.
 /// </summary>
 public override string GetAttribute(string localName, string namespaceURI)
 {
     return(AtRoot ? String.Empty : _navigator.GetAttribute(localName, namespaceURI));
 }
Beispiel #21
0
 /// <include file='doc\XPathNavigator.uex' path='docs/doc[@for="XPathNavigator.GetAttribute"]/*' />
 public override string GetAttribute(string localName, string namespaceURI)
 {
     return(_xn.GetAttribute(localName, namespaceURI));
 }
Beispiel #22
0
 public static string GetAttributeValue(XPathNavigator nav, string AttributeName)
 {
     return(nav.GetAttribute(AttributeName, ""));
 }
Beispiel #23
0
    // Set soundbank-related bool settings in the wproj file.
    public static bool EnableBoolSoundbankSettingInWproj(string SettingName, string WwiseProjectPath)
    {
        try
        {
            if (WwiseProjectPath.Length == 0)
            {
                //  The setup should not fail if there is no wproj file set. Silently succeed.
                return(true);
            }

            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.Load(WwiseProjectPath);
            XPathNavigator Navigator = doc.CreateNavigator();

            // Navigate the wproj file (XML format) to where our setting should be
            string          pathInXml  = String.Format("/WwiseDocument/ProjectInfo/Project/PropertyList/Property[@Name='{0}']", SettingName);
            XPathExpression expression = XPathExpression.Compile(pathInXml);
            XPathNavigator  node       = Navigator.SelectSingleNode(expression);
            if (node == null)
            {
                // Setting isn't in the wproj, add it
                // Navigate to the SoundBankHeaderFilePath property (it is always there)
                expression = XPathExpression.Compile("/WwiseDocument/ProjectInfo/Project/PropertyList/Property[@Name='SoundBankHeaderFilePath']");
                node       = Navigator.SelectSingleNode(expression);
                if (node == null)
                {
                    // SoundBankHeaderFilePath not in wproj, invalid wproj file
                    UnityEngine.Debug.LogError("Could not find SoundBankHeaderFilePath property in Wwise project file. File is invalid.");
                    return(false);
                }

                // Add the setting right above SoundBankHeaderFilePath
                string propertyToInsert = string.Format("<Property Name=\"{0}\" Type=\"bool\" Value=\"True\"/>", SettingName);
                node.InsertBefore(propertyToInsert);
            }
            else
            {
                // Value is present, we simply have to modify it.
                if (node.GetAttribute("Value", "") == "False")
                {
                    // Modify the value to true
                    if (!node.MoveToAttribute("Value", ""))
                    {
                        return(false);
                    }

                    node.SetValue("True");
                }
                else
                {
                    // Parameter already set, nothing to do!
                    return(true);
                }
            }

            doc.Save(WwiseProjectPath);
        }
        catch (Exception)
        {
            return(false);
        }

        return(true);
    }
Beispiel #24
0
        /// <inheritdoc />
        public override void WritePropertySyntax(XPathNavigator reflection, SyntaxWriter writer)
        {
            bool              isSettable         = (bool)reflection.Evaluate(apiIsWritePropertyExpression);
            bool              isSetterPublic     = (bool)reflection.Evaluate(apiIsSetterPublicExpression);
            bool              isAbstract         = (bool)reflection.Evaluate(apiIsAbstractProcedureExpression);
            string            propertyVisibility = (string)reflection.Evaluate(apiVisibilityExpression);
            XPathNodeIterator parameters         = reflection.Select(apiParametersExpression);

            XPathNavigator returnType                 = reflection.SelectSingleNode(apiReturnTypeExpression);
            bool           notWriteableReturnType     = (bool)returnType.Evaluate(noSettablePropertiesExpression);
            string         returnTypeId               = returnType.GetAttribute("api", string.Empty);
            string         returnTypeSubgroup         = (string)returnType.Evaluate(apiSubgroupExpression);
            bool           returnTypeIsAbstract       = (bool)returnType.Evaluate(apiIsAbstractTypeExpression);
            bool           returnTypeIsReadonlyStruct = (returnTypeSubgroup == "structure" && notWriteableReturnType &&
                                                         !IsPrimitiveType(returnTypeId));

            XPathNavigator containingType         = reflection.SelectSingleNode(apiContainingTypeExpression);
            string         containingTypeSubgroup = (string)containingType.Evaluate(apiSubgroupExpression);

            // an ordinary property, not an attached prop
            if (containingTypeSubgroup == "interface")
            {
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_noXamlSyntaxForInterfaceMembers, writer);
            }
            else if ((bool)containingType.Evaluate(apiIsAbstractTypeExpression) &&
                     (bool)containingType.Evaluate(apiIsSealedTypeExpression))
            {
                // the property's containing type is static if it's abstract and sealed
                // members of a static class cannot be used in XAML.
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_nonXamlParent, writer);
            }
            else if (IsExcludedSubClass(containingType))
            {
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_parentIsExcludedSubClass, writer);
            }
            else if (!DoesParentSupportXaml(reflection))
            {
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_nonXamlParent, writer);
            }
            else if (propertyVisibility != "public")
            {
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_notPublic, writer);
            }
            else if (isAbstract)
            {
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_abstract, writer);
            }
            else if (parameters.Count > 0)
            {
                // per DDUERELTools bug 1373: indexer properties cannot be used in XAML
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_nonXaml, writer);
            }
            else if (IsContentProperty(reflection) && !returnTypeIsReadonlyStruct)
            {
                PropertyContentElementUsageSimple(reflection, writer);
            }
            else if (!isSettable || !isSetterPublic)
            {
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_readOnly, writer);
            }
            else if (returnTypeIsAbstract && !HasTypeConverterAttribute(returnType))    // !EFW - Allow it if there's a type converter
            {
                WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_abstractType, returnType, writer);
            }
            else if (IsPrimitiveType(returnTypeId))
            {
                PropertyAttributeUsage(reflection, writer);
            }
            else if (returnTypeSubgroup == "enumeration")
            {
                PropertyAttributeUsage(reflection, writer);
            }
            else
            {
                bool hasDefaultConstructor = HasDefaultConstructor(returnType);
                if (HasTypeConverterAttribute(returnType))
                {
                    if (hasDefaultConstructor && !returnTypeIsReadonlyStruct)
                    {
                        PropertyElementUsageGrande(reflection, writer);
                    }
                    PropertyAttributeUsage(reflection, writer);
                }
                else if (hasDefaultConstructor && !returnTypeIsReadonlyStruct)
                {
                    PropertyElementUsageGrande(reflection, writer);
                }
                else
                {
                    WriteXamlBoilerplate(XamlBoilerplateID.propertyXamlSyntax_nonXaml, writer);
                }
            }
        }
Beispiel #25
0
        protected MathComponent(BuildAssembler assembler,
                                XPathNavigator configuration, bool isConceptual)
            : base(assembler, configuration)
        {
            try
            {
                _mathNumber   = 1;
                _numberByPage = true;

                XPathNavigator navigator = configuration.SelectSingleNode("paths");
                if (navigator == null)
                {
                    throw new BuildComponentException(
                              "The input/output paths, or <paths> tag, is required.");
                }
                _inputPath = navigator.GetAttribute("inputPath", String.Empty);

                if (String.IsNullOrEmpty(_inputPath))
                {
                    throw new BuildComponentException("The input path is required.");
                }
                _inputPath = Environment.ExpandEnvironmentVariables(_inputPath);
                _inputPath = Path.GetFullPath(_inputPath);
                // Delete the current input path...to empty the contents.
                try
                {
                    if (Directory.Exists(_inputPath))
                    {
                        Directory.Delete(_inputPath, true);
                    }
                }
                catch (Exception ex)
                {
                    this.WriteMessage(MessageLevel.Warn, ex);
                }
                // Create the input path...
                try
                {
                    if (!Directory.Exists(_inputPath))
                    {
                        Directory.CreateDirectory(_inputPath);
                    }
                }
                catch (Exception ex)
                {
                    this.WriteMessage(MessageLevel.Warn, ex);
                }

                _outputBasePath = navigator.GetAttribute("baseOutput", String.Empty);
                if (String.IsNullOrEmpty(_outputBasePath))
                {
                    throw new BuildComponentException("The base output path is required.");
                }
                _outputBasePath = Environment.ExpandEnvironmentVariables(_outputBasePath);
                _outputBasePath = Path.GetFullPath(_outputBasePath);

                _outputPath = navigator.GetAttribute("outputPath", String.Empty);
                if (String.IsNullOrEmpty(_outputPath))
                {
                    throw new BuildComponentException("The output path is required.");
                }
                _outputPath = Environment.ExpandEnvironmentVariables(_outputPath);
                _outputPath = Path.Combine(_outputBasePath, _outputPath);
                try
                {
                    if (!Directory.Exists(_outputPath))
                    {
                        Directory.CreateDirectory(_outputPath);
                    }
                }
                catch (Exception ex)
                {
                    this.WriteMessage(MessageLevel.Warn, ex);
                }

                //_linkPath = navigator.GetAttribute("link", String.Empty);
                //if (_linkPath[_linkPath.Length - 1] != '/')
                //{
                //    _linkPath = _linkPath + "/";
                //}

                navigator = configuration.SelectSingleNode("numbering");
                if (navigator != null)
                {
                    string attribute = navigator.GetAttribute("show", String.Empty);
                    if (String.IsNullOrEmpty(attribute) == false)
                    {
                        _numberShow = Convert.ToBoolean(attribute);
                    }
                    attribute = navigator.GetAttribute("byPage", String.Empty);
                    if (String.IsNullOrEmpty(attribute) == false)
                    {
                        _numberByPage = Convert.ToBoolean(attribute);
                    }
                    attribute = navigator.GetAttribute("format", String.Empty);
                    if (String.IsNullOrEmpty(attribute) == false)
                    {
                        _numberFormat = attribute;
                    }
                    attribute = navigator.GetAttribute("formatIncludesPage", String.Empty);
                    if (String.IsNullOrEmpty(attribute) == false)
                    {
                        _numberIncludesPage = Convert.ToBoolean(attribute);
                    }
                }

                if (String.IsNullOrEmpty(_numberFormat))
                {
                    if (_numberIncludesPage)
                    {
                        _numberFormat = "({0}.{1})";
                    }
                    else
                    {
                        _numberFormat = "({0})";
                    }
                }

                XPathNodeIterator iterator = configuration.Select("formatter");
                if (navigator == null)
                {
                    throw new BuildComponentException(
                              "At least a formatter is required to use this component.");
                }

                Type          compType  = this.GetType();
                MessageWriter msgWriter = assembler.MessageWriter;
                foreach (XPathNavigator formatter in iterator)
                {
                    string attribute = formatter.GetAttribute("format", String.Empty);
                    if (String.IsNullOrEmpty(attribute))
                    {
                        throw new BuildComponentException("The format tag is required.");
                    }

                    if (String.Equals(attribute, "latex",
                                      StringComparison.OrdinalIgnoreCase))
                    {
                        if (_latexFormatter == null)
                        {
                            string latexType = formatter.GetAttribute("type",
                                                                      String.Empty);
                            if (String.Equals(latexType, "MikTeX",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                _latexFormatter = new MathMikTeXFormatter(compType,
                                                                          msgWriter, formatter);

                                _latexFormatter.BeginUpdate(_inputPath, isConceptual);
                            }
                            else if (String.Equals(latexType, "MimeTeX",
                                                   StringComparison.OrdinalIgnoreCase))
                            {
                                _latexFormatter = new MathMimeTeXFormatter(
                                    compType, msgWriter, formatter);

                                _latexFormatter.BeginUpdate(_inputPath, isConceptual);
                            }
                        }
                    }
                }

                if (_latexFormatter != null)
                {
                    _latexFormatter.Update(configuration);

                    navigator = configuration.SelectSingleNode("naming");
                    if (navigator != null)
                    {
                        MathNamingMethod namingMethod = MathNamingMethod.Sequential;
                        string           attribute    = navigator.GetAttribute("method", String.Empty);
                        if (String.IsNullOrEmpty(attribute) == false)
                        {
                            namingMethod = (MathNamingMethod)Enum.Parse(
                                typeof(MathNamingMethod), attribute, true);

                            _latexFormatter.NamingMethod = namingMethod;

                            attribute = navigator.GetAttribute("prefix", String.Empty);
                            if (attribute != null)
                            {
                                _latexFormatter.NamingPrefix = attribute;
                            }
                        }
                    }

                    _latexFormatter.EndUpdate();
                }

                // Check the availability of a LaTeX distribution...
                _latexPath        = SearchExecutable("latex.exe");
                _isLaTeXInstalled = (!String.IsNullOrEmpty(_latexPath) && File.Exists(_latexPath));

                // Warn if no distribution is found...
                if (!_isLaTeXInstalled)
                {
                    this.WriteMessage(MessageLevel.Warn,
                                      "There is no LaTeX installation found. Please installed the MikTeX (http://www.miktex.org/).");
                }
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
Beispiel #26
0
        /// <summary>
        /// Create an (single or sequence) Attribute instance using a raw xml file (that is generated by the ODD).
        /// </summary>
        /// <param name="attributeNode">An Attribute node.</param>
        /// <returns>The created Attribute instance.</returns>
        public static Attribute Create(XPathNavigator attributeNode, AttributesAndMacros parent)
        {
            Attribute attribute = null; // Return value;
            string    name      = string.Empty;
            Tag       tag       = new Tag();


            //
            // Determine attribute name.
            //

            try
            {
                name = attributeNode.GetAttribute("Name", "");
            }
            catch (Exception exception)
            {
                throw (DefinitionFile.CreateException(attributeNode, "Attribute", "Unable to determine Name", exception));
            }


            //
            // Determine tag.
            //

            tag = Tag.Create(attributeNode);


            //
            // Construct a single attribute or a sequence attribute.
            //

            VR valueRepresentations   = VR.None;
            XPathNodeIterator vRNodes = attributeNode.Select("VR");

            if (vRNodes.MoveNext())
            {
                try
                {
                    valueRepresentations = (VR)System.Enum.Parse(typeof(VR), vRNodes.Current.Value.Replace('/', ','));
                }
                catch
                {
                    throw (DefinitionFile.CreateException(attributeNode, "Attribute", "VR node does not contain a valid VR.", null));
                }
            }
            else
            {
                throw (DefinitionFile.CreateException(attributeNode, "Attribute", "VR node not found.", null));
            }

            if (valueRepresentations == VR.SQ)
            {
                attribute = SequenceAttribute.Create(tag, name, attributeNode, parent);
            }
            else
            {
                attribute = new SingleAttribute(tag, valueRepresentations, name, parent);
            }


            //
            // Return the constructed attribute.
            //

            return(attribute);
        }
        //=====================================================================

        /// <summary>
        /// This is used to create an MSDN resolver for the reference link to use in looking up MSDN content iDs
        /// </summary>
        /// <param name="configuration">The component configuration</param>
        /// <returns>An MSDN resolver instance</returns>
        /// <remarks>This can be overridden in derived classes to provide persistent caches with backing stores
        /// other than the default dictionary serialized to a binary file.  It also allows sharing the cache
        /// across instances by placing it in the <see cref="BuildComponentCore.Data"/> dictionary using the key
        /// name <c>SharedMsdnContentIdCacheID</c>.
        ///
        /// <para>If overridden, the <see cref="UpdateMsdnContentIdCache"/> method should also be overridden to
        /// persist changes to the cache if needed.</para></remarks>
        protected virtual MsdnResolver CreateMsdnResolver(XPathNavigator configuration)
        {
            MsdnResolver newResolver;
            IDictionary <string, string> cache = null;

            if (BuildComponentCore.Data.ContainsKey(SharedMsdnContentIdCacheId))
            {
                cache = BuildComponentCore.Data[SharedMsdnContentIdCacheId] as IDictionary <string, string>;
            }

            // If the shared cache already exists, return an instance that uses it.  It is assumed that all
            // subsequent instances will use the same cache.
            if (cache != null)
            {
                return(new MsdnResolver(cache, true));
            }

            // If a <cache> element is not specified, we'll use the standard resolver without a persistent cache.
            // We will share it across all instances though.
            XPathNavigator node = configuration.SelectSingleNode("msdnContentIdCache");

            if (node == null)
            {
                newResolver = new MsdnResolver();
            }
            else
            {
                // Keep the filename.  If we own it, we'll update the cache file when disposed.
                msdnIdCacheFile = node.GetAttribute("path", String.Empty);

                if (String.IsNullOrWhiteSpace(msdnIdCacheFile))
                {
                    base.WriteMessage(MessageLevel.Error, "You must specify a path attribute value on the " +
                                      "msdnContentIdCache element.");
                }

                // Create the folder if it doesn't exist
                msdnIdCacheFile = Path.GetFullPath(Environment.ExpandEnvironmentVariables(msdnIdCacheFile));
                string path = Path.GetDirectoryName(msdnIdCacheFile);

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

                // Load the cache if it exists
                if (!File.Exists(msdnIdCacheFile))
                {
                    // Logged as a diagnostic message since looking up all IDs can significantly slow the build
                    base.WriteMessage(MessageLevel.Diagnostic, "The MSDN content ID cache '" + msdnIdCacheFile +
                                      "' does not exist yet.  All IDs will be looked up in this build which will slow it down.");

                    newResolver = new MsdnResolver();
                }
                else
                {
                    using (FileStream fs = new FileStream(msdnIdCacheFile, FileMode.Open, FileAccess.Read,
                                                          FileShare.Read))
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        newResolver = new MsdnResolver((IDictionary <string, string>)bf.Deserialize(fs), false);

                        base.WriteMessage(MessageLevel.Info, "Loaded {0} cached MSDN content ID entries",
                                          newResolver.MsdnContentIdCache.Count);
                    }
                }
            }

            BuildComponentCore.Data[SharedMsdnContentIdCacheId] = newResolver.MsdnContentIdCache;

            return(newResolver);
        }
Beispiel #28
0
        // the actual work of the component

        public override void Apply(XmlDocument document, string key)
        {
            // set the key in the XPath context
            _context["key"] = key;

            // perform each copy action
            foreach (CopyFromIndexCommand copyCommand in _copyCommands)
            {
                // get the source comment
                XPathExpression keyExpression = copyCommand.Key.Clone();
                keyExpression.SetContext(_context);
                string keyValue = (string)document.CreateNavigator().Evaluate(keyExpression);
                if (String.IsNullOrEmpty(keyValue))
                {
                    continue;
                }

                XPathNavigator data = copyCommand.Index.GetContent(keyValue);

                if (data == null && copyCommand.IgnoreCase == "true")
                {
                    data = copyCommand.Index.GetContent(keyValue.ToLower());
                }

                // notify if no entry
                if (data == null)
                {
                    WriteMessage(copyCommand.MissingEntry, String.Format(
                                     "No index entry found for key '{0}'.", keyValue));
                    continue;
                }

                // get the target node
                String          targetXPath       = copyCommand.Target.Clone().ToString();
                XPathExpression target_expression = XPathExpression.Compile(
                    String.Format(targetXPath, keyValue));
                target_expression.SetContext(_context);

                XPathNavigator target = document.CreateNavigator().SelectSingleNode(target_expression);

                // notify if no target found
                if (target == null)
                {
                    WriteMessage(copyCommand.MissingTarget, String.Format("Target node '{0}' not found.", target_expression.Expression));
                    continue;
                }

                // get the source nodes
                XPathExpression sourceExpression = copyCommand.Source.Clone();
                sourceExpression.SetContext(_context);
                XPathNodeIterator sources = data.CreateNavigator().Select(sourceExpression);

                // append the source nodes to the target node
                int sourceCount = 0;
                foreach (XPathNavigator source in sources)
                {
                    sourceCount++;

                    // If attribute=true, add the source attributes to current target.
                    // Otherwise append source as a child element to target
                    if (copyCommand.Attribute == "true" && source.HasAttributes)
                    {
                        string    source_name = source.LocalName;
                        XmlWriter attributes  = target.CreateAttributes();

                        source.MoveToFirstAttribute();
                        string attrFirst = target.GetAttribute(string.Format("{0}_{1}", source_name, source.Name), string.Empty);
                        if (string.IsNullOrEmpty(attrFirst))
                        {
                            attributes.WriteAttributeString(string.Format("{0}_{1}", source_name, source.Name), source.Value);
                        }

                        while (source.MoveToNextAttribute())
                        {
                            string attrNext = target.GetAttribute(string.Format("{0}_{1}", source_name, source.Name), string.Empty);
                            if (string.IsNullOrEmpty(attrNext))
                            {
                                attributes.WriteAttributeString(string.Format("{0}_{1}", source_name, source.Name), source.Value);
                            }
                        }
                        attributes.Close();
                    }
                    else
                    {
                        target.AppendChild(source);
                    }
                }

                // notify if no source found
                if (sourceCount == 0)
                {
                    WriteMessage(copyCommand.MissingSource, String.Format(
                                     "Source node '{0}' not found.", sourceExpression.Expression));
                }

                foreach (CopyComponent component in _copyComponents)
                {
                    component.Apply(document, key);
                }
            }
        }
        //============================================================
        //	PUBLIC METHODS
        //============================================================
        #region Load(XPathNavigator source)
        /// <summary>
        /// Loads this <see cref="AtomTextConstruct"/> using the supplied <see cref="XPathNavigator"/>.
        /// </summary>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <returns><b>true</b> if the <see cref="AtomTextConstruct"/> was initialized using the supplied <paramref name="source"/>, otherwise <b>false</b>.</returns>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="AtomTextConstruct"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        public bool Load(XPathNavigator source)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            bool wasLoaded = false;

            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");

            //------------------------------------------------------------
            //	Initialize XML namespace resolver
            //------------------------------------------------------------
            XmlNamespaceManager manager = AtomUtility.CreateNamespaceManager(source.NameTable);

            //------------------------------------------------------------
            //	Attempt to extract common attributes information
            //------------------------------------------------------------
            if (AtomUtility.FillCommonObjectAttributes(this, source))
            {
                wasLoaded = true;
            }

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            if (source.HasAttributes)
            {
                string typeAttribute = source.GetAttribute("type", String.Empty);
                if (!String.IsNullOrEmpty(typeAttribute))
                {
                    AtomTextConstructType type = AtomTextConstruct.ConstructTypeByName(typeAttribute);
                    if (type != AtomTextConstructType.None)
                    {
                        this.TextType = type;
                        wasLoaded     = true;
                    }
                }
            }

            if (this.TextType == AtomTextConstructType.Xhtml)
            {
                XPathNavigator xhtmlDivNavigator = source.SelectSingleNode("xhtml:div", manager);
                if (xhtmlDivNavigator != null && !String.IsNullOrEmpty(xhtmlDivNavigator.Value))
                {
                    this.Content = xhtmlDivNavigator.Value;
                    wasLoaded    = true;
                }
            }
            else if (this.TextType == AtomTextConstructType.Html && !String.IsNullOrEmpty(source.InnerXml))
            {
                this.Content = source.InnerXml;
                wasLoaded    = true;
            }
            else if (!String.IsNullOrEmpty(source.Value))
            {
                this.Content = source.Value;
                wasLoaded    = true;
            }

            return(wasLoaded);
        }
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            TargetDictionary  newTargets;
            ReferenceLinkType type;
            string            attrValue, id;

            targets  = new TargetTypeDictionary();
            resolver = new LinkTextResolver(targets);

            // Get the shared instances dictionary.  Create it if it doesn't exist.
            if (BuildComponentCore.Data.ContainsKey(SharedReferenceTargetsId))
            {
                sharedTargets = BuildComponentCore.Data[SharedReferenceTargetsId] as Dictionary <string, TargetDictionary>;
            }

            if (sharedTargets == null)
            {
                BuildComponentCore.Data[SharedReferenceTargetsId] = sharedTargets = new Dictionary <string, TargetDictionary>();
            }

            // base-url is an xpath expression applied against the current document to pick up the save location of the
            // document. If specified, local links will be made relative to the base-url.
            string baseUrlValue = configuration.GetAttribute("base-url", String.Empty);

            if (!String.IsNullOrEmpty(baseUrlValue))
            {
                baseUrl = XPathExpression.Compile(baseUrlValue);
            }

            // hrefFormat is a string format that is used to format the value of local href attributes. The
            // default is "{0}.htm" if not specified.
            hrefFormat = (string)configuration.Evaluate("string(hrefFormat/@value)");

            if (String.IsNullOrWhiteSpace(hrefFormat))
            {
                hrefFormat = "{0}.htm";
            }

            // The container XPath can be replaced; this is useful
            string containerValue = configuration.GetAttribute("container", String.Empty);

            if (!String.IsNullOrEmpty(containerValue))
            {
                XmlTargetDictionaryUtilities.ContainerExpression = containerValue;
            }

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

#if DEBUG
            base.WriteMessage(MessageLevel.Diagnostic, "Loading reference link target info");

            DateTime startLoad = DateTime.Now;
#endif
            foreach (XPathNavigator targetsNode in targetsNodes)
            {
                // Get target type
                attrValue = targetsNode.GetAttribute("type", String.Empty);

                if (String.IsNullOrEmpty(attrValue))
                {
                    base.WriteMessage(MessageLevel.Error, "Each targets element must have a type attribute " +
                                      "that specifies which type of links to create");
                }

                if (!Enum.TryParse <ReferenceLinkType>(attrValue, true, out type))
                {
                    base.WriteMessage(MessageLevel.Error, "'{0}' is not a supported reference link type",
                                      attrValue);
                }

                // Check for shared instance by ID.  If not there, create it and add it.
                id = targetsNode.GetAttribute("id", String.Empty);

                if (!sharedTargets.TryGetValue(id, out newTargets))
                {
                    this.WriteMessage(MessageLevel.Info, "Loading {0} reference link type targets", type);

                    newTargets = this.CreateTargetDictionary(targetsNode);
                    sharedTargets[newTargets.DictionaryId] = newTargets;
                }

                targets.Add(type, newTargets);
            }

#if DEBUG
            TimeSpan loadTime = (DateTime.Now - startLoad);
            base.WriteMessage(MessageLevel.Diagnostic, "Load time: {0} seconds", loadTime.TotalSeconds);

            // Dump targets for comparison to other versions
//            targets.DumpTargetDictionary(Path.GetFullPath("TargetDictionary.xml"));

            // Serialization test
//            targets.SerializeDictionary(Directory.GetCurrentDirectory());
#endif
            // Getting the count from a database cache can be expensive so only report it if it will be seen
            if (base.BuildAssembler.VerbosityLevel == MessageLevel.Info)
            {
                base.WriteMessage(MessageLevel.Info, "{0} total reference link targets", targets.Count);
            }

            if (targets.NeedsMsdnResolver)
            {
                base.WriteMessage(MessageLevel.Info, "Creating MSDN URL resolver");

                msdnResolver = this.CreateMsdnResolver(configuration);

                string localeValue = (string)configuration.Evaluate("string(locale/@value)");

                if (msdnResolver != null && !String.IsNullOrWhiteSpace(localeValue))
                {
                    msdnResolver.Locale = localeValue;
                }
            }

            linkTarget = (string)configuration.Evaluate("string(linkTarget/@value)");

            if (String.IsNullOrWhiteSpace(linkTarget))
            {
                linkTarget = "_blank";
            }
        }
Beispiel #31
0
 static string GetAttribute(XPathNavigator nav, string attribute)
 {
     return(nav.GetAttribute(attribute, ""));
 }