/// <summary>
        /// Convert any Assembly References to Project References. If a project references and assembly that is built by
        /// another project in this solution.  Then replace the assembly reference by a project reference.
        /// </summary>
        /// <param name="project">The project for which to construct ProjectReferences</param>
        private void FixReferences(ProjectEx project)
        {
            foreach (_BE.ProjectItem buildItem in project.MsBuildProject.GetItems("Reference"))
            {
                if (projects.ContainsKey(buildItem.Xml.Include))
                {
                    ProjectEx referencedProject = projects[buildItem.Xml.Include].Project;

                    project.MsBuildProject.RemoveItem(buildItem);

                    string rpName     = referencedProject.GetEvaluatedProperty("MSBuildProjectName");
                    string rpFullName = Path.GetFileName(referencedProject.FullFileName);
                    Dictionary <string, string> meta = new Dictionary <string, string>();

                    meta.Add("Project", referencedProject.GetEvaluatedProperty("ProjectGuid"));
                    meta.Add("Name", rpName);

                    project.MsBuildProject.AddItem("ProjectReference", project.PathToSolution + referencedProject.SolutionRelativePath, meta);
                }
            }
        }
        private void ReplaceGuidPropertyIfExists(ProjectEx project, string propertyName)
        {
            string value = project.GetEvaluatedProperty(propertyName);

            if (!string.IsNullOrEmpty(value))
            {
                try
                {
                    Guid   g = new Guid(value);
                    string replaceWith;
                    if (guidDictionary.TryGetValue(g, out replaceWith))
                    {
                        //VS Guid replacements don't include braces
                        replaceWith = "{" + replaceWith + "}";
                        project.MsBuildProject.SetProperty(propertyName, replaceWith.ToUpper());
                    }
                }
                catch (FormatException)
                {
                    Log.LogWarning("Project {0} has specified an {1} property not in the format of a Guid.", project.FullFileName, propertyName);
                }
            }
        }
        public override bool Execute()
        {
            if (!ValidateInputs())
            {
                return false;
            }

            try
            {
                ProjectEx.Task = this;
                ProjectEx.Terminals = terminalTargets;
                IEnumerator<KeyValuePair<string, ProjectToTransform>> ienum;
                Version version = new Version(major, minor, build, revision);

                BuildGuidDictionary();
                
                //Load all of the specified projects.
                for (int i = 0; i < srcProjects.Length; i++)
                {
                    ITaskItem srcProject = srcProjects[i];
                    ITaskItem destProject = destProjects[i];

                    if (RunSDKTransform)
                    {
                        string preTransform = srcProject.GetMetadata("PreTransform");
                        if (!string.IsNullOrEmpty(preTransform))
                        {
                            if (!File.Exists(preTransform))
                            {
                                Log.LogWarning("PreTransform \"{0}\" does not exist", preTransform);
                                preTransform = null;
                            }
                        }

                        string postTransform = srcProject.GetMetadata("PostTransform");
                        if (string.IsNullOrEmpty(postTransform))
                        {
                            postTransform = null;
                        }
                        else if (!File.Exists(postTransform))
                        {
                            Log.LogWarning("PostTransform \"{0}\" does not exist", postTransform);

                            postTransform = null;
                        }

                        string transformMetadataValue = srcProject.GetMetadata("Transform");
                        string transformType = "Client";
                        if (transformMetadataValue != null && transformMetadataValue.Equals("Server", StringComparison.OrdinalIgnoreCase))
                        {
                            transformType = "Server";
                        }

                        TransFormProject transformProj = new TransFormProject(transformType, version, srcProject.ItemSpec, destProject.ItemSpec, TargetToolsVersion);

                        transformProj.Transform(preTransform, postTransform);
                    }
                    else if(srcProject.GetMetadata("FullPath") != destProject.GetMetadata("FullPath"))
                    {
                        File.Copy(srcProject.GetMetadata("FullPath"), destProject.GetMetadata("FullPath"));
                    }

                    ProjectEx project = new ProjectEx(destProject, version, srcProject.GetMetadata("FullPath"));
                    project.TargetToolsVersion = TargetToolsVersion;

                    // only load after transform
                    project.Load();

                    RemoveSourceControlAnnotations(project);

                    string assemblyName = project.GetEvaluatedProperty("AssemblyName");
                    projects.Add(assemblyName, new ProjectToTransform { Project = project, DestinationFile = destProject.ItemSpec });

                    //Transforms all paths into relative paths... This probably isn't necessary, as all paths should be relative already...
                    //and a warning is spit out in GetProjectChildFiles now.
                    project.NormalizePaths(true);
                }


                if (RunSDKTransform)
                {
                    ienum = projects.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        ProjectEx project = ienum.Current.Value.Project;

                        List<Build.Construction.ProjectElement> groupsToRemove = new List<Build.Construction.ProjectElement>();

                        foreach (Build.Construction.ProjectPropertyGroupElement bpg in project.MsBuildProject.Xml.PropertyGroups)
                        {
                            if (bpg != null && !string.IsNullOrEmpty(bpg.Condition) && bpg.Condition.ToLower().Contains("$(spoclient)"))
                            {
                                Console.WriteLine("------ remove property group --- " + bpg.Condition);
                                groupsToRemove.Add(bpg);
                            }
                        }

                        foreach (Build.Construction.ProjectImportElement imp in project.MsBuildProject.Xml.Imports)
                        {
                            if (!string.IsNullOrEmpty(imp.Condition) && imp.Condition.ToLower().Contains("$(spoclient)"))
                            {
                                groupsToRemove.Add(imp);
                            }
                        }

                        foreach (Build.Construction.ProjectElement propertyG in groupsToRemove)
                        {
                            project.MsBuildProject.Xml.RemoveChild(propertyG);
                        }
                    }
                }

                if (RunTemplateTransform)
                {
                    ienum = projects.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        ProjectEx project = ienum.Current.Value.Project;
                        List<_BE.ProjectProperty> toRemove = new List<_BE.ProjectProperty>();

                        foreach (_BE.ProjectProperty property in project.MsBuildProject.AllEvaluatedProperties)
                        {
                            if (property.Name == "TemplateNameString" ||
                                property.Name == "TemplateNamePackage" ||
                                property.Name == "TemplateNameResID" ||
                                property.Name == "TemplateDescriptionString" ||
                                property.Name == "TemplateDescriptionPackage" ||
                                property.Name == "TeplateDescriptionResID" ||
                                property.Name == "TemplateIconFile" ||
                                property.Name == "TemplateIconPackage" ||
                                property.Name == "TemplateIconResID" ||
                                property.Name == "TemplateID" ||
                                property.Name == "TemplateDefaultName" ||
                                property.Name == "TemplateProjectType" ||
                                property.Name == "TemplateProjectSubType" ||
                                property.Name == "TemplateRequiredFrameworkVersion" ||
                                property.Name == "TemplateSortOrder")
                            {
                                toRemove.Add(property);
                            }
                        }

                        foreach (_BE.ProjectProperty prop in toRemove)
                        {
                            project.MsBuildProject.RemoveProperty(prop);
                        }

                        ReplaceGuidPropertyIfExists(project, "ProjectGuid");
                        ReplaceGuidPropertyIfExists(project, "EmulatorId");

                        foreach (_BE.ProjectItem item in project.MsBuildProject.GetItemsIgnoringCondition("ProjectReference"))
                        {
                            ReplaceGuidMetadataIfExists(item, "Project");
                        }

                        string rootNamepace = project.GetEvaluatedProperty("RootNamespace");
                        TransmorgificationUtilities.MakeTemplateReplacements(true, true, rootNamepace, project.FullFileName, project.MsBuildProject);
                    }
                }
                

                ienum = projects.GetEnumerator();
                while (ienum.MoveNext())
                {
                    /* Projects cannot be saved until multiple passes have been performed over all the projects to allow
                     * template transforms to replace all GUIDs with autogenerated GUID identifiers, and ProjectReferences
                     * to be updated to reflect those modified GUIDs */
                    ProjectEx project = ienum.Current.Value.Project;

                    //project.DefaultToolsVersion = TargetToolsVersion;
                    project.TargetToolsVersion = TargetToolsVersion;
                    string assemblyName = project.GetEvaluatedProperty("AssemblyName");
                    project.MsBuildProject.Save(ienum.Current.Value.DestinationFile, Encoding.UTF8);
                }

                if (!string.IsNullOrEmpty(solutionFile))
                {
                    WiXSolution sln = new WiXSolution();
                    sln.Shortcut = shortcutType;
                    sln.ParentDirectoryRef = parentDirectoryRef;
                    sln.FragmentIncludeFiles = fragmentIncludeFiles;
                    sln.ComponentIncludeFiles = componentIncludeFiles;

                    ienum = projects.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        sln.Add(new SolutionObject(ienum.Current.Value.Project));
                    }

                    if (extraSlnFiles != null && extraSlnFiles.Length > 0)
                    {
                        foreach (ITaskItem extraSlnFile in extraSlnFiles)
                        {
                            sln.Add(new SolutionObject(new SolutionFile(extraSlnFile)));
                        }
                    }

                    if (string.IsNullOrEmpty(wxsFile))
                    {
                        sln.Save(solutionFile);
                    }
                    else
                    {
                        if (componentGuid == default(Guid))
                        {
                            Log.LogError("ComponentGuid is required when a WiX output is specified");
                        }
                        else
                        {
                            sln.Save(solutionFile, wxsFile, componentGuid);
                        }
                    }
                }
                else
                {
                    //Warn that certain properties are ignored if a solution isn't specified.
                    if(!string.IsNullOrEmpty(wxsFile))
                    {
                        Log.LogWarning("Not generating WiX source {0}; WiX files are not generated unless a Visual Studio Solution is also generated.",
                            wxsFile);
                    }
                }

                return true;
            }
            catch (Exception e)
            {
                this.Log.LogErrorFromException(e, true, true, null);
                return false;
            }
        }
 private void ReplaceGuidPropertyIfExists(ProjectEx project, string propertyName)
 {
     string value = project.GetEvaluatedProperty(propertyName);
     if (!string.IsNullOrEmpty(value))
     {
         try
         {
             Guid g = new Guid(value);
             string replaceWith;
             if (guidDictionary.TryGetValue(g, out replaceWith))
             {
                 //VS Guid replacements don't include braces
                 replaceWith = "{" + replaceWith + "}";
                 project.MsBuildProject.SetProperty(propertyName, replaceWith.ToUpper());
             }
         }
         catch (FormatException)
         {
             Log.LogWarning("Project {0} has specified an {1} property not in the format of a Guid.", project.FullFileName, propertyName);
         }
     }
 }
        public override bool Execute()
        {
            if (!ValidateInputs())
            {
                return(false);
            }

            try
            {
                ProjectEx.Task      = this;
                ProjectEx.Terminals = terminalTargets;
                IEnumerator <KeyValuePair <string, ProjectToTransform> > ienum;
                Version version = new Version(major, minor, build, revision);

                BuildGuidDictionary();

                //Load all of the specified projects.
                for (int i = 0; i < srcProjects.Length; i++)
                {
                    ITaskItem srcProject  = srcProjects[i];
                    ITaskItem destProject = destProjects[i];

                    if (RunSDKTransform)
                    {
                        string preTransform = srcProject.GetMetadata("PreTransform");
                        if (!string.IsNullOrEmpty(preTransform))
                        {
                            if (!File.Exists(preTransform))
                            {
                                Log.LogWarning("PreTransform \"{0}\" does not exist", preTransform);
                                preTransform = null;
                            }
                        }

                        string postTransform = srcProject.GetMetadata("PostTransform");
                        if (string.IsNullOrEmpty(postTransform))
                        {
                            postTransform = null;
                        }
                        else if (!File.Exists(postTransform))
                        {
                            Log.LogWarning("PostTransform \"{0}\" does not exist", postTransform);

                            postTransform = null;
                        }

                        string transformMetadataValue = srcProject.GetMetadata("Transform");
                        string transformType          = "Client";
                        if (transformMetadataValue != null && transformMetadataValue.Equals("Server", StringComparison.OrdinalIgnoreCase))
                        {
                            transformType = "Server";
                        }

                        TransFormProject transformProj = new TransFormProject(transformType, version, srcProject.ItemSpec, destProject.ItemSpec, TargetToolsVersion);

                        transformProj.Transform(preTransform, postTransform);
                    }
                    else if (srcProject.GetMetadata("FullPath") != destProject.GetMetadata("FullPath"))
                    {
                        File.Copy(srcProject.GetMetadata("FullPath"), destProject.GetMetadata("FullPath"));
                    }

                    ProjectEx project = new ProjectEx(destProject, version, srcProject.GetMetadata("FullPath"));
                    project.TargetToolsVersion = TargetToolsVersion;

                    // only load after transform
                    project.Load();

                    RemoveSourceControlAnnotations(project);

                    string assemblyName = project.GetEvaluatedProperty("AssemblyName");
                    projects.Add(assemblyName, new ProjectToTransform {
                        Project = project, DestinationFile = destProject.ItemSpec
                    });

                    //Transforms all paths into relative paths... This probably isn't necessary, as all paths should be relative already...
                    //and a warning is spit out in GetProjectChildFiles now.
                    project.NormalizePaths(true);
                }


                if (RunSDKTransform)
                {
                    ienum = projects.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        ProjectEx project = ienum.Current.Value.Project;

                        List <Build.Construction.ProjectElement> groupsToRemove = new List <Build.Construction.ProjectElement>();

                        foreach (Build.Construction.ProjectPropertyGroupElement bpg in project.MsBuildProject.Xml.PropertyGroups)
                        {
                            if (bpg != null && !string.IsNullOrEmpty(bpg.Condition) && bpg.Condition.ToLower().Contains("$(spoclient)"))
                            {
                                Console.WriteLine("------ remove property group --- " + bpg.Condition);
                                groupsToRemove.Add(bpg);
                            }
                        }

                        foreach (Build.Construction.ProjectImportElement imp in project.MsBuildProject.Xml.Imports)
                        {
                            if (!string.IsNullOrEmpty(imp.Condition) && imp.Condition.ToLower().Contains("$(spoclient)"))
                            {
                                groupsToRemove.Add(imp);
                            }
                        }

                        foreach (Build.Construction.ProjectElement propertyG in groupsToRemove)
                        {
                            project.MsBuildProject.Xml.RemoveChild(propertyG);
                        }
                    }
                }

                if (RunTemplateTransform)
                {
                    ienum = projects.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        ProjectEx project = ienum.Current.Value.Project;
                        List <_BE.ProjectProperty> toRemove = new List <_BE.ProjectProperty>();

                        foreach (_BE.ProjectProperty property in project.MsBuildProject.AllEvaluatedProperties)
                        {
                            if (property.Name == "TemplateNameString" ||
                                property.Name == "TemplateNamePackage" ||
                                property.Name == "TemplateNameResID" ||
                                property.Name == "TemplateDescriptionString" ||
                                property.Name == "TemplateDescriptionPackage" ||
                                property.Name == "TeplateDescriptionResID" ||
                                property.Name == "TemplateIconFile" ||
                                property.Name == "TemplateIconPackage" ||
                                property.Name == "TemplateIconResID" ||
                                property.Name == "TemplateID" ||
                                property.Name == "TemplateDefaultName" ||
                                property.Name == "TemplateProjectType" ||
                                property.Name == "TemplateProjectSubType" ||
                                property.Name == "TemplateRequiredFrameworkVersion" ||
                                property.Name == "TemplateSortOrder")
                            {
                                toRemove.Add(property);
                            }
                        }

                        foreach (_BE.ProjectProperty prop in toRemove)
                        {
                            project.MsBuildProject.RemoveProperty(prop);
                        }

                        ReplaceGuidPropertyIfExists(project, "ProjectGuid");
                        ReplaceGuidPropertyIfExists(project, "EmulatorId");

                        foreach (_BE.ProjectItem item in project.MsBuildProject.GetItemsIgnoringCondition("ProjectReference"))
                        {
                            ReplaceGuidMetadataIfExists(item, "Project");
                        }

                        string rootNamepace = project.GetEvaluatedProperty("RootNamespace");
                        TransmorgificationUtilities.MakeTemplateReplacements(true, true, rootNamepace, project.FullFileName, project.MsBuildProject);
                    }
                }


                ienum = projects.GetEnumerator();
                while (ienum.MoveNext())
                {
                    /* Projects cannot be saved until multiple passes have been performed over all the projects to allow
                     * template transforms to replace all GUIDs with autogenerated GUID identifiers, and ProjectReferences
                     * to be updated to reflect those modified GUIDs */
                    ProjectEx project = ienum.Current.Value.Project;

                    //project.DefaultToolsVersion = TargetToolsVersion;
                    project.TargetToolsVersion = TargetToolsVersion;
                    string assemblyName = project.GetEvaluatedProperty("AssemblyName");
                    project.MsBuildProject.Save(ienum.Current.Value.DestinationFile, Encoding.UTF8);
                }

                if (!string.IsNullOrEmpty(solutionFile))
                {
                    WiXSolution sln = new WiXSolution();
                    sln.Shortcut              = shortcutType;
                    sln.ParentDirectoryRef    = parentDirectoryRef;
                    sln.FragmentIncludeFiles  = fragmentIncludeFiles;
                    sln.ComponentIncludeFiles = componentIncludeFiles;

                    ienum = projects.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        sln.Add(new SolutionObject(ienum.Current.Value.Project));
                    }

                    if (extraSlnFiles != null && extraSlnFiles.Length > 0)
                    {
                        foreach (ITaskItem extraSlnFile in extraSlnFiles)
                        {
                            sln.Add(new SolutionObject(new SolutionFile(extraSlnFile)));
                        }
                    }

                    if (string.IsNullOrEmpty(wxsFile))
                    {
                        sln.Save(solutionFile);
                    }
                    else
                    {
                        if (componentGuid == default(Guid))
                        {
                            Log.LogError("ComponentGuid is required when a WiX output is specified");
                        }
                        else
                        {
                            sln.Save(solutionFile, wxsFile, componentGuid);
                        }
                    }
                }
                else
                {
                    //Warn that certain properties are ignored if a solution isn't specified.
                    if (!string.IsNullOrEmpty(wxsFile))
                    {
                        Log.LogWarning("Not generating WiX source {0}; WiX files are not generated unless a Visual Studio Solution is also generated.",
                                       wxsFile);
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                this.Log.LogErrorFromException(e, true, true, null);
                return(false);
            }
        }
        public override bool Execute()
        {
            try
            {
                List <ITaskItem> contentsList   = new List <ITaskItem>();
                List <ITaskItem> dependencyList = new List <ITaskItem>();
                List <ITaskItem> templateList   = new List <ITaskItem>();
                HashSet <Guid>   guids          = new HashSet <Guid>();

                ProjectEx.Task = this;

                foreach (ITaskItem projectItem in projectFiles)
                {
                    string currentDirectory = Environment.CurrentDirectory;

                    ProjectEx project = new ProjectEx(projectItem);

                    project.Load();

                    Environment.CurrentDirectory = Path.GetDirectoryName(
                        project.FullFileName);

                    //Retrieve the list of Guids defined in the project, for later replacement.
                    string projectGuid = project.GetEvaluatedProperty("ProjectGuid");
                    if (!string.IsNullOrEmpty(projectGuid))
                    {
                        try
                        {
                            Guid guidProject = new Guid(projectGuid);
                            if (!guids.Contains(guidProject))
                            {
                                guids.Add(guidProject);
                            }
                        }
                        catch (FormatException)
                        {
                            Log.LogWarning("Project {0} has specified an ProjectGuid property not in the format of a Guid.", projectItem.ItemSpec);
                        }
                    }

                    string emulatorId = project.GetEvaluatedProperty("EmulatorId");
                    if (!string.IsNullOrEmpty(emulatorId))
                    {
                        try
                        {
                            Guid guidEmulator = new Guid(emulatorId);
                            if (!guids.Contains(guidEmulator))
                            {
                                guids.Add(guidEmulator);
                            }
                        }
                        catch (FormatException)
                        {
                            Log.LogWarning("Project {0} has specified an EmulatorId property not in the format of a Guid.", projectItem.ItemSpec);
                        }
                    }

                    //Select all the files referenced by the project.
                    foreach (string groupName in ProjectEx.FileGroups)
                    {
                        foreach (_BE.ProjectItem buildItem in project.MsBuildProject.GetItemsIgnoringCondition(groupName))
                        {
                            if (TransmorgificationUtilities.IsInRestrictedList(buildItem.Xml.Include))
                            {
                                Log.LogMessage("Skipping restricted file {0} in project {1}", buildItem.EvaluatedInclude, projectItem.ItemSpec);
                                continue;
                            }
                            else if (!File.Exists(buildItem.EvaluatedInclude)) // .GetMetadata("FullPath").EvaluatedValue))
                            {
                                Log.LogWarning("Cannot find file {0} referenced in project {1}", buildItem.EvaluatedInclude, projectItem.ItemSpec);
                                continue;
                            }

                            string fileName = buildItem.EvaluatedInclude;
                            if (Path.IsPathRooted(fileName))
                            {
                                Log.LogWarning("Project {0} references file {1} by absolute path, which is unsuitable for samples and templates", projectItem.ItemSpec, fileName);
                            }

                            TaskItem file           = new TaskItem(fileName);
                            bool     doReplacements = TransmorgificationUtilities.ValidMimeTypeForReplacements(buildItem.Xml.Include);
                            file.CopyMetadata(buildItem);
                            file.SetMetadata("DoReplacements", doReplacements.ToString().ToLowerInvariant());
                            file.SetMetadata("ItemCollection", buildItem.ItemType);
                            file.SetMetadata("ParentProject", projectItem.ItemSpec);
                            file.SetMetadata("ProjectDir", projectItem.GetMetadata("RelativeDir"));
                            string rootNamespace = project.GetEvaluatedProperty("RootNamespace");
                            if (rootNamespace == null)
                            {
                                rootNamespace = "";
                            }
                            file.SetMetadata("RootNamespace", rootNamespace);

                            contentsList.Add(file);
                        }
                    }

                    string templateIconFile = project.GetEvaluatedProperty("TemplateIconFile");
                    if (!string.IsNullOrEmpty(templateIconFile))
                    {
                        TaskItem file = CreateExtraFile(templateIconFile, projectItem);
                        if (file != null)
                        {
                            contentsList.Add(file);
                        }
                    }

                    foreach (string extraFile in project.ExtraFiles)
                    {
                        TaskItem file = CreateExtraFile(extraFile, projectItem);
                        if (file != null)
                        {
                            contentsList.Add(file);
                        }
                    }

                    /*
                     * if (project.PreTransform != null)
                     * {
                     *  dependencyList.Add(new TaskItem(project.PreTransform));
                     * }
                     *
                     * if (project.PostTransform != null)
                     * {
                     *  dependencyList.Add(new TaskItem(project.PostTransform));
                     * }
                     */

                    Environment.CurrentDirectory = currentDirectory;
                }


                List <ITaskItem> replacements = new List <ITaskItem>();
                int guidNum = 1;
                foreach (Guid guid in guids)
                {
                    TaskItem guidItem = new TaskItem(guid.ToString("D"));
                    guidItem.SetMetadata("ReplaceWith", "$guid" + guidNum.ToString() + "$");
                    replacements.Add(guidItem);
                    guidNum++;
                    if (guidNum > 10)
                    {
                        break;
                    }
                }

                projectContents     = contentsList.ToArray();
                projectDependencies = dependencyList.ToArray();
                guidReplacements    = replacements.ToArray();
                return(true);
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e, true, true, null);
                return(false);
            }
        }
Exemplo n.º 7
0
        public override bool Execute()
        {
            try
            {
                List<ITaskItem> contentsList = new List<ITaskItem>();
                List<ITaskItem> dependencyList = new List<ITaskItem>();
                List<ITaskItem> templateList = new List<ITaskItem>();
                HashSet<Guid>   guids = new HashSet<Guid>();

                ProjectEx.Task = this;

                foreach (ITaskItem projectItem in projectFiles)
                {
                    string currentDirectory = Environment.CurrentDirectory;

                    ProjectEx project = new ProjectEx(projectItem);

                    project.Load();

                    Environment.CurrentDirectory = Path.GetDirectoryName(
                        project.FullFileName);

                    //Retrieve the list of Guids defined in the project, for later replacement.
                    string projectGuid = project.GetEvaluatedProperty("ProjectGuid");
                    if (!string.IsNullOrEmpty(projectGuid))
                    {
                        try
                        {
                            Guid guidProject = new Guid(projectGuid);
                            if (!guids.Contains(guidProject))
                            {
                                guids.Add(guidProject);
                            }
                        }
                        catch (FormatException)
                        {
                            Log.LogWarning("Project {0} has specified an ProjectGuid property not in the format of a Guid.", projectItem.ItemSpec);
                        }
                    }

                    string emulatorId = project.GetEvaluatedProperty("EmulatorId");
                    if (!string.IsNullOrEmpty(emulatorId))
                    {
                        try
                        {
                            Guid guidEmulator = new Guid(emulatorId);
                            if (!guids.Contains(guidEmulator))
                            {
                                guids.Add(guidEmulator);
                            }
                        }
                        catch (FormatException)
                        {
                            Log.LogWarning("Project {0} has specified an EmulatorId property not in the format of a Guid.", projectItem.ItemSpec);
                        }
                    }

                    //Select all the files referenced by the project.
                    foreach (string groupName in ProjectEx.FileGroups)
                    {
                        foreach (_BE.ProjectItem buildItem in project.MsBuildProject.GetItemsIgnoringCondition(groupName))
                        {
                            if (TransmorgificationUtilities.IsInRestrictedList(buildItem.Xml.Include))
                            {
                                Log.LogMessage("Skipping restricted file {0} in project {1}", buildItem.EvaluatedInclude, projectItem.ItemSpec);
                                continue;
                            }
                            else if (!File.Exists(buildItem.EvaluatedInclude)) // .GetMetadata("FullPath").EvaluatedValue))
                            {
                                Log.LogWarning("Cannot find file {0} referenced in project {1}", buildItem.EvaluatedInclude, projectItem.ItemSpec);
                                continue;
                            }

                            string fileName = buildItem.EvaluatedInclude;
                            if (Path.IsPathRooted(fileName))
                            {
                                Log.LogWarning("Project {0} references file {1} by absolute path, which is unsuitable for samples and templates", projectItem.ItemSpec, fileName);
                            }

                            TaskItem file = new TaskItem(fileName);
                            bool doReplacements = TransmorgificationUtilities.ValidMimeTypeForReplacements(buildItem.Xml.Include);
                            file.CopyMetadata(buildItem);
                            file.SetMetadata("DoReplacements", doReplacements.ToString().ToLowerInvariant());
                            file.SetMetadata("ItemCollection", buildItem.ItemType);
                            file.SetMetadata("ParentProject", projectItem.ItemSpec);
                            file.SetMetadata("ProjectDir", projectItem.GetMetadata("RelativeDir"));
                            string rootNamespace = project.GetEvaluatedProperty("RootNamespace");
                            if (rootNamespace == null)
                            {
                                rootNamespace = "";
                            }
                            file.SetMetadata("RootNamespace", rootNamespace);

                            contentsList.Add(file);
                        }
                    }

                    string templateIconFile = project.GetEvaluatedProperty("TemplateIconFile");
                    if (!string.IsNullOrEmpty(templateIconFile))
                    {
                        TaskItem file = CreateExtraFile(templateIconFile, projectItem);
                        if (file != null)
                        {
                            contentsList.Add(file);
                        }
                    }

                    foreach (string extraFile in project.ExtraFiles)
                    {
                        TaskItem file = CreateExtraFile(extraFile, projectItem);
                        if (file != null)
                        {
                            contentsList.Add(file);
                        }
                    }

                    /*
                    if (project.PreTransform != null)
                    {
                        dependencyList.Add(new TaskItem(project.PreTransform));
                    }

                    if (project.PostTransform != null)
                    {
                        dependencyList.Add(new TaskItem(project.PostTransform));
                    }
                    */

                    Environment.CurrentDirectory = currentDirectory;
                }


                List<ITaskItem> replacements = new List<ITaskItem>();
                int guidNum = 1;
                foreach (Guid guid in guids)
                {
                    TaskItem guidItem = new TaskItem(guid.ToString("D"));
                    guidItem.SetMetadata("ReplaceWith", "$guid" + guidNum.ToString() + "$");
                    replacements.Add(guidItem);
                    guidNum++;
                    if (guidNum > 10)
                    {
                        break;
                    }
                }

                projectContents = contentsList.ToArray();
                projectDependencies = dependencyList.ToArray();
                guidReplacements = replacements.ToArray();
                return true;
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e, true, true, null);
                return false;
            }
        }
Exemplo n.º 8
0
        public void Save(string solutionFile)
        {
            string allProjectDecl = "";
            string allConfig      = "";

            string[] otherList = { "ActiveCfg", "Build.0", "Deploy.0" };

            string allSolutionDecl = "";

            foreach (SolutionObject slnObj in this)
            {
                if (slnObj.Object is ProjectEx)
                {
                    ProjectEx project     = slnObj.Object as ProjectEx;
                    string    projectDecl = BuildTaskResource.ProjectDeclarationTemplate;

                    string projectGuid = project.GetEvaluatedProperty("ProjectGuid").ToUpper();

                    projectDecl = projectDecl.Replace("<PROJECTNAME>", project.GetEvaluatedProperty("MSBuildProjectName"));
                    projectDecl = projectDecl.Replace("<PROJECTPATH>", project.SolutionRelativePath);
                    projectDecl = projectDecl.Replace("<PROJECTGUID>", projectGuid);

                    allProjectDecl += projectDecl;

                    foreach (string buildFlavor in project.BuildFlavors)
                    {
                        foreach (string other in otherList)
                        {
                            if (other == "Deploy.0" && !project.Deploy)
                            {
                                continue;
                            }

                            string projectConfig = BuildTaskResource.ProjectConfigurationPlatformTemplate;
                            projectConfig = projectConfig.Replace("<PROJECTGUID>", projectGuid);
                            projectConfig = projectConfig.Replace("<BUILDFLAVOR>", buildFlavor);
                            projectConfig = projectConfig.Replace("<OTHERINFO>", other);

                            allConfig += projectConfig;
                        }
                    }
                }
                else
                {
                    SolutionFile slnFileObj = slnObj.Object as SolutionFile;

                    if (slnFileObj.IncludeInSolution)
                    {
                        if (allSolutionDecl != "")
                        {
                            allSolutionDecl += "\r\n";
                        }
                        allSolutionDecl += BuildTaskResource.SolutionFileDeclarationTemplate.Replace(
                            "<SOLUTIONFILENAME>", Path.GetFileName(slnFileObj.File));
                    }
                }
            }

            if (allSolutionDecl != "")
            {
                string solutionProjectDecl = BuildTaskResource.SolutionProjectDeclarationTemplate;
                solutionProjectDecl = solutionProjectDecl.Replace(
                    "<SOLUTIONFILEDECLARATIONSECTION>",
                    allSolutionDecl);

                solutionProjectDecl = solutionProjectDecl.Replace(
                    "<SOLUTIONITEMSGUID>",
                    "{" + Guid.NewGuid().ToString().ToUpper() + "}");

                allProjectDecl += solutionProjectDecl;
            }

            string solutionBody = BuildTaskResource.SolutionTemplate;

            solutionBody = solutionBody.Replace("<PROJECTDECL>", allProjectDecl);
            solutionBody = solutionBody.Replace("<GLOBALPROJECTCONFIGURATIONPLATFORMS>", allConfig);

            StreamWriter writer = new StreamWriter(solutionFile);

            writer.Write(solutionBody);
            writer.Close();
        }