private TaskItem CreateExtraFile(string extraFile, ITaskItem projectItem)
        {
            string path     = BuildTaskUtility.ExpandEnvironmentVariables(extraFile);
            string fullPath = Path.GetFullPath(path);

            if (!File.Exists(fullPath))
            {
                Log.LogWarning("Cannot find extra file {0} for project {1}", extraFile, projectItem.ItemSpec);
                return(null);
            }

            TaskItem file           = new TaskItem(path);
            bool     doReplacements = TransmorgificationUtilities.ValidMimeTypeForReplacements(extraFile);

            file.SetMetadata("DoReplacements", doReplacements.ToString().ToLowerInvariant());
            file.SetMetadata("ItemCollection", "Extra");
            file.SetMetadata("ParentProject", projectItem.ItemSpec);
            file.SetMetadata("ProjectDir", projectItem.GetMetadata("RelativeDir"));

            return(file);
        }
        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);
            }
        }
        public override bool Execute()
        {
            if (sourceFiles == null || sourceFiles.Length == 0)
            {
                destinationFiles = new TaskItem[0];
                return(true);
            }
            if (!ValidateInputs())
            {
                return(false);
            }

            bool result = true;

            for (int i = 0; i < sourceFiles.Length; i++)
            {
                bool   doReplacements;
                string rootNamespace;
                if (!Boolean.TryParse(sourceFiles[i].GetMetadata("DoReplacements"), out doReplacements))
                {
                    Log.LogWarning("File {0} was passed to TransmorgifyTemplateFiles despite 'DoReplacements' metadata being unset.",
                                   sourceFiles[i].ItemSpec);
                    continue;
                }
                else if (doReplacements == false)
                {
                    Log.LogWarning("File {0} was passed to TransmorgifyTemplateFiles despite 'DoReplacements' metadata explicitly set to 'false'.",
                                   sourceFiles[i].ItemSpec);
                    continue;
                }
                rootNamespace = sourceFiles[i].GetMetadata("RootNamespace");
                if (string.IsNullOrEmpty(rootNamespace))
                {
                    Log.LogWarning("File {0} was passed to TransmorgifyTemplateFiles without RootNamespace metadata; transmorgification may be incomplete.",
                                   sourceFiles[i].ItemSpec);
                }

                string fullPath = sourceFiles[i].GetMetadata("FullPath");

                try
                {
                    string directoryName = Path.GetDirectoryName(destinationFiles[i].ItemSpec);
                    if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
                    {
                        Log.LogMessage(MessageImportance.Normal, "Creating directory \"{0}\".", directoryName);
                        Directory.CreateDirectory(directoryName);
                    }

                    string fileContents = null;
                    System.Text.Encoding fileEncoding = System.Text.UTF8Encoding.UTF8;

                    using (StreamReader sr = new StreamReader(sourceFiles[i].ItemSpec, true))
                    {
                        fileContents = sr.ReadToEnd();
                        fileEncoding = sr.CurrentEncoding;
                    }

                    TransmorgificationUtilities.MakeTemplateReplacements(false, true, rootNamespace, fullPath, ref fileContents);

                    using (StreamWriter sw = new StreamWriter(destinationFiles[i].ItemSpec, false, fileEncoding))
                    {
                        sw.Write(fileContents);
                    }

                    sourceFiles[i].CopyMetadataTo(destinationFiles[i]);
                }
                catch (Exception e)
                {
                    result = false;
                    Log.LogErrorFromException(e);
                }
            }

            return(result);
        }