示例#1
0
        protected override void OnReadContents(XmlReader reader)
        {
            if (_dependencies == null)
            {
                _dependencies = new DependencyContent();
            }

            if (reader.IsEmptyElement)
            {
                return;
            }

            string startElement = reader.Name;

            Debug.Assert(String.Equals(startElement, "content",
                                       StringComparison.OrdinalIgnoreCase));

            if (!String.Equals(startElement, "content",
                               StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (reader.ReadToDescendant(DependencyContent.TagName))
            {
                _dependencies.ReadXml(reader);
            }
        }
示例#2
0
 /// <overloads>
 /// Initializes a new instance of the <see cref="ReferenceLinkSource"/> class.
 /// </overloads>
 /// <summary>
 /// Initializes a new instance of the <see cref="ReferenceLinkSource"/> class
 /// with the default parameters.
 /// </summary>
 public ReferenceLinkSource()
 {
     _sourceId      = Guid.NewGuid().ToString();
     _linkType      = BuildLinkType.Local;
     _listItems     = new BuildList <ReferenceItem>();
     _dependencies  = new DependencyContent();
     _frameworkType = BuildFrameworkType.None;
 }
示例#3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ReferenceLinkSource"/> class
 /// with parameters copied from the specified instance of the
 /// <see cref="ReferenceLinkSource"/> class, a copy constructor.
 /// </summary>
 /// <param name="source">
 /// An instance of the <see cref="ReferenceLinkSource"/> class from which the
 /// initialization parameters or values will be copied.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// If the parameter <paramref name="source"/> is <see langword="null"/>.
 /// </exception>
 public ReferenceLinkSource(ReferenceLinkSource source)
     : base(source)
 {
     _linkType      = source._linkType;
     _sourceId      = source._sourceId;
     _listItems     = source._listItems;
     _dependencies  = source._dependencies;
     _frameworkType = source._frameworkType;
 }
示例#4
0
        public ReferenceContent()
        {
            _contentVersion = new Version(1, 0, 0, 0);
            _contentId      = Guid.NewGuid().ToString();
            _frameworkType  = BuildFrameworkType.Framework20;
            _dependencies   = new DependencyContent();

            _tocContent       = new HierarchicalTocContent();
            _commentContent   = new CommentContent();
            _typeFilters      = new ReferenceRootFilter(false);
            _attributeFilters = new ReferenceRootFilter(true);
        }
示例#5
0
        public void AddDependency(string assembly)
        {
            if (String.IsNullOrEmpty(assembly))
            {
                return;
            }
            if (_dependencies == null)
            {
                _dependencies = new DependencyContent();
            }

            _dependencies.Add(new DependencyItem(
                                  Path.GetFileName(assembly), assembly));
        }
        /// <summary>
        /// This creates the dependency information after the reflection.
        /// </summary>
        /// <param name="dependencies"></param>
        /// <param name="dependencyDir"></param>
        private void CreateDependency(DependencyContent dependencies,
                                      string dependencyDir)
        {
            if (dependencies == null || dependencies.Count == 0)
            {
                return;
            }

            int itemCount = dependencies.Count;

            for (int i = 0; i < itemCount; i++)
            {
                DependencyItem dependency = dependencies[i];
                if (dependency == null || dependency.IsEmpty)
                {
                    continue;
                }

                string dependencyFile = dependency.Location;
                // There is no need to include a reference assembly, if it is
                // a dependent assembly...
                //if (!String.IsNullOrEmpty(dependencyFile)
                //    && !_dictReference.ContainsKey(dependencyFile))
                // However, for some cases, especially where there is redirection
                // of assembly, the explicit dependency is still required...
                if (!String.IsNullOrEmpty(dependencyFile))
                {
                    string fileName = Path.GetFileName(dependencyFile);
                    fileName = Path.Combine(dependencyDir, fileName);
                    if (!File.Exists(fileName))
                    {
                        File.Copy(dependencyFile, fileName, true);
                        File.SetAttributes(fileName, FileAttributes.Normal);

                        // Set if the comment file exists and link it...
                        dependencyFile = Path.ChangeExtension(dependencyFile, ".xml");
                        if (File.Exists(dependencyFile))
                        {
                            _linkCommentFiles.Add(dependencyFile);
                        }

                        if (dependency.IsRedirected)
                        {
                            _bindingRedirects.Add(dependency);
                        }
                    }
                }
            }
        }
示例#7
0
 public ReferenceContent(ReferenceContent source)
     : base(source)
 {
     _isLoaded         = source._isLoaded;
     _contentId        = source._contentId;
     _contentVersion   = source._contentVersion;
     _contentFile      = source._contentFile;
     _contentDir       = source._contentDir;
     _frameworkType    = source._frameworkType;
     _tocContent       = source._tocContent;
     _dependencies     = source._dependencies;
     _commentContent   = source._commentContent;
     _typeFilters      = source._typeFilters;
     _attributeFilters = source._attributeFilters;
 }
        public override ReferenceContent Create(BuildGroupContext groupContext)
        {
            BuildExceptions.NotNull(groupContext, "groupContext");

            BuildContext context = groupContext.Context;
            BuildLogger  logger  = null;

            if (context != null)
            {
                logger = context.Logger;
            }

            if (!this.IsInitialized)
            {
                throw new BuildException(String.Format(
                                             "The content source '{0}' is not yet initialized.", this.Title));
            }
            if (!this.IsValid)
            {
                if (logger != null)
                {
                    logger.WriteLine(String.Format(
                                         "The content group source '{0}' is invalid.", this.Title),
                                     BuildLoggerLevel.Warn);
                }

                return(null);
            }

            string searchPattern = _searchPattern;

            if (String.IsNullOrEmpty(searchPattern))
            {
                searchPattern = "*.dll";
            }
            string[] fullPaths = Directory.GetFiles(_sourcePath.Path,
                                                    searchPattern, _isRecursive ? SearchOption.AllDirectories :
                                                    SearchOption.TopDirectoryOnly);

            if (fullPaths == null || fullPaths.Length == 0)
            {
                return(null);
            }

            HashSet <string> dependencyDirs = new HashSet <string>(
                StringComparer.OrdinalIgnoreCase);
            Dictionary <string, string> assemblies =
                new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (string fullPath in fullPaths)
            {
                string fileName = Path.GetFileName(fullPath);
                if (assemblies.ContainsKey(fileName) ||
                    (_excludeSet.Count != 0 && _excludeSet.Contains(fileName)))
                {
                    continue;
                }

                // We will not use the assemblies without comments as
                // dependencies, since we cannot verify these are .NET DLLs.
                string commentFile = Path.ChangeExtension(fullPath, ".xml");
                if (!File.Exists(commentFile))
                {
                    continue;
                }

                string dependencyDir = Path.GetDirectoryName(fullPath);
                if (!dependencyDir.EndsWith("\\"))
                {
                    dependencyDir += "\\";
                }
                dependencyDirs.Add(dependencyDir);

                assemblies[fileName] = fullPath;
            }

            if (assemblies.Count == 0)
            {
                return(null);
            }

            ReferenceContent content = new ReferenceContent();

            // Set the framework version...
            if (_frameworkType == BuildFrameworkType.Null ||
                _frameworkType == BuildFrameworkType.None)
            {
                BuildFramework framework = BuildFrameworks.LatestFramework;

                if (framework == null)
                {
                    // If not successful, use the default...
                    framework = BuildFrameworks.DefaultFramework;
                }

                content.FrameworkType = framework.FrameworkType;
            }
            else
            {
                content.FrameworkType = _frameworkType;
            }

            foreach (KeyValuePair <string, string> pair in assemblies)
            {
                string assemblyFile = pair.Value;
                string commentFile  = Path.ChangeExtension(assemblyFile, ".xml");

                content.AddItem(commentFile, assemblyFile);
            }

            // Provide the dependency information for the content...
            DependencyContent depContents = content.Dependencies;

            foreach (string dependencyDir in dependencyDirs)
            {
                depContents.Paths.Add(new BuildDirectoryPath(dependencyDir));
            }

            // Provide other user-supplied information to the content...
            content.Comments         = this.Comments;
            content.HierarchicalToc  = this.HierarchicalToc;
            content.TypeFilters      = this.TypeFilters;
            content.AttributeFilters = this.AttributeFilters;

            return(content);
        }
        private void ResolveDependency(ReferenceGroupContext sourceContext,
                                       ReferenceContent referenceContent)
        {
            BuildContext context = this.Context;
            BuildLogger  logger  = context.Logger;

            BuildFramework framework = sourceContext.Framework;

            if (framework == null)
            {
                throw new BuildException("No valid framework is specified.");
            }

            DependencyContent dependencies = referenceContent.Dependencies;

            _resolveContent = new DependencyContent();
            _listReference  = new List <ReferenceItem>();

            _dictionary = new Dictionary <string, bool>(
                StringComparer.OrdinalIgnoreCase);
            _dictDependency = new Dictionary <string, bool>(
                StringComparer.OrdinalIgnoreCase);
            _dictReference = new Dictionary <string, bool>(
                StringComparer.OrdinalIgnoreCase);

            if (dependencies != null && dependencies.Count != 0)
            {
                for (int i = 0; i < dependencies.Count; i++)
                {
                    DependencyItem depItem = dependencies[i];
                    if (!depItem.IsEmpty)
                    {
                        _dictDependency[depItem.Location] = true;
                    }
                }
            }

            // Index the reference items to prevent cross referencing...
            if (referenceContent != null && referenceContent.Count != 0)
            {
                for (int i = 0; i < referenceContent.Count; i++)
                {
                    ReferenceItem refItem = referenceContent[i];
                    if (!refItem.IsEmpty && !refItem.IsCommentOnly)
                    {
                        string refAssembly = refItem.Assembly;
                        if (!_dictReference.ContainsKey(refAssembly))
                        {
                            _dictReference[refAssembly] = true;
                            _listReference.Add(refItem);
                        }
                    }
                }
            }

            GeneralAssemblyResolver resolver = new GeneralAssemblyResolver();

            // Add the reference item directories, the most likely place to
            // find the dependencies
            for (int i = 0; i < _listReference.Count; i++)
            {
                resolver.AddSearchDirectory(
                    Path.GetDirectoryName(_listReference[i].Assembly));
            }

            // Add specified dependency directories, if any...
            IList <BuildDirectoryPath> dependencyPaths = dependencies.Paths;

            if (dependencyPaths != null && dependencyPaths.Count != 0)
            {
                for (int i = 0; i < dependencyPaths.Count; i++)
                {
                    BuildDirectoryPath dependencyPath = dependencyPaths[i];
                    if (dependencyPath.Exists)
                    {
                        resolver.AddSearchDirectory(dependencyPath);
                    }
                }
            }

            Version version = framework.Version;

            // Add, for the Silverlight, known installation directories...
            BuildFrameworkKind frameworkKind = framework.FrameworkType.Kind;

            if (frameworkKind == BuildFrameworkKind.Silverlight)
            {
                resolver.UseGac = false;

                string programFiles = PathUtils.ProgramFiles32;
                string searchDir    = Path.Combine(programFiles,
                                                   @"Microsoft Silverlight\" + version.ToString());
                if (Directory.Exists(searchDir))
                {
                    resolver.AddSearchDirectory(searchDir);
                }

                searchDir = Path.Combine(programFiles,
                                         @"Reference Assemblies\Microsoft\Framework\Silverlight\v" + version.ToString(2));
                if (Directory.Exists(searchDir))
                {
                    resolver.AddSearchDirectory(searchDir);
                }
                else
                {
                    if (version.Major == 5 && version.Minor > 0)
                    {
                        // For Silverlight 5.1, the assemblies are in different places...
                        searchDir = Path.Combine(programFiles,
                                                 @"Reference Assemblies\Microsoft\Framework\Silverlight\v5.0");
                        if (Directory.Exists(searchDir))
                        {
                            resolver.AddSearchDirectory(searchDir);
                        }
                    }
                }

                searchDir = Path.Combine(programFiles,
                                         @"Microsoft SDKs\Silverlight\v" + version.ToString(2));
                if (!Directory.Exists(searchDir))
                {
                    if (version.Major == 5 && version.Minor > 0)
                    {
                        // For Silverlight 5.1, the assemblies are in different places...
                        searchDir = Path.Combine(programFiles,
                                                 @"Microsoft SDKs\Silverlight\v5.0");
                    }
                }

                if (Directory.Exists(searchDir))
                {
                    resolver.AddSearchDirectory(searchDir);

                    string tempDir = String.Copy(searchDir);
                    searchDir = Path.Combine(tempDir, @"Libraries\Client");
                    if (Directory.Exists(searchDir))
                    {
                        resolver.AddSearchDirectory(searchDir);
                    }
                    searchDir = Path.Combine(tempDir, @"Libraries\Server");
                    if (Directory.Exists(searchDir))
                    {
                        resolver.AddSearchDirectory(searchDir);
                    }
                }

                if (version.Major == 3)
                {
                    // 3. The Expression 3.0 Blend SDK...
                    string otherDir = Path.Combine(programFiles,
                                                   @"Microsoft SDKs\Expression\Blend 3\Interactivity\Libraries\Silverlight");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                    otherDir = Path.Combine(programFiles,
                                            @"Microsoft SDKs\Expression\Blend 3\Prototyping\Libraries\Silverlight");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                }
                else if (version.Major == 4)
                {
                    // Consider the extension libraries...
                    // 1. The RIA Services...
                    string otherDir = Path.Combine(programFiles,
                                                   @"Microsoft SDKs\RIA Services\v1.0\Libraries\Silverlight");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                    // 2. For the Silverlight Toolkit...
                    otherDir = Path.Combine(programFiles,
                                            @"Microsoft SDKs\Silverlight\v4.0\Toolkit");
                    if (Directory.Exists(otherDir))
                    {
                        // Get the latest installed version...
                        string[] dirs = Directory.GetDirectories(otherDir);
                        if (dirs != null && dirs.Length != 0)
                        {
                            string   dir      = String.Empty;
                            DateTime latestDt = DateTime.MinValue;
                            for (int j = 0; j < dirs.Length; j++)
                            {
                                string   latestDir = Path.GetFileName(dirs[j]);
                                DateTime dt;
                                if (DateTime.TryParse(latestDir, out dt))
                                {
                                    if (dt > latestDt)
                                    {
                                        latestDt = dt;
                                        dir      = latestDir;
                                    }
                                }
                            }

                            otherDir = Path.Combine(otherDir, dir + @"\Bin");
                            if (Directory.Exists(otherDir))
                            {
                                resolver.AddSearchDirectory(otherDir);
                            }
                        }
                    }

                    // 3. The Expression 4.0 Blend SDK...
                    otherDir = Path.Combine(programFiles,
                                            @"Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                }
                else if (version.Major == 5)
                {
                    // Consider the extension libraries...
                    // 1. The RIA Services...
                    string otherDir = Path.Combine(programFiles,
                                                   @"Microsoft SDKs\RIA Services\v1.0\Libraries\Silverlight");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                    // 2. For the Silverlight Toolkit...
                    otherDir = Path.Combine(programFiles,
                                            @"Microsoft SDKs\Silverlight\v5.0\Toolkit");
                    if (Directory.Exists(otherDir))
                    {
                        // Get the latest installed version...
                        string[] dirs = Directory.GetDirectories(otherDir);
                        if (dirs != null && dirs.Length != 0)
                        {
                            string   dir      = String.Empty;
                            DateTime latestDt = DateTime.MinValue;
                            for (int j = 0; j < dirs.Length; j++)
                            {
                                string   latestDir = Path.GetFileName(dirs[j]);
                                DateTime dt;
                                if (DateTime.TryParse(latestDir, out dt))
                                {
                                    if (dt > latestDt)
                                    {
                                        latestDt = dt;
                                        dir      = latestDir;
                                    }
                                }
                            }

                            otherDir = Path.Combine(otherDir, dir + @"\Bin");
                            if (Directory.Exists(otherDir))
                            {
                                resolver.AddSearchDirectory(otherDir);
                            }
                        }
                    }

                    // 3. The Expression 5.0 Blend SDK...
                    otherDir = Path.Combine(programFiles,
                                            @"Microsoft SDKs\Expression\Blend\Silverlight\v5.0\Libraries");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                }
            }
            else if (frameworkKind == BuildFrameworkKind.Portable)
            {
                resolver.UseGac = false;
                resolver.AddSearchDirectory(framework.AssemblyDir);
            }
            else if (frameworkKind == BuildFrameworkKind.ScriptSharp)
            {
                resolver.UseGac = false;
                resolver.AddSearchDirectory(framework.AssemblyDir);
            }
            else if (frameworkKind == BuildFrameworkKind.Compact)
            {
                resolver.UseGac = false;
                resolver.AddSearchDirectory(framework.AssemblyDir);
            }
            else if (frameworkKind == BuildFrameworkKind.DotNet)
            {
                string programFiles = Environment.GetFolderPath(
                    Environment.SpecialFolder.ProgramFiles);
                if (version.Major == 3)
                {
                    // 3. The Expression 3.0 Blend SDK...
                    string otherDir = Path.Combine(programFiles,
                                                   @"Microsoft SDKs\Expression\Blend 3\Interactivity\Libraries\.NETFramework");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                }
                else if (version.Major == 4)
                {
                    string otherDir = Path.Combine(programFiles,
                                                   @"Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries");
                    if (Directory.Exists(otherDir))
                    {
                        resolver.AddSearchDirectory(otherDir);
                    }
                }
            }
            else
            {
                throw new NotSupportedException(String.Format(
                                                    "The framework kind '{0}' is not supported.", frameworkKind.ToString()));
            }

            // Finally, we look inside the binding sources if we are dealing
            // with link sources...
            if (sourceContext.IsLinkGroup || sourceContext.IsEmbeddedGroup)
            {
                IList <string> bindingSources = sourceContext.BindingSources;
                if (bindingSources != null && bindingSources.Count != 0)
                {
                    foreach (string bindingSource in bindingSources)
                    {
                        if (!String.IsNullOrEmpty(bindingSource) &&
                            Directory.Exists(bindingSource))
                        {
                            resolver.AddSearchDirectory(bindingSource);
                        }
                    }
                }
            }

            for (int i = 0; i < _listReference.Count; i++)
            {
                ReferenceItem      refItem = _listReference[i];
                AssemblyDefinition asmDef  = AssemblyDefinition.ReadAssembly(
                    refItem.Assembly);

                ModuleDefinition modDef = asmDef.MainModule;

                // Try resolving all the dependencies...
                if (modDef.HasAssemblyReferences)
                {
                    IList <AssemblyNameReference> asmRefs = modDef.AssemblyReferences;

                    if (asmRefs != null && asmRefs.Count != 0)
                    {
                        for (int j = 0; j < asmRefs.Count; j++)
                        {
                            this.Resolve(logger, asmRefs[j], resolver,
                                         frameworkKind);
                        }
                    }
                }

                // Try resolving all the XmlnsDefinitionAttribute attributes...
                if (asmDef.HasCustomAttributes && refItem.XamlSyntax)
                {
                    this.ResolveXmlnsDefinitions(sourceContext, asmDef, modDef.Name);
                }
            }

            string[] searchDirs = resolver.GetSearchDirectories();
            if (searchDirs != null && searchDirs.Length != 0)
            {
                if (_searchDirectories == null)
                {
                    _searchDirectories = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                }

                for (int i = 0; i < searchDirs.Length; i++)
                {
                    string searchDir = Path.GetFullPath(String.Copy(searchDirs[i]));
                    if (!searchDir.EndsWith("\\"))
                    {
                        searchDir += "\\";
                    }

                    _searchDirectories.Add(searchDir);
                }
            }
        }
        /// <summary>
        /// Applies the processing operations defined by this visitor to the
        /// specified reference group.
        /// </summary>
        /// <param name="group">
        /// The <see cref="ReferenceGroup">reference group</see> to which the processing
        /// operations defined by this visitor will be applied.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If the <paramref name="group"/> is <see langword="null"/>.
        /// </exception>
        protected override void OnVisit(ReferenceGroup group)
        {
            BuildExceptions.NotNull(group, "group");

            if (!this.IsInitialized)
            {
                throw new BuildException(
                          "ReferenceProjectVisitor: The reference dependency resolver is not initialized.");
            }

            BuildContext context = this.Context;
            BuildLogger  logger  = context.Logger;

            if (logger != null)
            {
                logger.WriteLine("Begin - Resolving reference dependencies.",
                                 BuildLoggerLevel.Info);
            }

            ReferenceGroupContext groupContext = context.GroupContexts[group.Id]
                                                 as ReferenceGroupContext;

            if (groupContext == null)
            {
                throw new BuildException(
                          "The group context is not provided, and it is required by the build system.");
            }

            ReferenceGroupContext sourceContext = groupContext;

            if (!String.IsNullOrEmpty(_sourceId))
            {
                sourceContext = groupContext.Contexts[_sourceId]
                                as ReferenceGroupContext;
            }

            if (sourceContext == null)
            {
                throw new BuildException(
                          "The group context is not provided, and it is required by the build system.");
            }

            _linkCommentFiles  = new List <string>();
            _bindingRedirects  = new List <DependencyItem>();
            _searchDirectories = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            sourceContext.LinkCommentFiles = _linkCommentFiles;
            sourceContext.BindingRedirects = _bindingRedirects;

            // We add the comment files from the link sources so that the
            // document can contain comments from these sources if needed...
            IList <ReferenceLinkSource> linkSources = context.GetValue("$ReferenceLinkSources")
                                                      as IList <ReferenceLinkSource>;

            if (linkSources != null && linkSources.Count != 0)
            {
                for (int i = 0; i < linkSources.Count; i++)
                {
                    ReferenceLinkSource         linkSource = linkSources[i];
                    IEnumerable <ReferenceItem> linkItems  = linkSource.Items;
                    foreach (ReferenceItem linkItem in linkItems)
                    {
                        // Set if the comment file exists and link it...
                        BuildFilePath linkCommentPath = linkItem.Comments;
                        if (linkCommentPath != null && linkCommentPath.Exists)
                        {
                            _linkCommentFiles.Add(linkCommentPath.Path);
                        }
                        else
                        {
                            string linkCommentFile = Path.ChangeExtension(
                                linkItem.Assembly, ".xml");
                            if (File.Exists(linkCommentFile))
                            {
                                _linkCommentFiles.Add(linkCommentFile);
                            }
                        }
                    }
                }
            }

            string dependencyDir = sourceContext.DependencyDir;

            string searchDir = String.Copy(dependencyDir);

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

            _searchDirectories.Add(searchDir);

            ReferenceContent content = _content;

            if (content == null)
            {
                content = group.Content;
            }

            DependencyContent dependencies = content.Dependencies;

            _dependencyContent = dependencies;

            this.ResolveDependency(sourceContext, content);

            if (_dependencyContent != null && _dependencyContent.Count != 0)
            {
                this.CreateDependency(_dependencyContent, dependencyDir);
            }
            if (_resolveContent != null && _resolveContent.Count != 0)
            {
                this.CreateDependency(_resolveContent, dependencyDir);
            }

            //IList<string> bindingSources = sourceContext.BindingSources;
            //if (bindingSources == null)
            //{
            //    bindingSources = new BuildList<string>();
            //    sourceContext.BindingSources = bindingSources;
            //}
            //foreach (string dir in _searchDirectories)
            //{
            //    bindingSources.Add(dir);
            //}

            if (logger != null)
            {
                logger.WriteLine("Completed - Resolving reference dependencies.",
                                 BuildLoggerLevel.Info);
            }
        }
示例#11
0
        private void CreateReflectionSteps(BuildMultiStep listSteps,
                                           ReferenceGroup group, string sandcastleDir, string helpStyle)
        {
            Debug.Assert(_engineSettings != null);
            if (_engineSettings == null)
            {
                return;
            }

            BuildContext  context  = this.Context;
            BuildSettings settings = this.Settings;

            ReferenceGroupContext groupContext =
                context.GroupContexts[group.Id] as ReferenceGroupContext;

            if (groupContext == null)
            {
                throw new BuildException(
                          "The group context is not provided, and it is required by the build system.");
            }

            string workingDir = context.WorkingDirectory;

            ReferenceContent content       = group.Content;
            string           assemblyDir   = Path.Combine(workingDir, groupContext.AssemblyFolder);
            string           dependencyDir = Path.Combine(workingDir, groupContext.DependencyFolder);

            DependencyContent dependencies = content.Dependencies;

            string reflectionFile = groupContext["$ReflectionFile"];
            string manifestFile   = groupContext["$ManifestFile"];
            string refBuilderFile = groupContext["$ReflectionBuilderFile"];
            string tocFile        = groupContext["$TocFile"];

            BuildStyleType outputStyle = settings.Style.StyleType;

            string tempText = null;

            string arguments   = null;
            string application = null;

            bool ripOldApis = true;

            string assemblyFiles     = null;
            string dependencyFiles   = null;
            string outputFile        = null;
            string configurationFile = null;

            ReferenceVisibilityConfiguration visibility =
                _engineSettings.Visibility;

            Debug.Assert(visibility != null);
            // 1. Create the reflection and the manifest
            StringBuilder textBuilder = new StringBuilder();

            if (group.IsSingleVersion)
            {
                // Call MRefBuilder to generate the reflection...
                // MRefBuilder Assembly.dll
                // /out:reflection.org /config:MRefBuilder.config
                //   /internal-
                application = Path.Combine(context.SandcastleToolsDirectory,
                                           "MRefBuilder.exe");

                assemblyFiles     = String.Format(@"{0}\*.*", assemblyDir);
                dependencyFiles   = String.Format(@"{0}\*.*", dependencyDir);
                outputFile        = Path.ChangeExtension(reflectionFile, ".ver");
                configurationFile = Path.Combine(workingDir, refBuilderFile);

                textBuilder.Append(assemblyFiles);
                textBuilder.Append(" /dep:" + dependencyFiles);

                textBuilder.AppendFormat(" /out:{0} /config:{1}",
                                         outputFile, refBuilderFile);
                if (visibility != null && visibility.IncludeInternalsMembers)
                {
                    textBuilder.Append(" /internal+");
                }
                else
                {
                    textBuilder.Append(" /internal-");
                }

                arguments = textBuilder.ToString();

                outputFile = Path.Combine(workingDir, outputFile);
            }
            else
            {
                // Call the VersionBuilder to create the combined reflection file...
                application = Path.Combine(context.SandcastleToolsDirectory,
                                           "VersionBuilder.exe");

                textBuilder.AppendFormat(" /config:{0} /out:{1}",
                                         groupContext["$ApiVersionsBuilderFile"],
                                         Path.ChangeExtension(reflectionFile, ".org"));

                configurationFile = Path.Combine(workingDir,
                                                 groupContext["$ApiVersionsBuilderFile"]);

                ReferenceVersionInfo versionInfo = group.VersionInfo;
                ripOldApis = versionInfo.RipOldApis;
                if (ripOldApis)
                {
                    textBuilder.Append(" /rip+");
                }
                else
                {
                    textBuilder.Append(" /rip-");
                }

                arguments = textBuilder.ToString();
            }
            StepReflectionBuilder refBuilder = new StepReflectionBuilder(workingDir,
                                                                         application, arguments);

            refBuilder.Group           = group;
            refBuilder.LogTitle        = String.Empty;
            refBuilder.Message         = "Creating XML-formatted reflection information.";
            refBuilder.CopyrightNotice = 2;

            // For the direct use of the Sandcastle library, we need the
            // following parameters...
            refBuilder.RipOldApis        = ripOldApis;
            refBuilder.DocumentInternals =
                (visibility != null && visibility.IncludeInternalsMembers);
            refBuilder.ConfigurationFile = configurationFile;
            refBuilder.ReflectionFile    = outputFile;
            refBuilder.AssemblyFiles.Add(assemblyFiles);
            refBuilder.DependencyFiles.Add(dependencyFiles);

            listSteps.Add(refBuilder);

            textBuilder.Length = 0;

            // 2. Create the reflection and comment refining step...
            StepReferenceRefine referenceRefine =
                new StepReferenceRefine(workingDir);

            referenceRefine.LogTitle = String.Empty;
            referenceRefine.Message  = "Refining the reflection files - filtering and cleaning";
            referenceRefine.Group    = group;

            listSteps.Add(referenceRefine);

            textBuilder.Length = 0;

            // 3. Apply Transforms
            // XslTransform.exe
            // /xsl:"%DXROOT%\ProductionTransforms\ApplyVSDocModel.xsl"
            //    reflection.org
            //    /xsl:"%DXROOT%\ProductionTransforms\AddFriendlyFilenames.xsl"
            //    /out:reflection.xml /arg:IncludeAllMembersTopic=true
            //    /arg:IncludeInheritedOverloadTopics=true /arg:project=Project
            application = Path.Combine(context.SandcastleToolsDirectory,
                                       "XslTransform.exe");
            string prodPath = Path.Combine(sandcastleDir, "ProductionTransforms");
            string textTemp = String.Empty;

            if (group.EnableXmlnsForXaml)
            {
                textTemp = Path.Combine(prodPath, "AddXamlSyntaxData.xsl");
                if (!String.IsNullOrEmpty(textTemp))
                {
                    textBuilder.AppendFormat(" /xsl:\"{0}\"", textTemp);
                    textTemp = String.Empty;
                }
            }

            if (outputStyle == BuildStyleType.ClassicWhite ||
                outputStyle == BuildStyleType.ClassicBlue)
            {
                textTemp = Path.Combine(prodPath, "ApplyVSDocModel.xsl");
            }
            else if (outputStyle == BuildStyleType.Lightweight)
            {
            }
            else if (outputStyle == BuildStyleType.ScriptFree)
            {
            }
            if (!String.IsNullOrEmpty(textTemp))
            {
                textBuilder.AppendFormat(" /xsl:\"{0}\"", textTemp);
                textTemp = String.Empty;
            }

            ReferenceNamingMethod namingMethod = _engineSettings.Naming;

            if (namingMethod == ReferenceNamingMethod.Guid)
            {
                textTemp = Path.Combine(prodPath, "AddGuidFilenames.xsl");
            }
            else if (namingMethod == ReferenceNamingMethod.MemberName)
            {
                textTemp = Path.Combine(prodPath, "AddFriendlyFilenames.xsl");
            }
            else
            {
                textTemp = Path.Combine(prodPath, "AddGuidFilenames.xsl");
            }
            if (!String.IsNullOrEmpty(textTemp))
            {
                textBuilder.AppendFormat(" /xsl:\"{0}\"", textTemp);
                textTemp = String.Empty;
            }

            textBuilder.Append(" " + Path.ChangeExtension(reflectionFile, ".org"));
            textBuilder.AppendFormat(" /out:{0}", reflectionFile);
            textBuilder.AppendFormat(" /arg:IncludeAllMembersTopic={0}",
                                     _engineSettings.IncludeAllMembersTopic ? "true" : "false");
            textBuilder.AppendFormat(" /arg:IncludeInheritedOverloadTopics={0}",
                                     _engineSettings.IncludeInheritedOverloadTopics ? "true" : "false");

            bool   rootContainer = _engineSettings.RootNamespaceContainer;
            string rootTitle     = group.RootNamespaceTitle;

            if (rootContainer && !String.IsNullOrEmpty(rootTitle))
            {
                textBuilder.Append(" /arg:project=Project");
                // Indicate that this reference group is rooted...
                groupContext["$IsRooted"] = Boolean.TrueString;
            }
            arguments = textBuilder.ToString();
            StepReferenceModel applyDocProcess = new StepReferenceModel(
                workingDir, application, arguments);

            applyDocProcess.Group           = group;
            applyDocProcess.LogTitle        = String.Empty;
            applyDocProcess.Message         = "Xsl Transformation - Applying model and adding filenames";
            applyDocProcess.CopyrightNotice = 2;

            listSteps.Add(applyDocProcess);

            textBuilder.Length = 0;

            // 4. and finally the manifest...
            // XslTransform.exe
            // /xsl:"%DXROOT%\ProductionTransforms\ReflectionToManifest.xsl"
            //   reflection.xml /out:manifest.xml
            application = Path.Combine(context.SandcastleToolsDirectory,
                                       "XslTransform.exe");
            textTemp = Path.Combine(prodPath, "ReflectionToManifest.xsl");
            textBuilder.AppendFormat(" /xsl:\"{0}\"", textTemp);
            textBuilder.AppendFormat(" {0} /out:{1}", reflectionFile, manifestFile);
            arguments = textBuilder.ToString();
            StepReferenceManifest manifestProcess = new StepReferenceManifest(
                workingDir, application, arguments);

            manifestProcess.Group           = group;
            manifestProcess.LogTitle        = String.Empty;
            manifestProcess.Message         = "Xsl Transformation - Reflection to Manifest";
            manifestProcess.CopyrightNotice = 2;

            listSteps.Add(manifestProcess);

            // 5. Create the reflection table of contents
            // XslTransform.exe
            // /xsl:"%DXROOT%\ProductionTransforms\createvstoc.xsl"
            //    reflection.xml /out:ApiToc.xml
            application = Path.Combine(context.SandcastleToolsDirectory,
                                       "XslTransform.exe");
            if (outputStyle == BuildStyleType.ClassicWhite ||
                outputStyle == BuildStyleType.ClassicBlue)
            {
                tempText = Path.Combine(sandcastleDir,
                                        @"ProductionTransforms\CreateVSToc.xsl");
            }
            else if (outputStyle == BuildStyleType.Lightweight)
            {
            }
            else if (outputStyle == BuildStyleType.ScriptFree)
            {
            }
            arguments = String.Format("/xsl:\"{0}\" {1} /out:{2}",
                                      tempText, reflectionFile, tocFile);
            StepReferenceToc tocProcess = new StepReferenceToc(workingDir,
                                                               application, arguments);

            tocProcess.LogTitle        = String.Empty;
            tocProcess.Message         = "Xsl Transformation - Creating References TOC";
            tocProcess.Group           = group;
            tocProcess.CopyrightNotice = 2;

            listSteps.Add(tocProcess);
        }
示例#12
0
        private void ReadContents(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                return;
            }

            string startElement = reader.Name;

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (String.Equals(reader.Name, "content",
                                      StringComparison.OrdinalIgnoreCase))
                    {
                        switch (reader.GetAttribute("type").ToLower())
                        {
                        case "comments":
                            if (_commentContent == null)
                            {
                                _commentContent = new CommentContent();
                            }
                            if (reader.IsEmptyElement)
                            {
                                string sourceFile = reader.GetAttribute("source");
                                if (!String.IsNullOrEmpty(sourceFile))
                                {
                                    _commentContent.ContentFile = new BuildFilePath(sourceFile);
                                    _commentContent.Load();
                                }
                            }
                            else
                            {
                                if (reader.ReadToDescendant(CommentContent.TagName))
                                {
                                    _commentContent.ReadXml(reader);
                                }
                            }
                            break;

                        case "dependencies":
                            if (_dependencies == null)
                            {
                                _dependencies = new DependencyContent();
                            }
                            if (!reader.IsEmptyElement && reader.ReadToDescendant(
                                    DependencyContent.TagName))
                            {
                                _dependencies.ReadXml(reader);
                            }
                            break;

                        case "hierarchicaltoc":
                            if (_tocContent == null)
                            {
                                _tocContent = new HierarchicalTocContent();
                            }
                            if (!reader.IsEmptyElement && reader.ReadToDescendant(
                                    HierarchicalTocContent.TagName))
                            {
                                _tocContent.ReadXml(reader);
                            }
                            break;
                        }
                    }
                }
                else if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (String.Equals(reader.Name, startElement,
                                      StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }
                }
            }
        }
示例#13
0
        /// <summary>
        /// This creates the reference content from the available VS.NET items.
        /// </summary>
        /// <param name="groupContext">
        /// The context of the group which owns this source.
        /// </param>
        /// <returns>
        /// An instance of the <see cref="ReferenceContent"/> if successful;
        /// otherwise, this is <see langword="null"/>.
        /// </returns>
        private ReferenceContent OnCreateContent(BuildGroupContext groupContext)
        {
            Dictionary <string, ProjectSection> projects = new Dictionary <string, ProjectSection>(
                StringComparer.OrdinalIgnoreCase);

            BuildContext context       = groupContext.Context;
            string       platform      = context.TargetPlatform;
            string       configuration = context.TargetConfiguration;

            BuildLogger logger = context.Logger;

            // For each item, create the project sections...
            for (int i = 0; i < _listItems.Count; i++)
            {
                ReferenceVsNetItem vsNetItem = _listItems[i];

                if (vsNetItem != null && !vsNetItem.IsEmpty)
                {
                    HashSet <string> includeSet = new HashSet <string>(
                        vsNetItem.Includes);

                    IList <ProjectSection> sections =
                        ProjectSectionFactory.CreateSections(
                            vsNetItem.SourcePath.Path, platform, configuration,
                            includeSet);

                    if (sections != null && sections.Count != 0)
                    {
                        string useXamlSyntax = vsNetItem.XamlSyntax.ToString();

                        for (int j = 0; j < sections.Count; j++)
                        {
                            ProjectSection section = sections[j];
                            if (!String.IsNullOrEmpty(section.TargetFrameworkVersion) ||
                                !String.IsNullOrEmpty(section.TargetFrameworkIdentifier))
                            {
                                // Since the mapping from the VS.NET items
                                // to the project section is lost after this,
                                // we save this information...
                                section["UseXamlSyntax"] = useXamlSyntax;

                                projects[section.ProjectGuid] = section;
                            }
                        }
                    }
                }
            }

            // This is not expected, no managed project is found...
            if (projects.Count == 0)
            {
                if (logger != null)
                {
                    logger.WriteLine(String.Format(
                                         "The '{0}' reference content source does not contain any valid project.",
                                         this.Title), BuildLoggerLevel.Warn);
                }

                return(null);
            }

            IList <ProjectSection> projectSetions = new List <ProjectSection>(
                projects.Values);

            if (String.IsNullOrEmpty(_targetIdentifier))
            {
                // We are not filtering a particular target framework...
                if (projectSetions.Count > 1)
                {
                    BuildMultiMap <string, ProjectSection> multiSections =
                        new BuildMultiMap <string, ProjectSection>(
                            StringComparer.OrdinalIgnoreCase);

                    for (int i = 0; i < projectSetions.Count; i++)
                    {
                        ProjectSection section          = projectSetions[i];
                        string         targetIdentifier = section.TargetFrameworkIdentifier;
                        if (!String.IsNullOrEmpty(targetIdentifier))
                        {
                            multiSections.Add(targetIdentifier, section);
                        }
                    }

                    List <string> targetIdentifiers = new List <string>(multiSections.Keys);
                    if (targetIdentifiers.Count > 1)
                    {
                        // Error, there are more one target framework identifier.
                        if (logger != null)
                        {
                            StringBuilder builder = new StringBuilder();
                            for (int i = 0; i < targetIdentifiers.Count; i++)
                            {
                                builder.Append(targetIdentifiers[i]);
                                if (i < (targetIdentifiers.Count - 1))
                                {
                                    builder.Append(";");
                                }
                            }

                            logger.WriteLine(String.Format(
                                                 "The project items of '{0}' contain more than one target framework identifier '{1}'.",
                                                 this.Title, builder.ToString()), BuildLoggerLevel.Error);
                        }

                        return(null);
                    }
                }
            }
            else
            {
                IList <ProjectSection> filteredSetions = new List <ProjectSection>(projectSetions.Count);
                for (int i = 0; i < projectSetions.Count; i++)
                {
                    ProjectSection section = projectSetions[i];
                    if (String.Equals(section.TargetFrameworkIdentifier,
                                      _targetIdentifier, StringComparison.OrdinalIgnoreCase))
                    {
                        filteredSetions.Add(section);
                    }
                }

                // We will use the filtered sections
                projectSetions = filteredSetions;
            }

            // This is not expected, no managed project is found...
            if (projectSetions == null || projectSetions.Count == 0)
            {
                if (logger != null)
                {
                    logger.WriteLine(String.Format(
                                         "The '{0}' reference content source does not contain any valid project.",
                                         this.Title), BuildLoggerLevel.Warn);
                }

                return(null);
            }

            ReferenceContent content = new ReferenceContent();

            HashSet <string> dependencyDirs = new HashSet <string>(
                StringComparer.OrdinalIgnoreCase);
            HashSet <string> referencedAssemblies = new HashSet <string>(
                StringComparer.OrdinalIgnoreCase);

            Version frameworkVersion = new Version(1, 0, 0, 0);

            for (int i = 0; i < projectSetions.Count; i++)
            {
                ProjectSection section = projectSetions[i];

                string commentFile = section.CommentFile;
                if (String.IsNullOrEmpty(commentFile) || !File.Exists(commentFile))
                {
                    throw new BuildException(String.Format(
                                                 "The project '{0}' has no comment file.",
                                                 section.ProjectName));
                }
                string assemblyFile = section.OutputFile;
                if (String.IsNullOrEmpty(assemblyFile) || !File.Exists(assemblyFile))
                {
                    throw new BuildException(String.Format(
                                                 "The project '{0}' has no assembly file.",
                                                 section.ProjectName));
                }

                ReferenceItem refItem = new ReferenceItem(commentFile,
                                                          assemblyFile);

                string tempText = section["UseXamlSyntax"];
                if (!String.IsNullOrEmpty(tempText))
                {
                    refItem.XamlSyntax = Convert.ToBoolean(tempText);
                }

                // This should normally be in the format: v2.0, v3.0 etc
                string versionText = section.TargetFrameworkVersion;
                if (versionText != null && versionText.StartsWith("v",
                                                                  StringComparison.OrdinalIgnoreCase))
                {
                    versionText = versionText.Substring(1);
                }
                if (!String.IsNullOrEmpty(versionText))
                {
                    Version version = new Version(versionText);
                    if (version > frameworkVersion)
                    {
                        frameworkVersion = version;
                    }
                }

                content.Add(refItem);

                // Recursively extract the dependent assemblies information...
                CreateDependencies(section, dependencyDirs,
                                   referencedAssemblies);
            }

            // Provide the framework information of the content...
            BuildFrameworkKind frameworkKind   = BuildFrameworkKind.None;
            string             targetIdentifer = projectSetions[0].TargetFrameworkIdentifier;

            if (String.IsNullOrEmpty(targetIdentifer))
            {
                if (logger != null)
                {
                    logger.WriteLine("The target framework identifier is not found. Standard .NET Framework is assumed.",
                                     BuildLoggerLevel.Warn);
                }

                frameworkKind = BuildFrameworkKind.DotNet;
            }
            else
            {
                switch (targetIdentifer.ToLower())
                {
                case ".netframework":
                    frameworkKind = BuildFrameworkKind.DotNet;
                    break;

                case "silverlight":
                    frameworkKind = BuildFrameworkKind.Silverlight;
                    break;

                case ".netportable":
                    frameworkKind = BuildFrameworkKind.Portable;
                    break;

                case "scriptsharp":
                    // For the Script#, the version starts from 1.0 and
                    // does not match the .NET Framework version
                    frameworkVersion = BuildFrameworks.LatestScriptSharpVersion;
                    frameworkKind    = BuildFrameworkKind.ScriptSharp;
                    break;

                case "compact":
                    frameworkKind = BuildFrameworkKind.Compact;
                    break;

                default:
                    frameworkKind = BuildFrameworkKind.DotNet;
                    break;
                }
            }

            // Get the best framework for this content...
            BuildFramework framework = BuildFrameworks.GetFramework(
                frameworkVersion.Major, frameworkVersion.Minor, frameworkKind);

            if (framework == null)
            {
                if (logger != null)
                {
                    logger.WriteLine(String.Format(
                                         "The expected version '{0}' for '{1}', cannot be found.",
                                         frameworkVersion, this.Title), BuildLoggerLevel.Warn);
                }

                framework = BuildFrameworks.LatestFramework;

                if (framework == null)
                {
                    // If not successful, use the default...
                    framework = BuildFrameworks.DefaultFramework;
                }
            }

            content.FrameworkType = framework.FrameworkType;

            // Provide the dependency information for the content...
            DependencyContent          depContents = content.Dependencies;
            IList <BuildDirectoryPath> depPaths    = depContents.Paths;

            foreach (string dependencyDir in dependencyDirs)
            {
                if (String.IsNullOrEmpty(dependencyDir) ||
                    !Directory.Exists(dependencyDir))
                {
                    continue;
                }

                depPaths.Add(new BuildDirectoryPath(dependencyDir));
            }
            foreach (string referencedAssembly in referencedAssemblies)
            {
                depContents.AddItem(referencedAssembly);
            }

            // Provide other user-supplied information to the content...
            content.Comments         = this.Comments;
            content.HierarchicalToc  = this.HierarchicalToc;
            content.TypeFilters      = this.TypeFilters;
            content.AttributeFilters = this.AttributeFilters;

            return(content);
        }